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