Annotate MediaStream and WebRTC idl with EnabledAtRuntime flag
[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 PageVisibilityStateVisible:
573         return WebPageVisibilityStateVisible;
574     case PageVisibilityStateHidden:
575         return WebPageVisibilityStateHidden;
576     case PageVisibilityStatePrerender:
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.setAccelerated2dCanvasEnabled([preferences accelerated2dCanvasEnabled]);
2665     settings.setLoadDeferringEnabled(shouldEnableLoadDeferring());
2666     settings.setWindowFocusRestricted(shouldRestrictWindowFocus());
2667     settings.setFrameFlatteningEnabled([preferences isFrameFlatteningEnabled]);
2668     settings.setSpatialNavigationEnabled([preferences isSpatialNavigationEnabled]);
2669     settings.setPaginateDuringLayoutEnabled([preferences paginateDuringLayoutEnabled]);
2670
2671     settings.setAsynchronousSpellCheckingEnabled([preferences asynchronousSpellCheckingEnabled]);
2672     settings.setHyperlinkAuditingEnabled([preferences hyperlinkAuditingEnabled]);
2673     settings.setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
2674     settings.setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
2675     settings.setValidationMessageTimerMagnification([self validationMessageTimerMagnification]);
2676
2677     BOOL mediaPlaybackRequiresUserGesture = [preferences mediaPlaybackRequiresUserGesture];
2678     settings.setVideoPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture || [preferences videoPlaybackRequiresUserGesture]);
2679     settings.setAudioPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture || [preferences audioPlaybackRequiresUserGesture]);
2680     settings.setRequiresUserGestureToLoadVideo(shouldRequireUserGestureToLoadVideo());
2681     settings.setMainContentUserGestureOverrideEnabled([preferences overrideUserGestureRequirementForMainContent]);
2682     settings.setAllowsInlineMediaPlayback([preferences mediaPlaybackAllowsInline]);
2683     settings.setAllowsInlineMediaPlaybackAfterFullscreen([preferences allowsInlineMediaPlaybackAfterFullscreen]);
2684     settings.setInlineMediaPlaybackRequiresPlaysInlineAttribute([preferences inlineMediaPlaybackRequiresPlaysInlineAttribute]);
2685     settings.setInvisibleAutoplayNotPermitted([preferences invisibleAutoplayNotPermitted]);
2686     settings.setAllowsPictureInPictureMediaPlayback([preferences allowsPictureInPictureMediaPlayback] && shouldAllowPictureInPictureMediaPlayback());
2687     settings.setMediaControlsScaleWithPageZoom([preferences mediaControlsScaleWithPageZoom]);
2688     settings.setSuppressesIncrementalRendering([preferences suppressesIncrementalRendering]);
2689     settings.setBackspaceKeyNavigationEnabled([preferences backspaceKeyNavigationEnabled]);
2690     settings.setWantsBalancedSetDefersLoadingBehavior([preferences wantsBalancedSetDefersLoadingBehavior]);
2691     settings.setMockScrollbarsEnabled([preferences mockScrollbarsEnabled]);
2692
2693     settings.setShouldRespectImageOrientation([preferences shouldRespectImageOrientation]);
2694
2695     settings.setRequestAnimationFrameEnabled([preferences requestAnimationFrameEnabled]);
2696     settings.setDiagnosticLoggingEnabled([preferences diagnosticLoggingEnabled]);
2697     settings.setLowPowerVideoAudioBufferSizeEnabled([preferences lowPowerVideoAudioBufferSizeEnabled]);
2698
2699     settings.setUseLegacyTextAlignPositionedElementBehavior([preferences useLegacyTextAlignPositionedElementBehavior]);
2700
2701     settings.setShouldConvertPositionStyleOnCopy([preferences shouldConvertPositionStyleOnCopy]);
2702     settings.setEnableInheritURIQueryComponent([preferences isInheritURIQueryComponentEnabled]);
2703
2704     settings.setAllowDisplayOfInsecureContent(shouldAllowDisplayAndRunningOfInsecureContent());
2705     settings.setAllowRunningOfInsecureContent(shouldAllowDisplayAndRunningOfInsecureContent());
2706
2707     settings.setVisualViewportEnabled([preferences visualViewportEnabled]);
2708
2709     switch ([preferences storageBlockingPolicy]) {
2710     case WebAllowAllStorage:
2711         settings.setStorageBlockingPolicy(SecurityOrigin::AllowAllStorage);
2712         break;
2713     case WebBlockThirdPartyStorage:
2714         settings.setStorageBlockingPolicy(SecurityOrigin::BlockThirdPartyStorage);
2715         break;
2716     case WebBlockAllStorage:
2717         settings.setStorageBlockingPolicy(SecurityOrigin::BlockAllStorage);
2718         break;
2719     }
2720
2721     settings.setPlugInSnapshottingEnabled([preferences plugInSnapshottingEnabled]);
2722     settings.setHttpEquivEnabled([preferences httpEquivEnabled]);
2723
2724     settings.setFixedPositionCreatesStackingContext(true);
2725 #if PLATFORM(MAC)
2726     settings.setAcceleratedCompositingForFixedPositionEnabled(true);
2727 #endif
2728
2729 #if ENABLE(RUBBER_BANDING)
2730     // FIXME: https://bugs.webkit.org/show_bug.cgi?id=136131
2731     settings.setRubberBandingForSubScrollableRegionsEnabled(false);
2732 #endif
2733
2734 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2735     settings.setAllowsAirPlayForMediaPlayback([preferences allowsAirPlayForMediaPlayback]);
2736 #endif
2737 #if PLATFORM(IOS)
2738     settings.setStandalone([preferences _standalone]);
2739     settings.setTelephoneNumberParsingEnabled([preferences _telephoneNumberParsingEnabled]);
2740     settings.setAllowMultiElementImplicitSubmission([preferences _allowMultiElementImplicitFormSubmission]);
2741     settings.setLayoutInterval(Seconds::fromMilliseconds([preferences _layoutInterval]));
2742     settings.setMaxParseDuration([preferences _maxParseDuration]);
2743     settings.setAlwaysUseAcceleratedOverflowScroll([preferences _alwaysUseAcceleratedOverflowScroll]);
2744     settings.setAudioSessionCategoryOverride([preferences audioSessionCategoryOverride]);
2745     settings.setNetworkDataUsageTrackingEnabled([preferences networkDataUsageTrackingEnabled]);
2746     settings.setNetworkInterfaceName([preferences networkInterfaceName]);
2747 #if HAVE(AVKIT)
2748     settings.setAVKitEnabled([preferences avKitEnabled]);
2749 #endif
2750     settings.setShouldTransformsAffectOverflow(shouldTransformsAffectOverflow());
2751     settings.setShouldDispatchJavaScriptWindowOnErrorEvents(shouldDispatchJavaScriptWindowOnErrorEvents());
2752
2753     settings.setPasswordEchoEnabled([preferences _allowPasswordEcho]);
2754     settings.setPasswordEchoDurationInSeconds([preferences _passwordEchoDuration]);
2755
2756     ASSERT_WITH_MESSAGE(settings.pageCacheSupportsPlugins(), "PageCacheSupportsPlugins should be enabled on iOS.");
2757     settings.setDelegatesPageScaling(true);
2758
2759 #if ENABLE(TEXT_AUTOSIZING)
2760     settings.setMinimumZoomFontSize([preferences _minimumZoomFontSize]);
2761     settings.setTextAutosizingEnabled([preferences _textAutosizingEnabled]);
2762 #endif
2763 #endif // PLATFORM(IOS)
2764
2765 #if PLATFORM(MAC)
2766     if ([preferences userStyleSheetEnabled]) {
2767         NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
2768         if ([location isEqualToString:@"apple-dashboard://stylesheet"])
2769             location = @"file:///System/Library/PrivateFrameworks/DashboardClient.framework/Resources/widget.css";
2770         settings.setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
2771     } else
2772         settings.setUserStyleSheetLocation([NSURL URLWithString:@""]);
2773
2774     settings.setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
2775     settings.setTreatsAnyTextCSSLinkAsStylesheet([self _needsLinkElementTextCSSQuirk]);
2776     settings.setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
2777     settings.setEnforceCSSMIMETypeInNoQuirksMode(!WKAppVersionCheckLessThan(@"com.apple.iWeb", -1, 2.1));
2778     settings.setNeedsIsLoadingInAPISenseQuirk([self _needsIsLoadingInAPISenseQuirk]);
2779     settings.setTextAreasAreResizable([preferences textAreasAreResizable]);
2780     settings.setExperimentalNotificationsEnabled([preferences experimentalNotificationsEnabled]);
2781     settings.setShowsURLsInToolTips([preferences showsURLsInToolTips]);
2782     settings.setShowsToolTipOverTruncatedText([preferences showsToolTipOverTruncatedText]);
2783     settings.setQTKitEnabled([preferences isQTKitEnabled]);
2784 #endif // PLATFORM(MAC)
2785
2786     DatabaseManager::singleton().setIsAvailable([preferences databasesEnabled]);
2787
2788 #if ENABLE(MEDIA_SOURCE)
2789     settings.setMediaSourceEnabled([preferences mediaSourceEnabled]);
2790 #endif
2791
2792 #if ENABLE(SERVICE_CONTROLS)
2793     settings.setImageControlsEnabled([preferences imageControlsEnabled]);
2794     settings.setServiceControlsEnabled([preferences serviceControlsEnabled]);
2795 #endif
2796
2797 #if ENABLE(VIDEO_TRACK)
2798     settings.setShouldDisplaySubtitles([preferences shouldDisplaySubtitles]);
2799     settings.setShouldDisplayCaptions([preferences shouldDisplayCaptions]);
2800     settings.setShouldDisplayTextDescriptions([preferences shouldDisplayTextDescriptions]);
2801 #endif
2802
2803 #if USE(AVFOUNDATION)
2804     settings.setAVFoundationEnabled([preferences isAVFoundationEnabled]);
2805     settings.setAVFoundationNSURLSessionEnabled([preferences isAVFoundationNSURLSessionEnabled]);
2806 #endif
2807
2808 #if ENABLE(MEDIA_STREAM)
2809     settings.setMockCaptureDevicesEnabled([preferences mockCaptureDevicesEnabled]);
2810     settings.setMediaCaptureRequiresSecureConnection([preferences mediaCaptureRequiresSecureConnection]);
2811     RuntimeEnabledFeatures::sharedFeatures().setMediaStreamEnabled([preferences mediaStreamEnabled]);
2812 #endif
2813
2814 #if ENABLE(WEB_RTC)
2815     RuntimeEnabledFeatures::sharedFeatures().setPeerConnectionEnabled([preferences peerConnectionEnabled]);
2816 #endif
2817
2818 #if ENABLE(WEB_AUDIO)
2819     settings.setWebAudioEnabled([preferences webAudioEnabled]);
2820 #endif
2821
2822 #if ENABLE(FULLSCREEN_API)
2823     settings.setFullScreenEnabled([preferences fullScreenEnabled]);
2824 #endif
2825
2826     settings.setHiddenPageDOMTimerThrottlingEnabled([preferences hiddenPageDOMTimerThrottlingEnabled]);
2827
2828     settings.setHiddenPageCSSAnimationSuspensionEnabled([preferences hiddenPageCSSAnimationSuspensionEnabled]);
2829
2830     settings.setResourceLoadStatisticsEnabled([preferences resourceLoadStatisticsEnabled]);
2831
2832 #if ENABLE(GAMEPAD)
2833     RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled([preferences gamepadsEnabled]);
2834 #endif
2835
2836 #if ENABLE(INDEXED_DATABASE)
2837     RuntimeEnabledFeatures::sharedFeatures().setWebkitIndexedDBEnabled(true);
2838 #endif
2839
2840     RuntimeEnabledFeatures::sharedFeatures().setShadowDOMEnabled([preferences shadowDOMEnabled]);
2841
2842     RuntimeEnabledFeatures::sharedFeatures().setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
2843
2844     RuntimeEnabledFeatures::sharedFeatures().setDOMIteratorEnabled([preferences DOMIteratorEnabled]);
2845
2846     RuntimeEnabledFeatures::sharedFeatures().setModernMediaControlsEnabled([preferences modernMediaControlsEnabled]);
2847
2848     RuntimeEnabledFeatures::sharedFeatures().setCustomElementsEnabled([preferences customElementsEnabled]);
2849
2850 #if ENABLE(FETCH_API)
2851     RuntimeEnabledFeatures::sharedFeatures().setFetchAPIEnabled([preferences fetchAPIEnabled]);
2852 #endif
2853
2854 #if ENABLE(WEBGL2)
2855     RuntimeEnabledFeatures::sharedFeatures().setWebGL2Enabled([preferences webGL2Enabled]);
2856 #endif
2857
2858 #if ENABLE(DOWNLOAD_ATTRIBUTE)
2859     RuntimeEnabledFeatures::sharedFeatures().setDownloadAttributeEnabled([preferences downloadAttributeEnabled]);
2860 #endif
2861
2862     settings.setEs6ModulesEnabled([preferences es6ModulesEnabled]);
2863
2864 #if ENABLE(CSS_GRID_LAYOUT)
2865     RuntimeEnabledFeatures::sharedFeatures().setCSSGridLayoutEnabled([preferences isCSSGridLayoutEnabled]);
2866 #endif
2867
2868 #if ENABLE(WEB_ANIMATIONS)
2869     RuntimeEnabledFeatures::sharedFeatures().setWebAnimationsEnabled([preferences webAnimationsEnabled]);
2870 #endif
2871
2872 #if ENABLE(INTERSECTION_OBSERVER)
2873     RuntimeEnabledFeatures::sharedFeatures().setIntersectionObserverEnabled(preferences.intersectionObserverEnabled);
2874 #endif
2875
2876 #if ENABLE(SUBTLE_CRYPTO)
2877     RuntimeEnabledFeatures::sharedFeatures().setSubtleCryptoEnabled([preferences subtleCryptoEnabled]);
2878 #endif
2879
2880     NSTimeInterval timeout = [preferences incrementalRenderingSuppressionTimeoutInSeconds];
2881     if (timeout > 0)
2882         settings.setIncrementalRenderingSuppressionTimeoutInSeconds(timeout);
2883
2884     // Application Cache Preferences are stored on the global cache storage manager, not in Settings.
2885     [WebApplicationCache setDefaultOriginQuota:[preferences applicationCacheDefaultOriginQuota]];
2886
2887     BOOL zoomsTextOnly = [preferences zoomsTextOnly];
2888     if (_private->zoomsTextOnly != zoomsTextOnly)
2889         [self _setZoomMultiplier:_private->zoomMultiplier isTextOnly:zoomsTextOnly];
2890
2891 #if PLATFORM(IOS)
2892     [[self window] setTileBordersVisible:[preferences showDebugBorders]];
2893     [[self window] setTilePaintCountsVisible:[preferences showRepaintCounter]];
2894     [[self window] setAcceleratedDrawingEnabled:[preferences acceleratedDrawingEnabled]];
2895     [WAKView _setInterpolationQuality:[preferences _interpolationQuality]];
2896 #endif
2897
2898 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
2899     settings.setMediaKeysStorageDirectory([preferences mediaKeysStorageDirectory]);
2900 #endif
2901
2902     settings.setMediaDataLoadsAutomatically([preferences mediaDataLoadsAutomatically]);
2903
2904 #if ENABLE(ATTACHMENT_ELEMENT)
2905     settings.setAttachmentElementEnabled([preferences attachmentElementEnabled]);
2906 #endif
2907
2908     settings.setAllowContentSecurityPolicySourceStarToMatchAnyProtocol(shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol());
2909
2910     settings.setAllowWindowOpenWithoutUserGesture(shouldAllowWindowOpenWithoutUserGesture());
2911
2912     settings.setShouldConvertInvalidURLsToBlank(shouldConvertInvalidURLsToBlank());
2913
2914     settings.setLargeImageAsyncDecodingEnabled([preferences largeImageAsyncDecodingEnabled]);
2915     settings.setAnimatedImageAsyncDecodingEnabled([preferences animatedImageAsyncDecodingEnabled]);
2916 }
2917
2918 static inline IMP getMethod(id o, SEL s)
2919 {
2920     return [o respondsToSelector:s] ? [o methodForSelector:s] : 0;
2921 }
2922
2923 #if PLATFORM(IOS)
2924 - (id)_UIKitDelegateForwarder
2925 {
2926     if (_private->closing)
2927         return nil;
2928         
2929     if (!_private->UIKitDelegateForwarder)
2930         _private->UIKitDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIKitDelegate defaultTarget:[WebDefaultUIKitDelegate sharedUIKitDelegate]];
2931     return _private->UIKitDelegateForwarder;
2932 }
2933 #endif
2934
2935 - (void)_cacheResourceLoadDelegateImplementations
2936 {
2937     WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
2938     id delegate = _private->resourceProgressDelegate;
2939
2940     if (!delegate) {
2941         bzero(cache, sizeof(WebResourceDelegateImplementationCache));
2942         return;
2943     }
2944
2945     cache->didFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFailLoadingWithError:fromDataSource:));
2946     cache->didFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFinishLoadingFromDataSource:));
2947     cache->didLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
2948     cache->didReceiveAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
2949 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
2950     cache->canAuthenticateAgainstProtectionSpaceFunc = getMethod(delegate, @selector(webView:resource:canAuthenticateAgainstProtectionSpace:forDataSource:));
2951 #endif
2952
2953 #if PLATFORM(IOS)
2954     cache->connectionPropertiesFunc = getMethod(delegate, @selector(webView:connectionPropertiesForResource:dataSource:));
2955     cache->webThreadDidFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFinishLoadingFromDataSource:));
2956     cache->webThreadDidFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFailLoadingWithError:fromDataSource:));
2957     cache->webThreadIdentifierForRequestFunc = getMethod(delegate, @selector(webThreadWebView:identifierForInitialRequest:fromDataSource:));
2958     cache->webThreadDidLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webThreadWebView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
2959     cache->webThreadWillSendRequestFunc = getMethod(delegate, @selector(webThreadWebView:resource:willSendRequest:redirectResponse:fromDataSource:));
2960     cache->webThreadDidReceiveResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveResponse:fromDataSource:));
2961     cache->webThreadDidReceiveContentLengthFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveContentLength:fromDataSource:));
2962     cache->webThreadWillCacheResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:willCacheResponse:fromDataSource:));
2963 #endif
2964
2965     cache->didReceiveContentLengthFunc = getMethod(delegate, @selector(webView:resource:didReceiveContentLength:fromDataSource:));
2966     cache->didReceiveResponseFunc = getMethod(delegate, @selector(webView:resource:didReceiveResponse:fromDataSource:));
2967     cache->identifierForRequestFunc = getMethod(delegate, @selector(webView:identifierForInitialRequest:fromDataSource:));
2968     cache->plugInFailedWithErrorFunc = getMethod(delegate, @selector(webView:plugInFailedWithError:dataSource:));
2969     cache->willCacheResponseFunc = getMethod(delegate, @selector(webView:resource:willCacheResponse:fromDataSource:));
2970     cache->willSendRequestFunc = getMethod(delegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:));
2971     cache->shouldUseCredentialStorageFunc = getMethod(delegate, @selector(webView:resource:shouldUseCredentialStorageForDataSource:));
2972     cache->shouldPaintBrokenImageForURLFunc = getMethod(delegate, @selector(webView:shouldPaintBrokenImageForURL:));
2973 }
2974
2975 - (void)_cacheFrameLoadDelegateImplementations
2976 {
2977     WebFrameLoadDelegateImplementationCache *cache = &_private->frameLoadDelegateImplementations;
2978     id delegate = _private->frameLoadDelegate;
2979
2980     if (!delegate) {
2981         bzero(cache, sizeof(WebFrameLoadDelegateImplementationCache));
2982         return;
2983     }
2984
2985     cache->didCancelClientRedirectForFrameFunc = getMethod(delegate, @selector(webView:didCancelClientRedirectForFrame:));
2986     cache->didChangeLocationWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didChangeLocationWithinPageForFrame:));
2987     cache->didPushStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPushStateWithinPageForFrame:));
2988     cache->didReplaceStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didReplaceStateWithinPageForFrame:));
2989     cache->didPopStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPopStateWithinPageForFrame:));
2990 #if JSC_OBJC_API_ENABLED
2991     cache->didCreateJavaScriptContextForFrameFunc = getMethod(delegate, @selector(webView:didCreateJavaScriptContext:forFrame:));
2992 #endif
2993     cache->didClearWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearWindowObject:forFrame:));
2994     cache->didClearWindowObjectForFrameInScriptWorldFunc = getMethod(delegate, @selector(webView:didClearWindowObjectForFrame:inScriptWorld:));
2995     cache->didClearInspectorWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearInspectorWindowObject:forFrame:));
2996     cache->didCommitLoadForFrameFunc = getMethod(delegate, @selector(webView:didCommitLoadForFrame:));
2997     cache->didFailLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailLoadWithError:forFrame:));
2998     cache->didFailProvisionalLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailProvisionalLoadWithError:forFrame:));
2999     cache->didFinishDocumentLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishDocumentLoadForFrame:));
3000     cache->didFinishLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishLoadForFrame:));
3001     cache->didFirstLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstLayoutInFrame:));
3002     cache->didFirstVisuallyNonEmptyLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstVisuallyNonEmptyLayoutInFrame:));
3003     cache->didLayoutFunc = getMethod(delegate, @selector(webView:didLayout:));
3004     cache->didHandleOnloadEventsForFrameFunc = getMethod(delegate, @selector(webView:didHandleOnloadEventsForFrame:));
3005 #if ENABLE(ICONDATABASE)
3006     cache->didReceiveIconForFrameFunc = getMethod(delegate, @selector(webView:didReceiveIcon:forFrame:));
3007 #endif
3008     cache->didReceiveServerRedirectForProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didReceiveServerRedirectForProvisionalLoadForFrame:));
3009     cache->didReceiveTitleForFrameFunc = getMethod(delegate, @selector(webView:didReceiveTitle:forFrame:));
3010     cache->didStartProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didStartProvisionalLoadForFrame:));
3011     cache->willCloseFrameFunc = getMethod(delegate, @selector(webView:willCloseFrame:));
3012     cache->willPerformClientRedirectToURLDelayFireDateForFrameFunc = getMethod(delegate, @selector(webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:));
3013     cache->windowScriptObjectAvailableFunc = getMethod(delegate, @selector(webView:windowScriptObjectAvailable:));
3014     cache->didDisplayInsecureContentFunc = getMethod(delegate, @selector(webViewDidDisplayInsecureContent:));
3015     cache->didRunInsecureContentFunc = getMethod(delegate, @selector(webView:didRunInsecureContent:));
3016     cache->didDetectXSSFunc = getMethod(delegate, @selector(webView:didDetectXSS:));
3017     cache->didRemoveFrameFromHierarchyFunc = getMethod(delegate, @selector(webView:didRemoveFrameFromHierarchy:));
3018 #if PLATFORM(IOS)
3019     cache->webThreadDidLayoutFunc = getMethod(delegate, @selector(webThreadWebView:didLayout:));
3020 #endif
3021
3022     // It would be nice to get rid of this code and transition all clients to using didLayout instead of
3023     // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
3024     // for backwards compatibility.
3025     Page* page = core(self);
3026     if (page) {
3027         unsigned milestones = DidFirstLayout;
3028 #if PLATFORM(IOS)
3029         milestones |= DidFirstVisuallyNonEmptyLayout;
3030 #else
3031         if (cache->didFirstVisuallyNonEmptyLayoutInFrameFunc)
3032             milestones |= DidFirstVisuallyNonEmptyLayout;
3033 #endif
3034         page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
3035     }
3036 }
3037
3038 - (void)_cacheScriptDebugDelegateImplementations
3039 {
3040     WebScriptDebugDelegateImplementationCache *cache = &_private->scriptDebugDelegateImplementations;
3041     id delegate = _private->scriptDebugDelegate;
3042
3043     if (!delegate) {
3044         bzero(cache, sizeof(WebScriptDebugDelegateImplementationCache));
3045         return;
3046     }
3047
3048     cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:baseLineNumber:fromURL:sourceId:forWebFrame:));
3049     if (cache->didParseSourceFunc)
3050         cache->didParseSourceExpectsBaseLineNumber = YES;
3051     else {
3052         cache->didParseSourceExpectsBaseLineNumber = NO;
3053         cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:fromURL:sourceId:forWebFrame:));
3054     }
3055
3056     cache->failedToParseSourceFunc = getMethod(delegate, @selector(webView:failedToParseSource:baseLineNumber:fromURL:withError:forWebFrame:));
3057
3058     cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:hasHandler:sourceId:line:forWebFrame:));
3059     if (cache->exceptionWasRaisedFunc)
3060         cache->exceptionWasRaisedExpectsHasHandlerFlag = YES;
3061     else {
3062         cache->exceptionWasRaisedExpectsHasHandlerFlag = NO;
3063         cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:sourceId:line:forWebFrame:));
3064     }
3065 }
3066
3067 - (void)_cacheHistoryDelegateImplementations
3068 {
3069     WebHistoryDelegateImplementationCache *cache = &_private->historyDelegateImplementations;
3070     id delegate = _private->historyDelegate;
3071
3072     if (!delegate) {
3073         bzero(cache, sizeof(WebHistoryDelegateImplementationCache));
3074         return;
3075     }
3076
3077     cache->navigatedFunc = getMethod(delegate, @selector(webView:didNavigateWithNavigationData:inFrame:));
3078     cache->clientRedirectFunc = getMethod(delegate, @selector(webView:didPerformClientRedirectFromURL:toURL:inFrame:));
3079     cache->serverRedirectFunc = getMethod(delegate, @selector(webView:didPerformServerRedirectFromURL:toURL:inFrame:));
3080     cache->deprecatedSetTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:));
3081     cache->setTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:inFrame:));
3082     cache->populateVisitedLinksFunc = getMethod(delegate, @selector(populateVisitedLinksForWebView:));
3083 }
3084
3085 - (id)_policyDelegateForwarder
3086 {
3087 #if PLATFORM(IOS)
3088     if (_private->closing)
3089         return nil;
3090 #endif
3091     if (!_private->policyDelegateForwarder)
3092         _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->policyDelegate defaultTarget:[WebDefaultPolicyDelegate sharedPolicyDelegate]];
3093     return _private->policyDelegateForwarder;
3094 }
3095
3096 - (id)_UIDelegateForwarder
3097 {
3098 #if PLATFORM(IOS)
3099     if (_private->closing)
3100         return nil;
3101 #endif
3102     if (!_private->UIDelegateForwarder)
3103         _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIDelegate defaultTarget:[WebDefaultUIDelegate sharedUIDelegate]];
3104     return _private->UIDelegateForwarder;
3105 }
3106
3107 #if PLATFORM(IOS)
3108 - (id)_UIDelegateForSelector:(SEL)selector
3109 {
3110     id delegate = self->_private->UIDelegate;
3111     if ([delegate respondsToSelector:selector])
3112         return delegate;
3113
3114     delegate = [WebDefaultUIDelegate sharedUIDelegate];
3115     if ([delegate respondsToSelector:selector])
3116         return delegate;
3117
3118     return nil;
3119 }
3120 #endif
3121
3122 - (id)_editingDelegateForwarder
3123 {
3124 #if PLATFORM(IOS)
3125     if (_private->closing)
3126         return nil;
3127 #endif    
3128     // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
3129     // Not sure if that is a bug or not.
3130     if (!_private)
3131         return nil;
3132
3133     if (!_private->editingDelegateForwarder)
3134         _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->editingDelegate defaultTarget:[WebDefaultEditingDelegate sharedEditingDelegate]];
3135     return _private->editingDelegateForwarder;
3136 }
3137
3138 - (void)_closeWindow
3139 {
3140     [[self _UIDelegateForwarder] webViewClose:self];
3141 }
3142
3143 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType
3144 {
3145     [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
3146     [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
3147     
3148     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
3149     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
3150     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
3151     MIMETypeRegistry::getSupportedNonImageMIMETypes().remove(MIMEType);
3152 }
3153
3154 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme
3155 {
3156     NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
3157     [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
3158
3159     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
3160     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
3161     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
3162     if ([viewClass class] == [WebHTMLView class])
3163         MIMETypeRegistry::getSupportedNonImageMIMETypes().add(MIMEType);
3164     
3165     // This is used to make _representationExistsForURLScheme faster.
3166     // Without this set, we'd have to create the MIME type each time.
3167     if (schemesWithRepresentationsSet == nil) {
3168         schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
3169     }
3170     [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
3171 }
3172
3173 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
3174 {
3175     return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
3176 }
3177
3178 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
3179 {
3180     return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
3181 }
3182
3183 + (BOOL)_canHandleRequest:(NSURLRequest *)request forMainFrame:(BOOL)forMainFrame
3184 {
3185     // FIXME: If <rdar://problem/5217309> gets fixed, this check can be removed.
3186     if (!request)
3187         return NO;
3188
3189     if ([NSURLConnection canHandleRequest:request])
3190         return YES;
3191
3192     NSString *scheme = [[request URL] scheme];
3193
3194     // Representations for URL schemes work at the top level.
3195     if (forMainFrame && [self _representationExistsForURLScheme:scheme])
3196         return YES;
3197
3198     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"applewebdata"])
3199         return YES;
3200
3201     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"blob"])
3202         return YES;
3203
3204     return NO;
3205 }
3206
3207 + (BOOL)_canHandleRequest:(NSURLRequest *)request
3208 {
3209     return [self _canHandleRequest:request forMainFrame:YES];
3210 }
3211
3212 + (NSString *)_decodeData:(NSData *)data
3213 {
3214     HTMLNames::init(); // this method is used for importing bookmarks at startup, so HTMLNames are likely to be uninitialized yet
3215     return TextResourceDecoder::create("text/html")->decodeAndFlush(static_cast<const char*>([data bytes]), [data length]); // bookmark files are HTML
3216 }
3217
3218 - (void)_pushPerformingProgrammaticFocus
3219 {
3220     _private->programmaticFocusCount++;
3221 }
3222
3223 - (void)_popPerformingProgrammaticFocus
3224 {
3225     _private->programmaticFocusCount--;
3226 }
3227
3228 - (BOOL)_isPerformingProgrammaticFocus
3229 {
3230     return _private->programmaticFocusCount != 0;
3231 }
3232
3233 #if !PLATFORM(IOS)
3234 - (void)_didChangeValueForKey: (NSString *)key
3235 {
3236     LOG (Bindings, "calling didChangeValueForKey: %@", key);
3237     [self didChangeValueForKey: key];
3238 }
3239
3240 - (void)_willChangeValueForKey: (NSString *)key
3241 {
3242     LOG (Bindings, "calling willChangeValueForKey: %@", key);
3243     [self willChangeValueForKey: key];
3244 }
3245
3246 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
3247     static NSSet *manualNotifyKeys = nil;
3248     if (!manualNotifyKeys)
3249         manualNotifyKeys = [[NSSet alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
3250             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey,
3251             nil];
3252     if ([manualNotifyKeys containsObject:key])
3253         return NO;
3254     return YES;
3255 }
3256
3257 - (NSArray *)_declaredKeys {
3258     static NSArray *declaredKeys = nil;
3259     if (!declaredKeys)
3260         declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
3261             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
3262     return declaredKeys;
3263 }
3264
3265 - (void)_willChangeBackForwardKeys
3266 {
3267     [self _willChangeValueForKey: _WebCanGoBackKey];
3268     [self _willChangeValueForKey: _WebCanGoForwardKey];
3269 }
3270
3271 - (void)_didChangeBackForwardKeys
3272 {
3273     [self _didChangeValueForKey: _WebCanGoBackKey];
3274     [self _didChangeValueForKey: _WebCanGoForwardKey];
3275 }
3276
3277 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
3278 {
3279     if (needsSelfRetainWhileLoadingQuirk())
3280         [self retain];
3281
3282     [self _willChangeBackForwardKeys];
3283     if (frame == [self mainFrame]){
3284         // Force an observer update by sending a will/did.
3285         [self _willChangeValueForKey: _WebIsLoadingKey];
3286         [self _didChangeValueForKey: _WebIsLoadingKey];
3287
3288         [self _willChangeValueForKey: _WebMainFrameURLKey];
3289     }
3290
3291     [NSApp setWindowsNeedUpdate:YES];
3292
3293 #if ENABLE(FULLSCREEN_API)
3294     Document* document = core([frame DOMDocument]);
3295     if (Element* element = document ? document->webkitCurrentFullScreenElement() : 0) {
3296         SEL selector = @selector(webView:closeFullScreenWithListener:);
3297         if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
3298             WebKitFullScreenListener *listener = [[WebKitFullScreenListener alloc] initWithElement:element];
3299             CallUIDelegate(self, selector, listener);
3300             [listener release];
3301         } else if (_private->newFullscreenController && [_private->newFullscreenController isFullScreen]) {
3302             [_private->newFullscreenController close];
3303         }
3304     }
3305 #endif
3306 }
3307
3308 - (void)_checkDidPerformFirstNavigation
3309 {
3310     if (_private->_didPerformFirstNavigation)
3311         return;
3312
3313     Page* page = _private->page;
3314     if (!page)
3315         return;
3316
3317     auto& backForwardController = page->backForward();
3318
3319     if (!backForwardController.backItem())
3320         return;
3321
3322     _private->_didPerformFirstNavigation = YES;
3323
3324     if (_private->preferences.automaticallyDetectsCacheModel && _private->preferences.cacheModel < WebCacheModelDocumentBrowser)
3325         _private->preferences.cacheModel = WebCacheModelDocumentBrowser;
3326 }
3327
3328 - (void)_didCommitLoadForFrame:(WebFrame *)frame
3329 {
3330     if (frame == [self mainFrame])
3331         [self _didChangeValueForKey: _WebMainFrameURLKey];
3332
3333     [self _checkDidPerformFirstNavigation];
3334
3335     [NSApp setWindowsNeedUpdate:YES];
3336 }
3337
3338 - (void)_didFinishLoadForFrame:(WebFrame *)frame
3339 {
3340     if (needsSelfRetainWhileLoadingQuirk())
3341         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3342         
3343     [self _didChangeBackForwardKeys];
3344     if (frame == [self mainFrame]){
3345         // Force an observer update by sending a will/did.
3346         [self _willChangeValueForKey: _WebIsLoadingKey];
3347         [self _didChangeValueForKey: _WebIsLoadingKey];
3348     }
3349     [NSApp setWindowsNeedUpdate:YES];
3350 }
3351
3352 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
3353 {
3354     if (needsSelfRetainWhileLoadingQuirk())
3355         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3356
3357     [self _didChangeBackForwardKeys];
3358     if (frame == [self mainFrame]){
3359         // Force an observer update by sending a will/did.
3360         [self _willChangeValueForKey: _WebIsLoadingKey];
3361         [self _didChangeValueForKey: _WebIsLoadingKey];
3362     }
3363     [NSApp setWindowsNeedUpdate:YES];
3364 }
3365
3366 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
3367 {
3368     if (needsSelfRetainWhileLoadingQuirk())
3369         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3370
3371     [self _didChangeBackForwardKeys];
3372     if (frame == [self mainFrame]){
3373         // Force an observer update by sending a will/did.
3374         [self _willChangeValueForKey: _WebIsLoadingKey];
3375         [self _didChangeValueForKey: _WebIsLoadingKey];
3376         
3377         [self _didChangeValueForKey: _WebMainFrameURLKey];
3378     }
3379     [NSApp setWindowsNeedUpdate:YES];
3380 }
3381
3382 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
3383 {
3384     RetainPtr<NSMutableURLRequest *> request = adoptNS([[NSMutableURLRequest alloc] initWithURL:URL]);
3385     [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
3386     NSCachedURLResponse *cachedResponse;
3387
3388     if (!_private->page)
3389         return nil;
3390
3391     if (CFURLStorageSessionRef storageSession = _private->page->mainFrame().loader().networkingContext()->storageSession().platformSession())
3392         cachedResponse = WKCachedResponseForRequest(storageSession, request.get());
3393     else
3394         cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request.get()];
3395
3396     return cachedResponse;
3397 }
3398
3399 - (void)_writeImageForElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
3400 {
3401     NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
3402     DOMElement *domElement = [element objectForKey:WebElementDOMNodeKey];
3403     [pasteboard _web_writeImage:(NSImage *)(domElement ? nil : [element objectForKey:WebElementImageKey])
3404                         element:domElement
3405                             URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
3406                           title:[element objectForKey:WebElementImageAltStringKey] 
3407                         archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
3408                           types:types
3409                          source:nil];
3410 }
3411
3412 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
3413 {
3414     [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
3415                      andTitle:[element objectForKey:WebElementLinkLabelKey]
3416                         types:types];
3417 }
3418
3419 #if ENABLE(DRAG_SUPPORT)
3420 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
3421 {
3422     if (!_private->page)
3423         return;
3424     _private->page->dragController().setDidInitiateDrag(initiatedDrag);
3425 }
3426 #endif
3427
3428 #else
3429
3430 - (void)_didCommitLoadForFrame:(WebFrame *)frame
3431 {
3432     if (frame == [self mainFrame])
3433         _private->didDrawTiles = 0;
3434 }
3435
3436 #endif // PLATFORM(IOS)
3437
3438 #if ENABLE(DASHBOARD_SUPPORT)
3439
3440 #define DASHBOARD_CONTROL_LABEL @"control"
3441
3442 - (void)_addControlRect:(NSRect)bounds clip:(NSRect)clip fromView:(NSView *)view toDashboardRegions:(NSMutableDictionary *)regions
3443 {
3444     NSRect adjustedBounds = bounds;
3445     adjustedBounds.origin = [self convertPoint:bounds.origin fromView:view];
3446     adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
3447     adjustedBounds.size = bounds.size;
3448
3449     NSRect adjustedClip;
3450     adjustedClip.origin = [self convertPoint:clip.origin fromView:view];
3451     adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
3452     adjustedClip.size = clip.size;
3453
3454     WebDashboardRegion *region = [[WebDashboardRegion alloc] initWithRect:adjustedBounds 
3455         clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle];
3456     NSMutableArray *scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
3457     if (!scrollerRegions) {
3458         scrollerRegions = [[NSMutableArray alloc] init];
3459         [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
3460         [scrollerRegions release];
3461     }
3462     [scrollerRegions addObject:region];
3463     [region release];
3464 }
3465
3466 - (void)_addScrollerDashboardRegionsForFrameView:(FrameView*)frameView dashboardRegions:(NSMutableDictionary *)regions
3467 {    
3468     NSView *documentView = [[kit(&frameView->frame()) frameView] documentView];
3469
3470     for (const auto& widget: frameView->children()) {
3471         if (is<FrameView>(*widget)) {
3472             [self _addScrollerDashboardRegionsForFrameView:downcast<FrameView>(widget.get()) dashboardRegions:regions];
3473             continue;
3474         }
3475
3476         if (!widget->isScrollbar())
3477             continue;
3478
3479         // FIXME: This should really pass an appropriate clip, but our first try got it wrong, and
3480         // it's not common to need this to be correct in Dashboard widgets.
3481         NSRect bounds = widget->frameRect();
3482         [self _addControlRect:bounds clip:bounds fromView:documentView toDashboardRegions:regions];
3483     }
3484 }
3485
3486 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
3487 {
3488     // Add scroller regions for NSScroller and WebCore scrollbars
3489     NSUInteger count = [views count];
3490     for (NSUInteger i = 0; i < count; i++) {
3491         NSView *view = [views objectAtIndex:i];
3492         
3493         if ([view isKindOfClass:[WebHTMLView class]]) {
3494             if (Frame* coreFrame = core([(WebHTMLView*)view _frame])) {
3495                 if (FrameView* coreView = coreFrame->view())
3496                     [self _addScrollerDashboardRegionsForFrameView:coreView dashboardRegions:regions];
3497             }
3498         } else if ([view isKindOfClass:[NSScroller class]]) {
3499             // AppKit places absent scrollers at -100,-100
3500             if ([view frame].origin.y < 0)
3501                 continue;
3502             [self _addControlRect:[view bounds] clip:[view visibleRect] fromView:view toDashboardRegions:regions];
3503         }
3504         [self _addScrollerDashboardRegions:regions from:[view subviews]];
3505     }
3506 }
3507
3508 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
3509 {
3510     [self _addScrollerDashboardRegions:regions from:[self subviews]];
3511 }
3512
3513 - (NSDictionary *)_dashboardRegions
3514 {
3515     // Only return regions from main frame.
3516     Frame* mainFrame = [self _mainCoreFrame];
3517     if (!mainFrame)
3518         return nil;
3519
3520     const Vector<AnnotatedRegionValue>& regions = mainFrame->document()->annotatedRegions();
3521     size_t size = regions.size();
3522
3523     NSMutableDictionary *webRegions = [NSMutableDictionary dictionaryWithCapacity:size];
3524     for (size_t i = 0; i < size; i++) {
3525         const AnnotatedRegionValue& region = regions[i];
3526
3527         if (region.type == StyleDashboardRegion::None)
3528             continue;
3529
3530         NSString *label = region.label;
3531         WebDashboardRegionType type = WebDashboardRegionTypeNone;
3532         if (region.type == StyleDashboardRegion::Circle)
3533             type = WebDashboardRegionTypeCircle;
3534         else if (region.type == StyleDashboardRegion::Rectangle)
3535             type = WebDashboardRegionTypeRectangle;
3536         NSMutableArray *regionValues = [webRegions objectForKey:label];
3537         if (!regionValues) {
3538             regionValues = [[NSMutableArray alloc] initWithCapacity:1];
3539             [webRegions setObject:regionValues forKey:label];
3540             [regionValues release];
3541         }
3542
3543         WebDashboardRegion *webRegion = [[WebDashboardRegion alloc] initWithRect:snappedIntRect(region.bounds) clip:snappedIntRect(region.clip) type:type];
3544         [regionValues addObject:webRegion];
3545         [webRegion release];
3546     }
3547
3548     [self _addScrollerDashboardRegions:webRegions];
3549
3550     return webRegions;
3551 }
3552
3553 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag
3554 {
3555     // FIXME: Remove this blanket assignment once Dashboard and Dashcode implement 
3556     // specific support for the backward compatibility mode flag.
3557     if (behavior == WebDashboardBehaviorAllowWheelScrolling && flag == NO && _private->page)
3558         _private->page->settings().setUsesDashboardBackwardCompatibilityMode(true);
3559     
3560     switch (behavior) {
3561         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3562             _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
3563             break;
3564         }
3565         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3566             _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
3567             break;
3568         }
3569         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3570             _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
3571             break;
3572         }
3573         case WebDashboardBehaviorAllowWheelScrolling: {
3574             _private->dashboardBehaviorAllowWheelScrolling = flag;
3575             break;
3576         }
3577         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3578             if (_private->page)
3579                 _private->page->settings().setUsesDashboardBackwardCompatibilityMode(flag);
3580 #if ENABLE(LEGACY_CSS_VENDOR_PREFIXES)
3581             RuntimeEnabledFeatures::sharedFeatures().setLegacyCSSVendorPrefixesEnabled(flag);
3582 #endif
3583             break;
3584         }
3585     }
3586
3587     // Pre-HTML5 parser quirks should be enabled if Dashboard is in backward
3588     // compatibility mode. See <rdar://problem/8175982>.
3589     if (_private->page)
3590         _private->page->settings().setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
3591 }
3592
3593 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
3594 {
3595     switch (behavior) {
3596         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3597             return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
3598         }
3599         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3600             return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
3601         }
3602         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3603             return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
3604         }
3605         case WebDashboardBehaviorAllowWheelScrolling: {
3606             return _private->dashboardBehaviorAllowWheelScrolling;
3607         }
3608         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3609             return _private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode();
3610         }
3611     }
3612     return NO;
3613 }
3614
3615 #endif /* ENABLE(DASHBOARD_SUPPORT) */
3616
3617 + (void)_setShouldUseFontSmoothing:(BOOL)f
3618 {
3619     FontCascade::setShouldUseSmoothing(f);
3620 }
3621
3622 + (BOOL)_shouldUseFontSmoothing
3623 {
3624     return FontCascade::shouldUseSmoothing();
3625 }
3626
3627 #if !PLATFORM(IOS)
3628 + (void)_setUsesTestModeFocusRingColor:(BOOL)f
3629 {
3630     setUsesTestModeFocusRingColor(f);
3631 }
3632
3633 + (BOOL)_usesTestModeFocusRingColor
3634 {
3635     return usesTestModeFocusRingColor();
3636 }
3637 #endif
3638
3639 #if PLATFORM(IOS)
3640 - (void)_setUIKitDelegate:(id)delegate
3641 {
3642     _private->UIKitDelegate = delegate;
3643     [_private->UIKitDelegateForwarder clearTarget];
3644     [_private->UIKitDelegateForwarder release];
3645     _private->UIKitDelegateForwarder = nil;
3646 }
3647
3648 - (id)_UIKitDelegate
3649 {
3650     return _private->UIKitDelegate;
3651 }
3652
3653 - (void)setWebMailDelegate:(id)delegate
3654 {
3655     _private->WebMailDelegate = delegate;
3656 }
3657
3658 - (id)_webMailDelegate
3659 {
3660     return _private->WebMailDelegate;
3661 }
3662
3663 - (id <WebCaretChangeListener>)caretChangeListener
3664 {
3665     return _private->_caretChangeListener;
3666 }
3667
3668 - (void)setCaretChangeListener:(id <WebCaretChangeListener>)listener
3669 {
3670     _private->_caretChangeListener = listener;
3671 }
3672
3673 - (NSSet *)caretChangeListeners
3674 {
3675     return _private->_caretChangeListeners;
3676 }
3677
3678 - (void)addCaretChangeListener:(id <WebCaretChangeListener>)listener
3679 {
3680     if (_private->_caretChangeListeners == nil) {
3681         _private->_caretChangeListeners = [[NSMutableSet alloc] init];
3682     }
3683     
3684     [_private->_caretChangeListeners addObject:listener];
3685 }
3686
3687 - (void)removeCaretChangeListener:(id <WebCaretChangeListener>)listener
3688 {
3689     [_private->_caretChangeListeners removeObject:listener];
3690 }
3691
3692 - (void)removeAllCaretChangeListeners
3693 {
3694     [_private->_caretChangeListeners removeAllObjects];
3695 }
3696
3697 - (void)caretChanged
3698 {
3699     [_private->_caretChangeListener caretChanged];
3700     NSSet *copy = [_private->_caretChangeListeners copy];
3701     for (id <WebCaretChangeListener> listener in copy) {
3702         [listener caretChanged];
3703     }
3704     [copy release];
3705 }
3706
3707 - (void)_clearDelegates
3708 {
3709     ASSERT(WebThreadIsLocked() || !WebThreadIsEnabled());
3710     
3711     [self _setFormDelegate:nil];
3712     [self _setUIKitDelegate:nil];
3713     [self setCaretChangeListener:nil];
3714     [self removeAllCaretChangeListeners];
3715     [self setWebMailDelegate:nil];
3716     
3717     [self setDownloadDelegate:nil];
3718     [self setEditingDelegate:nil]; 
3719     [self setFrameLoadDelegate:nil];
3720     [self setPolicyDelegate:nil];
3721     [self setResourceLoadDelegate:nil];
3722     [self setScriptDebugDelegate:nil];
3723     [self setUIDelegate:nil];     
3724 }
3725
3726 - (NSURL *)_displayURL
3727 {
3728     WebThreadLock();
3729     WebFrame *frame = [self mainFrame];
3730     // FIXME: <rdar://problem/6362369> We used to get provisionalDataSource here if in provisional state; how do we tell that now? Is this right?
3731     WebDataSource *dataSource = [frame provisionalDataSource];
3732     if (!dataSource)
3733         dataSource = [frame dataSource];
3734     NSURL *unreachableURL = [dataSource unreachableURL];
3735     NSURL *URL = unreachableURL != nil ? unreachableURL : [[dataSource request] URL];
3736     [[URL retain] autorelease];
3737     return URL;
3738 }
3739 #endif // PLATFORM(IOS)
3740
3741 #if !PLATFORM(IOS)
3742 - (void)setAlwaysShowVerticalScroller:(BOOL)flag
3743 {
3744     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3745     if (flag) {
3746         [scrollview setVerticalScrollingMode:ScrollbarAlwaysOn andLock:YES];
3747     } else {
3748         [scrollview setVerticalScrollingModeLocked:NO];
3749         [scrollview setVerticalScrollingMode:ScrollbarAuto andLock:NO];
3750     }
3751 }
3752
3753 - (BOOL)alwaysShowVerticalScroller
3754 {
3755     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3756     return [scrollview verticalScrollingModeLocked] && [scrollview verticalScrollingMode] == ScrollbarAlwaysOn;
3757 }
3758
3759 - (void)setAlwaysShowHorizontalScroller:(BOOL)flag
3760 {
3761     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3762     if (flag) {
3763         [scrollview setHorizontalScrollingMode:ScrollbarAlwaysOn andLock:YES];
3764     } else {
3765         [scrollview setHorizontalScrollingModeLocked:NO];
3766         [scrollview setHorizontalScrollingMode:ScrollbarAuto andLock:NO];
3767     }
3768 }
3769
3770 - (void)setProhibitsMainFrameScrolling:(BOOL)prohibits
3771 {
3772     if (Frame* mainFrame = [self _mainCoreFrame])
3773         mainFrame->view()->setProhibitsScrolling(prohibits);
3774 }
3775
3776 - (BOOL)alwaysShowHorizontalScroller
3777 {
3778     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3779     return [scrollview horizontalScrollingModeLocked] && [scrollview horizontalScrollingMode] == ScrollbarAlwaysOn;
3780 }
3781 #endif // !PLATFORM(IOS)
3782
3783 - (void)_setUseFastImageScalingMode:(BOOL)flag
3784 {
3785     if (_private->page && _private->page->inLowQualityImageInterpolationMode() != flag) {
3786         _private->page->setInLowQualityImageInterpolationMode(flag);
3787         [self setNeedsDisplay:YES];
3788     }
3789 }
3790
3791 - (BOOL)_inFastImageScalingMode
3792 {
3793     if (_private->page)
3794         return _private->page->inLowQualityImageInterpolationMode();
3795     return NO;
3796 }
3797
3798 - (BOOL)_cookieEnabled
3799 {
3800     if (_private->page)
3801         return _private->page->settings().cookieEnabled();
3802     return YES;
3803 }
3804
3805 - (void)_setCookieEnabled:(BOOL)enable
3806 {
3807     if (_private->page)
3808         _private->page->settings().setCookieEnabled(enable);
3809 }
3810
3811 #if !PLATFORM(IOS)
3812 - (void)_setAdditionalWebPlugInPaths:(NSArray *)newPaths
3813 {
3814     if (!_private->pluginDatabase)
3815         _private->pluginDatabase = [[WebPluginDatabase alloc] init];
3816         
3817     [_private->pluginDatabase setPlugInPaths:newPaths];
3818     [_private->pluginDatabase refresh];
3819 }
3820 #endif
3821
3822 #if PLATFORM(IOS)
3823 - (BOOL)_locked_plugInsAreRunningInFrame:(WebFrame *)frame
3824 {
3825     // Ask plug-ins in this frame
3826     id <WebDocumentView> documentView = [[frame frameView] documentView];
3827     if (documentView && [documentView isKindOfClass:[WebHTMLView class]]) {
3828         if ([[(WebHTMLView *)documentView _pluginController] plugInsAreRunning])
3829             return YES;
3830     }
3831
3832     // Ask plug-ins in child frames
3833     NSArray *childFrames = [frame childFrames];
3834     unsigned childCount = [childFrames count];
3835     unsigned childIndex;
3836     for (childIndex = 0; childIndex < childCount; childIndex++) {
3837         if ([self _locked_plugInsAreRunningInFrame:[childFrames objectAtIndex:childIndex]])
3838             return YES;
3839     }
3840     
3841     return NO;
3842 }
3843
3844 - (BOOL)_pluginsAreRunning
3845 {
3846     WebThreadLock();
3847     return [self _locked_plugInsAreRunningInFrame:[self mainFrame]];
3848 }
3849
3850 - (void)_locked_recursivelyPerformPlugInSelector:(SEL)selector inFrame:(WebFrame *)frame
3851 {
3852     // Send the message to plug-ins in this frame
3853     id <WebDocumentView> documentView = [[frame frameView] documentView];
3854     if (documentView && [documentView isKindOfClass:[WebHTMLView class]])
3855         [[(WebHTMLView *)documentView _pluginController] performSelector:selector];
3856
3857     // Send the message to plug-ins in child frames
3858     NSArray *childFrames = [frame childFrames];
3859     unsigned childCount = [childFrames count];
3860     unsigned childIndex;
3861     for (childIndex = 0; childIndex < childCount; childIndex++) {
3862         [self _locked_recursivelyPerformPlugInSelector:selector inFrame:[childFrames objectAtIndex:childIndex]];
3863     }
3864 }
3865
3866 - (void)_destroyAllPlugIns
3867 {
3868     WebThreadLock();
3869     [self _locked_recursivelyPerformPlugInSelector:@selector(destroyAllPlugins) inFrame:[self mainFrame]];
3870 }
3871
3872 - (void)_startAllPlugIns
3873 {
3874     WebThreadLock();
3875     [self _locked_recursivelyPerformPlugInSelector:@selector(startAllPlugins) inFrame:[self mainFrame]];
3876 }
3877
3878 - (void)_stopAllPlugIns
3879 {
3880     WebThreadLock();
3881     [self _locked_recursivelyPerformPlugInSelector:@selector(stopAllPlugins) inFrame:[self mainFrame]];
3882 }
3883
3884 - (void)_stopAllPlugInsForPageCache
3885 {
3886     WebThreadLock();
3887     [self _locked_recursivelyPerformPlugInSelector:@selector(stopPluginsForPageCache) inFrame:[self mainFrame]];
3888 }
3889
3890 - (void)_restorePlugInsFromCache
3891 {
3892     WebThreadLock();
3893     [self _locked_recursivelyPerformPlugInSelector:@selector(restorePluginsFromCache) inFrame:[self mainFrame]];
3894 }
3895
3896 - (BOOL)_setMediaLayer:(CALayer*)layer forPluginView:(NSView*)pluginView
3897 {
3898     WebThreadLock();
3899
3900     Frame* mainCoreFrame = [self _mainCoreFrame];
3901     for (Frame* frame = mainCoreFrame; frame; frame = frame->tree().traverseNext()) {
3902         FrameView* coreView = frame ? frame->view() : 0;
3903         if (!coreView)
3904             continue;
3905
3906         // Get the GraphicsLayer for this widget.
3907         GraphicsLayer* layerForWidget = coreView->graphicsLayerForPlatformWidget(pluginView);
3908         if (!layerForWidget)
3909             continue;
3910         
3911         if (layerForWidget->contentsLayerForMedia() != layer) {
3912             layerForWidget->setContentsToPlatformLayer(layer, GraphicsLayer::ContentsLayerForMedia);
3913             // We need to make sure the layer hierachy change is applied immediately.
3914             if (mainCoreFrame->view())
3915                 mainCoreFrame->view()->flushCompositingStateIncludingSubframes();
3916             return YES;
3917         }
3918     }
3919
3920     return NO;
3921 }
3922
3923 - (void)_setNeedsUnrestrictedGetMatchedCSSRules:(BOOL)flag
3924 {
3925     if (_private->page)
3926         _private->page->settings().setCrossOriginCheckInGetMatchedCSSRulesDisabled(flag);
3927 }
3928 #endif // PLATFORM(IOS)
3929
3930 - (void)_attachScriptDebuggerToAllFrames
3931 {
3932     for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext())
3933         [kit(frame) _attachScriptDebugger];
3934 }
3935
3936 - (void)_detachScriptDebuggerFromAllFrames
3937 {
3938     for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext())
3939         [kit(frame) _detachScriptDebugger];
3940 }
3941
3942 #if !PLATFORM(IOS)
3943 - (void)setBackgroundColor:(NSColor *)backgroundColor
3944 {
3945     if ([_private->backgroundColor isEqual:backgroundColor])
3946         return;
3947
3948     id old = _private->backgroundColor;
3949     _private->backgroundColor = [backgroundColor retain];
3950     [old release];
3951
3952     [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
3953 }
3954
3955 - (NSColor *)backgroundColor
3956 {
3957     return _private->backgroundColor;
3958 }
3959 #else
3960 - (void)setBackgroundColor:(CGColorRef)backgroundColor
3961 {
3962    if (!backgroundColor || CFEqual(_private->backgroundColor, backgroundColor))
3963         return;
3964
3965     CFTypeRef old = _private->backgroundColor;
3966     CFRetain(backgroundColor);
3967     _private->backgroundColor = backgroundColor;
3968     CFRelease(old);
3969
3970     [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
3971 }
3972
3973 - (CGColorRef)backgroundColor
3974 {
3975     return _private->backgroundColor;
3976 }
3977 #endif
3978
3979 - (BOOL)defersCallbacks
3980 {
3981     if (!_private->page)
3982         return NO;
3983     return _private->page->defersLoading();
3984 }
3985
3986 - (void)setDefersCallbacks:(BOOL)defer
3987 {
3988     if (!_private->page)
3989         return;
3990     return _private->page->setDefersLoading(defer);
3991 }
3992
3993 #if PLATFORM(IOS)
3994 - (NSDictionary *)quickLookContentForURL:(NSURL *)url
3995 {
3996 #if USE(QUICK_LOOK)
3997     NSString *uti = qlPreviewConverterUTIForURL(url);
3998     if (!uti)
3999         return nil;
4000
4001     NSString *fileName = qlPreviewConverterFileNameForURL(url);
4002     if (!fileName)
4003         return nil;
4004
4005     return [NSDictionary dictionaryWithObjectsAndKeys: fileName, WebQuickLookFileNameKey, uti, WebQuickLookUTIKey, nil];
4006 #else
4007     return nil;
4008 #endif
4009 }
4010
4011 - (BOOL)_isStopping
4012 {
4013     return _private->isStopping;
4014 }
4015
4016 - (BOOL)_isClosing
4017 {
4018     return _private->closing;
4019 }
4020
4021 + (NSArray *)_productivityDocumentMIMETypes
4022 {
4023 #if USE(QUICK_LOOK)
4024     return [QLPreviewGetSupportedMIMETypesSet() allObjects];
4025 #else
4026     return nil;
4027 #endif
4028 }
4029
4030 - (void)_setAllowsMessaging:(BOOL)aFlag
4031 {
4032     _private->allowsMessaging = aFlag;
4033 }
4034
4035 - (BOOL)_allowsMessaging
4036 {
4037     return _private->allowsMessaging;
4038 }
4039
4040 - (void)_setFixedLayoutSize:(CGSize)size
4041 {
4042     ASSERT(WebThreadIsLocked());
4043     _private->fixedLayoutSize = size;
4044     if (Frame* mainFrame = core([self mainFrame])) {
4045         IntSize newSize(size);
4046         mainFrame->view()->setFixedLayoutSize(newSize);
4047         mainFrame->view()->setUseFixedLayout(!newSize.isEmpty());
4048         [self setNeedsDisplay:YES];
4049     }
4050 }
4051
4052 - (CGSize)_fixedLayoutSize
4053 {
4054     return _private->fixedLayoutSize;
4055 }
4056
4057 - (void)_synchronizeCustomFixedPositionLayoutRect
4058 {
4059     ASSERT(WebThreadIsLocked());
4060
4061     IntRect newRect;
4062     {
4063         LockHolder locker(_private->pendingFixedPositionLayoutRectMutex);
4064         if (CGRectIsNull(_private->pendingFixedPositionLayoutRect))
4065             return;
4066         newRect = enclosingIntRect(_private->pendingFixedPositionLayoutRect);
4067         _private->pendingFixedPositionLayoutRect = CGRectNull;
4068     }
4069
4070     if (Frame* mainFrame = core([self mainFrame]))
4071         mainFrame->view()->setCustomFixedPositionLayoutRect(newRect);
4072 }
4073
4074 - (void)_setCustomFixedPositionLayoutRectInWebThread:(CGRect)rect synchronize:(BOOL)synchronize
4075 {
4076     {
4077         LockHolder locker(_private->pendingFixedPositionLayoutRectMutex);
4078         _private->pendingFixedPositionLayoutRect = rect;
4079     }
4080     if (!synchronize)
4081         return;
4082     WebThreadRun(^{
4083         [self _synchronizeCustomFixedPositionLayoutRect];
4084     });
4085 }
4086
4087 - (void)_setCustomFixedPositionLayoutRect:(CGRect)rect
4088 {
4089     ASSERT(WebThreadIsLocked());
4090     {
4091         LockHolder locker(_private->pendingFixedPositionLayoutRectMutex);
4092         _private->pendingFixedPositionLayoutRect = rect;
4093     }
4094     [self _synchronizeCustomFixedPositionLayoutRect];
4095 }
4096
4097 - (BOOL)_fetchCustomFixedPositionLayoutRect:(NSRect*)rect
4098 {
4099     LockHolder locker(_private->pendingFixedPositionLayoutRectMutex);
4100     if (CGRectIsNull(_private->pendingFixedPositionLayoutRect))
4101         return false;
4102
4103     *rect = _private->pendingFixedPositionLayoutRect;
4104     _private->pendingFixedPositionLayoutRect = CGRectNull;
4105     return true;
4106 }
4107
4108 - (void)_viewGeometryDidChange
4109 {
4110     ASSERT(WebThreadIsLocked());
4111     
4112     if (Frame* coreFrame = [self _mainCoreFrame])
4113         coreFrame->viewportOffsetChanged(Frame::IncrementalScrollOffset);
4114 }
4115
4116 - (void)_overflowScrollPositionChangedTo:(CGPoint)offset forNode:(DOMNode *)domNode isUserScroll:(BOOL)userScroll
4117 {
4118     // Find the frame
4119     Node* node = core(domNode);
4120     Frame* frame = node->document().frame();
4121     if (!frame)
4122         return;
4123
4124     frame->overflowScrollPositionChangedForNode(roundedIntPoint(offset), node, userScroll);
4125 }
4126
4127 + (void)_doNotStartObservingNetworkReachability
4128 {
4129     Settings::setShouldOptOutOfNetworkStateObservation(true);
4130 }
4131 #endif // PLATFORM(IOS)
4132
4133 #if ENABLE(TOUCH_EVENTS)
4134 - (NSArray *)_touchEventRegions
4135 {
4136     Frame* frame = [self _mainCoreFrame];
4137     if (!frame)
4138         return nil;
4139     
4140     Document* document = frame->document();
4141     if (!document)
4142         return nil;
4143
4144     Vector<IntRect> rects;
4145     document->getTouchRects(rects);
4146
4147     if (rects.size() == 0)
4148         return nil;
4149
4150     NSMutableArray *eventRegionArray = [[[NSMutableArray alloc] initWithCapacity:rects.size()] autorelease];
4151
4152     NSView <WebDocumentView> *documentView = [[[self mainFrame] frameView] documentView];
4153     Vector<IntRect>::const_iterator end = rects.end();
4154     for (Vector<IntRect>::const_iterator it = rects.begin(); it != end; ++it) {
4155         const IntRect& rect = *it;
4156         if (rect.isEmpty())
4157             continue;
4158
4159         // The touch rectangles are in the coordinate system of the document (inside the WebHTMLView), which is not
4160         // the same as the coordinate system of the WebView. UIWebView currently expects view coordinates, so we'll
4161         // convert them here now.
4162         IntRect viewRect = IntRect([documentView convertRect:rect toView:self]);
4163
4164         // The event region wants this points in this order:
4165         //  p2------p3
4166         //  |       |
4167         //  p1------p4
4168         //
4169         WebEventRegion *eventRegion = [[WebEventRegion alloc] initWithPoints:FloatPoint(viewRect.x(), viewRect.maxY())
4170                                                                             :FloatPoint(viewRect.x(), viewRect.y())
4171                                                                             :FloatPoint(viewRect.maxX(), viewRect.y())
4172                                                                             :FloatPoint(viewRect.maxX(), viewRect.maxY())];
4173         if (eventRegion) {
4174             [eventRegionArray addObject:eventRegion];
4175             [eventRegion release];
4176         }
4177     }
4178
4179     return eventRegionArray;
4180 }
4181 #endif // ENABLE(TOUCH_EVENTS)
4182
4183 // For backwards compatibility with the WebBackForwardList API, we honor both
4184 // a per-WebView and a per-preferences setting for whether to use the page cache.
4185
4186 - (BOOL)usesPageCache
4187 {
4188     return _private->usesPageCache && [[self preferences] usesPageCache];
4189 }
4190
4191 - (void)setUsesPageCache:(BOOL)usesPageCache
4192 {
4193     _private->usesPageCache = usesPageCache;
4194
4195     // Update our own settings and post the public notification only
4196     [self _preferencesChanged:[self preferences]];
4197     [[self preferences] _postPreferencesChangedAPINotification];
4198 }
4199
4200 - (WebHistoryItem *)_globalHistoryItem
4201 {
4202     if (!_private)
4203         return nil;
4204
4205     return kit(_private->_globalHistoryItem.get());
4206 }
4207
4208 - (void)_setGlobalHistoryItem:(HistoryItem*)historyItem
4209 {
4210     _private->_globalHistoryItem = historyItem;
4211 }
4212
4213 - (WebTextIterator *)textIteratorForRect:(NSRect)rect
4214 {
4215     IntPoint rectStart(rect.origin.x, rect.origin.y);
4216     IntPoint rectEnd(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height);
4217     
4218     Frame* coreFrame = [self _mainCoreFrame];
4219     if (!coreFrame)
4220         return nil;
4221     
4222     VisibleSelection selectionInsideRect(coreFrame->visiblePositionForPoint(rectStart), coreFrame->visiblePositionForPoint(rectEnd));
4223     
4224     return [[[WebTextIterator alloc] initWithRange:kit(selectionInsideRect.toNormalizedRange().get())] autorelease];
4225 }
4226
4227 #if !PLATFORM(IOS)
4228 - (void)_clearUndoRedoOperations
4229 {
4230     if (!_private->page)
4231         return;
4232     _private->page->clearUndoRedoOperations();
4233 }
4234 #endif
4235
4236 - (void)_executeCoreCommandByName:(NSString *)name value:(NSString *)value
4237 {
4238     Frame* coreFrame = [self _mainCoreFrame];
4239     if (!coreFrame)
4240         return;
4241     coreFrame->editor().command(name).execute(value);
4242 }
4243
4244 - (void)_clearMainFrameName
4245 {
4246     _private->page->mainFrame().tree().clearName();
4247 }
4248
4249 - (void)setSelectTrailingWhitespaceEnabled:(BOOL)flag
4250 {
4251     if (_private->page->settings().selectTrailingWhitespaceEnabled() != flag) {
4252         _private->page->settings().setSelectTrailingWhitespaceEnabled(flag);
4253         [self setSmartInsertDeleteEnabled:!flag];
4254     }
4255 }
4256
4257 - (BOOL)isSelectTrailingWhitespaceEnabled
4258 {
4259     return _private->page->settings().selectTrailingWhitespaceEnabled();
4260 }
4261
4262 - (void)setMemoryCacheDelegateCallsEnabled:(BOOL)enabled
4263 {
4264     _private->page->setMemoryCacheClientCallsEnabled(enabled);