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