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