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