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