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