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