Get rid of WebCore IconDatabase code.
[WebKit-https.git] / Source / WebKitLegacy / mac / WebView / WebView.mm
1 /*
2  * Copyright (C) 2005-2017 Apple Inc. All rights reserved.
3  * Copyright (C) 2006 David Smith (catfish.man@gmail.com)
4  * Copyright (C) 2010 Igalia S.L
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1.  Redistributions of source code must retain the above copyright
11  *     notice, this list of conditions and the following disclaimer. 
12  * 2.  Redistributions in binary form must reproduce the above copyright
13  *     notice, this list of conditions and the following disclaimer in the
14  *     documentation and/or other materials provided with the distribution. 
15  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
16  *     its contributors may be used to endorse or promote products derived
17  *     from this software without specific prior written permission. 
18  *
19  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
20  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
23  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #import "WebViewInternal.h"
32 #import "WebViewData.h"
33
34 #import "BackForwardList.h"
35 #import "DOMCSSStyleDeclarationInternal.h"
36 #import "DOMDocumentInternal.h"
37 #import "DOMInternal.h"
38 #import "DOMNodeInternal.h"
39 #import "DOMRangeInternal.h"
40 #import "StorageThread.h"
41 #import "WebAlternativeTextClient.h"
42 #import "WebApplicationCacheInternal.h"
43 #import "WebArchive.h"
44 #import "WebBackForwardListInternal.h"
45 #import "WebBaseNetscapePluginView.h"
46 #import "WebCache.h"
47 #import "WebChromeClient.h"
48 #import "WebDOMOperationsPrivate.h"
49 #import "WebDataSourceInternal.h"
50 #import "WebDatabaseManagerPrivate.h"
51 #import "WebDatabaseProvider.h"
52 #import "WebDefaultEditingDelegate.h"
53 #import "WebDefaultPolicyDelegate.h"
54 #import "WebDefaultUIDelegate.h"
55 #import "WebDelegateImplementationCaching.h"
56 #import "WebDeviceOrientationClient.h"
57 #import "WebDeviceOrientationProvider.h"
58 #import "WebDocument.h"
59 #import "WebDocumentInternal.h"
60 #import "WebDownload.h"
61 #import "WebDownloadInternal.h"
62 #import "WebDragClient.h"
63 #import "WebDynamicScrollBarsViewInternal.h"
64 #import "WebEditingDelegate.h"
65 #import "WebEditorClient.h"
66 #import "WebFormDelegatePrivate.h"
67 #import "WebFrameInternal.h"
68 #import "WebFrameLoaderClient.h"
69 #import "WebFrameNetworkingContext.h"
70 #import "WebFrameViewInternal.h"
71 #import "WebGeolocationClient.h"
72 #import "WebGeolocationPositionInternal.h"
73 #import "WebHTMLRepresentation.h"
74 #import "WebHTMLViewInternal.h"
75 #import "WebHistoryItemInternal.h"
76 #import "WebIconDatabase.h"
77 #import "WebInspector.h"
78 #import "WebInspectorClient.h"
79 #import "WebKitErrors.h"
80 #import "WebKitFullScreenListener.h"
81 #import "WebKitLogging.h"
82 #import "WebKitNSStringExtras.h"
83 #import "WebKitStatisticsPrivate.h"
84 #import "WebKitVersionChecks.h"
85 #import "WebLocalizableStrings.h"
86 #import "WebNSDataExtras.h"
87 #import "WebNSDataExtrasPrivate.h"
88 #import "WebNSDictionaryExtras.h"
89 #import "WebNSURLExtras.h"
90 #import "WebNSURLRequestExtras.h"
91 #import "WebNSViewExtras.h"
92 #import "WebNodeHighlight.h"
93 #import "WebNotificationClient.h"
94 #import "WebPDFView.h"
95 #import "WebPaymentCoordinatorClient.h"
96 #import "WebPlatformStrategies.h"
97 #import "WebPluginDatabase.h"
98 #import "WebPluginInfoProvider.h"
99 #import "WebPolicyDelegate.h"
100 #import "WebPreferenceKeysPrivate.h"
101 #import "WebPreferencesPrivate.h"
102 #import "WebProgressTrackerClient.h"
103 #import "WebResourceLoadScheduler.h"
104 #import "WebScriptDebugDelegate.h"
105 #import "WebScriptWorldInternal.h"
106 #import "WebSelectionServiceController.h"
107 #import "WebStorageManagerInternal.h"
108 #import "WebStorageNamespaceProvider.h"
109 #import "WebSystemInterface.h"
110 #import "WebTextCompletionController.h"
111 #import "WebTextIterator.h"
112 #import "WebUIDelegate.h"
113 #import "WebUIDelegatePrivate.h"
114 #import "WebUserMediaClient.h"
115 #import "WebValidationMessageClient.h"
116 #import "WebViewGroup.h"
117 #import "WebVisitedLinkStore.h"
118 #import <CoreFoundation/CFSet.h>
119 #import <Foundation/NSURLConnection.h>
120 #import <JavaScriptCore/APICast.h>
121 #import <JavaScriptCore/Exception.h>
122 #import <JavaScriptCore/JSValueRef.h>
123 #import <WebCore/AlternativeTextUIController.h>
124 #import <WebCore/ApplicationCacheStorage.h>
125 #import <WebCore/BackForwardController.h>
126 #import <WebCore/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/JSCSSStyleDeclaration.h>
158 #import <WebCore/JSDocument.h>
159 #import <WebCore/JSElement.h>
160 #import <WebCore/JSNodeList.h>
161 #import <WebCore/JSNotification.h>
162 #import <WebCore/LibWebRTCProvider.h>
163 #import <WebCore/LocalizedStrings.h>
164 #import <WebCore/LogInitialization.h>
165 #import <WebCore/MIMETypeRegistry.h>
166 #import <WebCore/MainFrame.h>
167 #import <WebCore/MemoryCache.h>
168 #import <WebCore/MemoryRelease.h>
169 #import <WebCore/NSSpellCheckerSPI.h>
170 #import <WebCore/NSTouchBarSPI.h>
171 #import <WebCore/NSURLFileTypeMappingsSPI.h>
172 #import <WebCore/NetworkStorageSession.h>
173 #import <WebCore/NodeList.h>
174 #import <WebCore/Notification.h>
175 #import <WebCore/NotificationController.h>
176 #import <WebCore/Page.h>
177 #import <WebCore/PageCache.h>
178 #import <WebCore/PageConfiguration.h>
179 #import <WebCore/PageGroup.h>
180 #import <WebCore/PathUtilities.h>
181 #import <WebCore/PlatformEventFactoryMac.h>
182 #import <WebCore/ProgressTracker.h>
183 #import <WebCore/RenderView.h>
184 #import <WebCore/RenderWidget.h>
185 #import <WebCore/ResourceHandle.h>
186 #import <WebCore/ResourceLoadObserver.h>
187 #import <WebCore/ResourceRequest.h>
188 #import <WebCore/RuntimeApplicationChecks.h>
189 #import <WebCore/RuntimeEnabledFeatures.h>
190 #import <WebCore/SchemeRegistry.h>
191 #import <WebCore/ScriptController.h>
192 #import <WebCore/SecurityOrigin.h>
193 #import <WebCore/SecurityPolicy.h>
194 #import <WebCore/Settings.h>
195 #import <WebCore/SocketProvider.h>
196 #import <WebCore/StyleProperties.h>
197 #import <WebCore/TextResourceDecoder.h>
198 #import <WebCore/ThreadCheck.h>
199 #import <WebCore/UserAgent.h>
200 #import <WebCore/UserContentController.h>
201 #import <WebCore/UserScript.h>
202 #import <WebCore/UserStyleSheet.h>
203 #import <WebCore/ValidationBubble.h>
204 #import <WebCore/WebCoreObjCExtras.h>
205 #import <WebCore/WebCoreView.h>
206 #import <WebCore/Widget.h>
207 #import <WebKitLegacy/DOM.h>
208 #import <WebKitLegacy/DOMExtensions.h>
209 #import <WebKitLegacy/DOMPrivate.h>
210 #import <WebKitSystemInterface.h>
211 #import <bindings/ScriptValue.h>
212 #import <mach-o/dyld.h>
213 #import <objc/runtime.h>
214 #import <runtime/ArrayPrototype.h>
215 #import <runtime/CatchScope.h>
216 #import <runtime/DateInstance.h>
217 #import <runtime/InitializeThreading.h>
218 #import <runtime/JSCJSValue.h>
219 #import <runtime/JSLock.h>
220 #import <wtf/Assertions.h>
221 #import <wtf/HashTraits.h>
222 #import <wtf/MainThread.h>
223 #import <wtf/ObjcRuntimeExtras.h>
224 #import <wtf/RAMSize.h>
225 #import <wtf/RefCountedLeakCounter.h>
226 #import <wtf/RefPtr.h>
227 #import <wtf/RunLoop.h>
228 #import <wtf/SetForScope.h>
229 #import <wtf/SoftLinking.h>
230 #import <wtf/StdLibExtras.h>
231 #import <wtf/WorkQueue.h>
232 #import <wtf/spi/darwin/dyldSPI.h>
233
234 #if !PLATFORM(IOS)
235 #import "WebContextMenuClient.h"
236 #import "WebFullScreenController.h"
237 #import "WebImmediateActionController.h"
238 #import "WebNSEventExtras.h"
239 #import "WebNSObjectExtras.h"
240 #import "WebNSPasteboardExtras.h"
241 #import "WebNSPrintOperationExtras.h"
242 #import "WebPDFView.h"
243 #import <WebCore/AVKitSPI.h>
244 #import <WebCore/LookupSPI.h>
245 #import <WebCore/NSImmediateActionGestureRecognizerSPI.h>
246 #import <WebCore/TextIndicator.h>
247 #import <WebCore/TextIndicatorWindow.h>
248 #import <WebCore/WebVideoFullscreenController.h>
249 #else
250 #import "MemoryMeasure.h"
251 #import "WebCaretChangeListener.h"
252 #import "WebChromeClientIOS.h"
253 #import "WebDefaultFormDelegate.h"
254 #import "WebDefaultFrameLoadDelegate.h"
255 #import "WebDefaultResourceLoadDelegate.h"
256 #import "WebDefaultUIKitDelegate.h"
257 #import "WebFixedPositionContent.h"
258 #import "WebMailDelegate.h"
259 #import "WebNSUserDefaultsExtras.h"
260 #import "WebPDFViewIOS.h"
261 #import "WebPlainWhiteView.h"
262 #import "WebPluginController.h"
263 #import "WebPolicyDelegatePrivate.h"
264 #import "WebStorageManagerPrivate.h"
265 #import "WebUIKitSupport.h"
266 #import "WebVisiblePosition.h"
267 #import <WebCore/EventNames.h>
268 #import <WebCore/FontCache.h>
269 #import <WebCore/GraphicsLayer.h>
270 #import <WebCore/LegacyTileCache.h>
271 #import <WebCore/MobileGestaltSPI.h>
272 #import <WebCore/PlatformScreen.h>
273 #import <WebCore/ResourceLoadStatistics.h>
274 #import <WebCore/SQLiteDatabaseTracker.h>
275 #import <WebCore/SmartReplace.h>
276 #import <WebCore/TileControllerMemoryHandlerIOS.h>
277 #import <WebCore/WAKWindow.h>
278 #import <WebCore/WKView.h>
279 #import <WebCore/WebCoreThread.h>
280 #import <WebCore/WebCoreThreadMessage.h>
281 #import <WebCore/WebCoreThreadRun.h>
282 #import <WebCore/WebEvent.h>
283 #import <WebCore/WebSQLiteDatabaseTrackerClient.h>
284 #import <WebCore/WebVideoFullscreenControllerAVKit.h>
285 #import <libkern/OSAtomic.h>
286 #import <wtf/FastMalloc.h>
287 #endif
288
289 #if ENABLE(DASHBOARD_SUPPORT)
290 #import <WebKitLegacy/WebDashboardRegion.h>
291 #endif
292
293 #if ENABLE(REMOTE_INSPECTOR)
294 #import <JavaScriptCore/RemoteInspector.h>
295 #if PLATFORM(IOS)
296 #import "WebIndicateLayer.h"
297 #endif
298 #endif
299
300 #if USE(QUICK_LOOK)
301 #include <WebCore/QuickLook.h>
302 #endif
303
304 #if ENABLE(IOS_TOUCH_EVENTS)
305 #import <WebCore/WebEventRegion.h>
306 #endif
307
308 #if ENABLE(GAMEPAD)
309 #import <WebCore/HIDGamepadProvider.h>
310 #endif
311
312 #if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS)
313 #import "WebMediaPlaybackTargetPicker.h"
314 #import <WebCore/WebMediaSessionManagerMac.h>
315 #endif
316
317
318 #if PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE)
319 #import <WebCore/WebPlaybackSessionInterfaceMac.h>
320 #import <WebCore/WebPlaybackSessionModelMediaElement.h>
321 #endif
322
323 #if ENABLE(DATA_INTERACTION)
324 #import <UIKit/UIBezierPath.h>
325 #import <UIKit/UIColor.h>
326 #import <UIKit/UIImage.h>
327 SOFT_LINK_FRAMEWORK(UIKit)
328 SOFT_LINK_CLASS(UIKit, UIBezierPath)
329 SOFT_LINK_CLASS(UIKit, UIColor)
330 SOFT_LINK_CLASS(UIKit, UIImage)
331 SOFT_LINK(UIKit, UIGraphicsBeginImageContextWithOptions, void, (CGSize size, BOOL opaque, CGFloat scale), (size, opaque, scale))
332 SOFT_LINK(UIKit, UIGraphicsGetCurrentContext, CGContextRef, (void), ())
333 SOFT_LINK(UIKit, UIGraphicsGetImageFromCurrentImageContext, UIImage *, (void), ())
334 SOFT_LINK(UIKit, UIGraphicsEndImageContext, void, (void), ())
335 #endif
336
337 #if HAVE(TOUCH_BAR) && ENABLE(WEB_PLAYBACK_CONTROLS_MANAGER)
338 SOFT_LINK_FRAMEWORK(AVKit)
339 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300
340 SOFT_LINK_CLASS(AVKit, AVTouchBarPlaybackControlsProvider)
341 SOFT_LINK_CLASS(AVKit, AVTouchBarScrubber)
342 #else
343 SOFT_LINK_CLASS(AVKit, AVFunctionBarPlaybackControlsProvider)
344 SOFT_LINK_CLASS(AVKit, AVFunctionBarScrubber)
345 #endif // __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300
346 #endif // HAVE(TOUCH_BAR) && ENABLE(WEB_PLAYBACK_CONTROLS_MANAGER)
347
348 #if PLATFORM(MAC)
349 SOFT_LINK_CONSTANT_MAY_FAIL(Lookup, LUNotificationPopoverWillClose, NSString *)
350 #endif
351
352 #if !PLATFORM(IOS)
353
354 @interface NSSpellChecker (WebNSSpellCheckerDetails)
355 - (void)_preflightChosenSpellServer;
356 @end
357
358 @interface NSView (WebNSViewDetails)
359 - (NSView *)_hitTest:(NSPoint *)aPoint dragTypes:(NSSet *)types;
360 - (void)_autoscrollForDraggingInfo:(id)dragInfo timeDelta:(NSTimeInterval)repeatDelta;
361 - (BOOL)_shouldAutoscrollForDraggingInfo:(id)dragInfo;
362 - (void)_windowChangedKeyState;
363 @end
364
365 @interface NSWindow (WebNSWindowDetails)
366 - (id)_oldFirstResponderBeforeBecoming;
367 - (void)_enableScreenUpdatesIfNeeded;
368 - (BOOL)_wrapsCarbonWindow;
369 - (BOOL)_hasKeyAppearance;
370 @end
371
372 #endif
373
374 using namespace JSC;
375 using namespace Inspector;
376 using namespace WebCore;
377
378 #define FOR_EACH_RESPONDER_SELECTOR(macro) \
379 macro(alignCenter) \
380 macro(alignJustified) \
381 macro(alignLeft) \
382 macro(alignRight) \
383 macro(capitalizeWord) \
384 macro(centerSelectionInVisibleArea) \
385 macro(changeAttributes) \
386 macro(changeBaseWritingDirection) \
387 macro(changeBaseWritingDirectionToLTR) \
388 macro(changeBaseWritingDirectionToRTL) \
389 macro(changeColor) \
390 macro(changeDocumentBackgroundColor) \
391 macro(changeFont) \
392 macro(changeSpelling) \
393 macro(checkSpelling) \
394 macro(complete) \
395 macro(copy) \
396 macro(copyFont) \
397 macro(cut) \
398 macro(delete) \
399 macro(deleteBackward) \
400 macro(deleteBackwardByDecomposingPreviousCharacter) \
401 macro(deleteForward) \
402 macro(deleteToBeginningOfLine) \
403 macro(deleteToBeginningOfParagraph) \
404 macro(deleteToEndOfLine) \
405 macro(deleteToEndOfParagraph) \
406 macro(deleteToMark) \
407 macro(deleteWordBackward) \
408 macro(deleteWordForward) \
409 macro(ignoreSpelling) \
410 macro(indent) \
411 macro(insertBacktab) \
412 macro(insertLineBreak) \
413 macro(insertNewline) \
414 macro(insertNewlineIgnoringFieldEditor) \
415 macro(insertParagraphSeparator) \
416 macro(insertTab) \
417 macro(insertTabIgnoringFieldEditor) \
418 macro(lowercaseWord) \
419 macro(makeBaseWritingDirectionLeftToRight) \
420 macro(makeBaseWritingDirectionRightToLeft) \
421 macro(makeTextWritingDirectionLeftToRight) \
422 macro(makeTextWritingDirectionNatural) \
423 macro(makeTextWritingDirectionRightToLeft) \
424 macro(moveBackward) \
425 macro(moveBackwardAndModifySelection) \
426 macro(moveDown) \
427 macro(moveDownAndModifySelection) \
428 macro(moveForward) \
429 macro(moveForwardAndModifySelection) \
430 macro(moveLeft) \
431 macro(moveLeftAndModifySelection) \
432 macro(moveParagraphBackwardAndModifySelection) \
433 macro(moveParagraphForwardAndModifySelection) \
434 macro(moveRight) \
435 macro(moveRightAndModifySelection) \
436 macro(moveToBeginningOfDocument) \
437 macro(moveToBeginningOfDocumentAndModifySelection) \
438 macro(moveToBeginningOfLine) \
439 macro(moveToBeginningOfLineAndModifySelection) \
440 macro(moveToBeginningOfParagraph) \
441 macro(moveToBeginningOfParagraphAndModifySelection) \
442 macro(moveToBeginningOfSentence) \
443 macro(moveToBeginningOfSentenceAndModifySelection) \
444 macro(moveToEndOfDocument) \
445 macro(moveToEndOfDocumentAndModifySelection) \
446 macro(moveToEndOfLine) \
447 macro(moveToEndOfLineAndModifySelection) \
448 macro(moveToEndOfParagraph) \
449 macro(moveToEndOfParagraphAndModifySelection) \
450 macro(moveToEndOfSentence) \
451 macro(moveToEndOfSentenceAndModifySelection) \
452 macro(moveToLeftEndOfLine) \
453 macro(moveToLeftEndOfLineAndModifySelection) \
454 macro(moveToRightEndOfLine) \
455 macro(moveToRightEndOfLineAndModifySelection) \
456 macro(moveUp) \
457 macro(moveUpAndModifySelection) \
458 macro(moveWordBackward) \
459 macro(moveWordBackwardAndModifySelection) \
460 macro(moveWordForward) \
461 macro(moveWordForwardAndModifySelection) \
462 macro(moveWordLeft) \
463 macro(moveWordLeftAndModifySelection) \
464 macro(moveWordRight) \
465 macro(moveWordRightAndModifySelection) \
466 macro(orderFrontSubstitutionsPanel) \
467 macro(outdent) \
468 macro(overWrite) \
469 macro(pageDown) \
470 macro(pageDownAndModifySelection) \
471 macro(pageUp) \
472 macro(pageUpAndModifySelection) \
473 macro(paste) \
474 macro(pasteAsPlainText) \
475 macro(pasteAsRichText) \
476 macro(pasteFont) \
477 macro(performFindPanelAction) \
478 macro(scrollLineDown) \
479 macro(scrollLineUp) \
480 macro(scrollPageDown) \
481 macro(scrollPageUp) \
482 macro(scrollToBeginningOfDocument) \
483 macro(scrollToEndOfDocument) \
484 macro(selectAll) \
485 macro(selectLine) \
486 macro(selectParagraph) \
487 macro(selectSentence) \
488 macro(selectToMark) \
489 macro(selectWord) \
490 macro(setMark) \
491 macro(showGuessPanel) \
492 macro(startSpeaking) \
493 macro(stopSpeaking) \
494 macro(subscript) \
495 macro(superscript) \
496 macro(swapWithMark) \
497 macro(takeFindStringFromSelection) \
498 macro(toggleBaseWritingDirection) \
499 macro(transpose) \
500 macro(underline) \
501 macro(unscript) \
502 macro(uppercaseWord) \
503 macro(yank) \
504 macro(yankAndSelect) \
505
506 #define WebKitOriginalTopPrintingMarginKey @"WebKitOriginalTopMargin"
507 #define WebKitOriginalBottomPrintingMarginKey @"WebKitOriginalBottomMargin"
508
509 #define KeyboardUIModeDidChangeNotification @"com.apple.KeyboardUIModeDidChange"
510 #define AppleKeyboardUIMode CFSTR("AppleKeyboardUIMode")
511
512 static BOOL s_didSetCacheModel;
513 static WebCacheModel s_cacheModel = WebCacheModelDocumentViewer;
514
515 #if PLATFORM(IOS)
516 static Class s_pdfRepresentationClass;
517 static Class s_pdfViewClass;
518 #endif
519
520 #ifndef NDEBUG
521 static const char webViewIsOpen[] = "At least one WebView is still open.";
522 #endif
523
524 #if PLATFORM(IOS)
525 @interface WebView(WebViewPrivate)
526 - (void)_preferencesChanged:(WebPreferences *)preferences;
527 - (void)_updateScreenScaleFromWindow;
528 @end
529 #endif
530
531 #if !PLATFORM(IOS)
532 @interface NSObject (WebValidateWithoutDelegate)
533 - (BOOL)validateUserInterfaceItemWithoutDelegate:(id <NSValidatedUserInterfaceItem>)item;
534 @end
535 #endif
536
537 #if PLATFORM(IOS)
538 @class _WebSafeForwarder;
539
540 @interface _WebSafeAsyncForwarder : NSObject {
541     _WebSafeForwarder *_forwarder;
542 }
543 - (id)initWithForwarder:(_WebSafeForwarder *)forwarder;
544 @end
545 #endif
546
547 @interface _WebSafeForwarder : NSObject
548 {
549     id target; // Non-retained. Don't retain delegates.
550     id defaultTarget;
551 #if PLATFORM(IOS)
552     _WebSafeAsyncForwarder *asyncForwarder;
553     dispatch_once_t asyncForwarderPred;
554 #endif
555 }
556 - (instancetype)initWithTarget:(id)target defaultTarget:(id)defaultTarget;
557 #if PLATFORM(IOS)
558 - (void)clearTarget;
559 - (id)asyncForwarder;
560 #endif
561 @end
562
563 FindOptions coreOptions(WebFindOptions options)
564 {
565     return (options & WebFindOptionsCaseInsensitive ? CaseInsensitive : 0)
566         | (options & WebFindOptionsAtWordStarts ? AtWordStarts : 0)
567         | (options & WebFindOptionsTreatMedialCapitalAsWordStart ? TreatMedialCapitalAsWordStart : 0)
568         | (options & WebFindOptionsBackwards ? Backwards : 0)
569         | (options & WebFindOptionsWrapAround ? WrapAround : 0)
570         | (options & WebFindOptionsStartInSelection ? StartInSelection : 0);
571 }
572
573 LayoutMilestones coreLayoutMilestones(WebLayoutMilestones milestones)
574 {
575     return (milestones & WebDidFirstLayout ? DidFirstLayout : 0)
576         | (milestones & WebDidFirstVisuallyNonEmptyLayout ? DidFirstVisuallyNonEmptyLayout : 0)
577         | (milestones & WebDidHitRelevantRepaintedObjectsAreaThreshold ? DidHitRelevantRepaintedObjectsAreaThreshold : 0);
578 }
579
580 WebLayoutMilestones kitLayoutMilestones(LayoutMilestones milestones)
581 {
582     return (milestones & DidFirstLayout ? WebDidFirstLayout : 0)
583         | (milestones & DidFirstVisuallyNonEmptyLayout ? WebDidFirstVisuallyNonEmptyLayout : 0)
584         | (milestones & DidHitRelevantRepaintedObjectsAreaThreshold ? WebDidHitRelevantRepaintedObjectsAreaThreshold : 0);
585 }
586
587 static WebPageVisibilityState kit(PageVisibilityState visibilityState)
588 {
589     switch (visibilityState) {
590     case PageVisibilityState::Visible:
591         return WebPageVisibilityStateVisible;
592     case PageVisibilityState::Hidden:
593         return WebPageVisibilityStateHidden;
594     case PageVisibilityState::Prerender:
595         return WebPageVisibilityStatePrerender;
596     }
597
598     ASSERT_NOT_REACHED();
599     return WebPageVisibilityStateVisible;
600 }
601
602 namespace WebKit {
603
604 class DeferredPageDestructor {
605 public:
606     static void createDeferredPageDestructor(std::unique_ptr<Page> page)
607     {
608         new DeferredPageDestructor(WTFMove(page));
609     }
610
611 private:
612     DeferredPageDestructor(std::unique_ptr<Page> page)
613         : m_page(WTFMove(page))
614     {
615         tryDestruction();
616     }
617
618     void tryDestruction()
619     {
620         if (m_page->insideNestedRunLoop()) {
621             m_page->whenUnnested([this] { tryDestruction(); });
622             return;
623         }
624
625         m_page = nullptr;
626         delete this;
627     }
628
629     std::unique_ptr<Page> m_page;
630 };
631
632 } // namespace WebKit
633
634 #if ENABLE(DATA_INTERACTION)
635
636 @implementation WebUITextIndicatorData
637
638 @synthesize dataInteractionImage=_dataInteractionImage;
639 @synthesize selectionRectInRootViewCoordinates=_selectionRectInRootViewCoordinates;
640 @synthesize textBoundingRectInRootViewCoordinates=_textBoundingRectInRootViewCoordinates;
641 @synthesize textRectsInBoundingRectCoordinates=_textRectsInBoundingRectCoordinates;
642 @synthesize contentImageWithHighlight=_contentImageWithHighlight;
643 @synthesize contentImageWithoutSelection=_contentImageWithoutSelection;
644 @synthesize contentImageWithoutSelectionRectInRootViewCoordinates=_contentImageWithoutSelectionRectInRootViewCoordinates;
645 @synthesize contentImage=_contentImage;
646 @synthesize estimatedBackgroundColor=_estimatedBackgroundColor;
647
648 @end
649
650 @implementation WebUITextIndicatorData (WebUITextIndicatorInternal)
651
652 - (WebUITextIndicatorData *)initWithImage:(CGImageRef)image textIndicatorData:(const TextIndicatorData&)indicatorData scale:(CGFloat)scale
653 {
654     if (!(self = [super init]))
655         return nil;
656     
657     _dataInteractionImage = [allocUIImageInstance() initWithCGImage:image scale:scale orientation:UIImageOrientationDownMirrored];
658     _selectionRectInRootViewCoordinates = indicatorData.selectionRectInRootViewCoordinates;
659     _textBoundingRectInRootViewCoordinates = indicatorData.textBoundingRectInRootViewCoordinates;
660     
661     NSMutableArray *textRectsInBoundingRectCoordinates = [NSMutableArray array];
662     for (auto rect : indicatorData.textRectsInBoundingRectCoordinates)
663         [textRectsInBoundingRectCoordinates addObject:[NSValue valueWithCGRect:rect]];
664     _textRectsInBoundingRectCoordinates = [[NSArray arrayWithArray:textRectsInBoundingRectCoordinates] retain];
665     _contentImageScaleFactor = indicatorData.contentImageScaleFactor;
666     if (indicatorData.contentImageWithHighlight)
667         _contentImageWithHighlight = [allocUIImageInstance() initWithCGImage:indicatorData.contentImageWithHighlight.get()->nativeImage().get() scale:scale orientation:UIImageOrientationDownMirrored];
668     if (indicatorData.contentImage)
669         _contentImage = [allocUIImageInstance() initWithCGImage:indicatorData.contentImage.get()->nativeImage().get() scale:scale orientation:UIImageOrientationUp];
670
671     if (indicatorData.contentImageWithoutSelection) {
672         auto nativeImage = indicatorData.contentImageWithoutSelection.get()->nativeImage();
673         if (nativeImage) {
674             _contentImageWithoutSelection = [allocUIImageInstance() initWithCGImage:nativeImage.get() scale:scale orientation:UIImageOrientationUp];
675             _contentImageWithoutSelectionRectInRootViewCoordinates = indicatorData.contentImageWithoutSelectionRectInRootViewCoordinates;
676         }
677     }
678
679     if (indicatorData.options & TextIndicatorOptionComputeEstimatedBackgroundColor)
680         _estimatedBackgroundColor = [allocUIColorInstance() initWithCGColor:cachedCGColor(indicatorData.estimatedBackgroundColor)];
681
682     return self;
683 }
684
685 - (WebUITextIndicatorData *)initWithImage:(CGImageRef)image scale:(CGFloat)scale
686 {
687     if (!(self = [super init]))
688         return nil;
689     
690     _dataInteractionImage = [allocUIImageInstance() initWithCGImage:image scale:scale orientation:UIImageOrientationDownMirrored];
691     
692     return self;
693 }
694
695 - (void)dealloc
696 {
697     [_dataInteractionImage release];
698     [_textRectsInBoundingRectCoordinates release];
699     [_contentImageWithHighlight release];
700     [_contentImageWithoutSelection release];
701     [_contentImage release];
702     [_estimatedBackgroundColor release];
703     
704     [super dealloc];
705 }
706
707 @end
708 #elif !PLATFORM(MAC)
709 @implementation WebUITextIndicatorData
710 @end
711 #endif // ENABLE(DATA_INTERACTION)
712
713 @interface WebView (WebFileInternal)
714 #if !PLATFORM(IOS)
715 - (float)_deviceScaleFactor;
716 #endif
717 - (BOOL)_isLoading;
718 - (WebFrameView *)_frameViewAtWindowPoint:(NSPoint)point;
719 - (WebFrame *)_focusedFrame;
720 + (void)_preflightSpellChecker;
721 - (BOOL)_continuousCheckingAllowed;
722 - (NSResponder *)_responderForResponderOperations;
723 @end
724
725 NSString *WebElementDOMNodeKey =            @"WebElementDOMNode";
726 NSString *WebElementFrameKey =              @"WebElementFrame";
727 NSString *WebElementImageKey =              @"WebElementImage";
728 NSString *WebElementImageAltStringKey =     @"WebElementImageAltString";
729 NSString *WebElementImageRectKey =          @"WebElementImageRect";
730 NSString *WebElementImageURLKey =           @"WebElementImageURL";
731 NSString *WebElementIsSelectedKey =         @"WebElementIsSelected";
732 NSString *WebElementLinkLabelKey =          @"WebElementLinkLabel";
733 NSString *WebElementLinkTargetFrameKey =    @"WebElementTargetFrame";
734 NSString *WebElementLinkTitleKey =          @"WebElementLinkTitle";
735 NSString *WebElementLinkURLKey =            @"WebElementLinkURL";
736 NSString *WebElementMediaURLKey =           @"WebElementMediaURL";
737 NSString *WebElementSpellingToolTipKey =    @"WebElementSpellingToolTip";
738 NSString *WebElementTitleKey =              @"WebElementTitle";
739 NSString *WebElementLinkIsLiveKey =         @"WebElementLinkIsLive";
740 NSString *WebElementIsInScrollBarKey =      @"WebElementIsInScrollBar";
741 NSString *WebElementIsContentEditableKey =  @"WebElementIsContentEditableKey";
742
743 NSString *WebViewProgressStartedNotification =          @"WebProgressStartedNotification";
744 NSString *WebViewProgressEstimateChangedNotification =  @"WebProgressEstimateChangedNotification";
745 #if !PLATFORM(IOS)
746 NSString *WebViewProgressFinishedNotification =         @"WebProgressFinishedNotification";
747 #else
748 NSString * const WebViewProgressEstimatedProgressKey = @"WebProgressEstimatedProgressKey";
749 NSString * const WebViewProgressBackgroundColorKey =   @"WebProgressBackgroundColorKey";
750 #endif
751
752 NSString * const WebViewDidBeginEditingNotification =         @"WebViewDidBeginEditingNotification";
753 NSString * const WebViewDidChangeNotification =               @"WebViewDidChangeNotification";
754 NSString * const WebViewDidEndEditingNotification =           @"WebViewDidEndEditingNotification";
755 NSString * const WebViewDidChangeTypingStyleNotification =    @"WebViewDidChangeTypingStyleNotification";
756 NSString * const WebViewDidChangeSelectionNotification =      @"WebViewDidChangeSelectionNotification";
757
758 enum { WebViewVersion = 4 };
759
760 #define timedLayoutSize 4096
761
762 static NSMutableSet *schemesWithRepresentationsSet;
763
764 #if !PLATFORM(IOS)
765 NSString *_WebCanGoBackKey =            @"canGoBack";
766 NSString *_WebCanGoForwardKey =         @"canGoForward";
767 NSString *_WebEstimatedProgressKey =    @"estimatedProgress";
768 NSString *_WebIsLoadingKey =            @"isLoading";
769 NSString *_WebMainFrameIconKey =        @"mainFrameIcon";
770 NSString *_WebMainFrameTitleKey =       @"mainFrameTitle";
771 NSString *_WebMainFrameURLKey =         @"mainFrameURL";
772 NSString *_WebMainFrameDocumentKey =    @"mainFrameDocument";
773 #endif
774
775 #if PLATFORM(IOS)
776 NSString *WebQuickLookFileNameKey = @"WebQuickLookFileNameKey";
777 NSString *WebQuickLookUTIKey      = @"WebQuickLookUTIKey";
778 #endif
779
780 NSString *_WebViewDidStartAcceleratedCompositingNotification = @"_WebViewDidStartAcceleratedCompositing";
781 NSString * const WebViewWillCloseNotification = @"WebViewWillCloseNotification";
782
783 #if ENABLE(REMOTE_INSPECTOR)
784 // FIXME: Legacy, remove this, switch to something from JavaScriptCore Inspector::RemoteInspectorServer.
785 NSString *_WebViewRemoteInspectorHasSessionChangedNotification = @"_WebViewRemoteInspectorHasSessionChangedNotification";
786 #endif
787
788 @interface WebProgressItem : NSObject
789 {
790 @public
791     long long bytesReceived;
792     long long estimatedLength;
793 }
794 @end
795
796 @implementation WebProgressItem
797 @end
798
799 static BOOL continuousSpellCheckingEnabled;
800 static BOOL iconLoadingEnabled = YES;
801 #if !PLATFORM(IOS)
802 static BOOL grammarCheckingEnabled;
803 static BOOL automaticQuoteSubstitutionEnabled;
804 static BOOL automaticLinkDetectionEnabled;
805 static BOOL automaticDashSubstitutionEnabled;
806 static BOOL automaticTextReplacementEnabled;
807 static BOOL automaticSpellingCorrectionEnabled;
808 #endif
809
810 #if HAVE(TOUCH_BAR)
811
812 enum class WebListType {
813     None = 0,
814     Ordered,
815     Unordered
816 };
817
818 @interface WebTextListTouchBarViewController : NSViewController {
819 @private
820     WebListType _currentListType;
821     WebView *_webView;
822 }
823
824 @property (nonatomic) WebListType currentListType;
825
826 - (instancetype)initWithWebView:(WebView *)webView;
827
828 @end
829
830 @implementation WebTextListTouchBarViewController
831
832 @synthesize currentListType=_currentListType;
833
834 static const CGFloat listControlSegmentWidth = 67.0;
835
836 static const NSUInteger noListSegment = 0;
837 static const NSUInteger unorderedListSegment = 1;
838 static const NSUInteger orderedListSegment = 2;
839
840 - (instancetype)initWithWebView:(WebView *)webView
841 {
842     if (!(self = [super init]))
843         return nil;
844
845     _webView = webView;
846
847     NSSegmentedControl *insertListControl = [NSSegmentedControl segmentedControlWithLabels:@[ WebCore::insertListTypeNone(), WebCore::insertListTypeBulleted(), WebCore::insertListTypeNumbered() ] trackingMode:NSSegmentSwitchTrackingSelectOne target:self action:@selector(_selectList:)];
848     [insertListControl setWidth:listControlSegmentWidth forSegment:noListSegment];
849     [insertListControl setWidth:listControlSegmentWidth forSegment:unorderedListSegment];
850     [insertListControl setWidth:listControlSegmentWidth forSegment:orderedListSegment];
851     insertListControl.font = [NSFont systemFontOfSize:15];
852
853 #pragma clang diagnostic push
854 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
855     id segmentElement = NSAccessibilityUnignoredDescendant(insertListControl);
856     NSArray *segments = [segmentElement accessibilityAttributeValue:NSAccessibilityChildrenAttribute];
857     ASSERT(segments.count == 3);
858     [segments[noListSegment] accessibilitySetOverrideValue:WebCore::insertListTypeNone() forAttribute:NSAccessibilityDescriptionAttribute];
859     [segments[unorderedListSegment] accessibilitySetOverrideValue:WebCore::insertListTypeBulletedAccessibilityTitle() forAttribute:NSAccessibilityDescriptionAttribute];
860     [segments[orderedListSegment] accessibilitySetOverrideValue:WebCore::insertListTypeNumberedAccessibilityTitle() forAttribute:NSAccessibilityDescriptionAttribute];
861 #pragma clang diagnostic pop
862
863     self.view = insertListControl;
864
865     return self;
866 }
867
868 - (void)_selectList:(id)sender
869 {
870     NSView *documentView = [[[_webView _selectedOrMainFrame] frameView] documentView];
871     if (![documentView isKindOfClass:[WebHTMLView class]])
872         return;
873
874     WebHTMLView *webHTMLView = (WebHTMLView *)documentView;
875     NSSegmentedControl *insertListControl = (NSSegmentedControl *)self.view;
876     switch (insertListControl.selectedSegment) {
877     case noListSegment:
878         // There is no "remove list" edit command, but _insertOrderedList and _insertUnorderedList both
879         // behave as toggles, so we can invoke the appropriate method depending on our _currentListType
880         // to remove an existing list. We don't have to do anything if _currentListType is WebListType::None.
881         if (_currentListType == WebListType::Ordered)
882             [webHTMLView _insertOrderedList];
883         else if (_currentListType == WebListType::Unordered)
884             [webHTMLView _insertUnorderedList];
885         break;
886     case unorderedListSegment:
887         [webHTMLView _insertUnorderedList];
888         break;
889     case orderedListSegment:
890         [webHTMLView _insertOrderedList];
891         break;
892     }
893
894     [_webView _dismissTextTouchBarPopoverItemWithIdentifier:NSTouchBarItemIdentifierTextList];
895 }
896
897 - (void)setCurrentListType:(WebListType)listType
898 {
899     NSSegmentedControl *insertListControl = (NSSegmentedControl *)self.view;
900     switch (listType) {
901     case WebListType::None:
902         [insertListControl setSelected:YES forSegment:noListSegment];
903         break;
904     case WebListType::Ordered:
905         [insertListControl setSelected:YES forSegment:orderedListSegment];
906         break;
907     case WebListType::Unordered:
908         [insertListControl setSelected:YES forSegment:unorderedListSegment];
909         break;
910     }
911
912     _currentListType = listType;
913 }
914
915 @end
916
917 @interface WebTextTouchBarItemController : NSTextTouchBarItemController {
918 @private
919     BOOL _textIsBold;
920     BOOL _textIsItalic;
921     BOOL _textIsUnderlined;
922     NSTextAlignment _currentTextAlignment;
923     RetainPtr<NSColor> _textColor;
924     RetainPtr<WebTextListTouchBarViewController> _textListTouchBarViewController;
925     WebView *_webView;
926 }
927
928 @property (nonatomic) BOOL textIsBold;
929 @property (nonatomic) BOOL textIsItalic;
930 @property (nonatomic) BOOL textIsUnderlined;
931 @property (nonatomic) NSTextAlignment currentTextAlignment;
932 @property (nonatomic, retain, readwrite) NSColor *textColor;
933
934 - (instancetype)initWithWebView:(WebView *)webView;
935 @end
936
937 @implementation WebTextTouchBarItemController
938
939 @synthesize textIsBold=_textIsBold;
940 @synthesize textIsItalic=_textIsItalic;
941 @synthesize textIsUnderlined=_textIsUnderlined;
942 @synthesize currentTextAlignment=_currentTextAlignment;
943
944 - (instancetype)initWithWebView:(WebView *)webView
945 {
946     if (!(self = [super init]))
947         return nil;
948
949     _webView = webView;
950
951     return self;
952 }
953
954 - (NSTouchBarItem *)itemForIdentifier:(NSString *)identifier
955 {
956     NSTouchBarItem *item = [super itemForIdentifier:identifier];
957     BOOL isTextFormatItem = [identifier isEqualToString:NSTouchBarItemIdentifierTextFormat];
958
959     if (isTextFormatItem || [identifier isEqualToString:NSTouchBarItemIdentifierTextStyle])
960         self.textStyle.action = @selector(_webChangeTextStyle:);
961
962     if (isTextFormatItem || [identifier isEqualToString:NSTouchBarItemIdentifierTextAlignment])
963         self.textAlignments.action = @selector(_webChangeTextAlignment:);
964
965     NSColorPickerTouchBarItem *colorPickerItem = nil;
966     if ([identifier isEqualToString:NSTouchBarItemIdentifierTextColorPicker] && [item isKindOfClass:[NSColorPickerTouchBarItem class]])
967         colorPickerItem = (NSColorPickerTouchBarItem *)item;
968     if (isTextFormatItem)
969         colorPickerItem = self.colorPickerItem;
970     if (colorPickerItem) {
971         colorPickerItem.target = self;
972         colorPickerItem.action = @selector(_webChangeColor:);
973         colorPickerItem.showsAlpha = NO;
974     }
975
976     return item;
977 }
978
979 - (WebTextListTouchBarViewController *)webTextListTouchBarViewController
980 {
981     return (WebTextListTouchBarViewController *)self.textListViewController;
982 }
983
984 - (void)setTextIsBold:(BOOL)bold
985 {
986     _textIsBold = bold;
987     if ([self.textStyle isSelectedForSegment:0] != _textIsBold)
988         [self.textStyle setSelected:_textIsBold forSegment:0];
989 }
990
991 - (void)setTextIsItalic:(BOOL)italic
992 {
993     _textIsItalic = italic;
994     if ([self.textStyle isSelectedForSegment:1] != _textIsItalic)
995         [self.textStyle setSelected:_textIsItalic forSegment:1];
996 }
997
998 - (void)setTextIsUnderlined:(BOOL)underlined
999 {
1000     _textIsUnderlined = underlined;
1001     if ([self.textStyle isSelectedForSegment:2] != _textIsUnderlined)
1002         [self.textStyle setSelected:_textIsUnderlined forSegment:2];
1003 }
1004
1005 - (void)_webChangeTextStyle:(id)sender
1006 {
1007     if ([self.textStyle isSelectedForSegment:0] != _textIsBold) {
1008         _textIsBold = !_textIsBold;
1009         [_webView _executeCoreCommandByName:@"ToggleBold" value:@""];
1010     }
1011
1012     if ([self.textStyle isSelectedForSegment:1] != _textIsItalic) {
1013         _textIsItalic = !_textIsItalic;
1014         [_webView _executeCoreCommandByName:@"ToggleItalic" value:@""];
1015     }
1016
1017     if ([self.textStyle isSelectedForSegment:2] != _textIsUnderlined) {
1018         _textIsUnderlined = !_textIsUnderlined;
1019         [_webView _executeCoreCommandByName:@"ToggleUnderline" value:@""];
1020     }
1021 }
1022
1023 - (void)setCurrentTextAlignment:(NSTextAlignment)alignment
1024 {
1025     _currentTextAlignment = alignment;
1026     [self.textAlignments selectSegmentWithTag:_currentTextAlignment];
1027 }
1028
1029 - (void)_webChangeTextAlignment:(id)sender
1030 {
1031     NSTextAlignment alignment = (NSTextAlignment)[self.textAlignments.cell tagForSegment:self.textAlignments.selectedSegment];
1032     switch (alignment) {
1033     case NSTextAlignmentLeft:
1034         _currentTextAlignment = NSTextAlignmentLeft;
1035         [_webView alignLeft:sender];
1036         break;
1037     case NSTextAlignmentRight:
1038         _currentTextAlignment = NSTextAlignmentRight;
1039         [_webView alignRight:sender];
1040         break;
1041     case NSTextAlignmentCenter:
1042         _currentTextAlignment = NSTextAlignmentCenter;
1043         [_webView alignCenter:sender];
1044         break;
1045     case NSTextAlignmentJustified:
1046         _currentTextAlignment = NSTextAlignmentJustified;
1047         [_webView alignJustified:sender];
1048         break;
1049     default:
1050         break;
1051     }
1052
1053     [_webView _dismissTextTouchBarPopoverItemWithIdentifier:NSTouchBarItemIdentifierTextAlignment];
1054 }
1055
1056 - (NSColor *)textColor
1057 {
1058     return _textColor.get();
1059 }
1060
1061 - (void)setTextColor:(NSColor *)color
1062 {
1063     _textColor = color;
1064     self.colorPickerItem.color = _textColor.get();
1065 }
1066
1067 - (void)_webChangeColor:(id)sender
1068 {
1069     _textColor = self.colorPickerItem.color;
1070     [_webView _executeCoreCommandByName:@"ForeColor" value: WebCore::colorFromNSColor(_textColor.get()).serialized()];
1071 }
1072
1073 - (NSViewController *)textListViewController
1074 {
1075     if (!_textListTouchBarViewController)
1076         _textListTouchBarViewController = adoptNS([[WebTextListTouchBarViewController alloc] initWithWebView:_webView]);
1077     return _textListTouchBarViewController.get();
1078 }
1079
1080 @end
1081
1082 #endif // HAVE(TOUCH_BAR)
1083
1084 @implementation WebView (AllWebViews)
1085
1086 static CFSetCallBacks NonRetainingSetCallbacks = {
1087     0,
1088     NULL,
1089     NULL,
1090     CFCopyDescription,
1091     CFEqual,
1092     CFHash
1093 };
1094
1095 static CFMutableSetRef allWebViewsSet;
1096
1097 + (void)_makeAllWebViewsPerformSelector:(SEL)selector
1098 {
1099     if (!allWebViewsSet)
1100         return;
1101
1102     [(NSMutableSet *)allWebViewsSet makeObjectsPerformSelector:selector];
1103 }
1104
1105 - (void)_removeFromAllWebViewsSet
1106 {
1107     if (allWebViewsSet)
1108         CFSetRemoveValue(allWebViewsSet, self);
1109 }
1110
1111 - (void)_addToAllWebViewsSet
1112 {
1113     if (!allWebViewsSet)
1114         allWebViewsSet = CFSetCreateMutable(NULL, 0, &NonRetainingSetCallbacks);
1115
1116     CFSetSetValue(allWebViewsSet, self);
1117 }
1118
1119 @end
1120
1121 @implementation WebView (WebPrivate)
1122
1123 static String webKitBundleVersionString()
1124 {
1125     return [[NSBundle bundleForClass:[WebView class]] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
1126 }
1127
1128 + (NSString *)_standardUserAgentWithApplicationName:(NSString *)applicationName
1129 {
1130     return standardUserAgentWithApplicationName(applicationName, webKitBundleVersionString());
1131 }
1132
1133 #if PLATFORM(IOS)
1134 - (void)_setBrowserUserAgentProductVersion:(NSString *)productVersion buildVersion:(NSString *)buildVersion bundleVersion:(NSString *)bundleVersion
1135 {
1136     [self setApplicationNameForUserAgent:[NSString stringWithFormat:@"Version/%@ Mobile/%@ Safari/%@", productVersion, buildVersion, bundleVersion]];
1137 }
1138
1139 - (void)_setUIWebViewUserAgentWithBuildVersion:(NSString *)buildVersion
1140 {
1141     [self setApplicationNameForUserAgent:[@"Mobile/" stringByAppendingString:buildVersion]];
1142 }
1143 #endif // PLATFORM(IOS)
1144
1145 + (void)_reportException:(JSValueRef)exception inContext:(JSContextRef)context
1146 {
1147     if (!exception || !context)
1148         return;
1149
1150     JSC::ExecState* execState = toJS(context);
1151     JSLockHolder lock(execState);
1152
1153     // Make sure the context has a DOMWindow global object, otherwise this context didn't originate from a WebView.
1154     JSC::JSGlobalObject* globalObject = execState->lexicalGlobalObject();
1155     if (!toJSDOMWindow(globalObject->vm(), globalObject))
1156         return;
1157
1158     reportException(execState, toJS(execState, exception));
1159 }
1160
1161 static bool shouldEnableLoadDeferring()
1162 {
1163 #if PLATFORM(IOS)
1164     return true;
1165 #else
1166     return !MacApplication::isAdobeInstaller();
1167 #endif
1168 }
1169
1170 static bool shouldRestrictWindowFocus()
1171 {
1172 #if PLATFORM(IOS)
1173     return true;
1174 #else
1175     return !MacApplication::isHRBlock();
1176 #endif
1177 }
1178
1179 - (void)_dispatchPendingLoadRequests
1180 {
1181     webResourceLoadScheduler().servePendingRequests();
1182 }
1183
1184 #if !PLATFORM(IOS)
1185
1186 - (void)_registerDraggedTypes
1187 {
1188     NSArray *editableTypes = [WebHTMLView _insertablePasteboardTypes];
1189     NSArray *URLTypes = [NSPasteboard _web_dragTypesForURL];
1190     NSMutableSet *types = [[NSMutableSet alloc] initWithArray:editableTypes];
1191     [types addObjectsFromArray:URLTypes];
1192     [types addObject:[WebHTMLView _dummyPasteboardType]];
1193     [self registerForDraggedTypes:[types allObjects]];
1194     [types release];
1195 }
1196
1197 static bool needsOutlookQuirksScript()
1198 {
1199     static bool isOutlookNeedingQuirksScript = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
1200         && MacApplication::isMicrosoftOutlook();
1201     return isOutlookNeedingQuirksScript;
1202 }
1203
1204 static NSString *leakOutlookQuirksUserScriptContents()
1205 {
1206     NSString *scriptPath = [[NSBundle bundleForClass:[WebView class]] pathForResource:@"OutlookQuirksUserScript" ofType:@"js"];
1207     NSStringEncoding encoding;
1208     return [[NSString alloc] initWithContentsOfFile:scriptPath usedEncoding:&encoding error:0];
1209 }
1210
1211 -(void)_injectOutlookQuirksScript
1212 {
1213     static NSString *outlookQuirksScriptContents = leakOutlookQuirksUserScriptContents();
1214     _private->group->userContentController().addUserScript(*core([WebScriptWorld world]), std::make_unique<UserScript>(outlookQuirksScriptContents, URL(), Vector<String>(), Vector<String>(), InjectAtDocumentEnd, InjectInAllFrames));
1215
1216 }
1217 #endif
1218
1219 static bool shouldRespectPriorityInCSSAttributeSetters()
1220 {
1221 #if PLATFORM(IOS)
1222     return false;
1223 #else
1224     static bool isIAdProducerNeedingAttributeSetterQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_ATTRIBUTE_SETTERS_IGNORING_PRIORITY)
1225         && [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.apple.iAdProducer"];
1226     return isIAdProducerNeedingAttributeSetterQuirk;
1227 #endif
1228 }
1229
1230 #if PLATFORM(IOS)
1231 static bool isInternalInstall()
1232 {
1233     static bool isInternal = MGGetBoolAnswer(kMGQAppleInternalInstallCapability);
1234     return isInternal;
1235 }
1236
1237 static bool didOneTimeInitialization = false;
1238 #endif
1239
1240 static bool shouldUseLegacyBackgroundSizeShorthandBehavior()
1241 {
1242 #if PLATFORM(IOS)
1243     static bool shouldUseLegacyBackgroundSizeShorthandBehavior = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LEGACY_BACKGROUNDSIZE_SHORTHAND_BEHAVIOR);
1244 #else
1245     static bool shouldUseLegacyBackgroundSizeShorthandBehavior = MacApplication::isVersions()
1246         && !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LEGACY_BACKGROUNDSIZE_SHORTHAND_BEHAVIOR);
1247 #endif
1248     return shouldUseLegacyBackgroundSizeShorthandBehavior;
1249 }
1250
1251 static bool shouldAllowDisplayAndRunningOfInsecureContent()
1252 {
1253     static bool shouldAllowDisplayAndRunningOfInsecureContent = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_INSECURE_CONTENT_BLOCKING);
1254     return shouldAllowDisplayAndRunningOfInsecureContent;
1255 }
1256
1257 static bool shouldAllowPictureInPictureMediaPlayback()
1258 {
1259 #if PLATFORM(IOS)
1260     static bool shouldAllowPictureInPictureMediaPlayback = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_9_0;
1261     return shouldAllowPictureInPictureMediaPlayback;
1262 #else
1263     return false;
1264 #endif
1265 }
1266
1267 static bool shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol()
1268 {
1269 #if PLATFORM(IOS)
1270     static bool shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CONTENT_SECURITY_POLICY_SOURCE_STAR_PROTOCOL_RESTRICTION);
1271     return shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol;
1272 #else
1273     return false;
1274 #endif
1275 }
1276
1277 static bool shouldAllowWindowOpenWithoutUserGesture()
1278 {
1279 #if PLATFORM(IOS)
1280     static bool shouldAllowWindowOpenWithoutUserGesture = IOSApplication::isTheSecretSocietyHiddenMystery() && dyld_get_program_sdk_version() < DYLD_IOS_VERSION_10_0;
1281     return shouldAllowWindowOpenWithoutUserGesture;
1282 #else
1283     return false;
1284 #endif
1285 }
1286
1287 static bool shouldConvertInvalidURLsToBlank()
1288 {
1289 #if PLATFORM(IOS)
1290     static bool shouldConvertInvalidURLsToBlank = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_10_0;
1291 #elif PLATFORM(MAC)
1292     static bool shouldConvertInvalidURLsToBlank = dyld_get_program_sdk_version() >= DYLD_MACOSX_VERSION_10_12;
1293 #else
1294     static bool shouldConvertInvalidURLsToBlank = true;
1295 #endif
1296
1297     return shouldConvertInvalidURLsToBlank;
1298 }
1299
1300 static bool shouldRequireUserGestureToLoadVideo()
1301 {
1302 #if PLATFORM(IOS)
1303     static bool shouldRequireUserGestureToLoadVideo = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_10_0;
1304     return shouldRequireUserGestureToLoadVideo;
1305 #else
1306     return true;
1307 #endif
1308 }
1309
1310 #if ENABLE(GAMEPAD)
1311 static void WebKitInitializeGamepadProviderIfNecessary()
1312 {
1313     static bool initialized = false;
1314     if (initialized)
1315         return;
1316
1317 #if PLATFORM(MAC)
1318     GamepadProvider::singleton().setSharedProvider(HIDGamepadProvider::singleton());
1319 #else
1320     GamepadProvider::singleton().setSharedProvider(GameControllerGamepadProvider::singleton());
1321 #endif
1322
1323     initialized = true;
1324 }
1325 #endif
1326
1327 - (void)_commonInitializationWithFrameName:(NSString *)frameName groupName:(NSString *)groupName
1328 {
1329     WebCoreThreadViolationCheckRoundTwo();
1330
1331 #ifndef NDEBUG
1332     WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
1333 #endif
1334     
1335     WebPreferences *standardPreferences = [WebPreferences standardPreferences];
1336     [standardPreferences willAddToWebView];
1337
1338     _private->preferences = [standardPreferences retain];
1339     _private->mainFrameDocumentReady = NO;
1340     _private->drawsBackground = YES;
1341 #if !PLATFORM(IOS)
1342     _private->backgroundColor = [[NSColor colorWithDeviceWhite:1 alpha:1] retain];
1343 #else
1344     _private->backgroundColor = CGColorRetain(cachedCGColor(Color::white));
1345 #endif
1346
1347 #if PLATFORM(MAC)
1348     _private->windowVisibilityObserver = adoptNS([[WebWindowVisibilityObserver alloc] initWithView:self]);
1349 #endif
1350
1351     NSRect f = [self frame];
1352     WebFrameView *frameView = [[WebFrameView alloc] initWithFrame: NSMakeRect(0,0,f.size.width,f.size.height)];
1353     [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1354     [self addSubview:frameView];
1355     [frameView release];
1356
1357 #if PLATFORM(MAC)
1358     if (Class gestureClass = NSClassFromString(@"NSImmediateActionGestureRecognizer")) {
1359         RetainPtr<NSImmediateActionGestureRecognizer> recognizer = adoptNS([(NSImmediateActionGestureRecognizer *)[gestureClass alloc] init]);
1360         _private->immediateActionController = [[WebImmediateActionController alloc] initWithWebView:self recognizer:recognizer.get()];
1361         [recognizer setDelegate:_private->immediateActionController];
1362         [recognizer setDelaysPrimaryMouseButtonEvents:NO];
1363     }
1364 #endif
1365
1366     [self updateTouchBar];
1367
1368 #if !PLATFORM(IOS)
1369     static bool didOneTimeInitialization = false;
1370 #endif
1371     if (!didOneTimeInitialization) {
1372 #if !LOG_DISABLED || !RELEASE_LOG_DISABLED
1373         WebKitInitializeLogChannelsIfNecessary();
1374         WebCore::initializeLogChannelsIfNecessary();
1375 #endif
1376
1377         // Initialize our platform strategies first before invoking the rest
1378         // of the initialization code which may depend on the strategies.
1379         WebPlatformStrategies::initializeIfNecessary();
1380
1381         initializeDOMWrapperHooks();
1382
1383 #if PLATFORM(IOS)
1384         // Set the WebSQLiteDatabaseTrackerClient.
1385         SQLiteDatabaseTracker::setClient(&WebSQLiteDatabaseTrackerClient::sharedWebSQLiteDatabaseTrackerClient());
1386
1387         if ([standardPreferences databasesEnabled])
1388 #endif
1389         [WebDatabaseManager sharedWebDatabaseManager];
1390
1391 #if PLATFORM(IOS)        
1392         if ([standardPreferences storageTrackerEnabled])
1393 #endif
1394         WebKitInitializeStorageIfNecessary();
1395
1396 #if ENABLE(GAMEPAD)
1397         WebKitInitializeGamepadProviderIfNecessary();
1398 #endif
1399         
1400         Settings::setShouldRespectPriorityInCSSAttributeSetters(shouldRespectPriorityInCSSAttributeSetters());
1401
1402 #if PLATFORM(IOS)
1403         if (IOSApplication::isMobileSafari())
1404             Settings::setShouldManageAudioSessionCategory(true);
1405 #endif
1406
1407         didOneTimeInitialization = true;
1408     }
1409
1410     _private->group = WebViewGroup::getOrCreate(groupName, _private->preferences._localStorageDatabasePath);
1411     _private->group->addWebView(self);
1412
1413     PageConfiguration pageConfiguration(
1414         makeUniqueRef<WebEditorClient>(self),
1415         SocketProvider::create(),
1416         makeUniqueRef<WebCore::LibWebRTCProvider>()
1417     );
1418 #if !PLATFORM(IOS)
1419     pageConfiguration.chromeClient = new WebChromeClient(self);
1420     pageConfiguration.contextMenuClient = new WebContextMenuClient(self);
1421     // FIXME: We should enable this on iOS as well.
1422     pageConfiguration.validationMessageClient = std::make_unique<WebValidationMessageClient>(self);
1423     pageConfiguration.inspectorClient = new WebInspectorClient(self);
1424 #else
1425     pageConfiguration.chromeClient = new WebChromeClientIOS(self);
1426     pageConfiguration.inspectorClient = new WebInspectorClient(self);
1427 #endif
1428
1429 #if ENABLE(DRAG_SUPPORT)
1430     pageConfiguration.dragClient = new WebDragClient(self);
1431 #endif
1432
1433     pageConfiguration.backForwardClient = BackForwardList::create(self);
1434
1435 #if ENABLE(APPLE_PAY)
1436     pageConfiguration.paymentCoordinatorClient = new WebPaymentCoordinatorClient();
1437 #endif
1438
1439     pageConfiguration.alternativeTextClient = new WebAlternativeTextClient(self);
1440     pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
1441     pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(self);
1442     pageConfiguration.applicationCacheStorage = &webApplicationCacheStorage();
1443     pageConfiguration.databaseProvider = &WebDatabaseProvider::singleton();
1444     pageConfiguration.pluginInfoProvider = &WebPluginInfoProvider::singleton();
1445     pageConfiguration.storageNamespaceProvider = &_private->group->storageNamespaceProvider();
1446     pageConfiguration.userContentProvider = &_private->group->userContentController();
1447     pageConfiguration.visitedLinkStore = &_private->group->visitedLinkStore();
1448     _private->page = new Page(WTFMove(pageConfiguration));
1449
1450     _private->page->setGroupName(groupName);
1451
1452 #if ENABLE(GEOLOCATION)
1453     WebCore::provideGeolocationTo(_private->page, new WebGeolocationClient(self));
1454 #endif
1455 #if ENABLE(NOTIFICATIONS)
1456     WebCore::provideNotification(_private->page, new WebNotificationClient(self));
1457 #endif
1458 #if ENABLE(DEVICE_ORIENTATION)
1459 #if !PLATFORM(IOS)
1460     WebCore::provideDeviceOrientationTo(_private->page, new WebDeviceOrientationClient(self));
1461 #endif
1462 #endif
1463 #if ENABLE(MEDIA_STREAM)
1464     WebCore::provideUserMediaTo(_private->page, new WebUserMediaClient(self));
1465 #endif
1466
1467 #if ENABLE(REMOTE_INSPECTOR)
1468     _private->page->setRemoteInspectionAllowed(true);
1469 #endif
1470
1471     _private->page->setCanStartMedia([self window]);
1472     _private->page->settings().setLocalStorageDatabasePath([[self preferences] _localStorageDatabasePath]);
1473     _private->page->settings().setUseLegacyBackgroundSizeShorthandBehavior(shouldUseLegacyBackgroundSizeShorthandBehavior());
1474
1475 #if !PLATFORM(IOS)
1476     if (needsOutlookQuirksScript()) {
1477         _private->page->settings().setShouldInjectUserScriptsInInitialEmptyDocument(true);
1478         [self _injectOutlookQuirksScript];
1479     }
1480 #endif
1481
1482 #if PLATFORM(IOS)
1483     // Preserve the behavior we had before <rdar://problem/7580867>
1484     // by enforcing a 5MB limit for session storage.
1485     _private->page->settings().setSessionStorageQuota(5 * 1024 * 1024);
1486
1487     [self _updateScreenScaleFromWindow];
1488     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
1489     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
1490     _private->_fixedPositionContent = [[WebFixedPositionContent alloc] initWithWebView:self];
1491 #if ENABLE(ORIENTATION_EVENTS)
1492     _private->deviceOrientation = [[self _UIKitDelegateForwarder] deviceOrientation];
1493 #endif
1494 #endif
1495
1496     if ([[NSUserDefaults standardUserDefaults] objectForKey:WebSmartInsertDeleteEnabled])
1497         [self setSmartInsertDeleteEnabled:[[NSUserDefaults standardUserDefaults] boolForKey:WebSmartInsertDeleteEnabled]];
1498
1499     [WebFrame _createMainFrameWithPage:_private->page frameName:frameName frameView:frameView];
1500
1501 #if PLATFORM(IOS)
1502     NSRunLoop *runLoop = WebThreadNSRunLoop();
1503 #else
1504     NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
1505 #endif
1506
1507     if (WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOADING_DURING_COMMON_RUNLOOP_MODES))
1508         [self scheduleInRunLoop:runLoop forMode:(NSString *)kCFRunLoopCommonModes];
1509     else
1510         [self scheduleInRunLoop:runLoop forMode:NSDefaultRunLoopMode];
1511
1512     [self _addToAllWebViewsSet];
1513     
1514     // If there's already a next key view (e.g., from a nib), wire it up to our
1515     // contained frame view. In any case, wire our next key view up to the our
1516     // contained frame view. This works together with our becomeFirstResponder 
1517     // and setNextKeyView overrides.
1518     NSView *nextKeyView = [self nextKeyView];
1519     if (nextKeyView && nextKeyView != frameView)
1520         [frameView setNextKeyView:nextKeyView];
1521     [super setNextKeyView:frameView];
1522
1523     if ([[self class] shouldIncludeInWebKitStatistics])
1524         ++WebViewCount;
1525
1526 #if !PLATFORM(IOS)
1527     [self _registerDraggedTypes];
1528 #endif
1529
1530     [self _setIsVisible:[self _isViewVisible]];
1531
1532     WebPreferences *prefs = [self preferences];
1533     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
1534                                                  name:WebPreferencesChangedInternalNotification object:prefs];
1535
1536 #if !PLATFORM(IOS)
1537     [self _preferencesChanged:[self preferences]];
1538     [[self preferences] _postPreferencesChangedAPINotification];
1539 #else
1540     // do this on the current thread on iOS, since the web thread could be blocked on the main thread,
1541     // and prefs need to be changed synchronously <rdar://problem/5841558>
1542     [self _preferencesChanged:prefs];
1543     _private->page->settings().setFontFallbackPrefersPictographs(true);
1544 #endif
1545
1546     WebInstallMemoryPressureHandler();
1547
1548 #if !PLATFORM(IOS)
1549     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
1550         // Originally, we allowed all local loads.
1551         SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForAll);
1552     } else if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_MORE_STRICT_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
1553         // Later, we allowed local loads for local URLs and documents loaded
1554         // with substitute data.
1555         SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1556     }
1557 #endif
1558
1559 #if PLATFORM(MAC)
1560     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_CONTENT_SNIFFING_FOR_FILE_URLS))
1561         ResourceHandle::forceContentSniffing();
1562
1563     _private->page->setDeviceScaleFactor([self _deviceScaleFactor]);
1564 #endif
1565
1566     _private->page->settings().setContentDispositionAttachmentSandboxEnabled(true);
1567 }
1568
1569 - (id)_initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName
1570 {
1571     self = [super initWithFrame:f];
1572     if (!self)
1573         return nil;
1574
1575 #ifdef ENABLE_WEBKIT_UNSET_DYLD_FRAMEWORK_PATH
1576     // DYLD_FRAMEWORK_PATH is used so Safari will load the development version of WebKit, which
1577     // may not work with other WebKit applications.  Unsetting DYLD_FRAMEWORK_PATH removes the
1578     // need for Safari to unset it to prevent it from being passed to applications it launches.
1579     // Unsetting it when a WebView is first created is as good a place as any.
1580     // See <http://bugs.webkit.org/show_bug.cgi?id=4286> for more details.
1581     if (getenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH")) {
1582         unsetenv("DYLD_FRAMEWORK_PATH");
1583         unsetenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH");
1584     }
1585 #endif
1586
1587     _private = [[WebViewPrivate alloc] init];
1588     [self _commonInitializationWithFrameName:frameName groupName:groupName];
1589     [self setMaintainsBackForwardList: YES];
1590     return self;
1591 }
1592
1593 - (void)_viewWillDrawInternal
1594 {
1595     Frame* frame = [self _mainCoreFrame];
1596     if (frame && frame->view())
1597         frame->view()->updateLayoutAndStyleIfNeededRecursive();
1598 }
1599
1600 + (NSArray *)_supportedMIMETypes
1601 {
1602     // Load the plug-in DB allowing plug-ins to install types.
1603     [WebPluginDatabase sharedDatabase];
1604     return [[WebFrameView _viewTypesAllowImageTypeOmission:NO] allKeys];
1605 }
1606
1607 #if !PLATFORM(IOS)
1608 + (NSArray *)_supportedFileExtensions
1609 {
1610     NSMutableSet *extensions = [[NSMutableSet alloc] init];
1611     NSArray *MIMETypes = [self _supportedMIMETypes];
1612     NSEnumerator *enumerator = [MIMETypes objectEnumerator];
1613     NSString *MIMEType;
1614     while ((MIMEType = [enumerator nextObject]) != nil) {
1615         NSArray *extensionsForType = [[NSURLFileTypeMappings sharedMappings] extensionsForMIMEType:MIMEType];
1616         if (extensionsForType) {
1617             [extensions addObjectsFromArray:extensionsForType];
1618         }
1619     }
1620     NSArray *uniqueExtensions = [extensions allObjects];
1621     [extensions release];
1622     return uniqueExtensions;
1623 }
1624 #endif
1625
1626 #if PLATFORM(IOS)
1627 + (void)enableWebThread
1628 {
1629     static BOOL isWebThreadEnabled = NO;
1630     if (!isWebThreadEnabled) {
1631         WebCoreObjCDeallocOnWebThread([DOMObject class]);
1632         WebCoreObjCDeallocOnWebThread([WebBasePluginPackage class]);
1633         WebCoreObjCDeallocOnWebThread([WebDataSource class]);
1634         WebCoreObjCDeallocOnWebThread([WebFrame class]);
1635         WebCoreObjCDeallocOnWebThread([WebHTMLView class]);
1636         WebCoreObjCDeallocOnWebThread([WebHistoryItem class]);
1637         WebCoreObjCDeallocOnWebThread([WebPlainWhiteView class]);
1638         WebCoreObjCDeallocOnWebThread([WebPolicyDecisionListener class]);
1639         WebCoreObjCDeallocOnWebThread([WebView class]);
1640         WebCoreObjCDeallocOnWebThread([WebVisiblePosition class]);
1641         WebThreadEnable();
1642         isWebThreadEnabled = YES;
1643     }
1644 }
1645
1646 - (id)initSimpleHTMLDocumentWithStyle:(NSString *)style frame:(CGRect)frame preferences:(WebPreferences *)preferences groupName:(NSString *)groupName
1647 {
1648     self = [super initWithFrame:frame];
1649     if (!self)
1650         return nil;
1651     
1652     _private = [[WebViewPrivate alloc] init];
1653     
1654 #ifndef NDEBUG
1655     WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
1656 #endif
1657     
1658     if (!preferences)
1659         preferences = [WebPreferences standardPreferences];
1660     [preferences willAddToWebView];
1661     
1662     _private->preferences = [preferences retain];
1663     _private->mainFrameDocumentReady = NO;
1664     _private->drawsBackground = YES;
1665     _private->backgroundColor = CGColorRetain(cachedCGColor(Color::white));
1666
1667     WebFrameView *frameView = nil;
1668     frameView = [[WebFrameView alloc] initWithFrame: CGRectMake(0,0,frame.size.width,frame.size.height)];
1669     [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1670     [self addSubview:frameView];
1671     [frameView release];
1672
1673     _private->group = WebViewGroup::getOrCreate(groupName, _private->preferences._localStorageDatabasePath);
1674     _private->group->addWebView(self);
1675
1676     PageConfiguration pageConfiguration(
1677         makeUniqueRef<WebEditorClient>(self),
1678         SocketProvider::create(),
1679         makeUniqueRef<WebCore::LibWebRTCProvider>()
1680     );
1681     pageConfiguration.chromeClient = new WebChromeClientIOS(self);
1682 #if ENABLE(DRAG_SUPPORT)
1683     pageConfiguration.dragClient = new WebDragClient(self);
1684 #endif
1685
1686 #if ENABLE(APPLE_PAY)
1687     pageConfiguration.paymentCoordinatorClient = new WebPaymentCoordinatorClient();
1688 #endif
1689
1690     pageConfiguration.backForwardClient = BackForwardList::create(self);
1691     pageConfiguration.inspectorClient = new WebInspectorClient(self);
1692     pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
1693     pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(self);
1694     pageConfiguration.applicationCacheStorage = &webApplicationCacheStorage();
1695     pageConfiguration.databaseProvider = &WebDatabaseProvider::singleton();
1696     pageConfiguration.storageNamespaceProvider = &_private->group->storageNamespaceProvider();
1697     pageConfiguration.userContentProvider = &_private->group->userContentController();
1698     pageConfiguration.visitedLinkStore = &_private->group->visitedLinkStore();
1699     pageConfiguration.pluginInfoProvider = &WebPluginInfoProvider::singleton();
1700
1701     _private->page = new Page(WTFMove(pageConfiguration));
1702     
1703     [self setSmartInsertDeleteEnabled:YES];
1704     
1705     // FIXME: <rdar://problem/6851451> Should respect preferences in fast path WebView initialization
1706     // We are ignoring the preferences object on fast path and just using Settings defaults (everything fancy off).
1707     // This matches how UIKit sets up the preferences. We need to set  default values for fonts though, <rdar://problem/6850611>.
1708     // This should be revisited later. There is some risk involved, _preferencesChanged used to show up badly in Shark.
1709     _private->page->settings().setMinimumLogicalFontSize(9);
1710     _private->page->settings().setDefaultFontSize([_private->preferences defaultFontSize]);
1711     _private->page->settings().setDefaultFixedFontSize(13);
1712     _private->page->settings().setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
1713     _private->page->settings().setDisplayListDrawingEnabled([preferences displayListDrawingEnabled]);
1714     
1715     _private->page->settings().setFontFallbackPrefersPictographs(true);
1716     _private->page->settings().setPictographFontFamily("AppleColorEmoji");
1717     
1718     _private->page->settings().setScriptMarkupEnabled(false);
1719     _private->page->settings().setScriptEnabled(true);
1720     
1721     // FIXME: this is a workaround for <rdar://problem/11518688> REGRESSION: Quoted text font changes when replying to certain email
1722     _private->page->settings().setStandardFontFamily([_private->preferences standardFontFamily]);
1723     
1724     // FIXME: this is a workaround for <rdar://problem/11820090> Quoted text changes in size when replying to certain email
1725     _private->page->settings().setMinimumFontSize([_private->preferences minimumFontSize]);
1726
1727     // This is a workaround for <rdar://problem/21309911>.
1728     _private->page->settings().setHttpEquivEnabled([_private->preferences httpEquivEnabled]);
1729
1730     _private->page->setGroupName(groupName);
1731
1732 #if ENABLE(REMOTE_INSPECTOR)
1733     _private->page->setRemoteInspectionAllowed(isInternalInstall());
1734 #endif
1735     
1736     [self _updateScreenScaleFromWindow];
1737     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
1738     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
1739
1740     [WebFrame _createMainFrameWithSimpleHTMLDocumentWithPage:_private->page frameView:frameView style:style];
1741     
1742     [self _addToAllWebViewsSet];
1743     
1744     ++WebViewCount;
1745     
1746     SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1747     
1748     return self;
1749 }
1750
1751 + (void)_releaseMemoryNow
1752 {
1753     WebThreadRun(^{
1754         WebCore::releaseMemory(Critical::Yes, Synchronous::Yes);
1755     });
1756 }
1757
1758 - (void)_replaceCurrentHistoryItem:(WebHistoryItem *)item
1759 {
1760     Frame* frame = [self _mainCoreFrame];
1761     if (frame)
1762         frame->loader().history().replaceCurrentItem(core(item));
1763 }
1764
1765 + (void)willEnterBackgroundWithCompletionHandler:(void(^)(void))handler
1766 {
1767     WebThreadRun(^{
1768         [WebView _releaseMemoryNow];
1769         dispatch_async(dispatch_get_main_queue(), handler);
1770     });
1771 }
1772
1773 + (BOOL)isCharacterSmartReplaceExempt:(unichar)character isPreviousCharacter:(BOOL)b
1774 {
1775     return WebCore::isCharacterSmartReplaceExempt(character, b);
1776 }
1777
1778 - (void)updateLayoutIgnorePendingStyleSheets
1779 {
1780     WebThreadRun(^{
1781         for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext()) {
1782             Document *document = frame->document();
1783             if (document)
1784                 document->updateLayoutIgnorePendingStylesheets();
1785         }
1786     });
1787 }
1788 #endif
1789
1790 #if ENABLE(DRAG_SUPPORT) && PLATFORM(IOS)
1791
1792 - (BOOL)_requestStartDataInteraction:(CGPoint)clientPosition globalPosition:(CGPoint)globalPosition
1793 {
1794     WebThreadLock();
1795     return _private->page->mainFrame().eventHandler().tryToBeginDataInteractionAtPoint(IntPoint(clientPosition), IntPoint(globalPosition));
1796 }
1797
1798 - (void)_startDrag:(const DragItem&)dragItem
1799 {
1800     auto& dragImage = dragItem.image;
1801     auto image = dragImage.get().get();
1802     auto indicatorData = dragImage.indicatorData();
1803
1804     if (indicatorData)
1805         _private->textIndicatorData = adoptNS([[WebUITextIndicatorData alloc] initWithImage:image textIndicatorData:indicatorData.value() scale:_private->page->deviceScaleFactor()]);
1806     else
1807         _private->textIndicatorData = adoptNS([[WebUITextIndicatorData alloc] initWithImage:image scale:_private->page->deviceScaleFactor()]);
1808     _private->draggedLinkURL = dragItem.url.isEmpty() ? nil : (NSURL *)dragItem.url;
1809     _private->draggedLinkTitle = dragItem.title.isEmpty() ? nil : (NSString *)dragItem.title;
1810     _private->draggedElementBounds = dragItem.elementBounds;
1811     _private->dragSourceAction = static_cast<WebDragSourceAction>(dragItem.sourceAction);
1812 }
1813
1814 - (CGRect)_dataInteractionCaretRect
1815 {
1816     WebThreadLock();
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