requestAnimationFrame should execute before the next frame
[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     if (_private->page)
1624         _private->page->renderingUpdate();
1625 }
1626
1627 + (NSArray *)_supportedMIMETypes
1628 {
1629     // Load the plug-in DB allowing plug-ins to install types.
1630     [WebPluginDatabase sharedDatabase];
1631     return [[WebFrameView _viewTypesAllowImageTypeOmission:NO] allKeys];
1632 }
1633
1634 #if !PLATFORM(IOS_FAMILY)
1635 + (NSArray *)_supportedFileExtensions
1636 {
1637     NSMutableSet *extensions = [[NSMutableSet alloc] init];
1638     NSArray *MIMETypes = [self _supportedMIMETypes];
1639     NSEnumerator *enumerator = [MIMETypes objectEnumerator];
1640     NSString *MIMEType;
1641     while ((MIMEType = [enumerator nextObject]) != nil) {
1642         NSArray *extensionsForType = [[NSURLFileTypeMappings sharedMappings] extensionsForMIMEType:MIMEType];
1643         if (extensionsForType) {
1644             [extensions addObjectsFromArray:extensionsForType];
1645         }
1646     }
1647     NSArray *uniqueExtensions = [extensions allObjects];
1648     [extensions release];
1649     return uniqueExtensions;
1650 }
1651 #endif
1652
1653 #if PLATFORM(IOS_FAMILY)
1654 + (void)enableWebThread
1655 {
1656     static BOOL isWebThreadEnabled = NO;
1657     if (!isWebThreadEnabled) {
1658         WebCoreObjCDeallocOnWebThread([DOMObject class]);
1659         WebCoreObjCDeallocOnWebThread([WebBasePluginPackage class]);
1660         WebCoreObjCDeallocOnWebThread([WebDataSource class]);
1661         WebCoreObjCDeallocOnWebThread([WebFrame class]);
1662         WebCoreObjCDeallocOnWebThread([WebHTMLView class]);
1663         WebCoreObjCDeallocOnWebThread([WebHistoryItem class]);
1664         WebCoreObjCDeallocOnWebThread([WebPlainWhiteView class]);
1665         WebCoreObjCDeallocOnWebThread([WebPolicyDecisionListener class]);
1666         WebCoreObjCDeallocOnWebThread([WebView class]);
1667         WebCoreObjCDeallocOnWebThread([WebVisiblePosition class]);
1668         WebThreadEnable();
1669         isWebThreadEnabled = YES;
1670     }
1671 }
1672
1673 - (id)initSimpleHTMLDocumentWithStyle:(NSString *)style frame:(CGRect)frame preferences:(WebPreferences *)preferences groupName:(NSString *)groupName
1674 {
1675     self = [super initWithFrame:frame];
1676     if (!self)
1677         return nil;
1678     
1679     _private = [[WebViewPrivate alloc] init];
1680     
1681 #ifndef NDEBUG
1682     WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
1683 #endif
1684     
1685     if (!preferences)
1686         preferences = [WebPreferences standardPreferences];
1687     [preferences willAddToWebView];
1688     
1689     _private->preferences = [preferences retain];
1690     _private->mainFrameDocumentReady = NO;
1691     _private->drawsBackground = YES;
1692     _private->backgroundColor = CGColorRetain(cachedCGColor(Color::white));
1693
1694     WebFrameView *frameView = nil;
1695     frameView = [[WebFrameView alloc] initWithFrame: CGRectMake(0,0,frame.size.width,frame.size.height)];
1696     [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1697     [self addSubview:frameView];
1698     [frameView release];
1699
1700     _private->group = WebViewGroup::getOrCreate(groupName, _private->preferences._localStorageDatabasePath);
1701     _private->group->addWebView(self);
1702
1703     auto storageProvider = PageStorageSessionProvider::create();
1704     PageConfiguration pageConfiguration(
1705         makeUniqueRef<WebEditorClient>(self),
1706         SocketProvider::create(),
1707         LibWebRTCProvider::create(),
1708         WebCore::CacheStorageProvider::create(),
1709         BackForwardList::create(self),
1710         CookieJar::create(storageProvider.copyRef())
1711     );
1712     pageConfiguration.chromeClient = new WebChromeClientIOS(self);
1713 #if ENABLE(DRAG_SUPPORT)
1714     pageConfiguration.dragClient = new WebDragClient(self);
1715 #endif
1716
1717 #if ENABLE(APPLE_PAY)
1718     pageConfiguration.paymentCoordinatorClient = new WebPaymentCoordinatorClient();
1719 #endif
1720
1721     pageConfiguration.inspectorClient = new WebInspectorClient(self);
1722     pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
1723     pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(self);
1724     pageConfiguration.applicationCacheStorage = &webApplicationCacheStorage();
1725     pageConfiguration.databaseProvider = &WebDatabaseProvider::singleton();
1726     pageConfiguration.storageNamespaceProvider = &_private->group->storageNamespaceProvider();
1727     pageConfiguration.userContentProvider = &_private->group->userContentController();
1728     pageConfiguration.visitedLinkStore = &_private->group->visitedLinkStore();
1729     pageConfiguration.pluginInfoProvider = &WebPluginInfoProvider::singleton();
1730
1731     _private->page = new Page(WTFMove(pageConfiguration));
1732     storageProvider->setPage(*_private->page);
1733     
1734     [self setSmartInsertDeleteEnabled:YES];
1735     
1736     // FIXME: <rdar://problem/6851451> Should respect preferences in fast path WebView initialization
1737     // We are ignoring the preferences object on fast path and just using Settings defaults (everything fancy off).
1738     // This matches how UIKit sets up the preferences. We need to set  default values for fonts though, <rdar://problem/6850611>.
1739     // This should be revisited later. There is some risk involved, _preferencesChanged used to show up badly in Shark.
1740     _private->page->settings().setMinimumLogicalFontSize(9);
1741     _private->page->settings().setDefaultFontSize([_private->preferences defaultFontSize]);
1742     _private->page->settings().setDefaultFixedFontSize(13);
1743     _private->page->settings().setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
1744     _private->page->settings().setDisplayListDrawingEnabled([preferences displayListDrawingEnabled]);
1745     
1746     _private->page->settings().setFontFallbackPrefersPictographs(true);
1747     _private->page->settings().setPictographFontFamily("AppleColorEmoji");
1748     
1749     _private->page->settings().setScriptMarkupEnabled(false);
1750     _private->page->settings().setScriptEnabled(true);
1751     
1752     // FIXME: this is a workaround for <rdar://problem/11518688> REGRESSION: Quoted text font changes when replying to certain email
1753     _private->page->settings().setStandardFontFamily([_private->preferences standardFontFamily]);
1754     
1755     // FIXME: this is a workaround for <rdar://problem/11820090> Quoted text changes in size when replying to certain email
1756     _private->page->settings().setMinimumFontSize([_private->preferences minimumFontSize]);
1757
1758     // This is a workaround for <rdar://problem/21309911>.
1759     _private->page->settings().setHttpEquivEnabled([_private->preferences httpEquivEnabled]);
1760
1761     _private->page->setGroupName(groupName);
1762
1763 #if ENABLE(REMOTE_INSPECTOR)
1764     _private->page->setRemoteInspectionAllowed(isInternalInstall());
1765 #endif
1766     
1767     [self _updateScreenScaleFromWindow];
1768     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
1769     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
1770
1771     [WebFrame _createMainFrameWithSimpleHTMLDocumentWithPage:_private->page frameView:frameView style:style];
1772     
1773     [self _addToAllWebViewsSet];
1774     
1775     ++WebViewCount;
1776     
1777     SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1778     
1779     RuntimeEnabledFeatures::sharedFeatures().setAttachmentElementEnabled(self.preferences.attachmentElementEnabled);
1780
1781     return self;
1782 }
1783
1784 + (void)_releaseMemoryNow
1785 {
1786     WebThreadRun(^{
1787         WebCore::releaseMemory(Critical::Yes, Synchronous::Yes);
1788     });
1789 }
1790
1791 - (void)_replaceCurrentHistoryItem:(WebHistoryItem *)item
1792 {
1793     Frame* frame = [self _mainCoreFrame];
1794     if (frame)
1795         frame->loader().history().replaceCurrentItem(core(item));
1796 }
1797
1798 + (void)willEnterBackgroundWithCompletionHandler:(void(^)(void))handler
1799 {
1800     WebThreadRun(^{
1801         [WebView _releaseMemoryNow];
1802         dispatch_async(dispatch_get_main_queue(), handler);
1803     });
1804 }
1805
1806 + (BOOL)isCharacterSmartReplaceExempt:(unichar)character isPreviousCharacter:(BOOL)b
1807 {
1808     return WebCore::isCharacterSmartReplaceExempt(character, b);
1809 }
1810
1811 - (void)updateLayoutIgnorePendingStyleSheets
1812 {
1813     WebThreadRun(^{
1814         for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext()) {
1815             Document *document = frame->document();
1816             if (document)
1817                 document->updateLayoutIgnorePendingStylesheets();
1818         }
1819     });
1820 }
1821 #endif
1822
1823 #if PLATFORM(IOS_FAMILY)
1824
1825 #if ENABLE(DRAG_SUPPORT)
1826
1827 - (BOOL)_requestStartDataInteraction:(CGPoint)clientPosition globalPosition:(CGPoint)globalPosition
1828 {
1829     WebThreadLock();
1830     return _private->page->mainFrame().eventHandler().tryToBeginDragAtPoint(IntPoint(clientPosition), IntPoint(globalPosition));
1831 }
1832
1833 - (void)_startDrag:(const DragItem&)dragItem
1834 {
1835     auto& dragImage = dragItem.image;
1836     auto image = dragImage.get().get();
1837     auto indicatorData = dragImage.indicatorData();
1838
1839     if (indicatorData)
1840         _private->textIndicatorData = adoptNS([[WebUITextIndicatorData alloc] initWithImage:image textIndicatorData:indicatorData.value() scale:_private->page->deviceScaleFactor()]);
1841     else
1842         _private->textIndicatorData = adoptNS([[WebUITextIndicatorData alloc] initWithImage:image scale:_private->page->deviceScaleFactor()]);
1843     _private->draggedLinkURL = dragItem.url.isEmpty() ? nil : (NSURL *)dragItem.url;
1844     _private->draggedLinkTitle = dragItem.title.isEmpty() ? nil : (NSString *)dragItem.title;
1845     _private->dragPreviewFrameInRootViewCoordinates = dragItem.dragPreviewFrameInRootViewCoordinates;
1846     _private->dragSourceAction = static_cast<WebDragSourceAction>(dragItem.sourceAction);
1847 }
1848
1849 - (CGRect)_dataInteractionCaretRect
1850 {
1851     WebThreadLock();
1852     if (auto* page = _private->page)
1853         return page->dragCaretController().caretRectInRootViewCoordinates();
1854
1855     return { };
1856 }
1857
1858 - (WebUITextIndicatorData *)_dataOperationTextIndicator
1859 {
1860     return _private->dataOperationTextIndicator.get();
1861 }
1862
1863 - (WebDragSourceAction)_dragSourceAction
1864 {
1865     return _private->dragSourceAction;
1866 }
1867
1868 - (NSString *)_draggedLinkTitle
1869 {
1870     return _private->draggedLinkTitle.get();
1871 }
1872
1873 - (NSURL *)_draggedLinkURL
1874 {
1875     return _private->draggedLinkURL.get();
1876 }
1877
1878 - (CGRect)_draggedElementBounds
1879 {
1880     return _private->dragPreviewFrameInRootViewCoordinates;
1881 }
1882
1883 - (WebUITextIndicatorData *)_getDataInteractionData
1884 {
1885     return _private->textIndicatorData.get();
1886 }
1887
1888 - (WebDragDestinationAction)dragDestinationActionMaskForSession:(id <UIDropSession>)session
1889 {
1890     return [self._UIDelegateForwarder webView:self dragDestinationActionMaskForSession:session];
1891 }
1892
1893 - (DragData)dragDataForSession:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1894 {
1895     auto dragOperationMask = static_cast<DragOperation>(operation);
1896     auto dragDestinationMask = static_cast<DragDestinationAction>([self dragDestinationActionMaskForSession:session]);
1897     return { session, roundedIntPoint(clientPosition), roundedIntPoint(globalPosition), dragOperationMask, DragApplicationNone, dragDestinationMask };
1898 }
1899
1900 - (uint64_t)_enteredDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1901 {
1902     WebThreadLock();
1903     auto dragData = [self dragDataForSession:session client:clientPosition global:globalPosition operation:operation];
1904     return _private->page->dragController().dragEntered(dragData);
1905 }
1906
1907 - (uint64_t)_updatedDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1908 {
1909     WebThreadLock();
1910     auto dragData = [self dragDataForSession:session client:clientPosition global:globalPosition operation:operation];
1911     return _private->page->dragController().dragUpdated(dragData);
1912 }
1913 - (void)_exitedDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1914 {
1915     WebThreadLock();
1916     auto dragData = [self dragDataForSession:session client:clientPosition global:globalPosition operation:operation];
1917     _private->page->dragController().dragExited(dragData);
1918 }
1919 - (void)_performDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1920 {
1921     [self _tryToPerformDataInteraction:session client:clientPosition global:globalPosition operation:operation];
1922 }
1923
1924 - (BOOL)_tryToPerformDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1925 {
1926     WebThreadLock();
1927     auto dragData = [self dragDataForSession:session client:clientPosition global:globalPosition operation:operation];
1928     return _private->page->dragController().performDragOperation(dragData);
1929 }
1930
1931 - (void)_endedDataInteraction:(CGPoint)clientPosition global:(CGPoint)globalPosition
1932 {
1933     WebThreadLock();
1934     _private->page->dragController().dragEnded();
1935     _private->dataOperationTextIndicator = nullptr;
1936     _private->dragPreviewFrameInRootViewCoordinates = CGRectNull;
1937     _private->dragSourceAction = WebDragSourceActionNone;
1938     _private->draggedLinkTitle = nil;
1939     _private->draggedLinkURL = nil;
1940 }
1941
1942 - (void)_didConcludeEditDrag
1943 {
1944     _private->dataOperationTextIndicator = nullptr;
1945     auto* page = _private->page;
1946     if (!page)
1947         return;
1948
1949     static auto defaultEditDragTextIndicatorOptions = TextIndicatorOptionIncludeSnapshotOfAllVisibleContentWithoutSelection | TextIndicatorOptionExpandClipBeyondVisibleRect | TextIndicatorOptionPaintAllContent | TextIndicatorOptionIncludeMarginIfRangeMatchesSelection | TextIndicatorOptionPaintBackgrounds | TextIndicatorOptionUseSelectionRectForSizing | TextIndicatorOptionIncludeSnapshotWithSelectionHighlight | TextIndicatorOptionRespectTextColor;
1950     auto& frame = page->focusController().focusedOrMainFrame();
1951     if (auto range = frame.selection().selection().toNormalizedRange()) {
1952         if (auto textIndicator = TextIndicator::createWithRange(*range, defaultEditDragTextIndicatorOptions, TextIndicatorPresentationTransition::None, FloatSize()))
1953             _private->dataOperationTextIndicator = adoptNS([[WebUITextIndicatorData alloc] initWithImage:nil textIndicatorData:textIndicator->data() scale:page->deviceScaleFactor()]);
1954     }
1955 }
1956
1957 #elif __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1958
1959 - (BOOL)_requestStartDataInteraction:(CGPoint)clientPosition globalPosition:(CGPoint)globalPosition
1960 {
1961     return NO;
1962 }
1963
1964 - (WebUITextIndicatorData *)_getDataInteractionData
1965 {
1966     return nil;
1967 }
1968
1969 - (WebUITextIndicatorData *)_dataOperationTextIndicator
1970 {
1971     return nil;
1972 }
1973
1974 - (NSUInteger)_dragSourceAction
1975 {
1976     return 0;
1977 }
1978
1979 - (NSString *)_draggedLinkTitle
1980 {
1981     return nil;
1982 }
1983
1984 - (NSURL *)_draggedLinkURL
1985 {
1986     return nil;
1987 }
1988
1989 - (CGRect)_draggedElementBounds
1990 {
1991     return CGRectNull;
1992 }
1993
1994 - (uint64_t)_enteredDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1995 {
1996     return 0;
1997 }
1998
1999 - (uint64_t)_updatedDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
2000 {
2001     return 0;
2002 }
2003
2004 - (void)_exitedDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
2005 {
2006 }
2007
2008 - (void)_performDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
2009 {
2010 }
2011
2012 - (BOOL)_tryToPerformDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
2013 {
2014     return NO;
2015 }
2016
2017 - (void)_endedDataInteraction:(CGPoint)clientPosition global:(CGPoint)globalPosition
2018 {
2019 }
2020
2021 - (CGRect)_dataInteractionCaretRect
2022 {
2023     return CGRectNull;
2024 }
2025
2026 #endif
2027 #endif // PLATFORM(IOS_FAMILY)
2028
2029 static NSMutableSet *knownPluginMIMETypes()
2030 {
2031     static NSMutableSet *mimeTypes = [[NSMutableSet alloc] init];
2032     
2033     return mimeTypes;
2034 }
2035
2036 + (void)_registerPluginMIMEType:(NSString *)MIMEType
2037 {
2038     [WebView registerViewClass:[WebHTMLView class] representationClass:[WebHTMLRepresentation class] forMIMEType:MIMEType];
2039     [knownPluginMIMETypes() addObject:MIMEType];
2040 }
2041
2042 + (void)_unregisterPluginMIMEType:(NSString *)MIMEType
2043 {
2044     [self _unregisterViewClassAndRepresentationClassForMIMEType:MIMEType];
2045     [knownPluginMIMETypes() removeObject:MIMEType];
2046 }
2047
2048 + (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType allowingPlugins:(BOOL)allowPlugins
2049 {
2050     MIMEType = [MIMEType lowercaseString];
2051     Class viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
2052     Class repClass = [[WebDataSource _repTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
2053
2054 #if PLATFORM(IOS_FAMILY)
2055 #define WebPDFView ([WebView _getPDFViewClass])
2056 #endif
2057     if (!viewClass || !repClass || [[WebPDFView supportedMIMETypes] containsObject:MIMEType]) {
2058 #if PLATFORM(IOS_FAMILY)
2059 #undef WebPDFView
2060 #endif
2061         // Our optimization to avoid loading the plug-in DB and image types for the HTML case failed.
2062
2063         if (allowPlugins) {
2064             // Load the plug-in DB allowing plug-ins to install types.
2065             [WebPluginDatabase sharedDatabase];
2066         }
2067
2068         // Load the image types and get the view class and rep class. This should be the fullest picture of all handled types.
2069         viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
2070         repClass = [[WebDataSource _repTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
2071     }
2072     
2073     if (viewClass && repClass) {
2074         if (viewClass == [WebHTMLView class] && repClass == [WebHTMLRepresentation class]) {
2075             // Special-case WebHTMLView for text types that shouldn't be shown.
2076             if ([[WebHTMLView unsupportedTextMIMETypes] containsObject:MIMEType])
2077                 return NO;
2078
2079             // If the MIME type is a known plug-in we might not want to load it.
2080             if (!allowPlugins && [knownPluginMIMETypes() containsObject:MIMEType]) {
2081                 BOOL isSupportedByWebKit = [[WebHTMLView supportedNonImageMIMETypes] containsObject:MIMEType] ||
2082                     [[WebHTMLView supportedMIMETypes] containsObject:MIMEType];
2083                 
2084                 // If this is a known plug-in MIME type and WebKit can't show it natively, we don't want to show it.
2085                 if (!isSupportedByWebKit)
2086                     return NO;
2087             }
2088         }
2089         if (vClass)
2090             *vClass = viewClass;
2091         if (rClass)
2092             *rClass = repClass;
2093         return YES;
2094     }
2095     
2096     return NO;
2097 }
2098
2099 - (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType
2100 {
2101     if ([[self class] _viewClass:vClass andRepresentationClass:rClass forMIMEType:MIMEType allowingPlugins:[_private->preferences arePlugInsEnabled]])
2102         return YES;
2103 #if !PLATFORM(IOS_FAMILY)
2104     if (_private->pluginDatabase) {
2105         WebBasePluginPackage *pluginPackage = [_private->pluginDatabase pluginForMIMEType:MIMEType];
2106         if (pluginPackage) {
2107             if (vClass)
2108                 *vClass = [WebHTMLView class];
2109             if (rClass)
2110                 *rClass = [WebHTMLRepresentation class];
2111             return YES;
2112         }
2113     }
2114 #endif
2115     return NO;
2116 }
2117
2118 + (void)_setAlwaysUsesComplexTextCodePath:(BOOL)f
2119 {
2120     FontCascade::setCodePath(f ? FontCascade::Complex : FontCascade::Auto);
2121 }
2122
2123 + (BOOL)canCloseAllWebViews
2124 {
2125     return DOMWindow::dispatchAllPendingBeforeUnloadEvents();
2126 }
2127
2128 + (void)closeAllWebViews
2129 {
2130     DOMWindow::dispatchAllPendingUnloadEvents();
2131
2132     // This will close the WebViews in a random order. Change this if close order is important.
2133     for (WebView *webView in [(__bridge NSSet *)allWebViewsSet allObjects])
2134         [webView close];
2135 }
2136
2137 + (BOOL)canShowFile:(NSString *)path
2138 {
2139     return [[self class] canShowMIMEType:[WebView _MIMETypeForFile:path]];
2140 }
2141
2142 #if !PLATFORM(IOS_FAMILY)
2143 + (NSString *)suggestedFileExtensionForMIMEType:(NSString *)type
2144 {
2145     return [[NSURLFileTypeMappings sharedMappings] preferredExtensionForMIMEType:type];
2146 }
2147 #endif
2148
2149 - (BOOL)_isClosed
2150 {
2151     return !_private || _private->closed;
2152 }
2153
2154 #if PLATFORM(IOS_FAMILY)
2155
2156 - (void)_dispatchUnloadEvent
2157 {
2158     WebThreadRun(^{
2159         WebFrame *mainFrame = [self mainFrame];
2160         Frame *coreMainFrame = core(mainFrame);
2161         if (coreMainFrame) {
2162             Document *document = coreMainFrame->document();
2163             if (document)
2164                 document->dispatchWindowEvent(Event::create(eventNames().unloadEvent, Event::CanBubble::No, Event::IsCancelable::No));
2165         }
2166     });
2167 }
2168
2169 - (DOMCSSStyleDeclaration *)styleAtSelectionStart
2170 {
2171     auto* mainFrame = [self _mainCoreFrame];
2172     if (!mainFrame)
2173         return nil;
2174     RefPtr<EditingStyle> editingStyle = EditingStyle::styleAtSelectionStart(mainFrame->selection().selection());
2175     if (!editingStyle)
2176         return nil;
2177     auto* style = editingStyle->style();
2178     if (!style)
2179         return nil;
2180     return kit(&style->ensureCSSStyleDeclaration());
2181 }
2182
2183 - (NSUInteger)_renderTreeSize
2184 {
2185     if (!_private->page)
2186         return 0;
2187     return _private->page->renderTreeSize();
2188 }
2189
2190 - (void)_dispatchTileDidDraw:(CALayer*)tile
2191 {
2192     id mailDelegate = [self _webMailDelegate];
2193     if ([mailDelegate respondsToSelector:@selector(_webthread_webView:tileDidDraw:)]) {
2194         [mailDelegate _webthread_webView:self tileDidDraw:tile];
2195         return;
2196     }
2197
2198     ALLOW_DEPRECATED_DECLARATIONS_BEGIN
2199     if (!OSAtomicCompareAndSwap32(0, 1, &_private->didDrawTiles))
2200         return;
2201     ALLOW_DEPRECATED_DECLARATIONS_END
2202
2203     WebThreadLock();
2204
2205     [[[self _UIKitDelegateForwarder] asyncForwarder] webViewDidDrawTiles:self];
2206 }
2207
2208 - (void)_willStartScrollingOrZooming
2209 {
2210     // Pause timers during top level interaction
2211     if (_private->mainViewIsScrollingOrZooming)
2212         return;
2213     _private->mainViewIsScrollingOrZooming = YES;
2214
2215     [self hideFormValidationMessage];
2216
2217     // This suspends active DOM objects like timers, but not media.
2218     [[self mainFrame] setTimeoutsPaused:YES];
2219
2220     // This defers loading callbacks only.
2221     // WARNING: This behavior could change if Bug 49401 lands in open source WebKit again.
2222     [self setDefersCallbacks:YES];
2223 }
2224
2225 - (void)_didFinishScrollingOrZooming
2226 {
2227     if (!_private->mainViewIsScrollingOrZooming)
2228         return;
2229     _private->mainViewIsScrollingOrZooming = NO;
2230     [self setDefersCallbacks:NO];
2231     [[self mainFrame] setTimeoutsPaused:NO];
2232     if (FrameView* view = [self _mainCoreFrame]->view())
2233         view->resumeVisibleImageAnimationsIncludingSubframes();
2234 }
2235
2236 - (void)_setResourceLoadSchedulerSuspended:(BOOL)suspend
2237 {
2238     if (suspend)
2239         webResourceLoadScheduler().suspendPendingRequests();
2240     else
2241         webResourceLoadScheduler().resumePendingRequests();
2242 }
2243
2244 + (BOOL)_isUnderMemoryPressure
2245 {
2246     return MemoryPressureHandler::singleton().isUnderMemoryPressure();
2247 }
2248
2249 #endif // PLATFORM(IOS_FAMILY)
2250
2251 - (void)_closePluginDatabases
2252 {
2253     pluginDatabaseClientCount--;
2254
2255     // Close both sets of plug-in databases because plug-ins need an opportunity to clean up files, etc.
2256
2257 #if !PLATFORM(IOS_FAMILY)
2258     // Unload the WebView local plug-in database. 
2259     if (_private->pluginDatabase) {
2260         [_private->pluginDatabase destroyAllPluginInstanceViews];
2261         [_private->pluginDatabase close];
2262         [_private->pluginDatabase release];
2263         _private->pluginDatabase = nil;
2264     }
2265 #endif
2266     
2267     // Keep the global plug-in database active until the app terminates to avoid having to reload plug-in bundles.
2268     if (!pluginDatabaseClientCount && applicationIsTerminating)
2269         [WebPluginDatabase closeSharedDatabase];
2270 }
2271
2272 - (void)_closeWithFastTeardown 
2273 {
2274 #ifndef NDEBUG
2275     WTF::RefCountedLeakCounter::suppressMessages("At least one WebView was closed with fast teardown.");
2276 #endif
2277
2278 #if !PLATFORM(IOS_FAMILY)
2279     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
2280 #endif
2281     [[NSNotificationCenter defaultCenter] removeObserver:self];
2282
2283     [self _closePluginDatabases];
2284 }
2285
2286 static bool fastDocumentTeardownEnabled()
2287 {
2288 #ifdef NDEBUG
2289     static bool enabled = ![[NSUserDefaults standardUserDefaults] boolForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
2290 #else
2291     static bool initialized = false;
2292     static bool enabled = false;
2293     if (!initialized) {
2294         // This allows debug builds to default to not have fast teardown, so leak checking still works.
2295         // But still allow the WebKitEnableFullDocumentTeardown default to override it if present.
2296         NSNumber *setting = [[NSUserDefaults standardUserDefaults] objectForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
2297         if (setting)
2298             enabled = ![setting boolValue];
2299         initialized = true;
2300     }
2301 #endif
2302     return enabled;
2303 }
2304
2305 // _close is here only for backward compatibility; clients and subclasses should use
2306 // public method -close instead.
2307 - (void)_close
2308 {
2309 #if PLATFORM(IOS_FAMILY)
2310     // Always clear delegates on calling thread, becasue caller can deallocate delegates right after calling -close
2311     // (and could in fact already be in delegate's -dealloc method, as seen in <rdar://problem/11540972>).
2312
2313     [self _clearDelegates];
2314
2315     // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
2316     WebThreadRun(^{
2317 #endif            
2318
2319     if (!_private || _private->closed)
2320         return;
2321
2322     [[NSNotificationCenter defaultCenter] postNotificationName:WebViewWillCloseNotification object:self];
2323
2324     _private->closed = YES;
2325     [self _removeFromAllWebViewsSet];
2326
2327 #ifndef NDEBUG
2328     WTF::RefCountedLeakCounter::cancelMessageSuppression(webViewIsOpen);
2329 #endif
2330
2331     // To quit the apps fast we skip document teardown, except plugins
2332     // need to be destroyed and unloaded.
2333     if (applicationIsTerminating && fastDocumentTeardownEnabled()) {
2334         [self _closeWithFastTeardown];
2335         return;
2336     }
2337
2338 #if ENABLE(VIDEO) && !PLATFORM(IOS_FAMILY)
2339     [self _exitVideoFullscreen];
2340 #endif
2341
2342 #if PLATFORM(IOS_FAMILY)
2343     _private->closing = YES;
2344 #endif
2345
2346     if (Frame* mainFrame = [self _mainCoreFrame])
2347         mainFrame->loader().detachFromParent();
2348
2349     [self setHostWindow:nil];
2350
2351 #if !PLATFORM(IOS_FAMILY)
2352     [self setDownloadDelegate:nil];
2353     [self setEditingDelegate:nil];
2354     [self setFrameLoadDelegate:nil];
2355     [self setPolicyDelegate:nil];
2356     [self setResourceLoadDelegate:nil];
2357     [self setScriptDebugDelegate:nil];
2358     [self setUIDelegate:nil];
2359
2360     [_private->inspector inspectedWebViewClosed];
2361 #endif
2362 #if PLATFORM(MAC)
2363     [_private->immediateActionController webViewClosed];
2364 #endif
2365
2366 #if !PLATFORM(IOS_FAMILY)
2367     // To avoid leaks, call removeDragCaret in case it wasn't called after moveDragCaretToPoint.
2368     [self removeDragCaret];
2369 #endif
2370
2371     _private->group->removeWebView(self);
2372
2373     // Deleteing the WebCore::Page will clear the page cache so we call destroy on
2374     // all the plug-ins in the page cache to break any retain cycles.
2375     // See comment in HistoryItem::releaseAllPendingPageCaches() for more information.
2376     Page* page = _private->page;
2377     _private->page = nullptr;
2378     WebKit::DeferredPageDestructor::createDeferredPageDestructor(std::unique_ptr<Page>(page));
2379
2380 #if !PLATFORM(IOS_FAMILY)
2381     if (_private->hasSpellCheckerDocumentTag) {
2382         [[NSSpellChecker sharedSpellChecker] closeSpellDocumentWithTag:_private->spellCheckerDocumentTag];
2383         _private->hasSpellCheckerDocumentTag = NO;
2384     }
2385 #endif
2386
2387     if (_private->layerFlushController) {
2388         _private->layerFlushController->invalidate();
2389         _private->layerFlushController = nullptr;
2390     }
2391
2392     [[self _notificationProvider] unregisterWebView:self];
2393
2394 #if !PLATFORM(IOS_FAMILY)
2395     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
2396 #endif
2397     [[NSNotificationCenter defaultCenter] removeObserver:self];
2398
2399     [WebPreferences _removeReferenceForIdentifier:[self preferencesIdentifier]];
2400
2401     WebPreferences *preferences = _private->preferences;
2402     _private->preferences = nil;
2403     [preferences didRemoveFromWebView];
2404     [preferences release];
2405
2406     [self _closePluginDatabases];
2407
2408 #if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS_FAMILY)
2409     if (_private->m_playbackTargetPicker) {
2410         _private->m_playbackTargetPicker->invalidate();
2411         _private->m_playbackTargetPicker = nullptr;
2412     }
2413 #endif
2414
2415 #ifndef NDEBUG
2416     // Need this to make leak messages accurate.
2417     if (applicationIsTerminating) {
2418         WebCore::GCController::singleton().garbageCollectNow();
2419         [WebCache setDisabled:YES];
2420     }
2421 #endif
2422 #if PLATFORM(IOS_FAMILY)
2423     // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
2424     });
2425 #endif            
2426 }
2427
2428 // Indicates if the WebView is in the midst of a user gesture.
2429 - (BOOL)_isProcessingUserGesture
2430 {
2431     return UserGestureIndicator::processingUserGesture();
2432 }
2433
2434 + (NSString *)_MIMETypeForFile:(NSString *)path
2435 {
2436 #if !PLATFORM(IOS_FAMILY)
2437     NSString *extension = [path pathExtension];
2438 #endif
2439     NSString *MIMEType = nil;
2440
2441 #if !PLATFORM(IOS_FAMILY)
2442     // Get the MIME type from the extension.
2443     if ([extension length] != 0) {
2444         MIMEType = [[NSURLFileTypeMappings sharedMappings] MIMETypeForExtension:extension];
2445     }
2446 #endif
2447
2448     // If we can't get a known MIME type from the extension, sniff.
2449     if ([MIMEType length] == 0 || [MIMEType isEqualToString:@"application/octet-stream"]) {
2450         NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
2451         NSData *data = [handle readDataOfLength:WEB_GUESS_MIME_TYPE_PEEK_LENGTH];
2452         [handle closeFile];
2453         if ([data length] != 0) {
2454             MIMEType = [data _webkit_guessedMIMEType];
2455         }
2456         if ([MIMEType length] == 0) {
2457             MIMEType = @"application/octet-stream";
2458         }
2459     }
2460
2461     return MIMEType;
2462 }
2463
2464 - (WebDownload *)_downloadURL:(NSURL *)URL
2465 {
2466     ASSERT(URL);
2467     
2468     NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
2469 ALLOW_DEPRECATED_DECLARATIONS_BEGIN
2470     WebDownload *download = [WebDownload _downloadWithRequest:request delegate:_private->downloadDelegate directory:nil];
2471 ALLOW_DEPRECATED_DECLARATIONS_END
2472     [request release];
2473
2474     return download;
2475 }
2476
2477 - (WebView *)_openNewWindowWithRequest:(NSURLRequest *)request
2478 {
2479     NSDictionary *features = [[NSDictionary alloc] init];
2480     WebView *newWindowWebView = [[self _UIDelegateForwarder] webView:self
2481                                             createWebViewWithRequest:nil
2482                                                       windowFeatures:features];
2483     [features release];
2484     if (!newWindowWebView)
2485         return nil;
2486
2487     CallUIDelegate(newWindowWebView, @selector(webViewShow:));
2488     return newWindowWebView;
2489 }
2490
2491 - (BOOL)_useDarkAppearance
2492 {
2493     if (!_private || !_private->page)
2494         return NO;
2495     return _private->page->useDarkAppearance();
2496 }
2497
2498 - (void)_setUseDarkAppearance:(BOOL)useDarkAppearance
2499 {
2500     if (!_private || !_private->page)
2501         return;
2502     _private->page->setUseDarkAppearance(useDarkAppearance);
2503 }
2504
2505 + (void)_setIconLoadingEnabled:(BOOL)enabled
2506 {
2507     iconLoadingEnabled = enabled;
2508 }
2509
2510 + (BOOL)_isIconLoadingEnabled
2511 {
2512     return iconLoadingEnabled;
2513 }
2514
2515 - (WebInspector *)inspector
2516 {
2517     if (!_private->inspector)
2518         _private->inspector = [[WebInspector alloc] initWithInspectedWebView:self];
2519     return _private->inspector;
2520 }
2521
2522 #if ENABLE(REMOTE_INSPECTOR)
2523 + (void)_enableRemoteInspector
2524 {
2525     RemoteInspector::singleton().start();
2526 }
2527
2528 + (void)_disableRemoteInspector
2529 {
2530     RemoteInspector::singleton().stop();
2531 }
2532
2533 + (void)_disableAutoStartRemoteInspector
2534 {
2535     RemoteInspector::startDisabled();
2536 }
2537
2538 + (BOOL)_isRemoteInspectorEnabled
2539 {
2540     return RemoteInspector::singleton().enabled();
2541 }
2542
2543 + (BOOL)_hasRemoteInspectorSession
2544 {
2545     return RemoteInspector::singleton().hasActiveDebugSession();
2546 }
2547
2548 - (BOOL)allowsRemoteInspection
2549 {
2550     return _private->page->remoteInspectionAllowed();
2551 }
2552
2553 - (void)setAllowsRemoteInspection:(BOOL)allow
2554 {
2555     _private->page->setRemoteInspectionAllowed(allow);
2556 }
2557
2558 - (void)setShowingInspectorIndication:(BOOL)showing
2559 {
2560 #if PLATFORM(IOS_FAMILY)
2561     ASSERT(WebThreadIsLocked());
2562
2563     if (showing) {
2564         if (!_private->indicateLayer) {
2565             _private->indicateLayer = [[WebIndicateLayer alloc] initWithWebView:self];
2566             [_private->indicateLayer setNeedsLayout];
2567             [[[self window] hostLayer] addSublayer:_private->indicateLayer];
2568         }
2569     } else {
2570         [_private->indicateLayer removeFromSuperlayer];
2571         [_private->indicateLayer release];
2572         _private->indicateLayer = nil;
2573     }
2574 #else
2575     // Implemented in WebCore::InspectorOverlay.
2576 #endif
2577 }
2578
2579 #if PLATFORM(IOS_FAMILY)
2580 - (void)_setHostApplicationProcessIdentifier:(pid_t)pid auditToken:(audit_token_t)auditToken
2581 {
2582     RetainPtr<CFDataRef> auditData = adoptCF(CFDataCreate(nullptr, (const UInt8*)&auditToken, sizeof(auditToken)));
2583     RemoteInspector::singleton().setParentProcessInformation(pid, auditData);
2584 }
2585 #endif // PLATFORM(IOS_FAMILY)
2586 #endif // ENABLE(REMOTE_INSPECTOR)
2587
2588 - (WebCore::Page*)page
2589 {
2590     return _private->page;
2591 }
2592
2593 #if !PLATFORM(IOS_FAMILY)
2594 - (NSMenu *)_menuForElement:(NSDictionary *)element defaultItems:(NSArray *)items
2595 {
2596     NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate] webView:self contextMenuItemsForElement:element defaultMenuItems:items];
2597     NSArray *menuItems = defaultMenuItems;
2598
2599     // CallUIDelegate returns nil if UIDelegate is nil or doesn't respond to the selector. So we need to check that here
2600     // to distinguish between using defaultMenuItems or the delegate really returning nil to say "no context menu".
2601     SEL selector = @selector(webView:contextMenuItemsForElement:defaultMenuItems:);
2602     if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
2603         menuItems = CallUIDelegate(self, selector, element, defaultMenuItems);
2604         if (!menuItems)
2605             return nil;
2606     }
2607
2608     unsigned count = [menuItems count];
2609     if (!count)
2610         return nil;
2611
2612     NSMenu *menu = [[NSMenu alloc] init];
2613     for (unsigned i = 0; i < count; i++)
2614         [menu addItem:[menuItems objectAtIndex:i]];
2615
2616     return [menu autorelease];
2617 }
2618 #endif
2619
2620 - (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(NSUInteger)modifierFlags
2621 {
2622     // We originally intended to call this delegate method sometimes with a nil dictionary, but due to
2623     // a bug dating back to WebKit 1.0 this delegate was never called with nil! Unfortunately we can't
2624     // start calling this with nil since it will break Adobe Help Viewer, and possibly other clients.
2625     if (!dictionary)
2626         return;
2627     CallUIDelegate(self, @selector(webView:mouseDidMoveOverElement:modifierFlags:), dictionary, modifierFlags);
2628 }
2629
2630 - (void)_loadBackForwardListFromOtherView:(WebView *)otherView
2631 {
2632     if (!_private->page)
2633         return;
2634     
2635     if (!otherView->_private->page)
2636         return;
2637     
2638     // It turns out the right combination of behavior is done with the back/forward load
2639     // type.  (See behavior matrix at the top of WebFramePrivate.)  So we copy all the items
2640     // in the back forward list, and go to the current one.
2641
2642     BackForwardController& backForward = _private->page->backForward();
2643     ASSERT(!backForward.currentItem()); // destination list should be empty
2644
2645     BackForwardController& otherBackForward = otherView->_private->page->backForward();
2646     if (!otherBackForward.currentItem())
2647         return; // empty back forward list, bail
2648     
2649     HistoryItem* newItemToGoTo = nullptr;
2650
2651     int lastItemIndex = otherBackForward.forwardCount();
2652     for (int i = -otherBackForward.backCount(); i <= lastItemIndex; ++i) {
2653         if (i == 0) {
2654             // If this item is showing , save away its current scroll and form state,
2655             // since that might have changed since loading and it is normally not saved
2656             // until we leave that page.
2657             otherView->_private->page->mainFrame().loader().history().saveDocumentAndScrollState();
2658         }
2659         Ref<HistoryItem> newItem = otherBackForward.itemAtIndex(i)->copy();
2660         if (i == 0) 
2661             newItemToGoTo = newItem.ptr();
2662         backForward.client().addItem(WTFMove(newItem));
2663     }
2664
2665     ASSERT(newItemToGoTo);
2666     _private->page->goToItem(*newItemToGoTo, FrameLoadType::IndexedBackForward, ShouldTreatAsContinuingLoad::No);
2667 }
2668
2669 - (void)_setFormDelegate: (id<WebFormDelegate>)delegate
2670 {
2671     _private->formDelegate = delegate;
2672 #if PLATFORM(IOS_FAMILY)
2673     [_private->formDelegateForwarder clearTarget];
2674     [_private->formDelegateForwarder release];
2675     _private->formDelegateForwarder = nil;
2676 #endif
2677 }
2678
2679 - (id<WebFormDelegate>)_formDelegate
2680 {
2681     return _private->formDelegate;
2682 }
2683
2684 #if PLATFORM(IOS_FAMILY)
2685 - (id)_formDelegateForwarder
2686 {
2687     if (_private->closing)
2688         return nil;
2689
2690     if (!_private->formDelegateForwarder)
2691         _private->formDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:[self _formDelegate] defaultTarget:[WebDefaultFormDelegate sharedFormDelegate]];
2692     return _private->formDelegateForwarder;
2693 }
2694
2695 - (id)_formDelegateForSelector:(SEL)selector
2696 {
2697     id delegate = self->_private->formDelegate;
2698     if ([delegate respondsToSelector:selector])
2699         return delegate;
2700
2701     delegate = [WebDefaultFormDelegate sharedFormDelegate];
2702     if ([delegate respondsToSelector:selector])
2703         return delegate;
2704
2705     return nil;
2706 }
2707 #endif
2708
2709 #if !PLATFORM(IOS_FAMILY)
2710 - (BOOL)_needsAdobeFrameReloadingQuirk
2711 {
2712     static BOOL needsQuirk = _CFAppVersionCheckLessThan(CFSTR("com.adobe.Acrobat"), -1, 9.0)
2713         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.Acrobat.Pro"), -1, 9.0)
2714         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.Reader"), -1, 9.0)
2715         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.distiller"), -1, 9.0)
2716         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.Contribute"), -1, 4.2)
2717         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.dreamweaver-9.0"), -1, 9.1)
2718         || _CFAppVersionCheckLessThan(CFSTR("com.macromedia.fireworks"), -1, 9.1)
2719         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.InCopy"), -1, 5.1)
2720         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.InDesign"), -1, 5.1)
2721         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.Soundbooth"), -1, 2);
2722
2723     return needsQuirk;
2724 }
2725
2726 - (BOOL)_needsLinkElementTextCSSQuirk
2727 {
2728     static BOOL needsQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LINK_ELEMENT_TEXT_CSS_QUIRK)
2729         && _CFAppVersionCheckLessThan(CFSTR("com.e-frontier.shade10"), -1, 10.6);
2730     return needsQuirk;
2731 }
2732
2733 - (BOOL)_needsFrameNameFallbackToIdQuirk
2734 {
2735     static BOOL needsQuirk = _CFAppVersionCheckLessThan(CFSTR("info.colloquy"), -1, 2.5);
2736     return needsQuirk;
2737 }
2738
2739 - (BOOL)_needsIsLoadingInAPISenseQuirk
2740 {
2741     static BOOL needsQuirk = _CFAppVersionCheckLessThan(CFSTR("com.apple.iAdProducer"), -1, 2.1);
2742     
2743     return needsQuirk;
2744 }
2745
2746 - (BOOL)_needsKeyboardEventDisambiguationQuirks
2747 {
2748     static BOOL needsQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_IE_COMPATIBLE_KEYBOARD_EVENT_DISPATCH) && !MacApplication::isSafari();
2749     return needsQuirks;
2750 }
2751
2752 - (BOOL)_needsFrameLoadDelegateRetainQuirk
2753 {
2754     static BOOL needsQuirk = _CFAppVersionCheckLessThan(CFSTR("com.equinux.iSale5"), -1, 5.6);
2755     return needsQuirk;
2756 }
2757
2758 static bool needsSelfRetainWhileLoadingQuirk()
2759 {
2760     static bool needsQuirk = MacApplication::isAperture();
2761     return needsQuirk;
2762 }
2763 #endif // !PLATFORM(IOS_FAMILY)
2764
2765 - (BOOL)_needsPreHTML5ParserQuirks
2766 {    
2767 #if !PLATFORM(IOS_FAMILY)
2768     // AOL Instant Messenger and Microsoft My Day contain markup incompatible
2769     // with the new HTML5 parser. If these applications were linked against a
2770     // version of WebKit prior to the introduction of the HTML5 parser, enable
2771     // parser quirks to maintain compatibility. For details, see 
2772     // <https://bugs.webkit.org/show_bug.cgi?id=46134> and
2773     // <https://bugs.webkit.org/show_bug.cgi?id=46334>.
2774     static bool isApplicationNeedingParserQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
2775         && (MacApplication::isAOLInstantMessenger() || MacApplication::isMicrosoftMyDay());
2776     
2777     // Mail.app must continue to display HTML email that contains quirky markup.
2778     static bool isAppleMail = MacApplication::isAppleMail();
2779
2780     return isApplicationNeedingParserQuirks
2781         || isAppleMail
2782 #if ENABLE(DASHBOARD_SUPPORT)
2783         // Pre-HTML5 parser quirks are required to remain compatible with many
2784         // Dashboard widgets. See <rdar://problem/8175982>.
2785         || (_private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode())
2786 #endif
2787         || [[self preferences] usePreHTML5ParserQuirks];
2788 #else
2789     return [[self preferences] usePreHTML5ParserQuirks];
2790 #endif
2791 }
2792
2793 - (void)_preferencesChangedNotification:(NSNotification *)notification
2794 {
2795 #if PLATFORM(IOS_FAMILY)
2796     // For WebViews that load synchronously, preference changes need to be propagated
2797     // down to WebCore synchronously so that loads in that WebView have the correct
2798     // up-to-date settings.
2799     if (!WebThreadIsLocked())
2800         WebThreadLock();
2801     if ([[self mainFrame] _loadsSynchronously]) {
2802 #endif
2803
2804     WebPreferences *preferences = (WebPreferences *)[notification object];
2805     [self _preferencesChanged:preferences];
2806
2807 #if PLATFORM(IOS_FAMILY)
2808     } else {
2809         WebThreadRun(^{
2810             // It is possible that the prefs object has already changed before the invocation could be called
2811             // on the web thread. This is not possible on TOT which is why they have a simple ASSERT.
2812             WebPreferences *preferences = (WebPreferences *)[notification object];
2813             if (preferences != [self preferences])
2814                 return;
2815             [self _preferencesChanged:preferences];
2816         });
2817     }
2818 #endif
2819 }
2820
2821 - (void)_preferencesChanged:(WebPreferences *)preferences
2822 {    
2823     ASSERT(preferences == [self preferences]);
2824     if (!_private->userAgentOverridden)
2825         [self _invalidateUserAgentCache];
2826
2827     // Cache this value so we don't have to read NSUserDefaults on each page load
2828     _private->useSiteSpecificSpoofing = [preferences _useSiteSpecificSpoofing];
2829
2830     // Update corresponding WebCore Settings object.
2831     if (!_private->page)
2832         return;
2833
2834 #if PLATFORM(IOS_FAMILY)
2835     // iOS waits to call [WebDatabaseManager sharedWebDatabaseManager] until
2836     // didOneTimeInitialization is true so that we don't initialize databases
2837     // until the first WebView has been created. This is because database
2838     // initialization current requires disk access to populate the origins
2839     // quota map and we want to do this lazily by waiting until WebKit is
2840     // used to display web content in a WebView. The possible cases are:
2841     //   - on one time initialize (the first WebView creation) if databases are enabled (default)
2842     //   - when databases are dynamically enabled later, and they were disabled at startup (this case)
2843     if (didOneTimeInitialization) {
2844         if ([preferences databasesEnabled])
2845             [WebDatabaseManager sharedWebDatabaseManager];
2846         if ([preferences storageTrackerEnabled])
2847             WebKitInitializeStorageIfNecessary();
2848     }
2849 #endif
2850
2851     Settings& settings = _private->page->settings();
2852
2853     settings.setCursiveFontFamily([preferences cursiveFontFamily]);
2854     settings.setDefaultFixedFontSize([preferences defaultFixedFontSize]);
2855     settings.setDefaultFontSize([preferences defaultFontSize]);
2856     settings.setDefaultTextEncodingName([preferences defaultTextEncodingName]);
2857     settings.setUsesEncodingDetector([preferences usesEncodingDetector]);
2858     settings.setFantasyFontFamily([preferences fantasyFontFamily]);
2859     settings.setFixedFontFamily([preferences fixedFontFamily]);
2860     settings.setForceFTPDirectoryListings([preferences _forceFTPDirectoryListings]);
2861     settings.setFTPDirectoryTemplatePath([preferences _ftpDirectoryTemplatePath]);
2862     settings.setLocalStorageDatabasePath([preferences _localStorageDatabasePath]);
2863     settings.setJavaEnabled([preferences isJavaEnabled]);
2864     settings.setScriptEnabled([preferences isJavaScriptEnabled]);
2865     settings.setScriptMarkupEnabled([preferences javaScriptMarkupEnabled]);
2866     settings.setWebSecurityEnabled([preferences isWebSecurityEnabled]);
2867     settings.setAllowUniversalAccessFromFileURLs([preferences allowUniversalAccessFromFileURLs]);
2868     settings.setAllowFileAccessFromFileURLs([preferences allowFileAccessFromFileURLs]);
2869     settings.setAllowCrossOriginSubresourcesToAskForCredentials([preferences allowCrossOriginSubresourcesToAskForCredentials]);
2870     settings.setNeedsStorageAccessFromFileURLsQuirk([preferences needsStorageAccessFromFileURLsQuirk]);
2871     settings.setMinimumFontSize([preferences minimumFontSize]);
2872     settings.setMinimumLogicalFontSize([preferences minimumLogicalFontSize]);
2873     settings.setPictographFontFamily([preferences pictographFontFamily]);
2874     settings.setPluginsEnabled([preferences arePlugInsEnabled]);
2875     settings.setLocalStorageEnabled([preferences localStorageEnabled]);
2876
2877     _private->page->enableLegacyPrivateBrowsing([preferences privateBrowsingEnabled]);
2878     settings.setSansSerifFontFamily([preferences sansSerifFontFamily]);
2879     settings.setSerifFontFamily([preferences serifFontFamily]);
2880     settings.setStandardFontFamily([preferences standardFontFamily]);
2881     settings.setLoadsImagesAutomatically([preferences loadsImagesAutomatically]);
2882     settings.setLoadsSiteIconsIgnoringImageLoadingSetting([preferences loadsSiteIconsIgnoringImageLoadingPreference]);
2883
2884     WebCore::setAdditionalSupportedImageTypes(WebCore::webCoreStringVectorFromNSStringArray([preferences additionalSupportedImageTypes]));
2885
2886 #if PLATFORM(IOS_FAMILY)
2887     settings.setShouldPrintBackgrounds(true);
2888 #else
2889     settings.setShouldPrintBackgrounds([preferences shouldPrintBackgrounds]);
2890 #endif
2891     settings.setShrinksStandaloneImagesToFit([preferences shrinksStandaloneImagesToFit]);
2892     settings.setEditableLinkBehavior(core([preferences editableLinkBehavior]));
2893     settings.setTextDirectionSubmenuInclusionBehavior(core([preferences textDirectionSubmenuInclusionBehavior]));
2894     settings.setDOMPasteAllowed([preferences isDOMPasteAllowed]);
2895     settings.setUsesPageCache([self usesPageCache]);
2896     settings.setPageCacheSupportsPlugins([preferences pageCacheSupportsPlugins]);
2897     settings.setBackForwardCacheExpirationInterval([preferences _backForwardCacheExpirationInterval]);
2898
2899     settings.setDeveloperExtrasEnabled([preferences developerExtrasEnabled]);
2900     settings.setJavaScriptRuntimeFlags(JSC::RuntimeFlags([preferences javaScriptRuntimeFlags]));
2901     settings.setAuthorAndUserStylesEnabled([preferences authorAndUserStylesEnabled]);
2902
2903     settings.setNeedsSiteSpecificQuirks(_private->useSiteSpecificSpoofing);
2904     settings.setDOMTimersThrottlingEnabled([preferences domTimersThrottlingEnabled]);
2905     settings.setWebArchiveDebugModeEnabled([preferences webArchiveDebugModeEnabled]);
2906     settings.setLocalFileContentSniffingEnabled([preferences localFileContentSniffingEnabled]);
2907     settings.setOfflineWebApplicationCacheEnabled([preferences offlineWebApplicationCacheEnabled]);
2908     settings.setJavaScriptCanAccessClipboard([preferences javaScriptCanAccessClipboard]);
2909     settings.setXSSAuditorEnabled([preferences isXSSAuditorEnabled]);
2910     settings.setDNSPrefetchingEnabled([preferences isDNSPrefetchingEnabled]);
2911
2912     settings.setAcceleratedCompositingEnabled([preferences acceleratedCompositingEnabled]);
2913     settings.setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
2914     settings.setDisplayListDrawingEnabled([preferences displayListDrawingEnabled]);
2915     settings.setCanvasUsesAcceleratedDrawing([preferences canvasUsesAcceleratedDrawing]);
2916     settings.setShowDebugBorders([preferences showDebugBorders]);
2917     settings.setSimpleLineLayoutEnabled([preferences simpleLineLayoutEnabled]);
2918     settings.setSimpleLineLayoutDebugBordersEnabled([preferences simpleLineLayoutDebugBordersEnabled]);
2919     settings.setShowRepaintCounter([preferences showRepaintCounter]);
2920     settings.setWebGLEnabled([preferences webGLEnabled]);
2921     settings.setSubpixelCSSOMElementMetricsEnabled([preferences subpixelCSSOMElementMetricsEnabled]);
2922     settings.setSubpixelAntialiasedLayerTextEnabled([preferences subpixelAntialiasedLayerTextEnabled]);
2923
2924     settings.setForceSoftwareWebGLRendering([preferences forceSoftwareWebGLRendering]);
2925     settings.setForceWebGLUsesLowPower([preferences forceLowPowerGPUForWebGL]);
2926     settings.setAccelerated2dCanvasEnabled([preferences accelerated2dCanvasEnabled]);
2927     settings.setLoadDeferringEnabled(shouldEnableLoadDeferring());
2928     settings.setWindowFocusRestricted(shouldRestrictWindowFocus());
2929     settings.setFrameFlattening((const WebCore::FrameFlattening)[preferences frameFlattening]);
2930     settings.setAsyncFrameScrollingEnabled([preferences asyncFrameScrollingEnabled]);
2931     settings.setSpatialNavigationEnabled([preferences isSpatialNavigationEnabled]);
2932     settings.setPaginateDuringLayoutEnabled([preferences paginateDuringLayoutEnabled]);
2933
2934     settings.setAsynchronousSpellCheckingEnabled([preferences asynchronousSpellCheckingEnabled]);
2935     settings.setHyperlinkAuditingEnabled([preferences hyperlinkAuditingEnabled]);
2936     settings.setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
2937     settings.setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
2938     settings.setValidationMessageTimerMagnification([self validationMessageTimerMagnification]);
2939
2940     BOOL mediaPlaybackRequiresUserGesture = [preferences mediaPlaybackRequiresUserGesture];
2941     settings.setVideoPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture || [preferences videoPlaybackRequiresUserGesture]);
2942     settings.setAudioPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture || [preferences audioPlaybackRequiresUserGesture]);
2943     settings.setRequiresUserGestureToLoadVideo(shouldRequireUserGestureToLoadVideo());
2944     settings.setMainContentUserGestureOverrideEnabled([preferences overrideUserGestureRequirementForMainContent]);
2945     settings.setAllowsInlineMediaPlayback([preferences mediaPlaybackAllowsInline]);
2946     settings.setAllowsInlineMediaPlaybackAfterFullscreen([preferences allowsInlineMediaPlaybackAfterFullscreen]);
2947     settings.setInlineMediaPlaybackRequiresPlaysInlineAttribute([preferences inlineMediaPlaybackRequiresPlaysInlineAttribute]);
2948     settings.setInvisibleAutoplayNotPermitted([preferences invisibleAutoplayNotPermitted]);
2949     settings.setAllowsPictureInPictureMediaPlayback([preferences allowsPictureInPictureMediaPlayback] && shouldAllowPictureInPictureMediaPlayback());
2950     settings.setMediaControlsScaleWithPageZoom([preferences mediaControlsScaleWithPageZoom]);
2951     settings.setSuppressesIncrementalRendering([preferences suppressesIncrementalRendering]);
2952     settings.setBackspaceKeyNavigationEnabled([preferences backspaceKeyNavigationEnabled]);
2953     settings.setWantsBalancedSetDefersLoadingBehavior([preferences wantsBalancedSetDefersLoadingBehavior]);
2954     DeprecatedGlobalSettings::setMockScrollbarsEnabled([preferences mockScrollbarsEnabled]);
2955
2956     settings.setShouldRespectImageOrientation([preferences shouldRespectImageOrientation]);
2957
2958     settings.setRequestAnimationFrameEnabled([preferences requestAnimationFrameEnabled]);
2959     settings.setDiagnosticLoggingEnabled([preferences diagnosticLoggingEnabled]);
2960     DeprecatedGlobalSettings::setLowPowerVideoAudioBufferSizeEnabled([preferences lowPowerVideoAudioBufferSizeEnabled]);
2961
2962     settings.setUseLegacyTextAlignPositionedElementBehavior([preferences useLegacyTextAlignPositionedElementBehavior]);
2963
2964     settings.setShouldConvertPositionStyleOnCopy([preferences shouldConvertPositionStyleOnCopy]);
2965     settings.setEnableInheritURIQueryComponent([preferences isInheritURIQueryComponentEnabled]);
2966
2967     settings.setAllowDisplayOfInsecureContent(shouldAllowDisplayAndRunningOfInsecureContent());
2968     settings.setAllowRunningOfInsecureContent(shouldAllowDisplayAndRunningOfInsecureContent());
2969
2970     settings.setJavaScriptCanOpenWindowsAutomatically([preferences javaScriptCanOpenWindowsAutomatically] || shouldAllowWindowOpenWithoutUserGesture());
2971
2972     settings.setVisualViewportAPIEnabled([preferences visualViewportAPIEnabled]);
2973     settings.setCSSOMViewScrollingAPIEnabled([preferences CSSOMViewScrollingAPIEnabled]);
2974     settings.setMediaContentTypesRequiringHardwareSupport([preferences mediaContentTypesRequiringHardwareSupport]);
2975
2976     switch ([preferences storageBlockingPolicy]) {
2977     case WebAllowAllStorage:
2978         settings.setStorageBlockingPolicy(SecurityOrigin::AllowAllStorage);
2979         break;
2980     case WebBlockThirdPartyStorage:
2981         settings.setStorageBlockingPolicy(SecurityOrigin::BlockThirdPartyStorage);
2982         break;
2983     case WebBlockAllStorage:
2984         settings.setStorageBlockingPolicy(SecurityOrigin::BlockAllStorage);
2985         break;
2986     }
2987
2988     settings.setPlugInSnapshottingEnabled([preferences plugInSnapshottingEnabled]);
2989     settings.setHttpEquivEnabled([preferences httpEquivEnabled]);
2990     settings.setColorFilterEnabled([preferences colorFilterEnabled]);
2991     settings.setPunchOutWhiteBackgroundsInDarkMode([preferences punchOutWhiteBackgroundsInDarkMode]);
2992
2993 #if PLATFORM(MAC)
2994     settings.setAcceleratedCompositingForFixedPositionEnabled(true);
2995 #endif
2996
2997 #if ENABLE(RUBBER_BANDING)
2998     // FIXME: https://bugs.webkit.org/show_bug.cgi?id=136131
2999     settings.setRubberBandingForSubScrollableRegionsEnabled(false);
3000 #endif
3001
3002 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
3003     settings.setAllowsAirPlayForMediaPlayback([preferences allowsAirPlayForMediaPlayback]);
3004 #endif
3005 #if PLATFORM(IOS_FAMILY)
3006     settings.setVisualViewportEnabled(false);
3007     settings.setVisualViewportAPIEnabled(false);
3008     settings.setStandalone([preferences _standalone]);
3009     settings.setTelephoneNumberParsingEnabled([preferences _telephoneNumberParsingEnabled]);
3010     settings.setAllowMultiElementImplicitSubmission([preferences _allowMultiElementImplicitFormSubmission]);
3011     settings.setLayoutInterval(Seconds::fromMilliseconds([preferences _layoutInterval]));
3012     settings.setMaxParseDuration([preferences _maxParseDuration]);
3013     settings.setAlwaysUseAcceleratedOverflowScroll([preferences _alwaysUseAcceleratedOverflowScroll]);
3014     settings.setContentChangeObserverEnabled([preferences contentChangeObserverEnabled]);
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)_locked_recur