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