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