Set a visited link store when creating a simple WebView
[WebKit-https.git] / Source / WebKit / mac / WebView / WebView.mm
1 /*
2  * Copyright (C) 2005-2013 Apple Inc. All rights reserved.
3  * Copyright (C) 2006 David Smith (catfish.man@gmail.com)
4  * Copyright (C) 2010 Igalia S.L
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1.  Redistributions of source code must retain the above copyright
11  *     notice, this list of conditions and the following disclaimer. 
12  * 2.  Redistributions in binary form must reproduce the above copyright
13  *     notice, this list of conditions and the following disclaimer in the
14  *     documentation and/or other materials provided with the distribution. 
15  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
16  *     its contributors may be used to endorse or promote products derived
17  *     from this software without specific prior written permission. 
18  *
19  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
20  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
23  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #import "WebViewInternal.h"
32 #import "WebViewData.h"
33
34 #import "DOMCSSStyleDeclarationInternal.h"
35 #import "DOMDocumentInternal.h"
36 #import "DOMNodeInternal.h"
37 #import "DOMRangeInternal.h"
38 #import "DictionaryPopupInfo.h"
39 #import "WebAlternativeTextClient.h"
40 #import "WebApplicationCache.h"
41 #import "WebBackForwardListInternal.h"
42 #import "WebBaseNetscapePluginView.h"
43 #import "WebCache.h"
44 #import "WebChromeClient.h"
45 #import "WebDOMOperationsPrivate.h"
46 #import "WebDataSourceInternal.h"
47 #import "WebDatabaseManagerPrivate.h"
48 #import "WebDefaultEditingDelegate.h"
49 #import "WebDefaultPolicyDelegate.h"
50 #import "WebDefaultUIDelegate.h"
51 #import "WebDelegateImplementationCaching.h"
52 #import "WebDeviceOrientationClient.h"
53 #import "WebDeviceOrientationProvider.h"
54 #import "WebDocument.h"
55 #import "WebDocumentInternal.h"
56 #import "WebDownload.h"
57 #import "WebDownloadInternal.h"
58 #import "WebDragClient.h"
59 #import "WebDynamicScrollBarsViewInternal.h"
60 #import "WebEditingDelegate.h"
61 #import "WebEditorClient.h"
62 #import "WebFormDelegatePrivate.h"
63 #import "WebFrameInternal.h"
64 #import "WebFrameLoaderClient.h"
65 #import "WebFrameNetworkingContext.h"
66 #import "WebFrameViewInternal.h"
67 #import "WebGeolocationClient.h"
68 #import "WebGeolocationPositionInternal.h"
69 #import "WebHTMLRepresentation.h"
70 #import "WebHTMLViewInternal.h"
71 #import "WebHistoryItemInternal.h"
72 #import "WebIconDatabaseInternal.h"
73 #import "WebInspector.h"
74 #import "WebInspectorClient.h"
75 #import "WebKitErrors.h"
76 #import "WebKitFullScreenListener.h"
77 #import "WebKitLogging.h"
78 #import "WebKitNSStringExtras.h"
79 #import "WebKitStatisticsPrivate.h"
80 #import "WebKitSystemBits.h"
81 #import "WebKitVersionChecks.h"
82 #import "WebLocalizableStrings.h"
83 #import "WebNSDataExtras.h"
84 #import "WebNSDataExtrasPrivate.h"
85 #import "WebNSDictionaryExtras.h"
86 #import "WebNSURLExtras.h"
87 #import "WebNSURLRequestExtras.h"
88 #import "WebNSViewExtras.h"
89 #import "WebNodeHighlight.h"
90 #import "WebNotificationClient.h"
91 #import "WebPDFView.h"
92 #import "WebPanelAuthenticationHandler.h"
93 #import "WebPlatformStrategies.h"
94 #import "WebPluginDatabase.h"
95 #import "WebPolicyDelegate.h"
96 #import "WebPreferenceKeysPrivate.h"
97 #import "WebPreferencesPrivate.h"
98 #import "WebProgressTrackerClient.h"
99 #import "WebScriptDebugDelegate.h"
100 #import "WebScriptWorldInternal.h"
101 #import "WebSelectionServiceController.h"
102 #import "WebStorageManagerInternal.h"
103 #import "WebSystemInterface.h"
104 #import "WebTextCompletionController.h"
105 #import "WebTextIterator.h"
106 #import "WebUIDelegate.h"
107 #import "WebUIDelegatePrivate.h"
108 #import "WebUserMediaClient.h"
109 #import "WebViewGroup.h"
110 #import "WebVisitedLinkStore.h"
111 #import <CoreFoundation/CFSet.h>
112 #import <Foundation/NSURLConnection.h>
113 #import <JavaScriptCore/APICast.h>
114 #import <JavaScriptCore/JSValueRef.h>
115 #import <WebCore/AlternativeTextUIController.h>
116 #import <WebCore/AnimationController.h>
117 #import <WebCore/ApplicationCacheStorage.h>
118 #import <WebCore/BackForwardController.h>
119 #import <WebCore/BackForwardList.h>
120 #import <WebCore/CFNetworkSPI.h>
121 #import <WebCore/Chrome.h>
122 #import <WebCore/ColorMac.h>
123 #import <WebCore/Cursor.h>
124 #import <WebCore/DatabaseManager.h>
125 #import <WebCore/Document.h>
126 #import <WebCore/DocumentLoader.h>
127 #import <WebCore/DragController.h>
128 #import <WebCore/DragData.h>
129 #import <WebCore/Editor.h>
130 #import <WebCore/EventHandler.h>
131 #import <WebCore/ExceptionHandlers.h>
132 #import <WebCore/FocusController.h>
133 #import <WebCore/FrameLoader.h>
134 #import <WebCore/FrameSelection.h>
135 #import <WebCore/FrameTree.h>
136 #import <WebCore/FrameView.h>
137 #import <WebCore/GCController.h>
138 #import <WebCore/GeolocationController.h>
139 #import <WebCore/GeolocationError.h>
140 #import <WebCore/HTMLNames.h>
141 #import <WebCore/HTMLVideoElement.h>
142 #import <WebCore/HistoryController.h>
143 #import <WebCore/HistoryItem.h>
144 #import <WebCore/IconDatabase.h>
145 #import <WebCore/JSCSSStyleDeclaration.h>
146 #import <WebCore/JSDocument.h>
147 #import <WebCore/JSElement.h>
148 #import <WebCore/JSNodeList.h>
149 #import <WebCore/JSNotification.h>
150 #import <WebCore/Logging.h>
151 #import <WebCore/MIMETypeRegistry.h>
152 #import <WebCore/MainFrame.h>
153 #import <WebCore/MemoryCache.h>
154 #import <WebCore/MemoryPressureHandler.h>
155 #import <WebCore/NSURLFileTypeMappingsSPI.h>
156 #import <WebCore/NodeList.h>
157 #import <WebCore/Notification.h>
158 #import <WebCore/NotificationController.h>
159 #import <WebCore/Page.h>
160 #import <WebCore/PageCache.h>
161 #import <WebCore/PageConfiguration.h>
162 #import <WebCore/PageGroup.h>
163 #import <WebCore/PlatformEventFactoryMac.h>
164 #import <WebCore/ProgressTracker.h>
165 #import <WebCore/RenderView.h>
166 #import <WebCore/RenderWidget.h>
167 #import <WebCore/ResourceHandle.h>
168 #import <WebCore/ResourceLoadScheduler.h>
169 #import <WebCore/ResourceRequest.h>
170 #import <WebCore/RuntimeApplicationChecks.h>
171 #import <WebCore/RuntimeEnabledFeatures.h>
172 #import <WebCore/SchemeRegistry.h>
173 #import <WebCore/ScriptController.h>
174 #import <WebCore/SecurityOrigin.h>
175 #import <WebCore/SecurityPolicy.h>
176 #import <WebCore/Settings.h>
177 #import <WebCore/StyleProperties.h>
178 #import <WebCore/TextResourceDecoder.h>
179 #import <WebCore/ThreadCheck.h>
180 #import <WebCore/UserAgent.h>
181 #import <WebCore/UserContentController.h>
182 #import <WebCore/WebCoreObjCExtras.h>
183 #import <WebCore/WebCoreView.h>
184 #import <WebCore/Widget.h>
185 #import <WebKitLegacy/DOM.h>
186 #import <WebKitLegacy/DOMExtensions.h>
187 #import <WebKitLegacy/DOMPrivate.h>
188 #import <WebKitSystemInterface.h>
189 #import <bindings/ScriptValue.h>
190 #import <mach-o/dyld.h>
191 #import <objc/objc-auto.h>
192 #import <objc/runtime.h>
193 #import <runtime/ArrayPrototype.h>
194 #import <runtime/DateInstance.h>
195 #import <runtime/InitializeThreading.h>
196 #import <runtime/JSCJSValue.h>
197 #import <runtime/JSLock.h>
198 #import <wtf/Assertions.h>
199 #import <wtf/HashTraits.h>
200 #import <wtf/MainThread.h>
201 #import <wtf/ObjcRuntimeExtras.h>
202 #import <wtf/RefCountedLeakCounter.h>
203 #import <wtf/RefPtr.h>
204 #import <wtf/RunLoop.h>
205 #import <wtf/StdLibExtras.h>
206
207 #if !PLATFORM(IOS)
208 #import "WebActionMenuController.h"
209 #import "WebContextMenuClient.h"
210 #import "WebFullScreenController.h"
211 #import "WebNSEventExtras.h"
212 #import "WebNSObjectExtras.h"
213 #import "WebNSPasteboardExtras.h"
214 #import "WebNSPrintOperationExtras.h"
215 #import "WebPDFView.h"
216 #import <WebCore/LookupSPI.h>
217 #import <WebCore/NSViewSPI.h>
218 #import <WebCore/SoftLinking.h>
219 #import <WebCore/TextIndicator.h>
220 #import <WebCore/TextIndicatorWindow.h>
221 #import <WebCore/WebVideoFullscreenController.h>
222 #else
223 #import "MemoryMeasure.h"
224 #import "WebCaretChangeListener.h"
225 #import "WebChromeClientIOS.h"
226 #import "WebDefaultFormDelegate.h"
227 #import "WebDefaultFrameLoadDelegate.h"
228 #import "WebDefaultResourceLoadDelegate.h"
229 #import "WebDefaultUIKitDelegate.h"
230 #import "WebFixedPositionContent.h"
231 #import "WebMailDelegate.h"
232 #import "WebNSUserDefaultsExtras.h"
233 #import "WebPDFViewIOS.h"
234 #import "WebPlainWhiteView.h"
235 #import "WebPluginController.h"
236 #import "WebPolicyDelegatePrivate.h"
237 #import "WebSQLiteDatabaseTrackerClient.h"
238 #import "WebStorageManagerPrivate.h"
239 #import "WebUIKitSupport.h"
240 #import "WebVisiblePosition.h"
241 #import <WebCore/DispatchSPI.h>
242 #import <WebCore/EventNames.h>
243 #import <WebCore/FontCache.h>
244 #import <WebCore/GraphicsLayer.h>
245 #import <WebCore/IconController.h>
246 #import <WebCore/LegacyTileCache.h>
247 #import <WebCore/MobileGestaltSPI.h>
248 #import <WebCore/NetworkStateNotifier.h>
249 #import <WebCore/RuntimeApplicationChecksIOS.h>
250 #import <WebCore/SQLiteDatabaseTracker.h>
251 #import <WebCore/SmartReplace.h>
252 #import <WebCore/TextRun.h>
253 #import <WebCore/TileControllerMemoryHandlerIOS.h>
254 #import <WebCore/WAKWindow.h>
255 #import <WebCore/WKView.h>
256 #import <WebCore/WebCoreThread.h>
257 #import <WebCore/WebCoreThreadMessage.h>
258 #import <WebCore/WebCoreThreadRun.h>
259 #import <WebCore/WebEvent.h>
260 #import <WebCore/WebVideoFullscreenControllerAVKit.h>
261 #import <wtf/FastMalloc.h>
262 #endif // !PLATFORM(IOS)
263
264 #if ENABLE(DASHBOARD_SUPPORT)
265 #import <WebKitLegacy/WebDashboardRegion.h>
266 #endif
267
268 #if ENABLE(REMOTE_INSPECTOR)
269 #import <JavaScriptCore/RemoteInspector.h>
270 #if PLATFORM(IOS)
271 #import "WebIndicateLayer.h"
272 #endif
273 #endif
274
275 #if USE(GLIB)
276 #import <glib.h>
277 #endif
278
279 #if USE(QUICK_LOOK)
280 #include <WebCore/QuickLook.h>
281 #endif
282
283 #if ENABLE(IOS_TOUCH_EVENTS)
284 #import <WebCore/WebEventRegion.h>
285 #endif
286
287 #if ENABLE(GAMEPAD)
288 #import <WebCore/HIDGamepadProvider.h>
289 #endif
290
291 #if PLATFORM(MAC)
292 SOFT_LINK_CONSTANT_MAY_FAIL(Lookup, LUNotificationPopoverWillClose, NSString *)
293 SOFT_LINK_CONSTANT_MAY_FAIL(Lookup, LUTermOptionDisableSearchTermIndicator, NSString *)
294 #endif
295
296 #if !PLATFORM(IOS)
297 @interface NSSpellChecker (WebNSSpellCheckerDetails)
298 - (void)_preflightChosenSpellServer;
299 @end
300
301 @interface NSView (WebNSViewDetails)
302 - (NSView *)_hitTest:(NSPoint *)aPoint dragTypes:(NSSet *)types;
303 - (void)_autoscrollForDraggingInfo:(id)dragInfo timeDelta:(NSTimeInterval)repeatDelta;
304 - (BOOL)_shouldAutoscrollForDraggingInfo:(id)dragInfo;
305 - (void)_windowChangedKeyState;
306 @end
307
308 @interface NSWindow (WebNSWindowDetails)
309 - (id)_oldFirstResponderBeforeBecoming;
310 - (void)_enableScreenUpdatesIfNeeded;
311 - (BOOL)_wrapsCarbonWindow;
312 - (BOOL)_hasKeyAppearance;
313 @end
314 #endif
315
316 using namespace JSC;
317 using namespace Inspector;
318 using namespace WebCore;
319
320 #define FOR_EACH_RESPONDER_SELECTOR(macro) \
321 macro(alignCenter) \
322 macro(alignJustified) \
323 macro(alignLeft) \
324 macro(alignRight) \
325 macro(capitalizeWord) \
326 macro(centerSelectionInVisibleArea) \
327 macro(changeAttributes) \
328 macro(changeBaseWritingDirection) \
329 macro(changeBaseWritingDirectionToLTR) \
330 macro(changeBaseWritingDirectionToRTL) \
331 macro(changeColor) \
332 macro(changeDocumentBackgroundColor) \
333 macro(changeFont) \
334 macro(changeSpelling) \
335 macro(checkSpelling) \
336 macro(complete) \
337 macro(copy) \
338 macro(copyFont) \
339 macro(cut) \
340 macro(delete) \
341 macro(deleteBackward) \
342 macro(deleteBackwardByDecomposingPreviousCharacter) \
343 macro(deleteForward) \
344 macro(deleteToBeginningOfLine) \
345 macro(deleteToBeginningOfParagraph) \
346 macro(deleteToEndOfLine) \
347 macro(deleteToEndOfParagraph) \
348 macro(deleteToMark) \
349 macro(deleteWordBackward) \
350 macro(deleteWordForward) \
351 macro(ignoreSpelling) \
352 macro(indent) \
353 macro(insertBacktab) \
354 macro(insertLineBreak) \
355 macro(insertNewline) \
356 macro(insertNewlineIgnoringFieldEditor) \
357 macro(insertParagraphSeparator) \
358 macro(insertTab) \
359 macro(insertTabIgnoringFieldEditor) \
360 macro(lowercaseWord) \
361 macro(makeBaseWritingDirectionLeftToRight) \
362 macro(makeBaseWritingDirectionRightToLeft) \
363 macro(makeTextWritingDirectionLeftToRight) \
364 macro(makeTextWritingDirectionNatural) \
365 macro(makeTextWritingDirectionRightToLeft) \
366 macro(moveBackward) \
367 macro(moveBackwardAndModifySelection) \
368 macro(moveDown) \
369 macro(moveDownAndModifySelection) \
370 macro(moveForward) \
371 macro(moveForwardAndModifySelection) \
372 macro(moveLeft) \
373 macro(moveLeftAndModifySelection) \
374 macro(moveParagraphBackwardAndModifySelection) \
375 macro(moveParagraphForwardAndModifySelection) \
376 macro(moveRight) \
377 macro(moveRightAndModifySelection) \
378 macro(moveToBeginningOfDocument) \
379 macro(moveToBeginningOfDocumentAndModifySelection) \
380 macro(moveToBeginningOfLine) \
381 macro(moveToBeginningOfLineAndModifySelection) \
382 macro(moveToBeginningOfParagraph) \
383 macro(moveToBeginningOfParagraphAndModifySelection) \
384 macro(moveToBeginningOfSentence) \
385 macro(moveToBeginningOfSentenceAndModifySelection) \
386 macro(moveToEndOfDocument) \
387 macro(moveToEndOfDocumentAndModifySelection) \
388 macro(moveToEndOfLine) \
389 macro(moveToEndOfLineAndModifySelection) \
390 macro(moveToEndOfParagraph) \
391 macro(moveToEndOfParagraphAndModifySelection) \
392 macro(moveToEndOfSentence) \
393 macro(moveToEndOfSentenceAndModifySelection) \
394 macro(moveToLeftEndOfLine) \
395 macro(moveToLeftEndOfLineAndModifySelection) \
396 macro(moveToRightEndOfLine) \
397 macro(moveToRightEndOfLineAndModifySelection) \
398 macro(moveUp) \
399 macro(moveUpAndModifySelection) \
400 macro(moveWordBackward) \
401 macro(moveWordBackwardAndModifySelection) \
402 macro(moveWordForward) \
403 macro(moveWordForwardAndModifySelection) \
404 macro(moveWordLeft) \
405 macro(moveWordLeftAndModifySelection) \
406 macro(moveWordRight) \
407 macro(moveWordRightAndModifySelection) \
408 macro(orderFrontSubstitutionsPanel) \
409 macro(outdent) \
410 macro(overWrite) \
411 macro(pageDown) \
412 macro(pageDownAndModifySelection) \
413 macro(pageUp) \
414 macro(pageUpAndModifySelection) \
415 macro(paste) \
416 macro(pasteAsPlainText) \
417 macro(pasteAsRichText) \
418 macro(pasteFont) \
419 macro(performFindPanelAction) \
420 macro(scrollLineDown) \
421 macro(scrollLineUp) \
422 macro(scrollPageDown) \
423 macro(scrollPageUp) \
424 macro(scrollToBeginningOfDocument) \
425 macro(scrollToEndOfDocument) \
426 macro(selectAll) \
427 macro(selectLine) \
428 macro(selectParagraph) \
429 macro(selectSentence) \
430 macro(selectToMark) \
431 macro(selectWord) \
432 macro(setMark) \
433 macro(showGuessPanel) \
434 macro(startSpeaking) \
435 macro(stopSpeaking) \
436 macro(subscript) \
437 macro(superscript) \
438 macro(swapWithMark) \
439 macro(takeFindStringFromSelection) \
440 macro(toggleBaseWritingDirection) \
441 macro(transpose) \
442 macro(underline) \
443 macro(unscript) \
444 macro(uppercaseWord) \
445 macro(yank) \
446 macro(yankAndSelect) \
447
448 #define WebKitOriginalTopPrintingMarginKey @"WebKitOriginalTopMargin"
449 #define WebKitOriginalBottomPrintingMarginKey @"WebKitOriginalBottomMargin"
450
451 #define KeyboardUIModeDidChangeNotification @"com.apple.KeyboardUIModeDidChange"
452 #define AppleKeyboardUIMode CFSTR("AppleKeyboardUIMode")
453
454 static BOOL s_didSetCacheModel;
455 static WebCacheModel s_cacheModel = WebCacheModelDocumentViewer;
456
457 #if PLATFORM(IOS)
458 static Class s_pdfRepresentationClass;
459 static Class s_pdfViewClass;
460 #endif
461
462 #ifndef NDEBUG
463 static const char webViewIsOpen[] = "At least one WebView is still open.";
464 #endif
465
466 #if PLATFORM(IOS)
467 @interface WebView(WebViewPrivate)
468 - (void)_preferencesChanged:(WebPreferences *)preferences;
469 - (void)_updateScreenScaleFromWindow;
470 @end
471
472 @interface NSURLCache (WebPrivate)
473 - (CFURLCacheRef)_CFURLCache;
474 @end
475 #endif
476
477 #if !PLATFORM(IOS)
478 @interface NSObject (WebValidateWithoutDelegate)
479 - (BOOL)validateUserInterfaceItemWithoutDelegate:(id <NSValidatedUserInterfaceItem>)item;
480 @end
481 #endif
482
483 #if PLATFORM(IOS)
484 @class _WebSafeForwarder;
485
486 @interface _WebSafeAsyncForwarder : NSObject {
487     _WebSafeForwarder *_forwarder;
488 }
489 - (id)initWithForwarder:(_WebSafeForwarder *)forwarder;
490 @end
491 #endif
492
493 @interface _WebSafeForwarder : NSObject
494 {
495     id target; // Non-retained. Don't retain delegates.
496     id defaultTarget;
497 #if PLATFORM(IOS)
498     _WebSafeAsyncForwarder *asyncForwarder;
499     dispatch_once_t asyncForwarderPred;
500 #endif
501 }
502 - (instancetype)initWithTarget:(id)target defaultTarget:(id)defaultTarget;
503 #if PLATFORM(IOS)
504 - (void)clearTarget;
505 - (id)asyncForwarder;
506 #endif
507 @end
508
509 FindOptions coreOptions(WebFindOptions options)
510 {
511     return (options & WebFindOptionsCaseInsensitive ? CaseInsensitive : 0)
512         | (options & WebFindOptionsAtWordStarts ? AtWordStarts : 0)
513         | (options & WebFindOptionsTreatMedialCapitalAsWordStart ? TreatMedialCapitalAsWordStart : 0)
514         | (options & WebFindOptionsBackwards ? Backwards : 0)
515         | (options & WebFindOptionsWrapAround ? WrapAround : 0)
516         | (options & WebFindOptionsStartInSelection ? StartInSelection : 0);
517 }
518
519 LayoutMilestones coreLayoutMilestones(WebLayoutMilestones milestones)
520 {
521     return (milestones & WebDidFirstLayout ? DidFirstLayout : 0)
522         | (milestones & WebDidFirstVisuallyNonEmptyLayout ? DidFirstVisuallyNonEmptyLayout : 0)
523         | (milestones & WebDidHitRelevantRepaintedObjectsAreaThreshold ? DidHitRelevantRepaintedObjectsAreaThreshold : 0);
524 }
525
526 WebLayoutMilestones kitLayoutMilestones(LayoutMilestones milestones)
527 {
528     return (milestones & DidFirstLayout ? WebDidFirstLayout : 0)
529         | (milestones & DidFirstVisuallyNonEmptyLayout ? WebDidFirstVisuallyNonEmptyLayout : 0)
530         | (milestones & DidHitRelevantRepaintedObjectsAreaThreshold ? WebDidHitRelevantRepaintedObjectsAreaThreshold : 0);
531 }
532
533 static WebPageVisibilityState kit(PageVisibilityState visibilityState)
534 {
535     switch (visibilityState) {
536     case PageVisibilityStateVisible:
537         return WebPageVisibilityStateVisible;
538     case PageVisibilityStateHidden:
539         return WebPageVisibilityStateHidden;
540     case PageVisibilityStatePrerender:
541         return WebPageVisibilityStatePrerender;
542     }
543
544     ASSERT_NOT_REACHED();
545     return WebPageVisibilityStateVisible;
546 }
547
548 @interface WebView (WebFileInternal)
549 #if !PLATFORM(IOS)
550 - (float)_deviceScaleFactor;
551 #endif
552 - (BOOL)_isLoading;
553 - (WebFrameView *)_frameViewAtWindowPoint:(NSPoint)point;
554 - (WebFrame *)_focusedFrame;
555 + (void)_preflightSpellChecker;
556 - (BOOL)_continuousCheckingAllowed;
557 - (NSResponder *)_responderForResponderOperations;
558 #if USE(GLIB)
559 - (void)_clearGlibLoopObserver;
560 #endif
561 @end
562
563 NSString *WebElementDOMNodeKey =            @"WebElementDOMNode";
564 NSString *WebElementFrameKey =              @"WebElementFrame";
565 NSString *WebElementImageKey =              @"WebElementImage";
566 NSString *WebElementImageAltStringKey =     @"WebElementImageAltString";
567 NSString *WebElementImageRectKey =          @"WebElementImageRect";
568 NSString *WebElementImageURLKey =           @"WebElementImageURL";
569 NSString *WebElementIsSelectedKey =         @"WebElementIsSelected";
570 NSString *WebElementLinkLabelKey =          @"WebElementLinkLabel";
571 NSString *WebElementLinkTargetFrameKey =    @"WebElementTargetFrame";
572 NSString *WebElementLinkTitleKey =          @"WebElementLinkTitle";
573 NSString *WebElementLinkURLKey =            @"WebElementLinkURL";
574 NSString *WebElementMediaURLKey =           @"WebElementMediaURL";
575 NSString *WebElementSpellingToolTipKey =    @"WebElementSpellingToolTip";
576 NSString *WebElementTitleKey =              @"WebElementTitle";
577 NSString *WebElementLinkIsLiveKey =         @"WebElementLinkIsLive";
578 NSString *WebElementIsInScrollBarKey =      @"WebElementIsInScrollBar";
579 NSString *WebElementIsContentEditableKey =  @"WebElementIsContentEditableKey";
580
581 NSString *WebViewProgressStartedNotification =          @"WebProgressStartedNotification";
582 NSString *WebViewProgressEstimateChangedNotification =  @"WebProgressEstimateChangedNotification";
583 #if !PLATFORM(IOS)
584 NSString *WebViewProgressFinishedNotification =         @"WebProgressFinishedNotification";
585 #else
586 NSString * const WebViewProgressEstimatedProgressKey = @"WebProgressEstimatedProgressKey";
587 NSString * const WebViewProgressBackgroundColorKey =   @"WebProgressBackgroundColorKey";
588 #endif
589
590 NSString * const WebViewDidBeginEditingNotification =         @"WebViewDidBeginEditingNotification";
591 NSString * const WebViewDidChangeNotification =               @"WebViewDidChangeNotification";
592 NSString * const WebViewDidEndEditingNotification =           @"WebViewDidEndEditingNotification";
593 NSString * const WebViewDidChangeTypingStyleNotification =    @"WebViewDidChangeTypingStyleNotification";
594 NSString * const WebViewDidChangeSelectionNotification =      @"WebViewDidChangeSelectionNotification";
595
596 enum { WebViewVersion = 4 };
597
598 #define timedLayoutSize 4096
599
600 static NSMutableSet *schemesWithRepresentationsSet;
601
602 #if !PLATFORM(IOS)
603 NSString *_WebCanGoBackKey =            @"canGoBack";
604 NSString *_WebCanGoForwardKey =         @"canGoForward";
605 NSString *_WebEstimatedProgressKey =    @"estimatedProgress";
606 NSString *_WebIsLoadingKey =            @"isLoading";
607 NSString *_WebMainFrameIconKey =        @"mainFrameIcon";
608 NSString *_WebMainFrameTitleKey =       @"mainFrameTitle";
609 NSString *_WebMainFrameURLKey =         @"mainFrameURL";
610 NSString *_WebMainFrameDocumentKey =    @"mainFrameDocument";
611 #endif
612
613 #if USE(QUICK_LOOK)
614 NSString *WebQuickLookFileNameKey = @"WebQuickLookFileNameKey";
615 NSString *WebQuickLookUTIKey      = @"WebQuickLookUTIKey";
616 #endif
617
618 NSString *_WebViewDidStartAcceleratedCompositingNotification = @"_WebViewDidStartAcceleratedCompositing";
619 NSString * const WebViewWillCloseNotification = @"WebViewWillCloseNotification";
620
621 #if ENABLE(REMOTE_INSPECTOR)
622 // FIXME: Legacy, remove this, switch to something from JavaScriptCore Inspector::RemoteInspectorServer.
623 NSString *_WebViewRemoteInspectorHasSessionChangedNotification = @"_WebViewRemoteInspectorHasSessionChangedNotification";
624 #endif
625
626 NSString *WebKitKerningAndLigaturesEnabledByDefaultDefaultsKey = @"WebKitKerningAndLigaturesEnabledByDefault";
627
628 @interface WebProgressItem : NSObject
629 {
630 @public
631     long long bytesReceived;
632     long long estimatedLength;
633 }
634 @end
635
636 @implementation WebProgressItem
637 @end
638
639 static BOOL continuousSpellCheckingEnabled;
640 #if !PLATFORM(IOS)
641 static BOOL grammarCheckingEnabled;
642 static BOOL automaticQuoteSubstitutionEnabled;
643 static BOOL automaticLinkDetectionEnabled;
644 static BOOL automaticDashSubstitutionEnabled;
645 static BOOL automaticTextReplacementEnabled;
646 static BOOL automaticSpellingCorrectionEnabled;
647 #endif
648
649 @implementation WebView (AllWebViews)
650
651 static CFSetCallBacks NonRetainingSetCallbacks = {
652     0,
653     NULL,
654     NULL,
655     CFCopyDescription,
656     CFEqual,
657     CFHash
658 };
659
660 static CFMutableSetRef allWebViewsSet;
661
662 + (void)_makeAllWebViewsPerformSelector:(SEL)selector
663 {
664     if (!allWebViewsSet)
665         return;
666
667     [(NSMutableSet *)allWebViewsSet makeObjectsPerformSelector:selector];
668 }
669
670 - (void)_removeFromAllWebViewsSet
671 {
672     if (allWebViewsSet)
673         CFSetRemoveValue(allWebViewsSet, self);
674 }
675
676 - (void)_addToAllWebViewsSet
677 {
678     if (!allWebViewsSet)
679         allWebViewsSet = CFSetCreateMutable(NULL, 0, &NonRetainingSetCallbacks);
680
681     CFSetSetValue(allWebViewsSet, self);
682 }
683
684 @end
685
686 @implementation WebView (WebPrivate)
687
688 static String webKitBundleVersionString()
689 {
690     return [[NSBundle bundleForClass:[WebView class]] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
691 }
692
693 + (NSString *)_standardUserAgentWithApplicationName:(NSString *)applicationName
694 {
695     return standardUserAgentWithApplicationName(applicationName, webKitBundleVersionString());
696 }
697
698 #if PLATFORM(IOS)
699 - (void)_setBrowserUserAgentProductVersion:(NSString *)productVersion buildVersion:(NSString *)buildVersion bundleVersion:(NSString *)bundleVersion
700 {
701     [self setApplicationNameForUserAgent:[NSString stringWithFormat:@"Version/%@ Mobile/%@ Safari/%@", productVersion, buildVersion, bundleVersion]];
702 }
703
704 - (void)_setUIWebViewUserAgentWithBuildVersion:(NSString *)buildVersion
705 {
706     [self setApplicationNameForUserAgent:[@"Mobile/" stringByAppendingString:buildVersion]];
707 }
708 #endif // PLATFORM(IOS)
709
710 + (void)_reportException:(JSValueRef)exception inContext:(JSContextRef)context
711 {
712     if (!exception || !context)
713         return;
714
715     JSC::ExecState* execState = toJS(context);
716     JSLockHolder lock(execState);
717
718     // Make sure the context has a DOMWindow global object, otherwise this context didn't originate from a WebView.
719     if (!toJSDOMWindow(execState->lexicalGlobalObject()))
720         return;
721
722     reportException(execState, toJS(execState, exception));
723 }
724
725 static void WebKitInitializeApplicationCachePathIfNecessary()
726 {
727     static BOOL initialized = NO;
728     if (initialized)
729         return;
730
731     NSString *appName = [[NSBundle mainBundle] bundleIdentifier];
732     if (!appName)
733         appName = [[NSProcessInfo processInfo] processName];
734 #if PLATFORM(IOS)
735     if (WebCore::applicationIsMobileSafari() || WebCore::applicationIsWebApp())
736         appName = @"com.apple.WebAppCache";
737 #endif
738
739     ASSERT(appName);
740
741     NSString* cacheDir = [NSString _webkit_localCacheDirectoryWithBundleIdentifier:appName];
742
743     cacheStorage().setCacheDirectory(cacheDir);
744     initialized = YES;
745 }
746
747 static bool shouldEnableLoadDeferring()
748 {
749     return !applicationIsAdobeInstaller();
750 }
751
752 static bool shouldRestrictWindowFocus()
753 {
754 #if PLATFORM(IOS)
755     return true;
756 #else
757     return !applicationIsHRBlock();
758 #endif
759 }
760
761 - (void)_dispatchPendingLoadRequests
762 {
763     resourceLoadScheduler()->servePendingRequests();
764 }
765
766 #if !PLATFORM(IOS)
767 - (void)_registerDraggedTypes
768 {
769     NSArray *editableTypes = [WebHTMLView _insertablePasteboardTypes];
770     NSArray *URLTypes = [NSPasteboard _web_dragTypesForURL];
771     NSMutableSet *types = [[NSMutableSet alloc] initWithArray:editableTypes];
772     [types addObjectsFromArray:URLTypes];
773     [self registerForDraggedTypes:[types allObjects]];
774     [types release];
775 }
776
777 static bool needsOutlookQuirksScript()
778 {
779     static bool isOutlookNeedingQuirksScript = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
780         && applicationIsMicrosoftOutlook();
781     return isOutlookNeedingQuirksScript;
782 }
783
784 static NSString *leakOutlookQuirksUserScriptContents()
785 {
786     NSString *scriptPath = [[NSBundle bundleForClass:[WebView class]] pathForResource:@"OutlookQuirksUserScript" ofType:@"js"];
787     NSStringEncoding encoding;
788     return [[NSString alloc] initWithContentsOfFile:scriptPath usedEncoding:&encoding error:0];
789 }
790
791 -(void)_injectOutlookQuirksScript
792 {
793     static NSString *outlookQuirksScriptContents = leakOutlookQuirksUserScriptContents();
794     _private->group->userContentController().addUserScript(*core([WebScriptWorld world]), std::make_unique<UserScript>(outlookQuirksScriptContents, URL(), Vector<String>(), Vector<String>(), InjectAtDocumentEnd, InjectInAllFrames));
795
796 }
797 #endif
798
799 static bool shouldRespectPriorityInCSSAttributeSetters()
800 {
801 #if PLATFORM(IOS)
802     static bool isStanzaNeedingAttributeSetterQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_ATTRIBUTE_SETTERS_IGNORING_PRIORITY)
803         && [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.lexcycle.stanza"];
804     return isStanzaNeedingAttributeSetterQuirk;
805 #else
806     static bool isIAdProducerNeedingAttributeSetterQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_ATTRIBUTE_SETTERS_IGNORING_PRIORITY)
807         && [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.apple.iAdProducer"];
808     return isIAdProducerNeedingAttributeSetterQuirk;
809 #endif
810 }
811
812 #if PLATFORM(IOS)
813 static bool shouldTransformsAffectOverflow()
814 {
815     static bool shouldTransformsAffectOverflow = !applicationIsOkCupid() || WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_TRANSFORMS_AFFECTING_OVERFLOW);
816     return shouldTransformsAffectOverflow;
817 }
818
819 static bool shouldDispatchJavaScriptWindowOnErrorEvents()
820 {
821     static bool shouldDispatchJavaScriptWindowOnErrorEvents = !applicationIsFacebook() || WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_WINDOW_ON_ERROR);
822     return shouldDispatchJavaScriptWindowOnErrorEvents;
823 }
824
825 static bool isInternalInstall()
826 {
827     static bool isInternal = MGGetBoolAnswer(kMGQAppleInternalInstallCapability);
828     return isInternal;
829 }
830
831 static bool didOneTimeInitialization = false;
832 #endif
833
834 static bool shouldUseLegacyBackgroundSizeShorthandBehavior()
835 {
836 #if PLATFORM(IOS)
837     static bool shouldUseLegacyBackgroundSizeShorthandBehavior = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LEGACY_BACKGROUNDSIZE_SHORTHAND_BEHAVIOR);
838 #else
839     static bool shouldUseLegacyBackgroundSizeShorthandBehavior = applicationIsVersions()
840         && !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LEGACY_BACKGROUNDSIZE_SHORTHAND_BEHAVIOR);
841 #endif
842     return shouldUseLegacyBackgroundSizeShorthandBehavior;
843 }
844
845 #if ENABLE(GAMEPAD)
846 static void WebKitInitializeGamepadProviderIfNecessary()
847 {
848     static bool initialized = false;
849     if (initialized)
850         return;
851
852     GamepadProvider::shared().setSharedProvider(HIDGamepadProvider::shared());
853     initialized = true;
854 }
855 #endif
856
857 - (void)_commonInitializationWithFrameName:(NSString *)frameName groupName:(NSString *)groupName
858 {
859     WebCoreThreadViolationCheckRoundTwo();
860
861 #ifndef NDEBUG
862     WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
863 #endif
864     
865     WebPreferences *standardPreferences = [WebPreferences standardPreferences];
866     [standardPreferences willAddToWebView];
867
868     _private->preferences = [standardPreferences retain];
869     _private->mainFrameDocumentReady = NO;
870     _private->drawsBackground = YES;
871 #if !PLATFORM(IOS)
872     _private->backgroundColor = [[NSColor colorWithDeviceWhite:1 alpha:1] retain];
873 #else
874     _private->backgroundColor = CGColorRetain(cachedCGColor(Color::white, ColorSpaceDeviceRGB));
875 #endif
876     _private->includesFlattenedCompositingLayersWhenDrawingToBitmap = YES;
877
878     NSRect f = [self frame];
879     WebFrameView *frameView = [[WebFrameView alloc] initWithFrame: NSMakeRect(0,0,f.size.width,f.size.height)];
880     [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
881     [self addSubview:frameView];
882     [frameView release];
883
884 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
885     if ([self respondsToSelector:@selector(setActionMenu:)]) {
886         RetainPtr<NSMenu> actionMenu = adoptNS([[NSMenu alloc] init]);
887         self.actionMenu = actionMenu.get();
888         _private->actionMenuController = [[WebActionMenuController alloc] initWithWebView:self];
889     }
890 #endif
891
892 #if !PLATFORM(IOS)
893     static bool didOneTimeInitialization = false;
894 #endif
895     if (!didOneTimeInitialization) {
896 #if !LOG_DISABLED
897         WebKitInitializeLoggingChannelsIfNecessary();
898         WebCore::initializeLoggingChannelsIfNecessary();
899 #endif // !LOG_DISABLED
900
901         // Initialize our platform strategies first before invoking the rest
902         // of the initialization code which may depend on the strategies.
903         WebPlatformStrategies::initializeIfNecessary();
904
905 #if ENABLE(SQL_DATABASE)
906 #if PLATFORM(IOS)
907         // Set the WebSQLiteDatabaseTrackerClient.
908         SQLiteDatabaseTracker::setClient(WebSQLiteDatabaseTrackerClient::sharedWebSQLiteDatabaseTrackerClient());
909
910         if ([standardPreferences databasesEnabled])
911 #endif
912         [WebDatabaseManager sharedWebDatabaseManager];
913 #endif
914
915 #if PLATFORM(IOS)        
916         if ([standardPreferences storageTrackerEnabled])
917 #endif
918         WebKitInitializeStorageIfNecessary();
919         WebKitInitializeApplicationCachePathIfNecessary();
920 #if ENABLE(GAMEPAD)
921         WebKitInitializeGamepadProviderIfNecessary();
922 #endif
923         
924         Settings::setDefaultMinDOMTimerInterval(0.004);
925         
926         Settings::setShouldRespectPriorityInCSSAttributeSetters(shouldRespectPriorityInCSSAttributeSetters());
927
928 #if PLATFORM(IOS)
929         if (applicationIsMobileSafari())
930             Settings::setShouldManageAudioSessionCategory(true);
931 #endif
932
933         didOneTimeInitialization = true;
934     }
935
936     _private->group = WebViewGroup::getOrCreate(groupName);
937     _private->group->addWebView(self);
938
939     PageConfiguration pageConfiguration;
940 #if !PLATFORM(IOS)
941     pageConfiguration.chromeClient = new WebChromeClient(self);
942     pageConfiguration.contextMenuClient = new WebContextMenuClient(self);
943 #if ENABLE(DRAG_SUPPORT)
944     pageConfiguration.dragClient = new WebDragClient(self);
945 #endif
946     pageConfiguration.inspectorClient = new WebInspectorClient(self);
947 #else
948     pageConfiguration.chromeClient = new WebChromeClientIOS(self);
949     pageConfiguration.inspectorClient = new WebInspectorClient(self);
950 #endif
951     pageConfiguration.editorClient = new WebEditorClient(self);
952     pageConfiguration.alternativeTextClient = new WebAlternativeTextClient(self);
953     pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
954     pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(self);
955     pageConfiguration.userContentController = &_private->group->userContentController();
956     pageConfiguration.visitedLinkStore = &_private->group->visitedLinkStore();
957     _private->page = new Page(pageConfiguration);
958
959     _private->page->setGroupName(groupName);
960
961 #if ENABLE(GEOLOCATION)
962     WebCore::provideGeolocationTo(_private->page, new WebGeolocationClient(self));
963 #endif
964 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
965     WebCore::provideNotification(_private->page, new WebNotificationClient(self));
966 #endif
967 #if ENABLE(DEVICE_ORIENTATION)
968 #if !PLATFORM(IOS)
969     WebCore::provideDeviceOrientationTo(_private->page, new WebDeviceOrientationClient(self));
970 #endif
971 #endif
972 #if ENABLE(MEDIA_STREAM)
973     WebCore::provideUserMediaTo(_private->page, new WebUserMediaClient(self));
974 #endif
975
976 #if ENABLE(REMOTE_INSPECTOR)
977     _private->page->setRemoteInspectionAllowed(true);
978 #endif
979
980     _private->page->setCanStartMedia([self window]);
981     _private->page->settings().setLocalStorageDatabasePath([[self preferences] _localStorageDatabasePath]);
982     _private->page->settings().setUseLegacyBackgroundSizeShorthandBehavior(shouldUseLegacyBackgroundSizeShorthandBehavior());
983
984 #if !PLATFORM(IOS)
985     if (needsOutlookQuirksScript()) {
986         _private->page->settings().setShouldInjectUserScriptsInInitialEmptyDocument(true);
987         [self _injectOutlookQuirksScript];
988     }
989 #endif
990
991 #if PLATFORM(IOS)
992     // Preserve the behavior we had before <rdar://problem/7580867>
993     // by enforcing a 5MB limit for session storage.
994     _private->page->settings().setSessionStorageQuota(5 * 1024 * 1024);
995
996     [self _updateScreenScaleFromWindow];
997     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
998     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
999     _private->_fixedPositionContent = [[WebFixedPositionContent alloc] initWithWebView:self];
1000 #endif
1001
1002     if ([[NSUserDefaults standardUserDefaults] objectForKey:WebSmartInsertDeleteEnabled])
1003         [self setSmartInsertDeleteEnabled:[[NSUserDefaults standardUserDefaults] boolForKey:WebSmartInsertDeleteEnabled]];
1004
1005     [WebFrame _createMainFrameWithPage:_private->page frameName:frameName frameView:frameView];
1006
1007 #if !PLATFORM(IOS)
1008     NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
1009
1010     if (WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOADING_DURING_COMMON_RUNLOOP_MODES))
1011         [self scheduleInRunLoop:runLoop forMode:(NSString *)kCFRunLoopCommonModes];
1012     else
1013         [self scheduleInRunLoop:runLoop forMode:NSDefaultRunLoopMode];
1014 #endif
1015
1016     [self _addToAllWebViewsSet];
1017     
1018     // If there's already a next key view (e.g., from a nib), wire it up to our
1019     // contained frame view. In any case, wire our next key view up to the our
1020     // contained frame view. This works together with our becomeFirstResponder 
1021     // and setNextKeyView overrides.
1022     NSView *nextKeyView = [self nextKeyView];
1023     if (nextKeyView && nextKeyView != frameView)
1024         [frameView setNextKeyView:nextKeyView];
1025     [super setNextKeyView:frameView];
1026
1027     if ([[self class] shouldIncludeInWebKitStatistics])
1028         ++WebViewCount;
1029
1030 #if !PLATFORM(IOS)
1031     [self _registerDraggedTypes];
1032 #endif
1033
1034     [self _setIsVisible:[self _isViewVisible]];
1035
1036     WebPreferences *prefs = [self preferences];
1037     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
1038                                                  name:WebPreferencesChangedInternalNotification object:prefs];
1039
1040 #if !PLATFORM(IOS)
1041     [self _preferencesChanged:[self preferences]];
1042     [[self preferences] _postPreferencesChangedAPINotification];
1043 #else
1044     // do this on the current thread on iOS, since the web thread could be blocked on the main thread,
1045     // and prefs need to be changed synchronously <rdar://problem/5841558>
1046     [self _preferencesChanged:prefs];
1047     _private->page->settings().setFontFallbackPrefersPictographs(true);
1048 #endif
1049
1050     memoryPressureHandler().install();
1051
1052     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
1053         // Originally, we allowed all local loads.
1054         SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForAll);
1055     } else if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_MORE_STRICT_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
1056         // Later, we allowed local loads for local URLs and documents loaded
1057         // with substitute data.
1058         SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1059     }
1060
1061 #if !PLATFORM(IOS)
1062     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_CONTENT_SNIFFING_FOR_FILE_URLS))
1063         ResourceHandle::forceContentSniffing();
1064 #endif
1065
1066 #if USE(GLIB)
1067     [self _scheduleGlibContextIterations];
1068 #endif
1069 }
1070
1071 - (id)_initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName
1072 {
1073     self = [super initWithFrame:f];
1074     if (!self)
1075         return nil;
1076
1077 #ifdef ENABLE_WEBKIT_UNSET_DYLD_FRAMEWORK_PATH
1078     // DYLD_FRAMEWORK_PATH is used so Safari will load the development version of WebKit, which
1079     // may not work with other WebKit applications.  Unsetting DYLD_FRAMEWORK_PATH removes the
1080     // need for Safari to unset it to prevent it from being passed to applications it launches.
1081     // Unsetting it when a WebView is first created is as good a place as any.
1082     // See <http://bugs.webkit.org/show_bug.cgi?id=4286> for more details.
1083     if (getenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH")) {
1084         unsetenv("DYLD_FRAMEWORK_PATH");
1085         unsetenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH");
1086     }
1087 #endif
1088
1089     _private = [[WebViewPrivate alloc] init];
1090     [self _commonInitializationWithFrameName:frameName groupName:groupName];
1091     [self setMaintainsBackForwardList: YES];
1092 #if !PLATFORM(IOS)
1093     _private->page->setDeviceScaleFactor([self _deviceScaleFactor]);
1094 #endif
1095     return self;
1096 }
1097
1098 - (void)_viewWillDrawInternal
1099 {
1100     Frame* frame = [self _mainCoreFrame];
1101     if (frame && frame->view())
1102         frame->view()->updateLayoutAndStyleIfNeededRecursive();
1103 }
1104
1105 + (NSArray *)_supportedMIMETypes
1106 {
1107     // Load the plug-in DB allowing plug-ins to install types.
1108     [WebPluginDatabase sharedDatabase];
1109     return [[WebFrameView _viewTypesAllowImageTypeOmission:NO] allKeys];
1110 }
1111
1112 #if !PLATFORM(IOS)
1113 + (NSArray *)_supportedFileExtensions
1114 {
1115     NSMutableSet *extensions = [[NSMutableSet alloc] init];
1116     NSArray *MIMETypes = [self _supportedMIMETypes];
1117     NSEnumerator *enumerator = [MIMETypes objectEnumerator];
1118     NSString *MIMEType;
1119     while ((MIMEType = [enumerator nextObject]) != nil) {
1120         NSArray *extensionsForType = [[NSURLFileTypeMappings sharedMappings] extensionsForMIMEType:MIMEType];
1121         if (extensionsForType) {
1122             [extensions addObjectsFromArray:extensionsForType];
1123         }
1124     }
1125     NSArray *uniqueExtensions = [extensions allObjects];
1126     [extensions release];
1127     return uniqueExtensions;
1128 }
1129 #endif
1130
1131 #if PLATFORM(IOS)
1132 + (void)enableWebThread
1133 {
1134     static BOOL isWebThreadEnabled = NO;
1135     if (!isWebThreadEnabled) {
1136         WebCoreObjCDeallocOnWebThread([WebBasePluginPackage class]);
1137         WebCoreObjCDeallocOnWebThread([WebDataSource class]);
1138         WebCoreObjCDeallocOnWebThread([WebFrame class]);
1139         WebCoreObjCDeallocOnWebThread([WebHTMLView class]);
1140         WebCoreObjCDeallocOnWebThread([WebHistoryItem class]);
1141         WebCoreObjCDeallocOnWebThread([WebPlainWhiteView class]);
1142         WebCoreObjCDeallocOnWebThread([WebPolicyDecisionListener class]);
1143         WebCoreObjCDeallocOnWebThread([WebView class]);
1144         WebCoreObjCDeallocOnWebThread([WebVisiblePosition class]);
1145         if (applicationIsTheEconomistOnIPhone() && !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_DELEGATE_CALLS_IN_COMMON_RUNLOOP_MODES))
1146             WebThreadSetDelegateSourceRunLoopMode(kCFRunLoopDefaultMode);
1147         WebThreadEnable();
1148         isWebThreadEnabled = YES;
1149     }
1150 }
1151
1152 - (id)initSimpleHTMLDocumentWithStyle:(NSString *)style frame:(CGRect)frame preferences:(WebPreferences *)preferences groupName:(NSString *)groupName
1153 {
1154     self = [super initWithFrame:frame];
1155     if (!self)
1156         return nil;
1157     
1158     _private = [[WebViewPrivate alloc] init];
1159     
1160 #ifndef NDEBUG
1161     WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
1162 #endif
1163     
1164     if (!preferences)
1165         preferences = [WebPreferences standardPreferences];
1166     [preferences willAddToWebView];
1167     
1168     _private->preferences = [preferences retain];
1169     _private->mainFrameDocumentReady = NO;
1170     _private->drawsBackground = YES;
1171     _private->backgroundColor = CGColorRetain(cachedCGColor(Color::white, ColorSpaceDeviceRGB));
1172     
1173     WebFrameView *frameView = nil;
1174     frameView = [[WebFrameView alloc] initWithFrame: CGRectMake(0,0,frame.size.width,frame.size.height)];
1175     [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1176     [self addSubview:frameView];
1177     [frameView release];
1178
1179     _private->group = WebViewGroup::getOrCreate(groupName);
1180     _private->group->addWebView(self);
1181
1182     PageConfiguration pageConfiguration;
1183     pageConfiguration.chromeClient = new WebChromeClientIOS(self);
1184 #if ENABLE(DRAG_SUPPORT)
1185     pageConfiguration.dragClient = new WebDragClient(self);
1186 #endif
1187     pageConfiguration.editorClient = new WebEditorClient(self);
1188     pageConfiguration.inspectorClient = new WebInspectorClient(self);
1189     pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
1190     pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(self);
1191     pageConfiguration.userContentController = &_private->group->userContentController();
1192     pageConfiguration.visitedLinkStore = &_private->group->visitedLinkStore();
1193
1194     _private->page = new Page(pageConfiguration);
1195     
1196     [self setSmartInsertDeleteEnabled:YES];
1197     
1198     // FIXME: <rdar://problem/6851451> Should respect preferences in fast path WebView initialization
1199     // We are ignoring the preferences object on fast path and just using Settings defaults (everything fancy off).
1200     // This matches how UIKit sets up the preferences. We need to set  default values for fonts though, <rdar://problem/6850611>.
1201     // This should be revisited later. There is some risk involved, _preferencesChanged used to show up badly in Shark.
1202     _private->page->settings().setMinimumLogicalFontSize(9);
1203     _private->page->settings().setDefaultFontSize([_private->preferences defaultFontSize]);
1204     _private->page->settings().setDefaultFixedFontSize(13);
1205     _private->page->settings().setDownloadableBinaryFontsEnabled(false);
1206     _private->page->settings().setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
1207     _private->page->settings().setScreenFontSubstitutionEnabled(false);
1208     
1209     // FIXME: <rdar://problem/7394370> Always use primary font baseline in text field base line calculation, ignore fallback fonts.
1210     _private->page->settings().setAlwaysUseBaselineOfPrimaryFont([preferences _alwaysUseBaselineOfPrimaryFont]);
1211
1212     _private->page->settings().setFontFallbackPrefersPictographs(true);
1213     _private->page->settings().setPictographFontFamily("AppleColorEmoji");
1214     
1215     // FIXME: this is a workaround for <rdar://problem/11518688> REGRESSION: Quoted text font changes when replying to certain email
1216     _private->page->settings().setStandardFontFamily([_private->preferences standardFontFamily]);
1217     
1218     // FIXME: this is a workaround for <rdar://problem/11820090> Quoted text changes in size when replying to certain email
1219     _private->page->settings().setMinimumFontSize([_private->preferences minimumFontSize]);
1220
1221     _private->page->setGroupName(groupName);
1222
1223 #if ENABLE(REMOTE_INSPECTOR)
1224     _private->page->setRemoteInspectionAllowed(isInternalInstall());
1225 #endif
1226     
1227     [self _updateScreenScaleFromWindow];
1228     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
1229     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
1230
1231     [WebFrame _createMainFrameWithSimpleHTMLDocumentWithPage:_private->page frameView:frameView style:style];
1232     
1233     [self _addToAllWebViewsSet];
1234     
1235     ++WebViewCount;
1236     
1237     SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1238     
1239     return self;
1240 }
1241
1242 + (void)_handleMemoryWarning
1243 {
1244     ASSERT(WebThreadIsCurrent());
1245     WebKit::MemoryMeasure totalMemory("Memory warning: Overall memory change from [WebView _handleMemoryWarning].");
1246
1247     // Always peform the following.
1248     [WebView purgeInactiveFontData];
1249
1250     // Only perform the remaining if a non-simple document was created.
1251     if (!didOneTimeInitialization)
1252         return;
1253
1254     tileControllerMemoryHandler().trimUnparentedTilesToTarget(0);
1255
1256     [WebStorageManager closeIdleLocalStorageDatabases];
1257
1258     [WebView _releaseMemoryNow];
1259 }
1260
1261 + (void)registerForMemoryNotifications
1262 {
1263     BOOL shouldAutoClearPressureOnMemoryRelease = !WebCore::applicationIsMobileSafari();
1264
1265     memoryPressureHandler().installMemoryReleaseBlock(^{
1266         [WebView _handleMemoryWarning];
1267     }, shouldAutoClearPressureOnMemoryRelease);
1268
1269 #if PLATFORM(IOS) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
1270     static dispatch_source_t memoryNotificationEventSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_MEMORYSTATUS, 0, DISPATCH_MEMORYSTATUS_PRESSURE_WARN, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
1271 #else
1272     static dispatch_source_t memoryNotificationEventSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_VM, 0, DISPATCH_VM_PRESSURE, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
1273 #endif
1274     dispatch_source_set_event_handler(memoryNotificationEventSource, ^{
1275         // Set memory pressure flag and schedule releasing memory in web thread runloop exit.
1276         memoryPressureHandler().setReceivedMemoryPressure(WebCore::MemoryPressureReasonVMPressure);
1277     });
1278
1279     dispatch_resume(memoryNotificationEventSource);
1280
1281     if (!shouldAutoClearPressureOnMemoryRelease) {
1282         // Listen to memory status notification to reset the memory pressure flag.
1283         static dispatch_source_t memoryStatusEventSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_MEMORYSTATUS,
1284                                                                                     0,
1285                                                                                     DISPATCH_MEMORYSTATUS_PRESSURE_WARN | DISPATCH_MEMORYSTATUS_PRESSURE_NORMAL,
1286                                                                                     dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
1287         dispatch_source_set_event_handler(memoryStatusEventSource, ^{
1288             unsigned long currentStatus = dispatch_source_get_data(memoryStatusEventSource);
1289             if (currentStatus == DISPATCH_MEMORYSTATUS_PRESSURE_NORMAL)
1290                 memoryPressureHandler().clearMemoryPressure();
1291             else if (currentStatus == DISPATCH_MEMORYSTATUS_PRESSURE_WARN)
1292                 memoryPressureHandler().setReceivedMemoryPressure(WebCore::MemoryPressureReasonVMStatus);
1293         });
1294
1295         dispatch_resume(memoryStatusEventSource);
1296     }
1297 }
1298
1299 + (void)_releaseMemoryNow
1300 {
1301     ASSERT(WebThreadIsCurrent());
1302     [WebView discardAllCompiledCode];
1303     [WebView garbageCollectNow];
1304     [WebView purgeInactiveFontData];
1305     [WebView drainLayerPool];
1306     [WebCache emptyInMemoryResources];
1307     [WebView releaseFastMallocMemoryOnCurrentThread];
1308
1309     dispatch_async(dispatch_get_main_queue(), ^{
1310         // Clear the main thread's TCMalloc thread cache.
1311         [WebView releaseFastMallocMemoryOnCurrentThread];
1312     });
1313 }
1314
1315 + (void)_clearPrivateBrowsingSessionCookieStorage
1316 {
1317     WebFrameNetworkingContext::clearPrivateBrowsingSessionCookieStorage();
1318 }
1319
1320 - (void)_replaceCurrentHistoryItem:(WebHistoryItem *)item
1321 {
1322     Frame* frame = [self _mainCoreFrame];
1323     if (frame)
1324         frame->loader().history().replaceCurrentItem(core(item));
1325 }
1326
1327 + (void)willEnterBackgroundWithCompletionHandler:(void(^)(void))handler
1328 {
1329     WebThreadRun(^{
1330         [WebView _releaseMemoryNow];
1331         dispatch_async(dispatch_get_main_queue(), handler);
1332     });
1333 }
1334
1335 + (void)releaseFastMallocMemoryOnCurrentThread
1336 {
1337     WebKit::MemoryMeasure measurer("Memory warning: Releasing fast malloc memory to system.");
1338     WTF::releaseFastMallocFreeMemory();
1339 }
1340
1341 + (void)garbageCollectNow
1342 {
1343     ASSERT(WebThreadIsCurrent());
1344     WebKit::MemoryMeasure measurer("Memory warning: Calling JavaScript GC.");
1345     gcController().garbageCollectNow();
1346 }
1347
1348 + (void)purgeInactiveFontData
1349 {
1350     ASSERT(WebThreadIsCurrent());
1351     WebKit::MemoryMeasure measurer("Memory warning: Purging inactive font data.");
1352     fontCache().purgeInactiveFontData();
1353 }
1354
1355 + (void)drainLayerPool
1356 {
1357     ASSERT(WebThreadIsCurrent());
1358     WebKit::MemoryMeasure measurer("Memory warning: Draining layer pool.");
1359     WebCore::LegacyTileCache::drainLayerPool();
1360 }
1361
1362 + (void)discardAllCompiledCode
1363 {
1364     ASSERT(WebThreadIsCurrent());
1365     WebKit::MemoryMeasure measurer("Memory warning: Discarding JIT'ed code.");
1366     gcController().discardAllCompiledCode();
1367 }
1368
1369 + (BOOL)isCharacterSmartReplaceExempt:(unichar)character isPreviousCharacter:(BOOL)b
1370 {
1371     return WebCore::isCharacterSmartReplaceExempt(character, b);
1372 }
1373
1374 - (void)updateLayoutIgnorePendingStyleSheets
1375 {
1376     WebThreadRun(^{
1377         for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext()) {
1378             Document *document = frame->document();
1379             if (document)
1380                 document->updateLayoutIgnorePendingStylesheets();
1381         }
1382     });
1383 }
1384 #endif // PLATFORM(IOS)
1385
1386 static NSMutableSet *knownPluginMIMETypes()
1387 {
1388     static NSMutableSet *mimeTypes = [[NSMutableSet alloc] init];
1389     
1390     return mimeTypes;
1391 }
1392
1393 + (void)_registerPluginMIMEType:(NSString *)MIMEType
1394 {
1395     [WebView registerViewClass:[WebHTMLView class] representationClass:[WebHTMLRepresentation class] forMIMEType:MIMEType];
1396     [knownPluginMIMETypes() addObject:MIMEType];
1397 }
1398
1399 + (void)_unregisterPluginMIMEType:(NSString *)MIMEType
1400 {
1401     [self _unregisterViewClassAndRepresentationClassForMIMEType:MIMEType];
1402     [knownPluginMIMETypes() removeObject:MIMEType];
1403 }
1404
1405 + (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType allowingPlugins:(BOOL)allowPlugins
1406 {
1407     MIMEType = [MIMEType lowercaseString];
1408     Class viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
1409     Class repClass = [[WebDataSource _repTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
1410
1411 #if PLATFORM(IOS)
1412 #define WebPDFView ([WebView _getPDFViewClass])
1413 #endif
1414     if (!viewClass || !repClass || [[WebPDFView supportedMIMETypes] containsObject:MIMEType]) {
1415 #if PLATFORM(IOS)
1416 #undef WebPDFView
1417 #endif
1418         // Our optimization to avoid loading the plug-in DB and image types for the HTML case failed.
1419
1420         if (allowPlugins) {
1421             // Load the plug-in DB allowing plug-ins to install types.
1422             [WebPluginDatabase sharedDatabase];
1423         }
1424
1425         // Load the image types and get the view class and rep class. This should be the fullest picture of all handled types.
1426         viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
1427         repClass = [[WebDataSource _repTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
1428     }
1429     
1430     if (viewClass && repClass) {
1431         if (viewClass == [WebHTMLView class] && repClass == [WebHTMLRepresentation class]) {
1432             // Special-case WebHTMLView for text types that shouldn't be shown.
1433             if ([[WebHTMLView unsupportedTextMIMETypes] containsObject:MIMEType])
1434                 return NO;
1435
1436             // If the MIME type is a known plug-in we might not want to load it.
1437             if (!allowPlugins && [knownPluginMIMETypes() containsObject:MIMEType]) {
1438                 BOOL isSupportedByWebKit = [[WebHTMLView supportedNonImageMIMETypes] containsObject:MIMEType] ||
1439                     [[WebHTMLView supportedMIMETypes] containsObject:MIMEType];
1440                 
1441                 // If this is a known plug-in MIME type and WebKit can't show it natively, we don't want to show it.
1442                 if (!isSupportedByWebKit)
1443                     return NO;
1444             }
1445         }
1446         if (vClass)
1447             *vClass = viewClass;
1448         if (rClass)
1449             *rClass = repClass;
1450         return YES;
1451     }
1452     
1453     return NO;
1454 }
1455
1456 - (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType
1457 {
1458     if ([[self class] _viewClass:vClass andRepresentationClass:rClass forMIMEType:MIMEType allowingPlugins:[_private->preferences arePlugInsEnabled]])
1459         return YES;
1460 #if !PLATFORM(IOS)
1461     if (_private->pluginDatabase) {
1462         WebBasePluginPackage *pluginPackage = [_private->pluginDatabase pluginForMIMEType:MIMEType];
1463         if (pluginPackage) {
1464             if (vClass)
1465                 *vClass = [WebHTMLView class];
1466             if (rClass)
1467                 *rClass = [WebHTMLRepresentation class];
1468             return YES;
1469         }
1470     }
1471 #endif
1472     return NO;
1473 }
1474
1475 + (void)_setAlwaysUsesComplexTextCodePath:(BOOL)f
1476 {
1477     Font::setCodePath(f ? Font::Complex : Font::Auto);
1478 }
1479
1480 + (void)_setAllowsRoundingHacks:(BOOL)allowsRoundingHacks
1481 {
1482     TextRun::setAllowsRoundingHacks(allowsRoundingHacks);
1483 }
1484
1485 + (BOOL)_allowsRoundingHacks
1486 {
1487     return TextRun::allowsRoundingHacks();
1488 }
1489
1490 + (BOOL)canCloseAllWebViews
1491 {
1492     return DOMWindow::dispatchAllPendingBeforeUnloadEvents();
1493 }
1494
1495 + (void)closeAllWebViews
1496 {
1497     DOMWindow::dispatchAllPendingUnloadEvents();
1498
1499     // This will close the WebViews in a random order. Change this if close order is important.
1500     // Make a new set to avoid mutating the set we are enumerating.
1501     NSSet *webViewsToClose = [NSSet setWithSet:(NSSet *)allWebViewsSet]; 
1502     NSEnumerator *enumerator = [webViewsToClose objectEnumerator];
1503     while (WebView *webView = [enumerator nextObject])
1504         [webView close];
1505 }
1506
1507 + (BOOL)canShowFile:(NSString *)path
1508 {
1509     return [[self class] canShowMIMEType:[WebView _MIMETypeForFile:path]];
1510 }
1511
1512 #if !PLATFORM(IOS)
1513 + (NSString *)suggestedFileExtensionForMIMEType:(NSString *)type
1514 {
1515     return [[NSURLFileTypeMappings sharedMappings] preferredExtensionForMIMEType:type];
1516 }
1517 #endif
1518
1519 - (BOOL)_isClosed
1520 {
1521     return !_private || _private->closed;
1522 }
1523
1524 #if PLATFORM(IOS)
1525 - (void)_dispatchUnloadEvent
1526 {
1527     WebThreadRun(^{
1528         WebFrame *mainFrame = [self mainFrame];
1529         Frame *coreMainFrame = core(mainFrame);
1530         if (coreMainFrame) {
1531             Document *document = coreMainFrame->document();
1532             if (document)
1533                 document->dispatchWindowEvent(Event::create(eventNames().unloadEvent, false, false));
1534         }
1535     });
1536 }
1537
1538 - (DOMCSSStyleDeclaration *)styleAtSelectionStart
1539 {
1540     WebFrame *mainFrame = [self mainFrame];
1541     Frame *coreMainFrame = core(mainFrame);
1542     if (!coreMainFrame)
1543         return nil;
1544     return coreMainFrame->styleAtSelectionStart();
1545 }
1546
1547 - (NSUInteger)_renderTreeSize
1548 {
1549     if (!_private->page)
1550         return 0;
1551     return _private->page->renderTreeSize();
1552 }
1553
1554 - (void)_dispatchTileDidDraw:(CALayer*)tile
1555 {
1556     id mailDelegate = [self _webMailDelegate];
1557     if ([mailDelegate respondsToSelector:@selector(_webthread_webView:tileDidDraw:)]) {
1558         [mailDelegate _webthread_webView:self tileDidDraw:tile];
1559         return;
1560     }
1561
1562     if (!OSAtomicCompareAndSwap32(0, 1, &_private->didDrawTiles))
1563         return;
1564
1565     WebThreadLock();
1566
1567     [[[self _UIKitDelegateForwarder] asyncForwarder] webViewDidDrawTiles:self];
1568 }
1569
1570 - (void)_willStartScrollingOrZooming
1571 {
1572     // Pause timers during top level interaction
1573     if (_private->mainViewIsScrollingOrZooming)
1574         return;
1575     _private->mainViewIsScrollingOrZooming = YES;
1576
1577     // This suspends active DOM objects like timers, but not media.
1578     [[self mainFrame] setTimeoutsPaused:YES];
1579
1580     // This defers loading callbacks only.
1581     // WARNING: This behavior could change if Bug 49401 lands in open source WebKit again.
1582     [self setDefersCallbacks:YES];
1583 }
1584
1585 - (void)_didFinishScrollingOrZooming
1586 {
1587     if (!_private->mainViewIsScrollingOrZooming)
1588         return;
1589     _private->mainViewIsScrollingOrZooming = NO;
1590     [self setDefersCallbacks:NO];
1591     [[self mainFrame] setTimeoutsPaused:NO];
1592     if (FrameView* view = [self _mainCoreFrame]->view())
1593         view->resumeVisibleImageAnimationsIncludingSubframes();
1594 }
1595
1596 - (void)_setResourceLoadSchedulerSuspended:(BOOL)suspend
1597 {
1598     if (suspend)
1599         resourceLoadScheduler()->suspendPendingRequests();
1600     else
1601         resourceLoadScheduler()->resumePendingRequests();
1602 }
1603
1604 + (void)_setAllowCookies:(BOOL)allow
1605 {
1606     ResourceRequestBase::setDefaultAllowCookies(allow);
1607 }
1608
1609 + (BOOL)_allowCookies
1610 {
1611     return ResourceRequestBase::defaultAllowCookies();
1612 }
1613
1614 + (BOOL)_isUnderMemoryPressure
1615 {
1616     return memoryPressureHandler().isUnderMemoryPressure();
1617 }
1618
1619 + (void)_clearMemoryPressure
1620 {
1621     memoryPressureHandler().clearMemoryPressure();
1622 }
1623
1624 + (BOOL)_shouldWaitForMemoryClearMessage
1625 {
1626     return memoryPressureHandler().shouldWaitForMemoryClearMessage();
1627 }
1628 #endif // PLATFORM(IOS)
1629
1630 - (void)_closePluginDatabases
1631 {
1632     pluginDatabaseClientCount--;
1633
1634     // Close both sets of plug-in databases because plug-ins need an opportunity to clean up files, etc.
1635
1636 #if !PLATFORM(IOS)
1637     // Unload the WebView local plug-in database. 
1638     if (_private->pluginDatabase) {
1639         [_private->pluginDatabase destroyAllPluginInstanceViews];
1640         [_private->pluginDatabase close];
1641         [_private->pluginDatabase release];
1642         _private->pluginDatabase = nil;
1643     }
1644 #endif
1645     
1646     // Keep the global plug-in database active until the app terminates to avoid having to reload plug-in bundles.
1647     if (!pluginDatabaseClientCount && applicationIsTerminating)
1648         [WebPluginDatabase closeSharedDatabase];
1649 }
1650
1651 - (void)_closeWithFastTeardown 
1652 {
1653 #ifndef NDEBUG
1654     WTF::RefCountedLeakCounter::suppressMessages("At least one WebView was closed with fast teardown.");
1655 #endif
1656
1657 #if !PLATFORM(IOS)
1658     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
1659 #endif
1660     [[NSNotificationCenter defaultCenter] removeObserver:self];
1661
1662     [self _closePluginDatabases];
1663 }
1664
1665 static bool fastDocumentTeardownEnabled()
1666 {
1667 #ifdef NDEBUG
1668     static bool enabled = ![[NSUserDefaults standardUserDefaults] boolForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
1669 #else
1670     static bool initialized = false;
1671     static bool enabled = false;
1672     if (!initialized) {
1673         // This allows debug builds to default to not have fast teardown, so leak checking still works.
1674         // But still allow the WebKitEnableFullDocumentTeardown default to override it if present.
1675         NSNumber *setting = [[NSUserDefaults standardUserDefaults] objectForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
1676         if (setting)
1677             enabled = ![setting boolValue];
1678         initialized = true;
1679     }
1680 #endif
1681     return enabled;
1682 }
1683
1684 // _close is here only for backward compatibility; clients and subclasses should use
1685 // public method -close instead.
1686 - (void)_close
1687 {
1688 #if PLATFORM(IOS)
1689     // Always clear delegates on calling thread, becasue caller can deallocate delegates right after calling -close
1690     // (and could in fact already be in delegate's -dealloc method, as seen in <rdar://problem/11540972>).
1691
1692     [self _clearDelegates];
1693
1694     // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
1695     WebThreadRun(^{
1696 #endif            
1697
1698     if (!_private || _private->closed)
1699         return;
1700
1701     [[NSNotificationCenter defaultCenter] postNotificationName:WebViewWillCloseNotification object:self];
1702
1703     _private->closed = YES;
1704     [self _removeFromAllWebViewsSet];
1705
1706 #ifndef NDEBUG
1707     WTF::RefCountedLeakCounter::cancelMessageSuppression(webViewIsOpen);
1708 #endif
1709
1710     // To quit the apps fast we skip document teardown, except plugins
1711     // need to be destroyed and unloaded.
1712     if (applicationIsTerminating && fastDocumentTeardownEnabled()) {
1713         [self _closeWithFastTeardown];
1714         return;
1715     }
1716
1717 #if ENABLE(VIDEO) && !PLATFORM(IOS)
1718     [self _exitVideoFullscreen];
1719 #endif
1720
1721 #if PLATFORM(IOS)
1722     _private->closing = YES;
1723 #endif
1724
1725     if (Frame* mainFrame = [self _mainCoreFrame])
1726         mainFrame->loader().detachFromParent();
1727
1728     [self setHostWindow:nil];
1729
1730 #if !PLATFORM(IOS)
1731     [self setDownloadDelegate:nil];
1732     [self setEditingDelegate:nil];
1733     [self setFrameLoadDelegate:nil];
1734     [self setPolicyDelegate:nil];
1735     [self setResourceLoadDelegate:nil];
1736     [self setScriptDebugDelegate:nil];
1737     [self setUIDelegate:nil];
1738
1739     [_private->inspector webViewClosed];
1740 #endif
1741 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
1742     [_private->actionMenuController webViewClosed];
1743 #endif
1744
1745 #if !PLATFORM(IOS)
1746     // To avoid leaks, call removeDragCaret in case it wasn't called after moveDragCaretToPoint.
1747     [self removeDragCaret];
1748 #endif
1749
1750     _private->group->removeWebView(self);
1751
1752     // Deleteing the WebCore::Page will clear the page cache so we call destroy on
1753     // all the plug-ins in the page cache to break any retain cycles.
1754     // See comment in HistoryItem::releaseAllPendingPageCaches() for more information.
1755     Page* page = _private->page;
1756     _private->page = 0;
1757     delete page;
1758
1759 #if !PLATFORM(IOS)
1760     if (_private->hasSpellCheckerDocumentTag) {
1761         [[NSSpellChecker sharedSpellChecker] closeSpellDocumentWithTag:_private->spellCheckerDocumentTag];
1762         _private->hasSpellCheckerDocumentTag = NO;
1763     }
1764 #endif
1765
1766     if (_private->layerFlushController) {
1767         _private->layerFlushController->invalidate();
1768         _private->layerFlushController = nullptr;
1769     }
1770     
1771 #if USE(GLIB)
1772     [self _clearGlibLoopObserver];
1773 #endif
1774
1775     [[self _notificationProvider] unregisterWebView:self];
1776
1777 #if !PLATFORM(IOS)
1778     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
1779 #endif
1780     [[NSNotificationCenter defaultCenter] removeObserver:self];
1781
1782     [WebPreferences _removeReferenceForIdentifier:[self preferencesIdentifier]];
1783
1784     WebPreferences *preferences = _private->preferences;
1785     _private->preferences = nil;
1786     [preferences didRemoveFromWebView];
1787     [preferences release];
1788
1789     [self _closePluginDatabases];
1790
1791 #ifndef NDEBUG
1792     // Need this to make leak messages accurate.
1793     if (applicationIsTerminating) {
1794         gcController().garbageCollectNow();
1795         [WebCache setDisabled:YES];
1796     }
1797 #endif
1798 #if PLATFORM(IOS)
1799     // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
1800     });
1801 #endif            
1802 }
1803
1804 // Indicates if the WebView is in the midst of a user gesture.
1805 - (BOOL)_isProcessingUserGesture
1806 {
1807     return ScriptController::processingUserGesture();
1808 }
1809
1810 + (NSString *)_MIMETypeForFile:(NSString *)path
1811 {
1812 #if !PLATFORM(IOS)
1813     NSString *extension = [path pathExtension];
1814 #endif
1815     NSString *MIMEType = nil;
1816
1817 #if !PLATFORM(IOS)
1818     // Get the MIME type from the extension.
1819     if ([extension length] != 0) {
1820         MIMEType = [[NSURLFileTypeMappings sharedMappings] MIMETypeForExtension:extension];
1821     }
1822 #endif
1823
1824     // If we can't get a known MIME type from the extension, sniff.
1825     if ([MIMEType length] == 0 || [MIMEType isEqualToString:@"application/octet-stream"]) {
1826         NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
1827         NSData *data = [handle readDataOfLength:WEB_GUESS_MIME_TYPE_PEEK_LENGTH];
1828         [handle closeFile];
1829         if ([data length] != 0) {
1830             MIMEType = [data _webkit_guessedMIMEType];
1831         }
1832         if ([MIMEType length] == 0) {
1833             MIMEType = @"application/octet-stream";
1834         }
1835     }
1836
1837     return MIMEType;
1838 }
1839
1840 - (WebDownload *)_downloadURL:(NSURL *)URL
1841 {
1842     ASSERT(URL);
1843     
1844     NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
1845     WebDownload *download = [WebDownload _downloadWithRequest:request
1846                                                      delegate:_private->downloadDelegate
1847                                                     directory:nil];
1848     [request release];
1849     
1850     return download;
1851 }
1852
1853 - (WebView *)_openNewWindowWithRequest:(NSURLRequest *)request
1854 {
1855     NSDictionary *features = [[NSDictionary alloc] init];
1856     WebView *newWindowWebView = [[self _UIDelegateForwarder] webView:self
1857                                             createWebViewWithRequest:nil
1858                                                       windowFeatures:features];
1859     [features release];
1860     if (!newWindowWebView)
1861         return nil;
1862
1863     CallUIDelegate(newWindowWebView, @selector(webViewShow:));
1864     return newWindowWebView;
1865 }
1866
1867 - (WebInspector *)inspector
1868 {
1869     if (!_private->inspector)
1870         _private->inspector = [[WebInspector alloc] initWithWebView:self];
1871     return _private->inspector;
1872 }
1873
1874 #if ENABLE(REMOTE_INSPECTOR)
1875 + (void)_enableRemoteInspector
1876 {
1877     RemoteInspector::shared().start();
1878 }
1879
1880 + (void)_disableRemoteInspector
1881 {
1882     RemoteInspector::shared().stop();
1883 }
1884
1885 + (void)_disableAutoStartRemoteInspector
1886 {
1887     RemoteInspector::startDisabled();
1888 }
1889
1890 + (BOOL)_isRemoteInspectorEnabled
1891 {
1892     return RemoteInspector::shared().enabled();
1893 }
1894
1895 + (BOOL)_hasRemoteInspectorSession
1896 {
1897     return RemoteInspector::shared().hasActiveDebugSession();
1898 }
1899
1900 - (BOOL)allowsRemoteInspection
1901 {
1902     return _private->page->remoteInspectionAllowed();
1903 }
1904
1905 - (void)setAllowsRemoteInspection:(BOOL)allow
1906 {
1907     _private->page->setRemoteInspectionAllowed(allow);
1908 }
1909
1910 - (void)setShowingInspectorIndication:(BOOL)showing
1911 {
1912 #if PLATFORM(IOS)
1913     ASSERT(WebThreadIsLocked());
1914
1915     if (showing) {
1916         if (!_private->indicateLayer) {
1917             _private->indicateLayer = [[WebIndicateLayer alloc] initWithWebView:self];
1918             [_private->indicateLayer setNeedsLayout];
1919             [[[self window] hostLayer] addSublayer:_private->indicateLayer];
1920         }
1921     } else {
1922         [_private->indicateLayer removeFromSuperlayer];
1923         [_private->indicateLayer release];
1924         _private->indicateLayer = nil;
1925     }
1926 #else
1927     // Implemented in WebCore::InspectorOverlay.
1928 #endif
1929 }
1930
1931 #if PLATFORM(IOS)
1932 - (void)_setHostApplicationProcessIdentifier:(pid_t)pid auditToken:(audit_token_t)auditToken
1933 {
1934     RetainPtr<CFDataRef> auditData = adoptCF(CFDataCreate(nullptr, (const UInt8*)&auditToken, sizeof(auditToken)));
1935     RemoteInspector::shared().setParentProcessInformation(pid, auditData);
1936 }
1937 #endif // PLATFORM(IOS)
1938 #endif // ENABLE(REMOTE_INSPECTOR)
1939
1940 - (WebCore::Page*)page
1941 {
1942     return _private->page;
1943 }
1944
1945 #if !PLATFORM(IOS)
1946 - (NSMenu *)_menuForElement:(NSDictionary *)element defaultItems:(NSArray *)items
1947 {
1948     NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate] webView:self contextMenuItemsForElement:element defaultMenuItems:items];
1949     NSArray *menuItems = defaultMenuItems;
1950
1951     // CallUIDelegate returns nil if UIDelegate is nil or doesn't respond to the selector. So we need to check that here
1952     // to distinguish between using defaultMenuItems or the delegate really returning nil to say "no context menu".
1953     SEL selector = @selector(webView:contextMenuItemsForElement:defaultMenuItems:);
1954     if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
1955         menuItems = CallUIDelegate(self, selector, element, defaultMenuItems);
1956         if (!menuItems)
1957             return nil;
1958     }
1959
1960     unsigned count = [menuItems count];
1961     if (!count)
1962         return nil;
1963
1964     NSMenu *menu = [[NSMenu alloc] init];
1965     for (unsigned i = 0; i < count; i++)
1966         [menu addItem:[menuItems objectAtIndex:i]];
1967
1968     return [menu autorelease];
1969 }
1970 #endif
1971
1972 - (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(NSUInteger)modifierFlags
1973 {
1974     // We originally intended to call this delegate method sometimes with a nil dictionary, but due to
1975     // a bug dating back to WebKit 1.0 this delegate was never called with nil! Unfortunately we can't
1976     // start calling this with nil since it will break Adobe Help Viewer, and possibly other clients.
1977     if (!dictionary)
1978         return;
1979     CallUIDelegate(self, @selector(webView:mouseDidMoveOverElement:modifierFlags:), dictionary, modifierFlags);
1980 }
1981
1982 - (void)_loadBackForwardListFromOtherView:(WebView *)otherView
1983 {
1984     if (!_private->page)
1985         return;
1986     
1987     if (!otherView->_private->page)
1988         return;
1989     
1990     // It turns out the right combination of behavior is done with the back/forward load
1991     // type.  (See behavior matrix at the top of WebFramePrivate.)  So we copy all the items
1992     // in the back forward list, and go to the current one.
1993
1994     BackForwardClient* backForwardClient = _private->page->backForward().client();
1995     ASSERT(!backForwardClient->currentItem()); // destination list should be empty
1996
1997     BackForwardClient* otherBackForwardClient = otherView->_private->page->backForward().client();
1998     if (!otherBackForwardClient->currentItem())
1999         return; // empty back forward list, bail
2000     
2001     HistoryItem* newItemToGoTo = 0;
2002
2003     int lastItemIndex = otherBackForwardClient->forwardListCount();
2004     for (int i = -otherBackForwardClient->backListCount(); i <= lastItemIndex; ++i) {
2005         if (i == 0) {
2006             // If this item is showing , save away its current scroll and form state,
2007             // since that might have changed since loading and it is normally not saved
2008             // until we leave that page.
2009             otherView->_private->page->mainFrame().loader().history().saveDocumentAndScrollState();
2010         }
2011         RefPtr<HistoryItem> newItem = otherBackForwardClient->itemAtIndex(i)->copy();
2012         if (i == 0) 
2013             newItemToGoTo = newItem.get();
2014         backForwardClient->addItem(newItem.release());
2015     }
2016     
2017     ASSERT(newItemToGoTo);
2018     _private->page->goToItem(newItemToGoTo, FrameLoadType::IndexedBackForward);
2019 }
2020
2021 - (void)_setFormDelegate: (id<WebFormDelegate>)delegate
2022 {
2023     _private->formDelegate = delegate;
2024 #if PLATFORM(IOS)
2025     [_private->formDelegateForwarder clearTarget];
2026     [_private->formDelegateForwarder release];
2027     _private->formDelegateForwarder = nil;
2028 #endif
2029 }
2030
2031 - (id<WebFormDelegate>)_formDelegate
2032 {
2033     return _private->formDelegate;
2034 }
2035
2036 #if PLATFORM(IOS)
2037 - (id)_formDelegateForwarder
2038 {
2039     if (_private->closing)
2040         return nil;
2041
2042     if (!_private->formDelegateForwarder)
2043         _private->formDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:[self _formDelegate] defaultTarget:[WebDefaultFormDelegate sharedFormDelegate]];
2044     return _private->formDelegateForwarder;
2045 }
2046
2047 - (id)_formDelegateForSelector:(SEL)selector
2048 {
2049     id delegate = self->_private->formDelegate;
2050     if ([delegate respondsToSelector:selector])
2051         return delegate;
2052
2053     delegate = [WebDefaultFormDelegate sharedFormDelegate];
2054     if ([delegate respondsToSelector:selector])
2055         return delegate;
2056
2057     return nil;
2058 }
2059 #endif
2060
2061 #if !PLATFORM(IOS)
2062 - (BOOL)_needsAdobeFrameReloadingQuirk
2063 {
2064     static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.adobe.Acrobat", -1, 9.0)
2065         || WKAppVersionCheckLessThan(@"com.adobe.Acrobat.Pro", -1, 9.0)
2066         || WKAppVersionCheckLessThan(@"com.adobe.Reader", -1, 9.0)
2067         || WKAppVersionCheckLessThan(@"com.adobe.distiller", -1, 9.0)
2068         || WKAppVersionCheckLessThan(@"com.adobe.Contribute", -1, 4.2)
2069         || WKAppVersionCheckLessThan(@"com.adobe.dreamweaver-9.0", -1, 9.1)
2070         || WKAppVersionCheckLessThan(@"com.macromedia.fireworks", -1, 9.1)
2071         || WKAppVersionCheckLessThan(@"com.adobe.InCopy", -1, 5.1)
2072         || WKAppVersionCheckLessThan(@"com.adobe.InDesign", -1, 5.1)
2073         || WKAppVersionCheckLessThan(@"com.adobe.Soundbooth", -1, 2);
2074
2075     return needsQuirk;
2076 }
2077
2078 - (BOOL)_needsLinkElementTextCSSQuirk
2079 {
2080     static BOOL needsQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LINK_ELEMENT_TEXT_CSS_QUIRK)
2081         && WKAppVersionCheckLessThan(@"com.e-frontier.shade10", -1, 10.6);
2082     return needsQuirk;
2083 }
2084
2085 - (BOOL)_needsIsLoadingInAPISenseQuirk
2086 {
2087     static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.apple.iAdProducer", -1, 2.1);
2088     
2089     return needsQuirk;
2090 }
2091
2092 - (BOOL)_needsKeyboardEventDisambiguationQuirks
2093 {
2094     static BOOL needsQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_IE_COMPATIBLE_KEYBOARD_EVENT_DISPATCH) && !applicationIsSafari();
2095     return needsQuirks;
2096 }
2097
2098 - (BOOL)_needsFrameLoadDelegateRetainQuirk
2099 {
2100     static BOOL needsQuirk = WKAppVersionCheckLessThan(@"com.equinux.iSale5", -1, 5.6);    
2101     return needsQuirk;
2102 }
2103
2104 static bool needsSelfRetainWhileLoadingQuirk()
2105 {
2106     static bool needsQuirk = applicationIsAperture();
2107     return needsQuirk;
2108 }
2109 #endif // !PLATFORM(IOS)
2110
2111 - (BOOL)_needsPreHTML5ParserQuirks
2112 {    
2113 #if !PLATFORM(IOS)
2114     // AOL Instant Messenger and Microsoft My Day contain markup incompatible
2115     // with the new HTML5 parser. If these applications were linked against a
2116     // version of WebKit prior to the introduction of the HTML5 parser, enable
2117     // parser quirks to maintain compatibility. For details, see 
2118     // <https://bugs.webkit.org/show_bug.cgi?id=46134> and
2119     // <https://bugs.webkit.org/show_bug.cgi?id=46334>.
2120     static bool isApplicationNeedingParserQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
2121         && (applicationIsAOLInstantMessenger() || applicationIsMicrosoftMyDay());
2122     
2123     // Mail.app must continue to display HTML email that contains quirky markup.
2124     static bool isAppleMail = applicationIsAppleMail();
2125
2126     return isApplicationNeedingParserQuirks
2127         || isAppleMail
2128 #if ENABLE(DASHBOARD_SUPPORT)
2129         // Pre-HTML5 parser quirks are required to remain compatible with many
2130         // Dashboard widgets. See <rdar://problem/8175982>.
2131         || (_private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode())
2132 #endif
2133         || [[self preferences] usePreHTML5ParserQuirks];
2134 #else
2135     static bool isApplicationNeedingParserQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER) && applicationIsDaijisenDictionary();
2136     return isApplicationNeedingParserQuirks || [[self preferences] usePreHTML5ParserQuirks];
2137 #endif
2138 }
2139
2140 - (void)_preferencesChangedNotification:(NSNotification *)notification
2141 {
2142 #if PLATFORM(IOS)
2143     // For WebViews that load synchronously, preference changes need to be propagated
2144     // down to WebCore synchronously so that loads in that WebView have the correct
2145     // up-to-date settings.
2146     if (!WebThreadIsLocked())
2147         WebThreadLock();
2148     if ([[self mainFrame] _loadsSynchronously]) {
2149 #endif
2150
2151     WebPreferences *preferences = (WebPreferences *)[notification object];
2152     [self _preferencesChanged:preferences];
2153
2154 #if PLATFORM(IOS)
2155     } else {
2156         WebThreadRun(^{
2157             // It is possible that the prefs object has already changed before the invocation could be called
2158             // on the web thread. This is not possible on TOT which is why they have a simple ASSERT.
2159             WebPreferences *preferences = (WebPreferences *)[notification object];
2160             if (preferences != [self preferences])
2161                 return;
2162             [self _preferencesChanged:preferences];
2163         });
2164     }
2165 #endif
2166 }
2167
2168 - (void)_preferencesChanged:(WebPreferences *)preferences
2169 {    
2170     ASSERT(preferences == [self preferences]);
2171     if (!_private->userAgentOverridden)
2172         _private->userAgent = String();
2173
2174     // Cache this value so we don't have to read NSUserDefaults on each page load
2175     _private->useSiteSpecificSpoofing = [preferences _useSiteSpecificSpoofing];
2176
2177     // Update corresponding WebCore Settings object.
2178     if (!_private->page)
2179         return;
2180
2181 #if PLATFORM(IOS)
2182     // iOS waits to call [WebDatabaseManager sharedWebDatabaseManager] until
2183     // didOneTimeInitialization is true so that we don't initialize databases
2184     // until the first WebView has been created. This is because database
2185     // initialization current requires disk access to populate the origins
2186     // quota map and we want to do this lazily by waiting until WebKit is
2187     // used to display web content in a WebView. The possible cases are:
2188     //   - on one time initialize (the first WebView creation) if databases are enabled (default)
2189     //   - when databases are dynamically enabled later, and they were disabled at startup (this case)
2190     if (didOneTimeInitialization) {
2191         if ([preferences databasesEnabled])
2192             [WebDatabaseManager sharedWebDatabaseManager];
2193         
2194         if ([preferences storageTrackerEnabled])
2195             WebKitInitializeStorageIfNecessary();
2196     }
2197 #endif
2198     
2199     Settings& settings = _private->page->settings();
2200
2201     settings.setCursiveFontFamily([preferences cursiveFontFamily]);
2202     settings.setDefaultFixedFontSize([preferences defaultFixedFontSize]);
2203     settings.setDefaultFontSize([preferences defaultFontSize]);
2204     settings.setDefaultTextEncodingName([preferences defaultTextEncodingName]);
2205     settings.setUsesEncodingDetector([preferences usesEncodingDetector]);
2206     settings.setFantasyFontFamily([preferences fantasyFontFamily]);
2207     settings.setFixedFontFamily([preferences fixedFontFamily]);
2208     settings.setScreenFontSubstitutionEnabled(
2209 #if !PLATFORM(IOS) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
2210         [[NSUserDefaults standardUserDefaults] boolForKey:@"NSFontDefaultScreenFontSubstitutionEnabled"] ||
2211 #endif
2212         [preferences screenFontSubstitutionEnabled]
2213     );
2214     settings.setForceFTPDirectoryListings([preferences _forceFTPDirectoryListings]);
2215     settings.setFTPDirectoryTemplatePath([preferences _ftpDirectoryTemplatePath]);
2216     settings.setLocalStorageDatabasePath([preferences _localStorageDatabasePath]);
2217     settings.setJavaEnabled([preferences isJavaEnabled]);
2218     settings.setScriptEnabled([preferences isJavaScriptEnabled]);
2219     settings.setWebSecurityEnabled([preferences isWebSecurityEnabled]);
2220     settings.setAllowUniversalAccessFromFileURLs([preferences allowUniversalAccessFromFileURLs]);
2221     settings.setAllowFileAccessFromFileURLs([preferences allowFileAccessFromFileURLs]);
2222     settings.setJavaScriptCanOpenWindowsAutomatically([preferences javaScriptCanOpenWindowsAutomatically]);
2223     settings.setMinimumFontSize([preferences minimumFontSize]);
2224     settings.setMinimumLogicalFontSize([preferences minimumLogicalFontSize]);
2225     settings.setPictographFontFamily([preferences pictographFontFamily]);
2226     settings.setPluginsEnabled([preferences arePlugInsEnabled]);
2227     settings.setLocalStorageEnabled([preferences localStorageEnabled]);
2228
2229     _private->page->enableLegacyPrivateBrowsing([preferences privateBrowsingEnabled]);
2230     settings.setSansSerifFontFamily([preferences sansSerifFontFamily]);
2231     settings.setSerifFontFamily([preferences serifFontFamily]);
2232     settings.setStandardFontFamily([preferences standardFontFamily]);
2233     settings.setLoadsImagesAutomatically([preferences loadsImagesAutomatically]);
2234     settings.setLoadsSiteIconsIgnoringImageLoadingSetting([preferences loadsSiteIconsIgnoringImageLoadingPreference]);
2235 #if PLATFORM(IOS)
2236     settings.setShouldPrintBackgrounds(true);
2237 #else
2238     settings.setShouldPrintBackgrounds([preferences shouldPrintBackgrounds]);
2239 #endif
2240     settings.setShrinksStandaloneImagesToFit([preferences shrinksStandaloneImagesToFit]);
2241     settings.setEditableLinkBehavior(core([preferences editableLinkBehavior]));
2242     settings.setTextDirectionSubmenuInclusionBehavior(core([preferences textDirectionSubmenuInclusionBehavior]));
2243     settings.setDOMPasteAllowed([preferences isDOMPasteAllowed]);
2244     settings.setUsesPageCache([self usesPageCache]);
2245     settings.setPageCacheSupportsPlugins([preferences pageCacheSupportsPlugins]);
2246     settings.setBackForwardCacheExpirationInterval([preferences _backForwardCacheExpirationInterval]);
2247
2248     settings.setDeveloperExtrasEnabled([preferences developerExtrasEnabled]);
2249     settings.setJavaScriptExperimentsEnabled([preferences javaScriptExperimentsEnabled]);
2250     settings.setAuthorAndUserStylesEnabled([preferences authorAndUserStylesEnabled]);
2251     settings.setApplicationChromeMode([preferences applicationChromeModeEnabled]);
2252
2253     settings.setNeedsSiteSpecificQuirks(_private->useSiteSpecificSpoofing);
2254     settings.setDOMTimersThrottlingEnabled([preferences domTimersThrottlingEnabled]);
2255     settings.setWebArchiveDebugModeEnabled([preferences webArchiveDebugModeEnabled]);
2256     settings.setLocalFileContentSniffingEnabled([preferences localFileContentSniffingEnabled]);
2257     settings.setOfflineWebApplicationCacheEnabled([preferences offlineWebApplicationCacheEnabled]);
2258     settings.setJavaScriptCanAccessClipboard([preferences javaScriptCanAccessClipboard]);
2259     settings.setXSSAuditorEnabled([preferences isXSSAuditorEnabled]);
2260     settings.setDNSPrefetchingEnabled([preferences isDNSPrefetchingEnabled]);
2261     
2262     // FIXME: Enabling accelerated compositing when WebGL is enabled causes tests to fail on Leopard which expect HW compositing to be disabled.
2263     // Until we fix that, I will comment out the test (CFM)
2264     settings.setAcceleratedCompositingEnabled([preferences acceleratedCompositingEnabled]);
2265     settings.setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
2266     settings.setCanvasUsesAcceleratedDrawing([preferences canvasUsesAcceleratedDrawing]);    
2267     settings.setShowDebugBorders([preferences showDebugBorders]);
2268     settings.setSimpleLineLayoutDebugBordersEnabled([preferences simpleLineLayoutDebugBordersEnabled]);
2269     settings.setShowRepaintCounter([preferences showRepaintCounter]);
2270     settings.setWebGLEnabled([preferences webGLEnabled]);
2271     settings.setSubpixelCSSOMElementMetricsEnabled([preferences subpixelCSSOMElementMetricsEnabled]);
2272
2273     settings.setForceSoftwareWebGLRendering([preferences forceSoftwareWebGLRendering]);
2274     settings.setAccelerated2dCanvasEnabled([preferences accelerated2dCanvasEnabled]);
2275     settings.setLoadDeferringEnabled(shouldEnableLoadDeferring());
2276     settings.setWindowFocusRestricted(shouldRestrictWindowFocus());
2277     settings.setFrameFlatteningEnabled([preferences isFrameFlatteningEnabled]);
2278     settings.setSpatialNavigationEnabled([preferences isSpatialNavigationEnabled]);
2279     settings.setPaginateDuringLayoutEnabled([preferences paginateDuringLayoutEnabled]);
2280     RuntimeEnabledFeatures::sharedFeatures().setCSSRegionsEnabled([preferences cssRegionsEnabled]);
2281     RuntimeEnabledFeatures::sharedFeatures().setCSSCompositingEnabled([preferences cssCompositingEnabled]);
2282
2283     settings.setAsynchronousSpellCheckingEnabled([preferences asynchronousSpellCheckingEnabled]);
2284     settings.setHyperlinkAuditingEnabled([preferences hyperlinkAuditingEnabled]);
2285     settings.setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
2286     settings.setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
2287     settings.setValidationMessageTimerMagnification([self validationMessageTimerMagnification]);
2288
2289     settings.setMediaPlaybackRequiresUserGesture([preferences mediaPlaybackRequiresUserGesture]);
2290     settings.setMediaPlaybackAllowsInline([preferences mediaPlaybackAllowsInline]);
2291     settings.setAllowsAlternateFullscreen([preferences allowsAlternateFullscreen]);
2292     settings.setSuppressesIncrementalRendering([preferences suppressesIncrementalRendering]);
2293     settings.setBackspaceKeyNavigationEnabled([preferences backspaceKeyNavigationEnabled]);
2294     settings.setWantsBalancedSetDefersLoadingBehavior([preferences wantsBalancedSetDefersLoadingBehavior]);
2295     settings.setMockScrollbarsEnabled([preferences mockScrollbarsEnabled]);
2296
2297     settings.setShouldRespectImageOrientation([preferences shouldRespectImageOrientation]);
2298
2299     settings.setRequestAnimationFrameEnabled([preferences requestAnimationFrameEnabled]);
2300     settings.setDiagnosticLoggingEnabled([preferences diagnosticLoggingEnabled]);
2301     settings.setLowPowerVideoAudioBufferSizeEnabled([preferences lowPowerVideoAudioBufferSizeEnabled]);
2302
2303     settings.setUseLegacyTextAlignPositionedElementBehavior([preferences useLegacyTextAlignPositionedElementBehavior]);
2304
2305     settings.setShouldConvertPositionStyleOnCopy([preferences shouldConvertPositionStyleOnCopy]);
2306     settings.setEnableInheritURIQueryComponent([preferences isInheritURIQueryComponentEnabled]);
2307
2308     switch ([preferences storageBlockingPolicy]) {
2309     case WebAllowAllStorage:
2310         settings.setStorageBlockingPolicy(SecurityOrigin::AllowAllStorage);
2311         break;
2312     case WebBlockThirdPartyStorage:
2313         settings.setStorageBlockingPolicy(SecurityOrigin::BlockThirdPartyStorage);
2314         break;
2315     case WebBlockAllStorage:
2316         settings.setStorageBlockingPolicy(SecurityOrigin::BlockAllStorage);
2317         break;
2318     }
2319
2320     settings.setPlugInSnapshottingEnabled([preferences plugInSnapshottingEnabled]);
2321
2322     settings.setFixedPositionCreatesStackingContext(true);
2323 #if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
2324     settings.setAcceleratedCompositingForFixedPositionEnabled(true);
2325 #endif
2326
2327 #if ENABLE(RUBBER_BANDING)
2328     // FIXME: https://bugs.webkit.org/show_bug.cgi?id=136131
2329     settings.setRubberBandingForSubScrollableRegionsEnabled(false);
2330 #endif
2331
2332 #if PLATFORM(IOS)
2333     settings.setStandalone([preferences _standalone]);
2334     settings.setTelephoneNumberParsingEnabled([preferences _telephoneNumberParsingEnabled]);
2335     settings.setAlwaysUseBaselineOfPrimaryFont([preferences _alwaysUseBaselineOfPrimaryFont]);
2336     settings.setAllowMultiElementImplicitSubmission([preferences _allowMultiElementImplicitFormSubmission]);
2337     settings.setLayoutInterval(std::chrono::milliseconds([preferences _layoutInterval]));
2338     settings.setMaxParseDuration([preferences _maxParseDuration]);
2339     settings.setAlwaysUseAcceleratedOverflowScroll([preferences _alwaysUseAcceleratedOverflowScroll]);
2340     settings.setMediaPlaybackAllowsAirPlay([preferences mediaPlaybackAllowsAirPlay]);
2341     settings.setAudioSessionCategoryOverride([preferences audioSessionCategoryOverride]);
2342     settings.setNetworkDataUsageTrackingEnabled([preferences networkDataUsageTrackingEnabled]);
2343     settings.setNetworkInterfaceName([preferences networkInterfaceName]);
2344     settings.setAVKitEnabled([preferences avKitEnabled]);
2345     settings.setShouldTransformsAffectOverflow(shouldTransformsAffectOverflow());
2346     settings.setShouldDispatchJavaScriptWindowOnErrorEvents(shouldDispatchJavaScriptWindowOnErrorEvents());
2347
2348     settings.setPasswordEchoEnabled([preferences _allowPasswordEcho]);
2349     settings.setPasswordEchoDurationInSeconds([preferences _passwordEchoDuration]);
2350
2351     ASSERT_WITH_MESSAGE(settings.pageCacheSupportsPlugins(), "PageCacheSupportsPlugins should be enabled on iOS.");
2352     settings.setDelegatesPageScaling(true);
2353
2354 #if ENABLE(IOS_TEXT_AUTOSIZING)
2355     settings.setMinimumZoomFontSize([preferences _minimumZoomFontSize]);
2356 #endif
2357 #endif // PLATFORM(IOS)
2358
2359 #if PLATFORM(MAC)
2360     if ([preferences userStyleSheetEnabled]) {
2361         NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
2362         if ([location isEqualToString:@"apple-dashboard://stylesheet"])
2363             location = @"file:///System/Library/PrivateFrameworks/DashboardClient.framework/Resources/widget.css";
2364         settings.setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
2365     } else
2366         settings.setUserStyleSheetLocation([NSURL URLWithString:@""]);
2367
2368     settings.setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
2369     settings.setTreatsAnyTextCSSLinkAsStylesheet([self _needsLinkElementTextCSSQuirk]);
2370     settings.setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
2371     settings.setEnforceCSSMIMETypeInNoQuirksMode(!WKAppVersionCheckLessThan(@"com.apple.iWeb", -1, 2.1));
2372     settings.setNeedsIsLoadingInAPISenseQuirk([self _needsIsLoadingInAPISenseQuirk]);
2373     settings.setTextAreasAreResizable([preferences textAreasAreResizable]);
2374     settings.setExperimentalNotificationsEnabled([preferences experimentalNotificationsEnabled]);
2375     settings.setShowsURLsInToolTips([preferences showsURLsInToolTips]);
2376     settings.setShowsToolTipOverTruncatedText([preferences showsToolTipOverTruncatedText]);
2377     settings.setQTKitEnabled([preferences isQTKitEnabled]);
2378 #endif // PLATFORM(MAC)
2379
2380 #if ENABLE(SQL_DATABASE)
2381     DatabaseManager::manager().setIsAvailable([preferences databasesEnabled]);
2382 #endif
2383
2384 #if ENABLE(MEDIA_SOURCE)
2385     settings.setMediaSourceEnabled([preferences mediaSourceEnabled]);
2386 #endif
2387
2388 #if ENABLE(SERVICE_CONTROLS)
2389     settings.setImageControlsEnabled([preferences imageControlsEnabled]);
2390     settings.setServiceControlsEnabled([preferences serviceControlsEnabled]);
2391 #endif
2392
2393 #if ENABLE(VIDEO_TRACK)
2394     settings.setShouldDisplaySubtitles([preferences shouldDisplaySubtitles]);
2395     settings.setShouldDisplayCaptions([preferences shouldDisplayCaptions]);
2396     settings.setShouldDisplayTextDescriptions([preferences shouldDisplayTextDescriptions]);
2397 #endif
2398
2399 #if USE(AVFOUNDATION)
2400     settings.setAVFoundationEnabled([preferences isAVFoundationEnabled]);
2401 #endif
2402
2403 #if ENABLE(WEB_AUDIO)
2404     settings.setWebAudioEnabled([preferences webAudioEnabled]);
2405 #endif
2406
2407 #if ENABLE(FULLSCREEN_API)
2408     settings.setFullScreenEnabled([preferences fullScreenEnabled]);
2409 #endif
2410
2411 #if ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING)
2412     settings.setHiddenPageDOMTimerThrottlingEnabled([preferences hiddenPageDOMTimerThrottlingEnabled]);
2413 #endif
2414
2415     settings.setHiddenPageCSSAnimationSuspensionEnabled([preferences hiddenPageCSSAnimationSuspensionEnabled]);
2416
2417 #if ENABLE(GAMEPAD)
2418     RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled([preferences gamepadsEnabled]);
2419 #endif
2420
2421     NSTimeInterval timeout = [preferences incrementalRenderingSuppressionTimeoutInSeconds];
2422     if (timeout > 0)
2423         settings.setIncrementalRenderingSuppressionTimeoutInSeconds(timeout);
2424
2425     // Application Cache Preferences are stored on the global cache storage manager, not in Settings.
2426     [WebApplicationCache setDefaultOriginQuota:[preferences applicationCacheDefaultOriginQuota]];
2427
2428     BOOL zoomsTextOnly = [preferences zoomsTextOnly];
2429     if (_private->zoomsTextOnly != zoomsTextOnly)
2430         [self _setZoomMultiplier:_private->zoomMultiplier isTextOnly:zoomsTextOnly];
2431
2432 #if PLATFORM(IOS)
2433     [[self window] setTileBordersVisible:[preferences showDebugBorders]];
2434     [[self window] setTilePaintCountsVisible:[preferences showRepaintCounter]];
2435     [[self window] setAcceleratedDrawingEnabled:[preferences acceleratedDrawingEnabled]];
2436     [WAKView _setInterpolationQuality:[preferences _interpolationQuality]];
2437 #endif
2438
2439 #if ENABLE(ENCRYPTED_MEDIA_V2)
2440     settings.setMediaKeysStorageDirectory([preferences mediaKeysStorageDirectory]);
2441 #endif
2442 }
2443
2444 static inline IMP getMethod(id o, SEL s)
2445 {
2446     return [o respondsToSelector:s] ? [o methodForSelector:s] : 0;
2447 }
2448
2449 #if PLATFORM(IOS)
2450 - (id)_UIKitDelegateForwarder
2451 {
2452     if (_private->closing)
2453         return nil;
2454         
2455     if (!_private->UIKitDelegateForwarder)
2456         _private->UIKitDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIKitDelegate defaultTarget:[WebDefaultUIKitDelegate sharedUIKitDelegate]];
2457     return _private->UIKitDelegateForwarder;
2458 }
2459 #endif
2460
2461 - (void)_cacheResourceLoadDelegateImplementations
2462 {
2463     WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
2464     id delegate = _private->resourceProgressDelegate;
2465
2466     if (!delegate) {
2467         bzero(cache, sizeof(WebResourceDelegateImplementationCache));
2468         return;
2469     }
2470
2471     cache->didCancelAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didCancelAuthenticationChallenge:fromDataSource:));
2472     cache->didFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFailLoadingWithError:fromDataSource:));
2473     cache->didFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFinishLoadingFromDataSource:));
2474     cache->didLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
2475     cache->didReceiveAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
2476 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
2477     cache->canAuthenticateAgainstProtectionSpaceFunc = getMethod(delegate, @selector(webView:resource:canAuthenticateAgainstProtectionSpace:forDataSource:));
2478 #endif
2479
2480 #if PLATFORM(IOS)
2481     cache->connectionPropertiesFunc = getMethod(delegate, @selector(webView:connectionPropertiesForResource:dataSource:));
2482     cache->webThreadDidFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFinishLoadingFromDataSource:));
2483     cache->webThreadDidFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFailLoadingWithError:fromDataSource:));
2484     cache->webThreadIdentifierForRequestFunc = getMethod(delegate, @selector(webThreadWebView:identifierForInitialRequest:fromDataSource:));
2485     cache->webThreadDidLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webThreadWebView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
2486     cache->webThreadWillSendRequestFunc = getMethod(delegate, @selector(webThreadWebView:resource:willSendRequest:redirectResponse:fromDataSource:));
2487     cache->webThreadDidReceiveResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveResponse:fromDataSource:));
2488     cache->webThreadDidReceiveContentLengthFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveContentLength:fromDataSource:));
2489     cache->webThreadWillCacheResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:willCacheResponse:fromDataSource:));
2490 #endif
2491
2492     cache->didReceiveContentLengthFunc = getMethod(delegate, @selector(webView:resource:didReceiveContentLength:fromDataSource:));
2493     cache->didReceiveResponseFunc = getMethod(delegate, @selector(webView:resource:didReceiveResponse:fromDataSource:));
2494     cache->identifierForRequestFunc = getMethod(delegate, @selector(webView:identifierForInitialRequest:fromDataSource:));
2495     cache->plugInFailedWithErrorFunc = getMethod(delegate, @selector(webView:plugInFailedWithError:dataSource:));
2496     cache->willCacheResponseFunc = getMethod(delegate, @selector(webView:resource:willCacheResponse:fromDataSource:));
2497     cache->willSendRequestFunc = getMethod(delegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:));
2498     cache->shouldUseCredentialStorageFunc = getMethod(delegate, @selector(webView:resource:shouldUseCredentialStorageForDataSource:));
2499     cache->shouldPaintBrokenImageForURLFunc = getMethod(delegate, @selector(webView:shouldPaintBrokenImageForURL:));
2500 }
2501
2502 - (void)_cacheFrameLoadDelegateImplementations
2503 {
2504     WebFrameLoadDelegateImplementationCache *cache = &_private->frameLoadDelegateImplementations;
2505     id delegate = _private->frameLoadDelegate;
2506
2507     if (!delegate) {
2508         bzero(cache, sizeof(WebFrameLoadDelegateImplementationCache));
2509         return;
2510     }
2511
2512     cache->didCancelClientRedirectForFrameFunc = getMethod(delegate, @selector(webView:didCancelClientRedirectForFrame:));
2513     cache->didChangeLocationWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didChangeLocationWithinPageForFrame:));
2514     cache->didPushStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPushStateWithinPageForFrame:));
2515     cache->didReplaceStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didReplaceStateWithinPageForFrame:));
2516     cache->didPopStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPopStateWithinPageForFrame:));
2517 #if JSC_OBJC_API_ENABLED
2518     cache->didCreateJavaScriptContextForFrameFunc = getMethod(delegate, @selector(webView:didCreateJavaScriptContext:forFrame:));
2519 #endif
2520     cache->didClearWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearWindowObject:forFrame:));
2521     cache->didClearWindowObjectForFrameInScriptWorldFunc = getMethod(delegate, @selector(webView:didClearWindowObjectForFrame:inScriptWorld:));
2522     cache->didClearInspectorWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearInspectorWindowObject:forFrame:));
2523     cache->didCommitLoadForFrameFunc = getMethod(delegate, @selector(webView:didCommitLoadForFrame:));
2524     cache->didFailLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailLoadWithError:forFrame:));
2525     cache->didFailProvisionalLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailProvisionalLoadWithError:forFrame:));
2526     cache->didFinishDocumentLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishDocumentLoadForFrame:));
2527     cache->didFinishLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishLoadForFrame:));
2528     cache->didFirstLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstLayoutInFrame:));
2529     cache->didFirstVisuallyNonEmptyLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstVisuallyNonEmptyLayoutInFrame:));
2530     cache->didLayoutFunc = getMethod(delegate, @selector(webView:didLayout:));
2531     cache->didHandleOnloadEventsForFrameFunc = getMethod(delegate, @selector(webView:didHandleOnloadEventsForFrame:));
2532 #if ENABLE(ICONDATABASE)
2533     cache->didReceiveIconForFrameFunc = getMethod(delegate, @selector(webView:didReceiveIcon:forFrame:));
2534 #endif
2535     cache->didReceiveServerRedirectForProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didReceiveServerRedirectForProvisionalLoadForFrame:));
2536     cache->didReceiveTitleForFrameFunc = getMethod(delegate, @selector(webView:didReceiveTitle:forFrame:));
2537     cache->didStartProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didStartProvisionalLoadForFrame:));
2538     cache->willCloseFrameFunc = getMethod(delegate, @selector(webView:willCloseFrame:));
2539     cache->willPerformClientRedirectToURLDelayFireDateForFrameFunc = getMethod(delegate, @selector(webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:));
2540     cache->windowScriptObjectAvailableFunc = getMethod(delegate, @selector(webView:windowScriptObjectAvailable:));
2541     cache->didDisplayInsecureContentFunc = getMethod(delegate, @selector(webViewDidDisplayInsecureContent:));
2542     cache->didRunInsecureContentFunc = getMethod(delegate, @selector(webView:didRunInsecureContent:));
2543     cache->didDetectXSSFunc = getMethod(delegate, @selector(webView:didDetectXSS:));
2544     cache->didRemoveFrameFromHierarchyFunc = getMethod(delegate, @selector(webView:didRemoveFrameFromHierarchy:));
2545 #if PLATFORM(IOS)
2546     cache->webThreadDidLayoutFunc = getMethod(delegate, @selector(webThreadWebView:didLayout:));
2547 #endif
2548
2549     // It would be nice to get rid of this code and transition all clients to using didLayout instead of
2550     // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
2551     // for backwards compatibility.
2552     Page* page = core(self);
2553     if (page) {
2554         unsigned milestones = DidFirstLayout;
2555 #if PLATFORM(IOS)
2556         milestones |= DidFirstVisuallyNonEmptyLayout;
2557 #else
2558         if (cache->didFirstVisuallyNonEmptyLayoutInFrameFunc)
2559             milestones |= DidFirstVisuallyNonEmptyLayout;
2560 #endif
2561         page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
2562     }
2563 }
2564
2565 - (void)_cacheScriptDebugDelegateImplementations
2566 {
2567     WebScriptDebugDelegateImplementationCache *cache = &_private->scriptDebugDelegateImplementations;
2568     id delegate = _private->scriptDebugDelegate;
2569
2570     if (!delegate) {
2571         bzero(cache, sizeof(WebScriptDebugDelegateImplementationCache));
2572         return;
2573     }
2574
2575     cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:baseLineNumber:fromURL:sourceId:forWebFrame:));
2576     if (cache->didParseSourceFunc)
2577         cache->didParseSourceExpectsBaseLineNumber = YES;
2578     else {
2579         cache->didParseSourceExpectsBaseLineNumber = NO;
2580         cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:fromURL:sourceId:forWebFrame:));
2581     }
2582
2583     cache->failedToParseSourceFunc = getMethod(delegate, @selector(webView:failedToParseSource:baseLineNumber:fromURL:withError:forWebFrame:));
2584
2585     cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:hasHandler:sourceId:line:forWebFrame:));
2586     if (cache->exceptionWasRaisedFunc)
2587         cache->exceptionWasRaisedExpectsHasHandlerFlag = YES;
2588     else {
2589         cache->exceptionWasRaisedExpectsHasHandlerFlag = NO;
2590         cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:sourceId:line:forWebFrame:));
2591     }
2592 }
2593
2594 - (void)_cacheHistoryDelegateImplementations
2595 {
2596     WebHistoryDelegateImplementationCache *cache = &_private->historyDelegateImplementations;
2597     id delegate = _private->historyDelegate;
2598
2599     if (!delegate) {
2600         bzero(cache, sizeof(WebHistoryDelegateImplementationCache));
2601         return;
2602     }
2603
2604     cache->navigatedFunc = getMethod(delegate, @selector(webView:didNavigateWithNavigationData:inFrame:));
2605     cache->clientRedirectFunc = getMethod(delegate, @selector(webView:didPerformClientRedirectFromURL:toURL:inFrame:));
2606     cache->serverRedirectFunc = getMethod(delegate, @selector(webView:didPerformServerRedirectFromURL:toURL:inFrame:));
2607     cache->deprecatedSetTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:));
2608     cache->setTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:inFrame:));
2609     cache->populateVisitedLinksFunc = getMethod(delegate, @selector(populateVisitedLinksForWebView:));
2610 }
2611
2612 - (id)_policyDelegateForwarder
2613 {
2614 #if PLATFORM(IOS)
2615     if (_private->closing)
2616         return nil;
2617 #endif
2618     if (!_private->policyDelegateForwarder)
2619         _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->policyDelegate defaultTarget:[WebDefaultPolicyDelegate sharedPolicyDelegate]];
2620     return _private->policyDelegateForwarder;
2621 }
2622
2623 - (id)_UIDelegateForwarder
2624 {
2625 #if PLATFORM(IOS)
2626     if (_private->closing)
2627         return nil;
2628 #endif
2629     if (!_private->UIDelegateForwarder)
2630         _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIDelegate defaultTarget:[WebDefaultUIDelegate sharedUIDelegate]];
2631     return _private->UIDelegateForwarder;
2632 }
2633
2634 #if PLATFORM(IOS)
2635 - (id)_UIDelegateForSelector:(SEL)selector
2636 {
2637     id delegate = self->_private->UIDelegate;
2638     if ([delegate respondsToSelector:selector])
2639         return delegate;
2640
2641     delegate = [WebDefaultUIDelegate sharedUIDelegate];
2642     if ([delegate respondsToSelector:selector])
2643         return delegate;
2644
2645     return nil;
2646 }
2647 #endif
2648
2649 - (id)_editingDelegateForwarder
2650 {
2651 #if PLATFORM(IOS)
2652     if (_private->closing)
2653         return nil;
2654 #endif    
2655     // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
2656     // Not sure if that is a bug or not.
2657     if (!_private)
2658         return nil;
2659
2660     if (!_private->editingDelegateForwarder)
2661         _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->editingDelegate defaultTarget:[WebDefaultEditingDelegate sharedEditingDelegate]];
2662     return _private->editingDelegateForwarder;
2663 }
2664
2665 - (void)_closeWindow
2666 {
2667     [[self _UIDelegateForwarder] webViewClose:self];
2668 }
2669
2670 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType
2671 {
2672     [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
2673     [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
2674     
2675     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
2676     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
2677     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
2678     MIMETypeRegistry::getSupportedNonImageMIMETypes().remove(MIMEType);
2679 }
2680
2681 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme
2682 {
2683     NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
2684     [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
2685
2686     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
2687     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
2688     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
2689     if ([viewClass class] == [WebHTMLView class])
2690         MIMETypeRegistry::getSupportedNonImageMIMETypes().add(MIMEType);
2691     
2692     // This is used to make _representationExistsForURLScheme faster.
2693     // Without this set, we'd have to create the MIME type each time.
2694     if (schemesWithRepresentationsSet == nil) {
2695         schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
2696     }
2697     [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
2698 }
2699
2700 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
2701 {
2702     return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
2703 }
2704
2705 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
2706 {
2707     return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
2708 }
2709
2710 + (BOOL)_canHandleRequest:(NSURLRequest *)request forMainFrame:(BOOL)forMainFrame
2711 {
2712     // FIXME: If <rdar://problem/5217309> gets fixed, this check can be removed.
2713     if (!request)
2714         return NO;
2715
2716     if ([NSURLConnection canHandleRequest:request])
2717         return YES;
2718
2719     NSString *scheme = [[request URL] scheme];
2720
2721     // Representations for URL schemes work at the top level.
2722     if (forMainFrame && [self _representationExistsForURLScheme:scheme])
2723         return YES;
2724
2725     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"applewebdata"])
2726         return YES;
2727
2728     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"blob"])
2729         return YES;
2730
2731     return NO;
2732 }
2733
2734 + (BOOL)_canHandleRequest:(NSURLRequest *)request
2735 {
2736     return [self _canHandleRequest:request forMainFrame:YES];
2737 }
2738
2739 + (NSString *)_decodeData:(NSData *)data
2740 {
2741     HTMLNames::init(); // this method is used for importing bookmarks at startup, so HTMLNames are likely to be uninitialized yet
2742     return TextResourceDecoder::create("text/html")->decodeAndFlush(static_cast<const char*>([data bytes]), [data length]); // bookmark files are HTML
2743 }
2744
2745 - (void)_pushPerformingProgrammaticFocus
2746 {
2747     _private->programmaticFocusCount++;
2748 }
2749
2750 - (void)_popPerformingProgrammaticFocus
2751 {
2752     _private->programmaticFocusCount--;
2753 }
2754
2755 - (BOOL)_isPerformingProgrammaticFocus
2756 {
2757     return _private->programmaticFocusCount != 0;
2758 }
2759
2760 #if !PLATFORM(IOS)
2761 - (void)_didChangeValueForKey: (NSString *)key
2762 {
2763     LOG (Bindings, "calling didChangeValueForKey: %@", key);
2764     [self didChangeValueForKey: key];
2765 }
2766
2767 - (void)_willChangeValueForKey: (NSString *)key
2768 {
2769     LOG (Bindings, "calling willChangeValueForKey: %@", key);
2770     [self willChangeValueForKey: key];
2771 }
2772
2773 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
2774     static NSSet *manualNotifyKeys = nil;
2775     if (!manualNotifyKeys)
2776         manualNotifyKeys = [[NSSet alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
2777             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey,
2778             nil];
2779     if ([manualNotifyKeys containsObject:key])
2780         return NO;
2781     return YES;
2782 }
2783
2784 - (NSArray *)_declaredKeys {
2785     static NSArray *declaredKeys = nil;
2786     if (!declaredKeys)
2787         declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
2788             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
2789     return declaredKeys;
2790 }
2791
2792 - (void)setObservationInfo:(void *)info
2793 {
2794     _private->observationInfo = info;
2795 }
2796
2797 - (void *)observationInfo
2798 {
2799     return _private->observationInfo;
2800 }
2801
2802 - (void)_willChangeBackForwardKeys
2803 {
2804     [self _willChangeValueForKey: _WebCanGoBackKey];
2805     [self _willChangeValueForKey: _WebCanGoForwardKey];
2806 }
2807
2808 - (void)_didChangeBackForwardKeys
2809 {
2810     [self _didChangeValueForKey: _WebCanGoBackKey];
2811     [self _didChangeValueForKey: _WebCanGoForwardKey];
2812 }
2813
2814 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
2815 {
2816     if (needsSelfRetainWhileLoadingQuirk())
2817         [self retain];
2818
2819     [self _willChangeBackForwardKeys];
2820     if (frame == [self mainFrame]){
2821         // Force an observer update by sending a will/did.
2822         [self _willChangeValueForKey: _WebIsLoadingKey];
2823         [self _didChangeValueForKey: _WebIsLoadingKey];
2824
2825         [self _willChangeValueForKey: _WebMainFrameURLKey];
2826     }
2827
2828     [NSApp setWindowsNeedUpdate:YES];
2829
2830 #if ENABLE(FULLSCREEN_API)
2831     Document* document = core([frame DOMDocument]);
2832     if (Element* element = document ? document->webkitCurrentFullScreenElement() : 0) {
2833         SEL selector = @selector(webView:closeFullScreenWithListener:);
2834         if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
2835             WebKitFullScreenListener *listener = [[WebKitFullScreenListener alloc] initWithElement:element];
2836             CallUIDelegate(self, selector, listener);
2837             [listener release];
2838         } else if (_private->newFullscreenController && [_private->newFullscreenController isFullScreen]) {
2839             [_private->newFullscreenController close];
2840         }
2841     }
2842 #endif
2843 }
2844
2845 - (void)_checkDidPerformFirstNavigation
2846 {
2847     if (_private->_didPerformFirstNavigation)
2848         return;
2849
2850     Page* page = _private->page;
2851     if (!page)
2852         return;
2853
2854     auto& backForwardController = page->backForward();
2855
2856     if (!backForwardController.backItem())
2857         return;
2858
2859     _private->_didPerformFirstNavigation = YES;
2860
2861     if (_private->preferences.automaticallyDetectsCacheModel && _private->preferences.cacheModel < WebCacheModelDocumentBrowser)
2862         _private->preferences.cacheModel = WebCacheModelDocumentBrowser;
2863 }
2864
2865 - (void)_didCommitLoadForFrame:(WebFrame *)frame
2866 {
2867     if (frame == [self mainFrame])
2868         [self _didChangeValueForKey: _WebMainFrameURLKey];
2869
2870     [self _checkDidPerformFirstNavigation];
2871
2872     [NSApp setWindowsNeedUpdate:YES];
2873 }
2874
2875 - (void)_didFinishLoadForFrame:(WebFrame *)frame
2876 {
2877     if (needsSelfRetainWhileLoadingQuirk())
2878         [self performSelector:@selector(release) withObject:nil afterDelay:0];
2879         
2880     [self _didChangeBackForwardKeys];
2881     if (frame == [self mainFrame]){
2882         // Force an observer update by sending a will/did.
2883         [self _willChangeValueForKey: _WebIsLoadingKey];
2884         [self _didChangeValueForKey: _WebIsLoadingKey];
2885     }
2886     [NSApp setWindowsNeedUpdate:YES];
2887 }
2888
2889 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
2890 {
2891     if (needsSelfRetainWhileLoadingQuirk())
2892         [self performSelector:@selector(release) withObject:nil afterDelay:0];
2893
2894     [self _didChangeBackForwardKeys];
2895     if (frame == [self mainFrame]){
2896         // Force an observer update by sending a will/did.
2897         [self _willChangeValueForKey: _WebIsLoadingKey];
2898         [self _didChangeValueForKey: _WebIsLoadingKey];
2899     }
2900     [NSApp setWindowsNeedUpdate:YES];
2901 }
2902
2903 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
2904 {
2905     if (needsSelfRetainWhileLoadingQuirk())
2906         [self performSelector:@selector(release) withObject:nil afterDelay:0];
2907
2908     [self _didChangeBackForwardKeys];
2909     if (frame == [self mainFrame]){
2910         // Force an observer update by sending a will/did.
2911         [self _willChangeValueForKey: _WebIsLoadingKey];
2912         [self _didChangeValueForKey: _WebIsLoadingKey];
2913         
2914         [self _didChangeValueForKey: _WebMainFrameURLKey];
2915     }
2916     [NSApp setWindowsNeedUpdate:YES];
2917 }
2918
2919 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
2920 {
2921     RetainPtr<NSMutableURLRequest *> request = adoptNS([[NSMutableURLRequest alloc] initWithURL:URL]);
2922     [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
2923     NSCachedURLResponse *cachedResponse;
2924
2925     if (!_private->page)
2926         return nil;
2927
2928     if (CFURLStorageSessionRef storageSession = _private->page->mainFrame().loader().networkingContext()->storageSession().platformSession())
2929         cachedResponse = WKCachedResponseForRequest(storageSession, request.get());
2930     else
2931         cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request.get()];
2932
2933     return cachedResponse;
2934 }
2935
2936 - (void)_writeImageForElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
2937 {
2938     NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
2939     DOMElement *domElement = [element objectForKey:WebElementDOMNodeKey];
2940     [pasteboard _web_writeImage:(NSImage *)(domElement ? nil : [element objectForKey:WebElementImageKey])
2941                         element:domElement
2942                             URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
2943                           title:[element objectForKey:WebElementImageAltStringKey] 
2944                         archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
2945                           types:types
2946                          source:nil];
2947 }
2948
2949 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
2950 {
2951     [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
2952                      andTitle:[element objectForKey:WebElementLinkLabelKey]
2953                         types:types];
2954 }
2955
2956 #if ENABLE(DRAG_SUPPORT)
2957 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
2958 {
2959     if (!_private->page)
2960         return;
2961     _private->page->dragController().setDidInitiateDrag(initiatedDrag);
2962 }
2963 #endif
2964
2965 #else
2966
2967 - (void)_didCommitLoadForFrame:(WebFrame *)frame
2968 {
2969     if (frame == [self mainFrame])
2970         _private->didDrawTiles = 0;
2971 }
2972
2973 #endif // PLATFORM(IOS)
2974
2975 #if ENABLE(DASHBOARD_SUPPORT)
2976
2977 #define DASHBOARD_CONTROL_LABEL @"control"
2978
2979 - (void)_addControlRect:(NSRect)bounds clip:(NSRect)clip fromView:(NSView *)view toDashboardRegions:(NSMutableDictionary *)regions
2980 {
2981     NSRect adjustedBounds = bounds;
2982     adjustedBounds.origin = [self convertPoint:bounds.origin fromView:view];
2983     adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
2984     adjustedBounds.size = bounds.size;
2985
2986     NSRect adjustedClip;
2987     adjustedClip.origin = [self convertPoint:clip.origin fromView:view];
2988     adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
2989     adjustedClip.size = clip.size;
2990
2991     WebDashboardRegion *region = [[WebDashboardRegion alloc] initWithRect:adjustedBounds 
2992         clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle];
2993     NSMutableArray *scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
2994     if (!scrollerRegions) {
2995         scrollerRegions = [[NSMutableArray alloc] init];
2996         [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
2997         [scrollerRegions release];
2998     }
2999     [scrollerRegions addObject:region];
3000     [region release];
3001 }
3002
3003 - (void)_addScrollerDashboardRegionsForFrameView:(FrameView*)frameView dashboardRegions:(NSMutableDictionary *)regions
3004 {    
3005     NSView *documentView = [[kit(&frameView->frame()) frameView] documentView];
3006
3007     for (const auto& widget: frameView->children()) {
3008         if (is<FrameView>(*widget)) {
3009             [self _addScrollerDashboardRegionsForFrameView:downcast<FrameView>(widget.get()) dashboardRegions:regions];
3010             continue;
3011         }
3012
3013         if (!widget->isScrollbar())
3014             continue;
3015
3016         // FIXME: This should really pass an appropriate clip, but our first try got it wrong, and
3017         // it's not common to need this to be correct in Dashboard widgets.
3018         NSRect bounds = widget->frameRect();
3019         [self _addControlRect:bounds clip:bounds fromView:documentView toDashboardRegions:regions];
3020     }
3021 }
3022
3023 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
3024 {
3025     // Add scroller regions for NSScroller and WebCore scrollbars
3026     NSUInteger count = [views count];
3027     for (NSUInteger i = 0; i < count; i++) {
3028         NSView *view = [views objectAtIndex:i];
3029         
3030         if ([view isKindOfClass:[WebHTMLView class]]) {
3031             if (Frame* coreFrame = core([(WebHTMLView*)view _frame])) {
3032                 if (FrameView* coreView = coreFrame->view())
3033                     [self _addScrollerDashboardRegionsForFrameView:coreView dashboardRegions:regions];
3034             }
3035         } else if ([view isKindOfClass:[NSScroller class]]) {
3036             // AppKit places absent scrollers at -100,-100
3037             if ([view frame].origin.y < 0)
3038                 continue;
3039             [self _addControlRect:[view bounds] clip:[view visibleRect] fromView:view toDashboardRegions:regions];
3040         }
3041         [self _addScrollerDashboardRegions:regions from:[view subviews]];
3042     }
3043 }
3044
3045 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
3046 {
3047     [self _addScrollerDashboardRegions:regions from:[self subviews]];
3048 }
3049
3050 - (NSDictionary *)_dashboardRegions
3051 {
3052     // Only return regions from main frame.
3053     Frame* mainFrame = [self _mainCoreFrame];
3054     if (!mainFrame)
3055         return nil;
3056
3057     const Vector<AnnotatedRegionValue>& regions = mainFrame->document()->annotatedRegions();
3058     size_t size = regions.size();
3059
3060     NSMutableDictionary *webRegions = [NSMutableDictionary dictionaryWithCapacity:size];
3061     for (size_t i = 0; i < size; i++) {
3062         const AnnotatedRegionValue& region = regions[i];
3063
3064         if (region.type == StyleDashboardRegion::None)
3065             continue;
3066
3067         NSString *label = region.label;
3068         WebDashboardRegionType type = WebDashboardRegionTypeNone;
3069         if (region.type == StyleDashboardRegion::Circle)
3070             type = WebDashboardRegionTypeCircle;
3071         else if (region.type == StyleDashboardRegion::Rectangle)
3072             type = WebDashboardRegionTypeRectangle;
3073         NSMutableArray *regionValues = [webRegions objectForKey:label];
3074         if (!regionValues) {
3075             regionValues = [[NSMutableArray alloc] initWithCapacity:1];
3076             [webRegions setObject:regionValues forKey:label];
3077             [regionValues release];
3078         }
3079
3080         WebDashboardRegion *webRegion = [[WebDashboardRegion alloc] initWithRect:snappedIntRect(region.bounds) clip:snappedIntRect(region.clip) type:type];
3081         [regionValues addObject:webRegion];
3082         [webRegion release];
3083     }
3084
3085     [self _addScrollerDashboardRegions:webRegions];
3086
3087     return webRegions;
3088 }
3089
3090 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag
3091 {
3092     // FIXME: Remove this blanket assignment once Dashboard and Dashcode implement 
3093     // specific support for the backward compatibility mode flag.
3094     if (behavior == WebDashboardBehaviorAllowWheelScrolling && flag == NO && _private->page)
3095         _private->page->settings().setUsesDashboardBackwardCompatibilityMode(true);
3096     
3097     switch (behavior) {
3098         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3099             _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
3100             break;
3101         }
3102         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3103             _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
3104             break;
3105         }
3106         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3107             _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
3108             break;
3109         }
3110         case WebDashboardBehaviorAllowWheelScrolling: {
3111             _private->dashboardBehaviorAllowWheelScrolling = flag;
3112             break;
3113         }
3114         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3115             if (_private->page)
3116                 _private->page->settings().setUsesDashboardBackwardCompatibilityMode(flag);
3117 #if ENABLE(LEGACY_CSS_VENDOR_PREFIXES)
3118             RuntimeEnabledFeatures::sharedFeatures().setLegacyCSSVendorPrefixesEnabled(flag);
3119 #endif
3120             break;
3121         }
3122     }
3123
3124     // Pre-HTML5 parser quirks should be enabled if Dashboard is in backward
3125     // compatibility mode. See <rdar://problem/8175982>.
3126     if (_private->page)
3127         _private->page->settings().setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
3128 }
3129
3130 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
3131 {
3132     switch (behavior) {
3133         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3134             return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
3135         }
3136         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3137             return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
3138         }
3139         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3140             return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
3141         }
3142         case WebDashboardBehaviorAllowWheelScrolling: {
3143             return _private->dashboardBehaviorAllowWheelScrolling;
3144         }
3145         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3146             return _private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode();
3147         }
3148     }
3149     return NO;
3150 }
3151
3152 #endif /* ENABLE(DASHBOARD_SUPPORT) */
3153
3154 + (void)_setShouldUseFontSmoothing:(BOOL)f
3155 {
3156     Font::setShouldUseSmoothing(f);
3157 }
3158
3159 + (BOOL)_shouldUseFontSmoothing
3160 {
3161     return Font::shouldUseSmoothing();
3162 }
3163
3164 #if !PLATFORM(IOS)
3165 + (void)_setUsesTestModeFocusRingColor:(BOOL)f
3166 {
3167     setUsesTestModeFocusRingColor(f);
3168 }
3169
3170 + (BOOL)_usesTestModeFocusRingColor
3171 {
3172     return usesTestModeFocusRingColor();
3173 }
3174 #endif
3175
3176 #if PLATFORM(IOS)
3177 - (void)_setUIKitDelegate:(id)delegate
3178 {
3179     _private->UIKitDelegate = delegate;
3180     [_private->UIKitDelegateForwarder clearTarget];
3181     [_private->UIKitDelegateForwarder release];
3182     _private->UIKitDelegateForwarder = nil;
3183 }
3184
3185 - (id)_UIKitDelegate
3186 {
3187     return _private->UIKitDelegate;
3188 }
3189
3190 - (void)setWebMailDelegate:(id)delegate
3191 {
3192     _private->WebMailDelegate = delegate;
3193 }
3194
3195 - (id)_webMailDelegate
3196 {
3197     return _private->WebMailDelegate;
3198 }
3199
3200 - (id <WebCaretChangeListener>)caretChangeListener
3201 {
3202     return _private->_caretChangeListener;
3203 }
3204
3205 - (void)setCaretChangeListener:(id <WebCaretChangeListener>)listener
3206 {
3207     _private->_caretChangeListener = listener;
3208 }
3209
3210 - (NSSet *)caretChangeListeners
3211 {
3212     return _private->_caretChangeListeners;
3213 }
3214
3215 - (void)addCaretChangeListener:(id <WebCaretChangeListener>)listener
3216 {
3217     if (_private->_caretChangeListeners == nil) {
3218         _private->_caretChangeListeners = [[NSMutableSet alloc] init];
3219     }
3220     
3221     [_private->_caretChangeListeners addObject:listener];
3222 }
3223
3224 - (void)removeCaretChangeListener:(id <WebCaretChangeListener>)listener
3225 {
3226     [_private->_caretChangeListeners removeObject:listener];
3227 }
3228
3229 - (void)removeAllCaretChangeListeners
3230 {
3231     [_private->_caretChangeListeners removeAllObjects];
3232 }
3233
3234 - (void)caretChanged
3235 {
3236     [_private->_caretChangeListener caretChanged];
3237     NSSet *copy = [_private->_caretChangeListeners copy];
3238     for (id <WebCaretChangeListener> listener in copy) {
3239         [listener caretChanged];
3240     }
3241     [copy release];
3242 }
3243
3244 - (void)_clearDelegates
3245 {
3246     ASSERT(WebThreadIsLocked() || !WebThreadIsEnabled());
3247     
3248     [self _setFormDelegate:nil];
3249     [self _setUIKitDelegate:nil];
3250     [self setCaretChangeListener:nil];
3251     [self removeAllCaretChangeListeners];
3252     [self setWebMailDelegate:nil];
3253     
3254     [self setDownloadDelegate:nil];
3255     [self setEditingDelegate:nil]; 
3256     [self setFrameLoadDelegate:nil];
3257     [self setPolicyDelegate:nil];
3258     [self setResourceLoadDelegate:nil];
3259     [self setScriptDebugDelegate:nil];
3260     [self setUIDelegate:nil];     
3261 }
3262
3263 - (NSURL *)_displayURL
3264 {
3265     WebThreadLock();
3266     WebFrame *frame = [self mainFrame];
3267     // FIXME: <rdar://problem/6362369> We used to get provisionalDataSource here if in provisional state; how do we tell that now? Is this right?
3268     WebDataSource *dataSource = [frame provisionalDataSource];
3269     if (!dataSource)
3270         dataSource = [frame dataSource];
3271     NSURL *unreachableURL = [dataSource unreachableURL];
3272     NSURL *URL = unreachableURL != nil ? unreachableURL : [[dataSource request] URL];
3273     [[URL retain] autorelease];
3274     return URL;
3275 }
3276 #endif // PLATFORM(IOS)
3277
3278 #if !PLATFORM(IOS)
3279 - (void)setAlwaysShowVerticalScroller:(BOOL)flag
3280 {
3281     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3282     if (flag) {
3283         [scrollview setVerticalScrollingMode:ScrollbarAlwaysOn andLock:YES];
3284     } else {
3285         [scrollview setVerticalScrollingModeLocked:NO];
3286         [scrollview setVerticalScrollingMode:ScrollbarAuto andLock:NO];
3287     }
3288 }
3289
3290 - (BOOL)alwaysShowVerticalScroller
3291 {
3292     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3293     return [scrollview verticalScrollingModeLocked] && [scrollview verticalScrollingMode] == ScrollbarAlwaysOn;
3294 }
3295
3296 - (void)setAlwaysShowHorizontalScroller:(BOOL)flag
3297 {
3298     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3299     if (flag) {
3300         [scrollview setHorizontalScrollingMode:ScrollbarAlwaysOn andLock:YES];
3301     } else {
3302         [scrollview setHorizontalScrollingModeLocked:NO];
3303         [scrollview setHorizontalScrollingMode:ScrollbarAuto andLock:NO];
3304     }
3305 }
3306
3307 - (void)setProhibitsMainFrameScrolling:(BOOL)prohibits
3308 {
3309     if (Frame* mainFrame = [self _mainCoreFrame])
3310         mainFrame->view()->setProhibitsScrolling(prohibits);
3311 }
3312
3313 - (BOOL)alwaysShowHorizontalScroller
3314 {
3315     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3316     return [scrollview horizontalScrollingModeLocked] && [scrollview horizontalScrollingMode] == ScrollbarAlwaysOn;
3317 }
3318 #endif // !PLATFORM(IOS)
3319
3320 - (void)_setUseFastImageScalingMode:(BOOL)flag
3321 {
3322     if (_private->page && _private->page->inLowQualityImageInterpolationMode() != flag) {
3323         _private->page->setInLowQualityImageInterpolationMode(flag);
3324         [self setNeedsDisplay:YES];
3325     }
3326 }
3327
3328 - (BOOL)_inFastImageScalingMode
3329 {
3330     if (_private->page)
3331         return _private->page->inLowQualityImageInterpolationMode();
3332     return NO;
3333 }
3334
3335 - (BOOL)_cookieEnabled
3336 {
3337     if (_private->page)
3338         return _private->page->settings().cookieEnabled();
3339     return YES;
3340 }
3341
3342 - (void)_setCookieEnabled:(BOOL)enable
3343 {
3344     if (_private->page)
3345         _private->page->settings().setCookieEnabled(enable);
3346 }
3347
3348 #if !PLATFORM(IOS)
3349 - (void)_setAdditionalWebPlugInPaths:(NSArray *)newPaths
3350 {
3351     if (!_private->pluginDatabase)
3352         _private->pluginDatabase = [[WebPluginDatabase alloc] init];
3353         
3354     [_private->pluginDatabase setPlugInPaths:newPaths];
3355     [_private->pluginDatabase refresh];
3356 }
3357 #endif
3358
3359 #if PLATFORM(IOS)
3360 - (BOOL)_locked_plugInsAreRunningInFrame:(WebFrame *)frame
3361 {
3362     // Ask plug-ins in this frame
3363     id <WebDocumentView> documentView = [[frame frameView] documentView];
3364     if (documentView && [documentView isKindOfClass:[WebHTMLView class]]) {
3365         if ([[(WebHTMLView *)documentView _pluginController] plugInsAreRunning])
3366             return YES;
3367     }
3368
3369     // Ask plug-ins in child frames
3370     NSArray *childFrames = [frame childFrames];
3371     unsigned childCount = [childFrames count];
3372     unsigned childIndex;
3373     for (childIndex = 0; childIndex < childCount; childIndex++) {
3374         if ([self _locked_plugInsAreRunningInFrame:[childFrames objectAtIndex:childIndex]])
3375             return YES;
3376     }
3377     
3378     return NO;
3379 }
3380
3381 - (BOOL)_pluginsAreRunning
3382 {
3383     WebThreadLock();
3384     return [self _locked_plugInsAreRunningInFrame:[self mainFrame]];
3385 }
3386
3387 - (void)_locked_recursivelyPerformPlugInSelector:(SEL)selector inFrame:(WebFrame *)frame
3388 {
3389     // Send the message to plug-ins in this frame
3390     id <WebDocumentView> documentView = [[frame frameView] documentView];
3391     if (documentView && [documentView isKindOfClass:[WebHTMLView class]])
3392         [[(WebHTMLView *)documentView _pluginController] performSelector:selector];
3393
3394     // Send the message to plug-ins in child frames
3395     NSArray *childFrames = [frame childFrames];
3396     unsigned childCount = [childFrames count];
3397     unsigned childIndex;
3398     for (childIndex = 0; childIndex < childCount; childIndex++) {
3399         [self _locked_recursivelyPerformPlugInSelector:selector inFrame:[childFrames objectAtIndex:childIndex]];
3400     }
3401 }
3402
3403 - (void)_destroyAllPlugIns
3404 {
3405     WebThreadLock();
3406     [self _locked_recursivelyPerformPlugInSelector:@selector(destroyAllPlugins) inFrame:[self mainFrame]];
3407 }
3408
3409 - (void)_clearBackForwardCache
3410 {
3411     WebThreadRun(^{
3412         WebKit::MemoryMeasure measurer("[WebView _clearBackForwardCache]");
3413         BackForwardList* bfList = core([self backForwardList]);
3414         if (!bfList)
3415             return;
3416
3417         BOOL didClearBFCache = bfList->clearAllPageCaches();
3418         if (WebKit::MemoryMeasure::isLoggingEnabled())
3419             NSLog(@"[WebView _clearBackForwardCache] %@ empty cache\n", (didClearBFCache ? @"DID" : @"did NOT"));
3420     });
3421 }
3422
3423 - (void)_startAllPlugIns
3424 {
3425     WebThreadLock();
3426     [self _locked_recursivelyPerformPlugInSelector:@selector(startAllPlugins) inFrame:[self mainFrame]];
3427 }
3428
3429 - (void)_stopAllPlugIns
3430 {
3431     WebThreadLock();
3432     [self _locked_recursivelyPerformPlugInSelector:@selector(stopAllPlugins) inFrame:[self mainFrame]];
3433 }
3434
3435 - (void)_stopAllPlugInsForPageCache
3436 {
3437     WebThreadLock();
3438     [self _locked_recursivelyPerformPlugInSelector:@selector(stopPluginsForPageCache) inFrame:[self mainFrame]];
3439 }
3440
3441 - (void)_restorePlugInsFromCache
3442 {
3443     WebThreadLock();
3444     [self _locked_recursivelyPerformPlugInSelector:@selector(restorePluginsFromCache) inFrame:[self mainFrame]];
3445 }
3446
3447 - (BOOL)_setMediaLayer:(CALayer*)layer forPluginView:(NSView*)pluginView
3448 {
3449     WebThreadLock();
3450
3451     Frame* mainCoreFrame = [self _mainCoreFrame];
3452     for (Frame* frame = mainCoreFrame; frame; frame = frame->tree().traverseNext()) {
3453         FrameView* coreView = frame ? frame->view() : 0;
3454         if (!coreView)
3455             continue;
3456
3457         // Get the GraphicsLayer for this widget.
3458         GraphicsLayer* layerForWidget = coreView->graphicsLayerForPlatformWidget(pluginView);
3459         if (!layerForWidget)
3460             continue;
3461         
3462         if (layerForWidget->contentsLayerForMedia() != layer) {
3463             layerForWidget->setContentsToPlatformLayer(layer, GraphicsLayer::ContentsLayerForMedia);
3464             // We need to make sure the layer hierachy change is applied immediately.
3465             if (mainCoreFrame->view())
3466                 mainCoreFrame->view()->flushCompositingStateIncludingSubframes();
3467             return YES;
3468         }
3469     }
3470
3471     return NO;
3472 }
3473
3474 - (void)_setNeedsUnrestrictedGetMatchedCSSRules:(BOOL)flag
3475 {
3476     if (_private->page)
3477         _private->page->settings().setCrossOriginCheckInGetMatchedCSSRulesDisabled(flag);
3478 }
3479 #endif // PLATFORM(IOS)
3480
3481 - (void)_attachScriptDebuggerToAllFrames
3482 {
3483     for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext())
3484         [kit(frame) _attachScriptDebugger];
3485 }
3486
3487 - (void)_detachScriptDebuggerFromAllFrames
3488 {
3489     for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext())
3490         [kit(frame) _detachScriptDebugger];
3491 }
3492
3493 #if !PLATFORM(IOS)
3494 - (void)setBackgroundColor:(NSColor *)backgroundColor
3495 {
3496     if ([_private->backgroundColor isEqual:backgroundColor])
3497         return;
3498
3499     id old = _private->backgroundColor;
3500     _private->backgroundColor = [backgroundColor retain];
3501     [old release];
3502
3503     [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
3504 }
3505
3506 - (NSColor *)backgroundColor
3507 {
3508     return _private->backgroundColor;
3509 }
3510 #else
3511 - (void)setBackgroundColor:(CGColorRef)backgroundColor
3512 {
3513    if (!backgroundColor || CFEqual(_private->backgroundColor, backgroundColor))
3514         return;
3515
3516     CFTypeRef old = _private->backgroundColor;
3517     CFRetain(backgroundColor);
3518     _private->backgroundColor = backgroundColor;
3519     CFRelease(old);
3520
3521     [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
3522 }
3523
3524 - (CGColorRef)backgroundColor
3525 {
3526     return _private->backgroundColor;
3527 }
3528 #endif
3529
3530 - (BOOL)defersCallbacks
3531 {
3532     if (!_private->page)
3533         return NO;
3534     return _private->page->defersLoading();
3535 }
3536
3537 - (void)setDefersCallbacks:(BOOL)defer
3538 {
3539     if (!_private->page)
3540         return;
3541     return _private->page->setDefersLoading(defer);
3542 }
3543
3544 #if TARGET_OS_IPHONE && USE(QUICK_LOOK)
3545 - (NSDictionary *)quickLookContentForURL:(NSURL *)url
3546 {
3547     NSString *uti = qlPreviewConverterUTIForURL(url);
3548     if (!uti)
3549         return nil;
3550
3551     NSString *fileName = qlPreviewConverterFileNameForURL(url);
3552     if (!fileName)
3553         return nil;
3554
3555     return [NSDictionary dictionaryWithObjectsAndKeys: fileName, WebQuickLookFileNameKey, uti, WebQuickLookUTIKey, nil];
3556 }
3557 #endif
3558
3559 #if PLATFORM(IOS)
3560 - (BOOL)_isStopping
3561 {
3562     return _private->isStopping;
3563 }
3564
3565 - (BOOL)_isClosing
3566 {
3567     return _private->closing;
3568 }
3569
3570 + (NSArray *)_productivityDocumentMIMETypes
3571 {
3572 #if USE(QUICK_LOOK)
3573     return [QLPreviewGetSupportedMIMETypesSet() allObjects];
3574 #else
3575     return nil;
3576 #endif
3577 }
3578
3579 - (void)_setAllowsMessaging:(BOOL)aFlag
3580 {
3581     _private->allowsMessaging = aFlag;
3582 }
3583
3584 - (BOOL)_allowsMessaging
3585 {
3586     return _private->allowsMessaging;
3587 }
3588
3589 - (void)_setFixedLayoutSize:(CGSize)size
3590 {
3591     ASSERT(WebThreadIsLocked());
3592     _private->fixedLayoutSize = size;
3593     if (Frame* mainFrame = core([self mainFrame])) {
3594         IntSize newSize(size);
3595         mainFrame->view()->setFixedLayoutSize(newSize);
3596         mainFrame->view()->setUseFixedLayout(!newSize.isEmpty());
3597         [self setNeedsDisplay:YES];
3598     }
3599 }
3600
3601 - (CGSize)_fixedLayoutSize
3602 {
3603     return _private->fixedLayoutSize;
3604 }
3605
3606 - (void)_synchronizeCustomFixedPositionLayoutRect
3607 {
3608     ASSERT(WebThreadIsLocked());
3609
3610     IntRect newRect;
3611     {
3612         MutexLocker locker(_private->pendingFixedPositionLayoutRectMutex);
3613         if (CGRectIsNull(_private->pendingFixedPositionLayoutRect))
3614             return;
3615         newRect = enclosingIntRect(_private->pendingFixedPositionLayoutRect);
3616         _private->pendingFixedPositionLayoutRect = CGRectNull;
3617     }
3618
3619     if (Frame* mainFrame = core([self mainFrame]))