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