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