Have prefers-color-scheme: light always match on macOS versions before Mojave.
[WebKit-https.git] / Source / WebKitLegacy / mac / WebView / WebView.mm
1 /*
2  * Copyright (C) 2005-2018 Apple Inc. All rights reserved.
3  * Copyright (C) 2006 David Smith (catfish.man@gmail.com)
4  * Copyright (C) 2010 Igalia S.L
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1.  Redistributions of source code must retain the above copyright
11  *     notice, this list of conditions and the following disclaimer. 
12  * 2.  Redistributions in binary form must reproduce the above copyright
13  *     notice, this list of conditions and the following disclaimer in the
14  *     documentation and/or other materials provided with the distribution. 
15  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
16  *     its contributors may be used to endorse or promote products derived
17  *     from this software without specific prior written permission. 
18  *
19  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
20  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
23  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #import "WebViewInternal.h"
32 #import "WebViewData.h"
33
34 #import "BackForwardList.h"
35 #import "DOMCSSStyleDeclarationInternal.h"
36 #import "DOMDocumentInternal.h"
37 #import "DOMInternal.h"
38 #import "DOMNodeInternal.h"
39 #import "DOMRangeInternal.h"
40 #import "StorageThread.h"
41 #import "WebAlternativeTextClient.h"
42 #import "WebApplicationCacheInternal.h"
43 #import "WebArchive.h"
44 #import "WebBackForwardListInternal.h"
45 #import "WebBaseNetscapePluginView.h"
46 #import "WebCache.h"
47 #import "WebChromeClient.h"
48 #import "WebDOMOperationsPrivate.h"
49 #import "WebDataSourceInternal.h"
50 #import "WebDatabaseManagerPrivate.h"
51 #import "WebDatabaseProvider.h"
52 #import "WebDefaultEditingDelegate.h"
53 #import "WebDefaultPolicyDelegate.h"
54 #import "WebDefaultUIDelegate.h"
55 #import "WebDelegateImplementationCaching.h"
56 #import "WebDeviceOrientationClient.h"
57 #import "WebDeviceOrientationProvider.h"
58 #import "WebDocument.h"
59 #import "WebDocumentInternal.h"
60 #import "WebDownload.h"
61 #import "WebDragClient.h"
62 #import "WebDynamicScrollBarsViewInternal.h"
63 #import "WebEditingDelegate.h"
64 #import "WebEditorClient.h"
65 #import "WebFormDelegatePrivate.h"
66 #import "WebFrameInternal.h"
67 #import "WebFrameLoadDelegatePrivate.h"
68 #import "WebFrameLoaderClient.h"
69 #import "WebFrameNetworkingContext.h"
70 #import "WebFrameViewInternal.h"
71 #import "WebGeolocationClient.h"
72 #import "WebGeolocationPositionInternal.h"
73 #import "WebHTMLRepresentation.h"
74 #import "WebHTMLViewInternal.h"
75 #import "WebHistoryDelegate.h"
76 #import "WebHistoryItemInternal.h"
77 #import "WebIconDatabase.h"
78 #import "WebInspector.h"
79 #import "WebInspectorClient.h"
80 #import "WebKitErrors.h"
81 #import "WebKitFullScreenListener.h"
82 #import "WebKitLogging.h"
83 #import "WebKitNSStringExtras.h"
84 #import "WebKitStatisticsPrivate.h"
85 #import "WebKitVersionChecks.h"
86 #import "WebLocalizableStrings.h"
87 #import "WebNSDataExtras.h"
88 #import "WebNSDataExtrasPrivate.h"
89 #import "WebNSDictionaryExtras.h"
90 #import "WebNSURLExtras.h"
91 #import "WebNSURLRequestExtras.h"
92 #import "WebNSViewExtras.h"
93 #import "WebNodeHighlight.h"
94 #import "WebNotificationClient.h"
95 #import "WebPDFView.h"
96 #import "WebPaymentCoordinatorClient.h"
97 #import "WebPlatformStrategies.h"
98 #import "WebPluginDatabase.h"
99 #import "WebPluginInfoProvider.h"
100 #import "WebPolicyDelegate.h"
101 #import "WebPreferenceKeysPrivate.h"
102 #import "WebPreferencesPrivate.h"
103 #import "WebProgressTrackerClient.h"
104 #import "WebResourceLoadDelegate.h"
105 #import "WebResourceLoadDelegatePrivate.h"
106 #import "WebResourceLoadScheduler.h"
107 #import "WebScriptDebugDelegate.h"
108 #import "WebScriptWorldInternal.h"
109 #import "WebSelectionServiceController.h"
110 #import "WebStorageManagerInternal.h"
111 #import "WebStorageNamespaceProvider.h"
112 #import "WebTextCompletionController.h"
113 #import "WebTextIterator.h"
114 #import "WebUIDelegate.h"
115 #import "WebUIDelegatePrivate.h"
116 #import "WebValidationMessageClient.h"
117 #import "WebViewGroup.h"
118 #import "WebVisitedLinkStore.h"
119 #import <CoreFoundation/CFSet.h>
120 #import <Foundation/NSURLConnection.h>
121 #import <JavaScriptCore/APICast.h>
122 #import <JavaScriptCore/ArrayPrototype.h>
123 #import <JavaScriptCore/CatchScope.h>
124 #import <JavaScriptCore/DateInstance.h>
125 #import <JavaScriptCore/Exception.h>
126 #import <JavaScriptCore/InitializeThreading.h>
127 #import <JavaScriptCore/JSCJSValue.h>
128 #import <JavaScriptCore/JSLock.h>
129 #import <JavaScriptCore/JSValueRef.h>
130 #import <WebCore/AlternativeTextUIController.h>
131 #import <WebCore/ApplicationCacheStorage.h>
132 #import <WebCore/BackForwardController.h>
133 #import <WebCore/CSSAnimationController.h>
134 #import <WebCore/CacheStorageProvider.h>
135 #import <WebCore/Chrome.h>
136 #import <WebCore/ColorMac.h>
137 #import <WebCore/DatabaseManager.h>
138 #import <WebCore/DeprecatedGlobalSettings.h>
139 #import <WebCore/DictionaryLookup.h>
140 #import <WebCore/Document.h>
141 #import <WebCore/DocumentLoader.h>
142 #import <WebCore/DragController.h>
143 #import <WebCore/DragData.h>
144 #import <WebCore/DragItem.h>
145 #import <WebCore/Editing.h>
146 #import <WebCore/Editor.h>
147 #import <WebCore/Event.h>
148 #import <WebCore/EventHandler.h>
149 #import <WebCore/FileSystem.h>
150 #import <WebCore/FocusController.h>
151 #import <WebCore/FontAttributes.h>
152 #import <WebCore/FontCache.h>
153 #import <WebCore/Frame.h>
154 #import <WebCore/FrameLoader.h>
155 #import <WebCore/FrameSelection.h>
156 #import <WebCore/FrameTree.h>
157 #import <WebCore/FrameView.h>
158 #import <WebCore/GCController.h>
159 #import <WebCore/GameControllerGamepadProvider.h>
160 #import <WebCore/GeolocationController.h>
161 #import <WebCore/GeolocationError.h>
162 #import <WebCore/HTMLNames.h>
163 #import <WebCore/HTMLOListElement.h>
164 #import <WebCore/HTMLUListElement.h>
165 #import <WebCore/HTMLVideoElement.h>
166 #import <WebCore/HistoryController.h>
167 #import <WebCore/HistoryItem.h>
168 #import <WebCore/JSCSSStyleDeclaration.h>
169 #import <WebCore/JSDocument.h>
170 #import <WebCore/JSElement.h>
171 #import <WebCore/JSNodeList.h>
172 #import <WebCore/JSNotification.h>
173 #import <WebCore/LegacyNSPasteboardTypes.h>
174 #import <WebCore/LibWebRTCProvider.h>
175 #import <WebCore/LocalizedStrings.h>
176 #import <WebCore/LogInitialization.h>
177 #import <WebCore/MIMETypeRegistry.h>
178 #import <WebCore/MemoryCache.h>
179 #import <WebCore/MemoryRelease.h>
180 #import <WebCore/NetworkStorageSession.h>
181 #import <WebCore/NodeList.h>
182 #import <WebCore/Notification.h>
183 #import <WebCore/NotificationController.h>
184 #import <WebCore/Page.h>
185 #import <WebCore/PageCache.h>
186 #import <WebCore/PageConfiguration.h>
187 #import <WebCore/PageGroup.h>
188 #import <WebCore/PathUtilities.h>
189 #import <WebCore/PlatformEventFactoryMac.h>
190 #import <WebCore/ProgressTracker.h>
191 #import <WebCore/RenderTheme.h>
192 #import <WebCore/RenderView.h>
193 #import <WebCore/RenderWidget.h>
194 #import <WebCore/ResourceHandle.h>
195 #import <WebCore/ResourceLoadObserver.h>
196 #import <WebCore/ResourceRequest.h>
197 #import <WebCore/RuntimeApplicationChecks.h>
198 #import <WebCore/RuntimeEnabledFeatures.h>
199 #import <WebCore/SchemeRegistry.h>
200 #import <WebCore/ScriptController.h>
201 #import <WebCore/SecurityOrigin.h>
202 #import <WebCore/SecurityPolicy.h>
203 #import <WebCore/Settings.h>
204 #import <WebCore/ShouldTreatAsContinuingLoad.h>
205 #import <WebCore/SocketProvider.h>
206 #import <WebCore/StyleProperties.h>
207 #import <WebCore/TextResourceDecoder.h>
208 #import <WebCore/ThreadCheck.h>
209 #import <WebCore/UserAgent.h>
210 #import <WebCore/UserContentController.h>
211 #import <WebCore/UserGestureIndicator.h>
212 #import <WebCore/UserScript.h>
213 #import <WebCore/UserStyleSheet.h>
214 #import <WebCore/ValidationBubble.h>
215 #import <WebCore/WebCoreObjCExtras.h>
216 #import <WebCore/WebCoreView.h>
217 #import <WebCore/Widget.h>
218 #import <WebKitLegacy/DOM.h>
219 #import <WebKitLegacy/DOMExtensions.h>
220 #import <WebKitLegacy/DOMPrivate.h>
221 #import <mach-o/dyld.h>
222 #import <objc/runtime.h>
223 #import <pal/spi/cf/CFNetworkSPI.h>
224 #import <pal/spi/cf/CFUtilitiesSPI.h>
225 #import <pal/spi/cocoa/NSTouchBarSPI.h>
226 #import <pal/spi/cocoa/NSURLDownloadSPI.h>
227 #import <pal/spi/cocoa/NSURLFileTypeMappingsSPI.h>
228 #import <pal/spi/mac/NSResponderSPI.h>
229 #import <pal/spi/mac/NSSpellCheckerSPI.h>
230 #import <pal/spi/mac/NSWindowSPI.h>
231 #import <wtf/Assertions.h>
232 #import <wtf/HashTraits.h>
233 #import <wtf/MainThread.h>
234 #import <wtf/ObjCRuntimeExtras.h>
235 #import <wtf/ProcessPrivilege.h>
236 #import <wtf/RAMSize.h>
237 #import <wtf/RefCountedLeakCounter.h>
238 #import <wtf/RefPtr.h>
239 #import <wtf/RunLoop.h>
240 #import <wtf/SetForScope.h>
241 #import <wtf/SoftLinking.h>
242 #import <wtf/StdLibExtras.h>
243 #import <wtf/WorkQueue.h>
244 #import <wtf/spi/darwin/dyldSPI.h>
245
246 #if !PLATFORM(IOS_FAMILY)
247 #import "WebContextMenuClient.h"
248 #import "WebFullScreenController.h"
249 #import "WebImmediateActionController.h"
250 #import "WebNSEventExtras.h"
251 #import "WebNSObjectExtras.h"
252 #import "WebNSPasteboardExtras.h"
253 #import "WebNSPrintOperationExtras.h"
254 #import "WebPDFView.h"
255 #import "WebSwitchingGPUClient.h"
256 #import <WebCore/TextIndicator.h>
257 #import <WebCore/TextIndicatorWindow.h>
258 #import <pal/spi/cocoa/AVKitSPI.h>
259 #import <pal/spi/mac/LookupSPI.h>
260 #import <pal/spi/mac/NSImmediateActionGestureRecognizerSPI.h>
261 #else
262 #import "MemoryMeasure.h"
263 #import "WebCaretChangeListener.h"
264 #import "WebChromeClientIOS.h"
265 #import "WebDefaultFormDelegate.h"
266 #import "WebDefaultFrameLoadDelegate.h"
267 #import "WebDefaultResourceLoadDelegate.h"
268 #import "WebDefaultUIKitDelegate.h"
269 #import "WebFixedPositionContent.h"
270 #import "WebMailDelegate.h"
271 #import "WebNSUserDefaultsExtras.h"
272 #import "WebPDFViewIOS.h"
273 #import "WebPlainWhiteView.h"
274 #import "WebPluginController.h"
275 #import "WebPolicyDelegatePrivate.h"
276 #import "WebStorageManagerPrivate.h"
277 #import "WebUIKitSupport.h"
278 #import "WebVisiblePosition.h"
279 #import <WebCore/EventNames.h>
280 #import <WebCore/FontCache.h>
281 #import <WebCore/GraphicsLayer.h>
282 #import <WebCore/LegacyTileCache.h>
283 #import <WebCore/PlatformScreen.h>
284 #import <WebCore/ResourceLoadStatistics.h>
285 #import <WebCore/SQLiteDatabaseTracker.h>
286 #import <WebCore/SmartReplace.h>
287 #import <WebCore/TileControllerMemoryHandlerIOS.h>
288 #import <WebCore/WAKWindow.h>
289 #import <WebCore/WKView.h>
290 #import <WebCore/WebCoreThread.h>
291 #import <WebCore/WebCoreThreadMessage.h>
292 #import <WebCore/WebCoreThreadRun.h>
293 #import <WebCore/WebEvent.h>
294 #import <WebCore/WebSQLiteDatabaseTrackerClient.h>
295 #import <WebCore/WebVideoFullscreenControllerAVKit.h>
296 #import <libkern/OSAtomic.h>
297 #import <pal/spi/ios/MobileGestaltSPI.h>
298 #import <wtf/FastMalloc.h>
299 #endif
300
301 #if ENABLE(DASHBOARD_SUPPORT)
302 #import <WebKitLegacy/WebDashboardRegion.h>
303 #endif
304
305 #if ENABLE(REMOTE_INSPECTOR)
306 #import <JavaScriptCore/RemoteInspector.h>
307 #if PLATFORM(IOS_FAMILY)
308 #import "WebIndicateLayer.h"
309 #endif
310 #endif
311
312 #if USE(QUICK_LOOK)
313 #include <WebCore/QuickLook.h>
314 #endif
315
316 #if ENABLE(IOS_TOUCH_EVENTS)
317 #import <WebCore/WebEventRegion.h>
318 #endif
319
320 #if ENABLE(GAMEPAD)
321 #import <WebCore/HIDGamepadProvider.h>
322 #endif
323
324 #if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS_FAMILY)
325 #import "WebMediaPlaybackTargetPicker.h"
326 #import <WebCore/WebMediaSessionManagerMac.h>
327 #endif
328
329
330 #if PLATFORM(MAC) && ENABLE(VIDEO_PRESENTATION_MODE)
331 #import <WebCore/PlaybackSessionInterfaceMac.h>
332 #import <WebCore/PlaybackSessionModelMediaElement.h>
333 #endif
334
335 #if ENABLE(DATA_INTERACTION)
336 #import <UIKit/UIBezierPath.h>
337 #import <UIKit/UIColor.h>
338 #import <UIKit/UIImage.h>
339 SOFT_LINK_FRAMEWORK(UIKit)
340 SOFT_LINK_CLASS(UIKit, UIBezierPath)
341 SOFT_LINK_CLASS(UIKit, UIColor)
342 SOFT_LINK_CLASS(UIKit, UIImage)
343 SOFT_LINK(UIKit, UIGraphicsBeginImageContextWithOptions, void, (CGSize size, BOOL opaque, CGFloat scale), (size, opaque, scale))
344 SOFT_LINK(UIKit, UIGraphicsGetCurrentContext, CGContextRef, (void), ())
345 SOFT_LINK(UIKit, UIGraphicsGetImageFromCurrentImageContext, UIImage *, (void), ())
346 SOFT_LINK(UIKit, UIGraphicsEndImageContext, void, (void), ())
347 #endif
348
349 #if HAVE(TOUCH_BAR) && ENABLE(WEB_PLAYBACK_CONTROLS_MANAGER)
350 SOFT_LINK_FRAMEWORK(AVKit)
351 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300
352 SOFT_LINK_CLASS(AVKit, AVTouchBarPlaybackControlsProvider)
353 SOFT_LINK_CLASS(AVKit, AVTouchBarScrubber)
354 #else
355 SOFT_LINK_CLASS(AVKit, AVFunctionBarPlaybackControlsProvider)
356 SOFT_LINK_CLASS(AVKit, AVFunctionBarScrubber)
357 #endif // __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300
358 #endif // HAVE(TOUCH_BAR) && ENABLE(WEB_PLAYBACK_CONTROLS_MANAGER)
359
360 #if PLATFORM(MAC) && !ENABLE(REVEAL)
361 SOFT_LINK_CONSTANT_MAY_FAIL(Lookup, LUNotificationPopoverWillClose, NSString *)
362 #endif
363
364 #if !PLATFORM(IOS_FAMILY)
365
366 @interface NSSpellChecker (WebNSSpellCheckerDetails)
367 - (void)_preflightChosenSpellServer;
368 @end
369
370 @interface NSView (WebNSViewDetails)
371 - (NSView *)_hitTest:(NSPoint *)aPoint dragTypes:(NSSet *)types;
372 - (void)_autoscrollForDraggingInfo:(id)dragInfo timeDelta:(NSTimeInterval)repeatDelta;
373 - (BOOL)_shouldAutoscrollForDraggingInfo:(id)dragInfo;
374 - (void)_windowChangedKeyState;
375 @end
376
377 @interface NSWindow (WebNSWindowDetails)
378 - (id)_oldFirstResponderBeforeBecoming;
379 - (void)_enableScreenUpdatesIfNeeded;
380 - (BOOL)_wrapsCarbonWindow;
381 - (BOOL)_hasKeyAppearance;
382 @end
383
384 #endif
385
386 using namespace JSC;
387 using namespace Inspector;
388 using namespace WebCore;
389
390 #define FOR_EACH_RESPONDER_SELECTOR(macro) \
391 macro(alignCenter) \
392 macro(alignJustified) \
393 macro(alignLeft) \
394 macro(alignRight) \
395 macro(capitalizeWord) \
396 macro(centerSelectionInVisibleArea) \
397 macro(changeAttributes) \
398 _Pragma("clang diagnostic push") \
399 _Pragma("clang diagnostic ignored \"-Wundeclared-selector\"") \
400 macro(changeBaseWritingDirection) \
401 macro(changeBaseWritingDirectionToLTR) \
402 macro(changeBaseWritingDirectionToRTL) \
403 _Pragma("clang diagnostic pop") \
404 macro(changeColor) \
405 macro(changeDocumentBackgroundColor) \
406 macro(changeFont) \
407 macro(changeSpelling) \
408 macro(checkSpelling) \
409 macro(complete) \
410 macro(copy) \
411 macro(copyFont) \
412 macro(cut) \
413 macro(delete) \
414 macro(deleteBackward) \
415 macro(deleteBackwardByDecomposingPreviousCharacter) \
416 macro(deleteForward) \
417 macro(deleteToBeginningOfLine) \
418 macro(deleteToBeginningOfParagraph) \
419 macro(deleteToEndOfLine) \
420 macro(deleteToEndOfParagraph) \
421 macro(deleteToMark) \
422 macro(deleteWordBackward) \
423 macro(deleteWordForward) \
424 macro(ignoreSpelling) \
425 macro(indent) \
426 macro(insertBacktab) \
427 macro(insertLineBreak) \
428 macro(insertNewline) \
429 macro(insertNewlineIgnoringFieldEditor) \
430 macro(insertParagraphSeparator) \
431 macro(insertTab) \
432 macro(insertTabIgnoringFieldEditor) \
433 macro(lowercaseWord) \
434 macro(makeBaseWritingDirectionLeftToRight) \
435 macro(makeBaseWritingDirectionRightToLeft) \
436 macro(makeTextWritingDirectionLeftToRight) \
437 macro(makeTextWritingDirectionNatural) \
438 macro(makeTextWritingDirectionRightToLeft) \
439 macro(moveBackward) \
440 macro(moveBackwardAndModifySelection) \
441 macro(moveDown) \
442 macro(moveDownAndModifySelection) \
443 macro(moveForward) \
444 macro(moveForwardAndModifySelection) \
445 macro(moveLeft) \
446 macro(moveLeftAndModifySelection) \
447 macro(moveParagraphBackwardAndModifySelection) \
448 macro(moveParagraphForwardAndModifySelection) \
449 macro(moveRight) \
450 macro(moveRightAndModifySelection) \
451 macro(moveToBeginningOfDocument) \
452 macro(moveToBeginningOfDocumentAndModifySelection) \
453 macro(moveToBeginningOfLine) \
454 macro(moveToBeginningOfLineAndModifySelection) \
455 macro(moveToBeginningOfParagraph) \
456 macro(moveToBeginningOfParagraphAndModifySelection) \
457 macro(moveToBeginningOfSentence) \
458 macro(moveToBeginningOfSentenceAndModifySelection) \
459 macro(moveToEndOfDocument) \
460 macro(moveToEndOfDocumentAndModifySelection) \
461 macro(moveToEndOfLine) \
462 macro(moveToEndOfLineAndModifySelection) \
463 macro(moveToEndOfParagraph) \
464 macro(moveToEndOfParagraphAndModifySelection) \
465 macro(moveToEndOfSentence) \
466 macro(moveToEndOfSentenceAndModifySelection) \
467 macro(moveToLeftEndOfLine) \
468 macro(moveToLeftEndOfLineAndModifySelection) \
469 macro(moveToRightEndOfLine) \
470 macro(moveToRightEndOfLineAndModifySelection) \
471 macro(moveUp) \
472 macro(moveUpAndModifySelection) \
473 macro(moveWordBackward) \
474 macro(moveWordBackwardAndModifySelection) \
475 macro(moveWordForward) \
476 macro(moveWordForwardAndModifySelection) \
477 macro(moveWordLeft) \
478 macro(moveWordLeftAndModifySelection) \
479 macro(moveWordRight) \
480 macro(moveWordRightAndModifySelection) \
481 macro(orderFrontSubstitutionsPanel) \
482 macro(outdent) \
483 macro(overWrite) \
484 macro(pageDown) \
485 macro(pageDownAndModifySelection) \
486 macro(pageUp) \
487 macro(pageUpAndModifySelection) \
488 macro(paste) \
489 macro(pasteAsPlainText) \
490 macro(pasteAsRichText) \
491 macro(pasteFont) \
492 macro(performFindPanelAction) \
493 macro(scrollLineDown) \
494 macro(scrollLineUp) \
495 macro(scrollPageDown) \
496 macro(scrollPageUp) \
497 macro(scrollToBeginningOfDocument) \
498 macro(scrollToEndOfDocument) \
499 macro(selectAll) \
500 macro(selectLine) \
501 macro(selectParagraph) \
502 macro(selectSentence) \
503 macro(selectToMark) \
504 macro(selectWord) \
505 macro(setMark) \
506 macro(showGuessPanel) \
507 macro(startSpeaking) \
508 macro(stopSpeaking) \
509 macro(subscript) \
510 macro(superscript) \
511 macro(swapWithMark) \
512 _Pragma("clang diagnostic push") \
513 _Pragma("clang diagnostic ignored \"-Wundeclared-selector\"") \
514 macro(takeFindStringFromSelection) \
515 _Pragma("clang diagnostic pop") \
516 macro(toggleBaseWritingDirection) \
517 macro(transpose) \
518 macro(underline) \
519 macro(unscript) \
520 macro(uppercaseWord) \
521 macro(yank) \
522 _Pragma("clang diagnostic push") \
523 _Pragma("clang diagnostic ignored \"-Wundeclared-selector\"") \
524 macro(yankAndSelect) \
525 _Pragma("clang diagnostic pop") \
526
527 #define WebKitOriginalTopPrintingMarginKey @"WebKitOriginalTopMargin"
528 #define WebKitOriginalBottomPrintingMarginKey @"WebKitOriginalBottomMargin"
529
530 #define KeyboardUIModeDidChangeNotification @"com.apple.KeyboardUIModeDidChange"
531 #define AppleKeyboardUIMode CFSTR("AppleKeyboardUIMode")
532
533 static BOOL s_didSetCacheModel;
534 static WebCacheModel s_cacheModel = WebCacheModelDocumentViewer;
535
536 #if PLATFORM(IOS_FAMILY)
537 static Class s_pdfRepresentationClass;
538 static Class s_pdfViewClass;
539 #endif
540
541 #ifndef NDEBUG
542 static const char webViewIsOpen[] = "At least one WebView is still open.";
543 #endif
544
545 #if PLATFORM(IOS_FAMILY)
546 @interface WebView(WebViewPrivate)
547 - (void)_preferencesChanged:(WebPreferences *)preferences;
548 - (void)_updateScreenScaleFromWindow;
549 @end
550 #endif
551
552 #if !PLATFORM(IOS_FAMILY)
553 @interface NSObject (WebValidateWithoutDelegate)
554 - (BOOL)validateUserInterfaceItemWithoutDelegate:(id <NSValidatedUserInterfaceItem>)item;
555 @end
556 #endif
557
558 #if PLATFORM(IOS_FAMILY)
559 @class _WebSafeForwarder;
560
561 @interface _WebSafeAsyncForwarder : NSObject {
562     _WebSafeForwarder *_forwarder;
563 }
564 - (id)initWithForwarder:(_WebSafeForwarder *)forwarder;
565 @end
566 #endif
567
568 @interface _WebSafeForwarder : NSObject
569 {
570     id target; // Non-retained. Don't retain delegates.
571     id defaultTarget;
572 #if PLATFORM(IOS_FAMILY)
573     _WebSafeAsyncForwarder *asyncForwarder;
574     dispatch_once_t asyncForwarderPred;
575 #endif
576 }
577 - (instancetype)initWithTarget:(id)target defaultTarget:(id)defaultTarget;
578 #if PLATFORM(IOS_FAMILY)
579 - (void)clearTarget;
580 - (id)asyncForwarder;
581 #endif
582 @end
583
584 FindOptions coreOptions(WebFindOptions options)
585 {
586     FindOptions findOptions;
587     if (options & WebFindOptionsCaseInsensitive)
588         findOptions.add(CaseInsensitive);
589     if (options & WebFindOptionsAtWordStarts)
590         findOptions.add(AtWordStarts);
591     if (options & WebFindOptionsTreatMedialCapitalAsWordStart)
592         findOptions.add(TreatMedialCapitalAsWordStart);
593     if (options & WebFindOptionsBackwards)
594         findOptions.add(Backwards);
595     if (options & WebFindOptionsWrapAround)
596         findOptions.add(WrapAround);
597     if (options & WebFindOptionsStartInSelection)
598         findOptions.add(StartInSelection);
599     return findOptions;
600 }
601
602 OptionSet<WebCore::LayoutMilestone> coreLayoutMilestones(WebLayoutMilestones milestones)
603 {
604     OptionSet<WebCore::LayoutMilestone> layoutMilestone;
605     if (milestones & WebDidFirstLayout)
606         layoutMilestone.add(DidFirstLayout);
607     if (milestones & WebDidFirstVisuallyNonEmptyLayout)
608         layoutMilestone.add(DidFirstVisuallyNonEmptyLayout);
609     if (milestones & WebDidHitRelevantRepaintedObjectsAreaThreshold)
610         layoutMilestone.add(DidHitRelevantRepaintedObjectsAreaThreshold);
611     return layoutMilestone;
612 }
613
614 WebLayoutMilestones kitLayoutMilestones(OptionSet<WebCore::LayoutMilestone> milestones)
615 {
616     return (milestones & DidFirstLayout ? WebDidFirstLayout : 0)
617         | (milestones & DidFirstVisuallyNonEmptyLayout ? WebDidFirstVisuallyNonEmptyLayout : 0)
618         | (milestones & DidHitRelevantRepaintedObjectsAreaThreshold ? WebDidHitRelevantRepaintedObjectsAreaThreshold : 0);
619 }
620
621 static WebPageVisibilityState kit(VisibilityState visibilityState)
622 {
623     switch (visibilityState) {
624     case VisibilityState::Visible:
625         return WebPageVisibilityStateVisible;
626     case VisibilityState::Hidden:
627         return WebPageVisibilityStateHidden;
628     case VisibilityState::Prerender:
629         return WebPageVisibilityStatePrerender;
630     }
631
632     ASSERT_NOT_REACHED();
633     return WebPageVisibilityStateVisible;
634 }
635
636 namespace WebKit {
637
638 class DeferredPageDestructor {
639 public:
640     static void createDeferredPageDestructor(std::unique_ptr<Page> page)
641     {
642         new DeferredPageDestructor(WTFMove(page));
643     }
644
645 private:
646     DeferredPageDestructor(std::unique_ptr<Page> page)
647         : m_page(WTFMove(page))
648     {
649         tryDestruction();
650     }
651
652     void tryDestruction()
653     {
654         if (m_page->insideNestedRunLoop()) {
655             m_page->whenUnnested([this] { tryDestruction(); });
656             return;
657         }
658
659         m_page = nullptr;
660         delete this;
661     }
662
663     std::unique_ptr<Page> m_page;
664 };
665
666 } // namespace WebKit
667
668 #if ENABLE(DATA_INTERACTION)
669
670 @implementation WebUITextIndicatorData
671
672 @synthesize dataInteractionImage=_dataInteractionImage;
673 @synthesize selectionRectInRootViewCoordinates=_selectionRectInRootViewCoordinates;
674 @synthesize textBoundingRectInRootViewCoordinates=_textBoundingRectInRootViewCoordinates;
675 @synthesize textRectsInBoundingRectCoordinates=_textRectsInBoundingRectCoordinates;
676 @synthesize contentImageWithHighlight=_contentImageWithHighlight;
677 @synthesize contentImageWithoutSelection=_contentImageWithoutSelection;
678 @synthesize contentImageWithoutSelectionRectInRootViewCoordinates=_contentImageWithoutSelectionRectInRootViewCoordinates;
679 @synthesize contentImage=_contentImage;
680 @synthesize estimatedBackgroundColor=_estimatedBackgroundColor;
681
682 - (void)dealloc
683 {
684     [_dataInteractionImage release];
685     [_textRectsInBoundingRectCoordinates release];
686     [_contentImageWithHighlight release];
687     [_contentImageWithoutSelection release];
688     [_contentImage release];
689     [_estimatedBackgroundColor release];
690
691     [super dealloc];
692 }
693
694 @end
695
696 @implementation WebUITextIndicatorData (WebUITextIndicatorInternal)
697
698 - (WebUITextIndicatorData *)initWithImage:(CGImageRef)image textIndicatorData:(const TextIndicatorData&)indicatorData scale:(CGFloat)scale
699 {
700     if (!(self = [super init]))
701         return nil;
702     
703     _dataInteractionImage = [allocUIImageInstance() initWithCGImage:image scale:scale orientation:UIImageOrientationDownMirrored];
704     _selectionRectInRootViewCoordinates = indicatorData.selectionRectInRootViewCoordinates;
705     _textBoundingRectInRootViewCoordinates = indicatorData.textBoundingRectInRootViewCoordinates;
706     
707     NSMutableArray *textRectsInBoundingRectCoordinates = [NSMutableArray array];
708     for (auto rect : indicatorData.textRectsInBoundingRectCoordinates)
709         [textRectsInBoundingRectCoordinates addObject:[NSValue valueWithCGRect:rect]];
710     _textRectsInBoundingRectCoordinates = [[NSArray arrayWithArray:textRectsInBoundingRectCoordinates] retain];
711     _contentImageScaleFactor = indicatorData.contentImageScaleFactor;
712     if (indicatorData.contentImageWithHighlight)
713         _contentImageWithHighlight = [allocUIImageInstance() initWithCGImage:indicatorData.contentImageWithHighlight.get()->nativeImage().get() scale:scale orientation:UIImageOrientationDownMirrored];
714     if (indicatorData.contentImage)
715         _contentImage = [allocUIImageInstance() initWithCGImage:indicatorData.contentImage.get()->nativeImage().get() scale:scale orientation:UIImageOrientationUp];
716
717     if (indicatorData.contentImageWithoutSelection) {
718         auto nativeImage = indicatorData.contentImageWithoutSelection.get()->nativeImage();
719         if (nativeImage) {
720             _contentImageWithoutSelection = [allocUIImageInstance() initWithCGImage:nativeImage.get() scale:scale orientation:UIImageOrientationUp];
721             _contentImageWithoutSelectionRectInRootViewCoordinates = indicatorData.contentImageWithoutSelectionRectInRootViewCoordinates;
722         }
723     }
724
725     if (indicatorData.options & TextIndicatorOptionComputeEstimatedBackgroundColor)
726         _estimatedBackgroundColor = [allocUIColorInstance() initWithCGColor:cachedCGColor(indicatorData.estimatedBackgroundColor)];
727
728     return self;
729 }
730
731 - (WebUITextIndicatorData *)initWithImage:(CGImageRef)image scale:(CGFloat)scale
732 {
733     if (!(self = [super init]))
734         return nil;
735     
736     _dataInteractionImage = [allocUIImageInstance() initWithCGImage:image scale:scale orientation:UIImageOrientationDownMirrored];
737     
738     return self;
739 }
740
741 @end
742 #elif !PLATFORM(MAC)
743 @implementation WebUITextIndicatorData
744 @end
745 #endif // ENABLE(DATA_INTERACTION)
746
747 NSString *WebElementDOMNodeKey =            @"WebElementDOMNode";
748 NSString *WebElementFrameKey =              @"WebElementFrame";
749 NSString *WebElementImageKey =              @"WebElementImage";
750 NSString *WebElementImageAltStringKey =     @"WebElementImageAltString";
751 NSString *WebElementImageRectKey =          @"WebElementImageRect";
752 NSString *WebElementImageURLKey =           @"WebElementImageURL";
753 NSString *WebElementIsSelectedKey =         @"WebElementIsSelected";
754 NSString *WebElementLinkLabelKey =          @"WebElementLinkLabel";
755 NSString *WebElementLinkTargetFrameKey =    @"WebElementTargetFrame";
756 NSString *WebElementLinkTitleKey =          @"WebElementLinkTitle";
757 NSString *WebElementLinkURLKey =            @"WebElementLinkURL";
758 NSString *WebElementMediaURLKey =           @"WebElementMediaURL";
759 NSString *WebElementSpellingToolTipKey =    @"WebElementSpellingToolTip";
760 NSString *WebElementTitleKey =              @"WebElementTitle";
761 NSString *WebElementLinkIsLiveKey =         @"WebElementLinkIsLive";
762 NSString *WebElementIsInScrollBarKey =      @"WebElementIsInScrollBar";
763 NSString *WebElementIsContentEditableKey =  @"WebElementIsContentEditableKey";
764
765 NSString *WebViewProgressStartedNotification =          @"WebProgressStartedNotification";
766 NSString *WebViewProgressEstimateChangedNotification =  @"WebProgressEstimateChangedNotification";
767 #if !PLATFORM(IOS_FAMILY)
768 NSString *WebViewProgressFinishedNotification =         @"WebProgressFinishedNotification";
769 #else
770 NSString * const WebViewProgressEstimatedProgressKey = @"WebProgressEstimatedProgressKey";
771 NSString * const WebViewProgressBackgroundColorKey =   @"WebProgressBackgroundColorKey";
772 #endif
773
774 NSString * const WebViewDidBeginEditingNotification =         @"WebViewDidBeginEditingNotification";
775 NSString * const WebViewDidChangeNotification =               @"WebViewDidChangeNotification";
776 NSString * const WebViewDidEndEditingNotification =           @"WebViewDidEndEditingNotification";
777 NSString * const WebViewDidChangeTypingStyleNotification =    @"WebViewDidChangeTypingStyleNotification";
778 NSString * const WebViewDidChangeSelectionNotification =      @"WebViewDidChangeSelectionNotification";
779
780 enum { WebViewVersion = 4 };
781
782 #define timedLayoutSize 4096
783
784 static NSMutableSet *schemesWithRepresentationsSet;
785
786 #if !PLATFORM(IOS_FAMILY)
787 NSString *_WebCanGoBackKey =            @"canGoBack";
788 NSString *_WebCanGoForwardKey =         @"canGoForward";
789 NSString *_WebEstimatedProgressKey =    @"estimatedProgress";
790 NSString *_WebIsLoadingKey =            @"isLoading";
791 NSString *_WebMainFrameIconKey =        @"mainFrameIcon";
792 NSString *_WebMainFrameTitleKey =       @"mainFrameTitle";
793 NSString *_WebMainFrameURLKey =         @"mainFrameURL";
794 NSString *_WebMainFrameDocumentKey =    @"mainFrameDocument";
795 #endif
796
797 #if PLATFORM(IOS_FAMILY)
798 NSString *WebQuickLookFileNameKey = @"WebQuickLookFileNameKey";
799 NSString *WebQuickLookUTIKey      = @"WebQuickLookUTIKey";
800 #endif
801
802 NSString *_WebViewDidStartAcceleratedCompositingNotification = @"_WebViewDidStartAcceleratedCompositing";
803 NSString * const WebViewWillCloseNotification = @"WebViewWillCloseNotification";
804
805 #if ENABLE(REMOTE_INSPECTOR)
806 // FIXME: Legacy, remove this, switch to something from JavaScriptCore Inspector::RemoteInspectorServer.
807 NSString *_WebViewRemoteInspectorHasSessionChangedNotification = @"_WebViewRemoteInspectorHasSessionChangedNotification";
808 #endif
809
810 @interface WebProgressItem : NSObject
811 {
812 @public
813     long long bytesReceived;
814     long long estimatedLength;
815 }
816 @end
817
818 @implementation WebProgressItem
819 @end
820
821 static BOOL continuousSpellCheckingEnabled;
822 static BOOL iconLoadingEnabled = YES;
823 #if !PLATFORM(IOS_FAMILY)
824 static BOOL grammarCheckingEnabled;
825 static BOOL automaticQuoteSubstitutionEnabled;
826 static BOOL automaticLinkDetectionEnabled;
827 static BOOL automaticDashSubstitutionEnabled;
828 static BOOL automaticTextReplacementEnabled;
829 static BOOL automaticSpellingCorrectionEnabled;
830 #endif
831
832 #if HAVE(TOUCH_BAR)
833
834 enum class WebListType {
835     None = 0,
836     Ordered,
837     Unordered
838 };
839
840 @interface WebTextListTouchBarViewController : NSViewController {
841 @private
842     WebListType _currentListType;
843     WebView *_webView;
844 }
845
846 @property (nonatomic) WebListType currentListType;
847
848 - (instancetype)initWithWebView:(WebView *)webView;
849
850 @end
851
852 @implementation WebTextListTouchBarViewController
853
854 @synthesize currentListType=_currentListType;
855
856 static const CGFloat listControlSegmentWidth = 67.0;
857
858 static const NSUInteger noListSegment = 0;
859 static const NSUInteger unorderedListSegment = 1;
860 static const NSUInteger orderedListSegment = 2;
861
862 - (instancetype)initWithWebView:(WebView *)webView
863 {
864     if (!(self = [super init]))
865         return nil;
866
867     _webView = webView;
868
869     NSSegmentedControl *insertListControl = [NSSegmentedControl segmentedControlWithLabels:@[ WebCore::insertListTypeNone(), WebCore::insertListTypeBulleted(), WebCore::insertListTypeNumbered() ] trackingMode:NSSegmentSwitchTrackingSelectOne target:self action:@selector(_selectList:)];
870     [insertListControl setWidth:listControlSegmentWidth forSegment:noListSegment];
871     [insertListControl setWidth:listControlSegmentWidth forSegment:unorderedListSegment];
872     [insertListControl setWidth:listControlSegmentWidth forSegment:orderedListSegment];
873     insertListControl.font = [NSFont systemFontOfSize:15];
874
875     ALLOW_DEPRECATED_DECLARATIONS_BEGIN
876     id segmentElement = NSAccessibilityUnignoredDescendant(insertListControl);
877     NSArray *segments = [segmentElement accessibilityAttributeValue:NSAccessibilityChildrenAttribute];
878     ASSERT(segments.count == 3);
879     [segments[noListSegment] accessibilitySetOverrideValue:WebCore::insertListTypeNone() forAttribute:NSAccessibilityDescriptionAttribute];
880     [segments[unorderedListSegment] accessibilitySetOverrideValue:WebCore::insertListTypeBulletedAccessibilityTitle() forAttribute:NSAccessibilityDescriptionAttribute];
881     [segments[orderedListSegment] accessibilitySetOverrideValue:WebCore::insertListTypeNumberedAccessibilityTitle() forAttribute:NSAccessibilityDescriptionAttribute];
882     ALLOW_DEPRECATED_DECLARATIONS_END
883
884     self.view = insertListControl;
885
886     return self;
887 }
888
889 - (void)_selectList:(id)sender
890 {
891     NSView *documentView = [[[_webView _selectedOrMainFrame] frameView] documentView];
892     if (![documentView isKindOfClass:[WebHTMLView class]])
893         return;
894
895     WebHTMLView *webHTMLView = (WebHTMLView *)documentView;
896     NSSegmentedControl *insertListControl = (NSSegmentedControl *)self.view;
897     switch (insertListControl.selectedSegment) {
898     case noListSegment:
899         // There is no "remove list" edit command, but _insertOrderedList and _insertUnorderedList both
900         // behave as toggles, so we can invoke the appropriate method depending on our _currentListType
901         // to remove an existing list. We don't have to do anything if _currentListType is WebListType::None.
902         if (_currentListType == WebListType::Ordered)
903             [webHTMLView _insertOrderedList];
904         else if (_currentListType == WebListType::Unordered)
905             [webHTMLView _insertUnorderedList];
906         break;
907     case unorderedListSegment:
908         [webHTMLView _insertUnorderedList];
909         break;
910     case orderedListSegment:
911         [webHTMLView _insertOrderedList];
912         break;
913     }
914
915     [_webView _dismissTextTouchBarPopoverItemWithIdentifier:NSTouchBarItemIdentifierTextList];
916 }
917
918 - (void)setCurrentListType:(WebListType)listType
919 {
920     NSSegmentedControl *insertListControl = (NSSegmentedControl *)self.view;
921     switch (listType) {
922     case WebListType::None:
923         [insertListControl setSelected:YES forSegment:noListSegment];
924         break;
925     case WebListType::Ordered:
926         [insertListControl setSelected:YES forSegment:orderedListSegment];
927         break;
928     case WebListType::Unordered:
929         [insertListControl setSelected:YES forSegment:unorderedListSegment];
930         break;
931     }
932
933     _currentListType = listType;
934 }
935
936 @end
937
938 @interface WebTextTouchBarItemController : NSTextTouchBarItemController {
939 @private
940     BOOL _textIsBold;
941     BOOL _textIsItalic;
942     BOOL _textIsUnderlined;
943     NSTextAlignment _currentTextAlignment;
944     RetainPtr<NSColor> _textColor;
945     RetainPtr<WebTextListTouchBarViewController> _textListTouchBarViewController;
946     WebView *_webView;
947 }
948
949 @property (nonatomic) BOOL textIsBold;
950 @property (nonatomic) BOOL textIsItalic;
951 @property (nonatomic) BOOL textIsUnderlined;
952 @property (nonatomic) NSTextAlignment currentTextAlignment;
953 @property (nonatomic, retain, readwrite) NSColor *textColor;
954
955 - (instancetype)initWithWebView:(WebView *)webView;
956 @end
957
958 @implementation WebTextTouchBarItemController
959
960 @synthesize textIsBold=_textIsBold;
961 @synthesize textIsItalic=_textIsItalic;
962 @synthesize textIsUnderlined=_textIsUnderlined;
963 @synthesize currentTextAlignment=_currentTextAlignment;
964
965 - (instancetype)initWithWebView:(WebView *)webView
966 {
967     if (!(self = [super init]))
968         return nil;
969
970     _webView = webView;
971
972     return self;
973 }
974
975 - (NSTouchBarItem *)itemForIdentifier:(NSString *)identifier
976 {
977     NSTouchBarItem *item = [super itemForIdentifier:identifier];
978     BOOL isTextFormatItem = [identifier isEqualToString:NSTouchBarItemIdentifierTextFormat];
979
980     if (isTextFormatItem || [identifier isEqualToString:NSTouchBarItemIdentifierTextStyle])
981         self.textStyle.action = @selector(_webChangeTextStyle:);
982
983     if (isTextFormatItem || [identifier isEqualToString:NSTouchBarItemIdentifierTextAlignment])
984         self.textAlignments.action = @selector(_webChangeTextAlignment:);
985
986     NSColorPickerTouchBarItem *colorPickerItem = nil;
987     if ([identifier isEqualToString:NSTouchBarItemIdentifierTextColorPicker] && [item isKindOfClass:[NSColorPickerTouchBarItem class]])
988         colorPickerItem = (NSColorPickerTouchBarItem *)item;
989     if (isTextFormatItem)
990         colorPickerItem = self.colorPickerItem;
991     if (colorPickerItem) {
992         colorPickerItem.target = self;
993         colorPickerItem.action = @selector(_webChangeColor:);
994         colorPickerItem.showsAlpha = NO;
995     }
996
997     return item;
998 }
999
1000 - (WebTextListTouchBarViewController *)webTextListTouchBarViewController
1001 {
1002     return (WebTextListTouchBarViewController *)self.textListViewController;
1003 }
1004
1005 - (void)setTextIsBold:(BOOL)bold
1006 {
1007     _textIsBold = bold;
1008     if ([self.textStyle isSelectedForSegment:0] != _textIsBold)
1009         [self.textStyle setSelected:_textIsBold forSegment:0];
1010 }
1011
1012 - (void)setTextIsItalic:(BOOL)italic
1013 {
1014     _textIsItalic = italic;
1015     if ([self.textStyle isSelectedForSegment:1] != _textIsItalic)
1016         [self.textStyle setSelected:_textIsItalic forSegment:1];
1017 }
1018
1019 - (void)setTextIsUnderlined:(BOOL)underlined
1020 {
1021     _textIsUnderlined = underlined;
1022     if ([self.textStyle isSelectedForSegment:2] != _textIsUnderlined)
1023         [self.textStyle setSelected:_textIsUnderlined forSegment:2];
1024 }
1025
1026 - (void)_webChangeTextStyle:(id)sender
1027 {
1028     if ([self.textStyle isSelectedForSegment:0] != _textIsBold) {
1029         _textIsBold = !_textIsBold;
1030         [_webView _executeCoreCommandByName:@"ToggleBold" value:@""];
1031     }
1032
1033     if ([self.textStyle isSelectedForSegment:1] != _textIsItalic) {
1034         _textIsItalic = !_textIsItalic;
1035         [_webView _executeCoreCommandByName:@"ToggleItalic" value:@""];
1036     }
1037
1038     if ([self.textStyle isSelectedForSegment:2] != _textIsUnderlined) {
1039         _textIsUnderlined = !_textIsUnderlined;
1040         [_webView _executeCoreCommandByName:@"ToggleUnderline" value:@""];
1041     }
1042 }
1043
1044 - (void)setCurrentTextAlignment:(NSTextAlignment)alignment
1045 {
1046     _currentTextAlignment = alignment;
1047     [self.textAlignments selectSegmentWithTag:_currentTextAlignment];
1048 }
1049
1050 - (void)_webChangeTextAlignment:(id)sender
1051 {
1052     NSTextAlignment alignment = (NSTextAlignment)[self.textAlignments.cell tagForSegment:self.textAlignments.selectedSegment];
1053     switch (alignment) {
1054     case NSTextAlignmentLeft:
1055         _currentTextAlignment = NSTextAlignmentLeft;
1056         [_webView alignLeft:sender];
1057         break;
1058     case NSTextAlignmentRight:
1059         _currentTextAlignment = NSTextAlignmentRight;
1060         [_webView alignRight:sender];
1061         break;
1062     case NSTextAlignmentCenter:
1063         _currentTextAlignment = NSTextAlignmentCenter;
1064         [_webView alignCenter:sender];
1065         break;
1066     case NSTextAlignmentJustified:
1067         _currentTextAlignment = NSTextAlignmentJustified;
1068         [_webView alignJustified:sender];
1069         break;
1070     default:
1071         break;
1072     }
1073
1074     [_webView _dismissTextTouchBarPopoverItemWithIdentifier:NSTouchBarItemIdentifierTextAlignment];
1075 }
1076
1077 - (NSColor *)textColor
1078 {
1079     return _textColor.get();
1080 }
1081
1082 - (void)setTextColor:(NSColor *)color
1083 {
1084     _textColor = color;
1085     self.colorPickerItem.color = _textColor.get();
1086 }
1087
1088 - (void)_webChangeColor:(id)sender
1089 {
1090     _textColor = self.colorPickerItem.color;
1091     [_webView _executeCoreCommandByName:@"ForeColor" value: WebCore::colorFromNSColor(_textColor.get()).serialized()];
1092 }
1093
1094 - (NSViewController *)textListViewController
1095 {
1096     if (!_textListTouchBarViewController)
1097         _textListTouchBarViewController = adoptNS([[WebTextListTouchBarViewController alloc] initWithWebView:_webView]);
1098     return _textListTouchBarViewController.get();
1099 }
1100
1101 @end
1102
1103 #endif // HAVE(TOUCH_BAR)
1104
1105 @interface WebView ()
1106 #if PLATFORM(IOS_FAMILY)
1107 - (void)_wakWindowScreenScaleChanged:(NSNotification *)notification;
1108 - (void)_wakWindowVisibilityChanged:(NSNotification *)notification;
1109 #else
1110 - (float)_deviceScaleFactor;
1111 #endif
1112 @end
1113
1114 @implementation WebView (AllWebViews)
1115
1116 static CFSetCallBacks NonRetainingSetCallbacks = {
1117     0,
1118     NULL,
1119     NULL,
1120     CFCopyDescription,
1121     CFEqual,
1122     CFHash
1123 };
1124
1125 static CFMutableSetRef allWebViewsSet;
1126
1127 + (void)_makeAllWebViewsPerformSelector:(SEL)selector
1128 {
1129     if (!allWebViewsSet)
1130         return;
1131
1132     [(__bridge NSMutableSet *)allWebViewsSet makeObjectsPerformSelector:selector];
1133 }
1134
1135 - (void)_removeFromAllWebViewsSet
1136 {
1137     if (allWebViewsSet)
1138         CFSetRemoveValue(allWebViewsSet, (__bridge CFTypeRef)self);
1139 }
1140
1141 - (void)_addToAllWebViewsSet
1142 {
1143     if (!allWebViewsSet)
1144         allWebViewsSet = CFSetCreateMutable(NULL, 0, &NonRetainingSetCallbacks);
1145
1146     CFSetSetValue(allWebViewsSet, (__bridge CFTypeRef)self);
1147 }
1148
1149 @end
1150
1151 @implementation WebView (WebPrivate)
1152
1153 + (NSString *)_standardUserAgentWithApplicationName:(NSString *)applicationName
1154 {
1155     return standardUserAgentWithApplicationName(applicationName);
1156 }
1157
1158 #if PLATFORM(IOS_FAMILY)
1159 - (void)_setBrowserUserAgentProductVersion:(NSString *)productVersion buildVersion:(NSString *)buildVersion bundleVersion:(NSString *)bundleVersion
1160 {
1161     // The web-visible build and bundle versions are frozen to remove a fingerprinting surface
1162     UNUSED_PARAM(buildVersion);
1163     [self setApplicationNameForUserAgent:[NSString stringWithFormat:@"Version/%@ Mobile/15E148 Safari/%@", productVersion, bundleVersion]];
1164 }
1165
1166 - (void)_setUIWebViewUserAgentWithBuildVersion:(NSString *)buildVersion
1167 {
1168     UNUSED_PARAM(buildVersion);
1169     [self setApplicationNameForUserAgent:@"Mobile/15E148"];
1170 }
1171 #endif // PLATFORM(IOS_FAMILY)
1172
1173 + (void)_reportException:(JSValueRef)exception inContext:(JSContextRef)context
1174 {
1175     if (!exception || !context)
1176         return;
1177
1178     JSC::ExecState* execState = toJS(context);
1179     JSLockHolder lock(execState);
1180
1181     // Make sure the context has a DOMWindow global object, otherwise this context didn't originate from a WebView.
1182     JSC::JSGlobalObject* globalObject = execState->lexicalGlobalObject();
1183     if (!toJSDOMWindow(globalObject->vm(), globalObject))
1184         return;
1185
1186     reportException(execState, toJS(execState, exception));
1187 }
1188
1189 static bool shouldEnableLoadDeferring()
1190 {
1191 #if PLATFORM(IOS_FAMILY)
1192     return true;
1193 #else
1194     return !MacApplication::isAdobeInstaller();
1195 #endif
1196 }
1197
1198 static bool shouldRestrictWindowFocus()
1199 {
1200 #if PLATFORM(IOS_FAMILY)
1201     return true;
1202 #else
1203     return !MacApplication::isHRBlock();
1204 #endif
1205 }
1206
1207 - (void)_dispatchPendingLoadRequests
1208 {
1209     webResourceLoadScheduler().servePendingRequests();
1210 }
1211
1212 #if !PLATFORM(IOS_FAMILY)
1213
1214 - (void)_registerDraggedTypes
1215 {
1216     NSArray *editableTypes = [WebHTMLView _insertablePasteboardTypes];
1217     NSArray *URLTypes = [NSPasteboard _web_dragTypesForURL];
1218     NSMutableSet *types = [[NSMutableSet alloc] initWithArray:editableTypes];
1219     [types addObjectsFromArray:URLTypes];
1220     [types addObject:[WebHTMLView _dummyPasteboardType]];
1221     [self registerForDraggedTypes:[types allObjects]];
1222     [types release];
1223 }
1224
1225 static bool needsOutlookQuirksScript()
1226 {
1227     static bool isOutlookNeedingQuirksScript = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
1228         && MacApplication::isMicrosoftOutlook();
1229     return isOutlookNeedingQuirksScript;
1230 }
1231
1232 static NSString *leakOutlookQuirksUserScriptContents()
1233 {
1234     NSString *scriptPath = [[NSBundle bundleForClass:[WebView class]] pathForResource:@"OutlookQuirksUserScript" ofType:@"js"];
1235     NSStringEncoding encoding;
1236     return [[NSString alloc] initWithContentsOfFile:scriptPath usedEncoding:&encoding error:0];
1237 }
1238
1239 -(void)_injectOutlookQuirksScript
1240 {
1241     static NSString *outlookQuirksScriptContents = leakOutlookQuirksUserScriptContents();
1242     _private->group->userContentController().addUserScript(*core([WebScriptWorld world]), std::make_unique<UserScript>(outlookQuirksScriptContents, URL(), Vector<String>(), Vector<String>(), InjectAtDocumentEnd, InjectInAllFrames));
1243
1244 }
1245 #endif
1246
1247 static bool shouldRespectPriorityInCSSAttributeSetters()
1248 {
1249 #if PLATFORM(IOS_FAMILY)
1250     return false;
1251 #else
1252     static bool isIAdProducerNeedingAttributeSetterQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CSS_ATTRIBUTE_SETTERS_IGNORING_PRIORITY)
1253         && [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.apple.iAdProducer"];
1254     return isIAdProducerNeedingAttributeSetterQuirk;
1255 #endif
1256 }
1257
1258 #if PLATFORM(IOS_FAMILY)
1259 static bool isInternalInstall()
1260 {
1261     static bool isInternal = MGGetBoolAnswer(kMGQAppleInternalInstallCapability);
1262     return isInternal;
1263 }
1264
1265 static bool didOneTimeInitialization = false;
1266 #endif
1267
1268 static bool shouldUseLegacyBackgroundSizeShorthandBehavior()
1269 {
1270 #if PLATFORM(IOS_FAMILY)
1271     static bool shouldUseLegacyBackgroundSizeShorthandBehavior = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LEGACY_BACKGROUNDSIZE_SHORTHAND_BEHAVIOR);
1272 #else
1273     static bool shouldUseLegacyBackgroundSizeShorthandBehavior = MacApplication::isVersions()
1274         && !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LEGACY_BACKGROUNDSIZE_SHORTHAND_BEHAVIOR);
1275 #endif
1276     return shouldUseLegacyBackgroundSizeShorthandBehavior;
1277 }
1278
1279 static bool shouldAllowDisplayAndRunningOfInsecureContent()
1280 {
1281     static bool shouldAllowDisplayAndRunningOfInsecureContent = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_INSECURE_CONTENT_BLOCKING);
1282     return shouldAllowDisplayAndRunningOfInsecureContent;
1283 }
1284
1285 static bool shouldAllowPictureInPictureMediaPlayback()
1286 {
1287 #if PLATFORM(IOS_FAMILY)
1288     static bool shouldAllowPictureInPictureMediaPlayback = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_9_0;
1289     return shouldAllowPictureInPictureMediaPlayback;
1290 #else
1291     return false;
1292 #endif
1293 }
1294
1295 static bool shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol()
1296 {
1297 #if PLATFORM(IOS_FAMILY)
1298     static bool shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_CONTENT_SECURITY_POLICY_SOURCE_STAR_PROTOCOL_RESTRICTION);
1299     return shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol;
1300 #else
1301     return false;
1302 #endif
1303 }
1304
1305 static bool shouldAllowWindowOpenWithoutUserGesture()
1306 {
1307 #if PLATFORM(IOS_FAMILY)
1308     static bool shouldAllowWindowOpenWithoutUserGesture = IOSApplication::isTheSecretSocietyHiddenMystery() && dyld_get_program_sdk_version() < DYLD_IOS_VERSION_10_0;
1309     return shouldAllowWindowOpenWithoutUserGesture;
1310 #else
1311     return false;
1312 #endif
1313 }
1314
1315 static bool shouldConvertInvalidURLsToBlank()
1316 {
1317 #if PLATFORM(IOS_FAMILY)
1318     static bool shouldConvertInvalidURLsToBlank = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_10_0;
1319 #elif PLATFORM(MAC)
1320     static bool shouldConvertInvalidURLsToBlank = dyld_get_program_sdk_version() >= DYLD_MACOSX_VERSION_10_12;
1321 #else
1322     static bool shouldConvertInvalidURLsToBlank = true;
1323 #endif
1324
1325     return shouldConvertInvalidURLsToBlank;
1326 }
1327
1328 static bool shouldRequireUserGestureToLoadVideo()
1329 {
1330 #if PLATFORM(IOS_FAMILY)
1331     static bool shouldRequireUserGestureToLoadVideo = dyld_get_program_sdk_version() >= DYLD_IOS_VERSION_10_0;
1332     return shouldRequireUserGestureToLoadVideo;
1333 #else
1334     return false;
1335 #endif
1336 }
1337
1338 #if ENABLE(GAMEPAD)
1339 static void WebKitInitializeGamepadProviderIfNecessary()
1340 {
1341     static bool initialized = false;
1342     if (initialized)
1343         return;
1344
1345 #if PLATFORM(MAC)
1346     GamepadProvider::singleton().setSharedProvider(HIDGamepadProvider::singleton());
1347 #else
1348     GamepadProvider::singleton().setSharedProvider(GameControllerGamepadProvider::singleton());
1349 #endif
1350
1351     initialized = true;
1352 }
1353 #endif
1354
1355 - (void)_commonInitializationWithFrameName:(NSString *)frameName groupName:(NSString *)groupName
1356 {
1357     WebCoreThreadViolationCheckRoundTwo();
1358
1359 #ifndef NDEBUG
1360     WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
1361 #endif
1362     
1363     WebPreferences *standardPreferences = [WebPreferences standardPreferences];
1364     [standardPreferences willAddToWebView];
1365
1366     _private->preferences = [standardPreferences retain];
1367     _private->mainFrameDocumentReady = NO;
1368     _private->drawsBackground = YES;
1369 #if !PLATFORM(IOS_FAMILY)
1370     _private->backgroundColor = [[NSColor colorWithDeviceWhite:1 alpha:1] retain];
1371 #else
1372     _private->backgroundColor = CGColorRetain(cachedCGColor(Color::white));
1373 #endif
1374
1375 #if PLATFORM(MAC)
1376     _private->windowVisibilityObserver = adoptNS([[WebWindowVisibilityObserver alloc] initWithView:self]);
1377 #endif
1378
1379     NSRect f = [self frame];
1380     WebFrameView *frameView = [[WebFrameView alloc] initWithFrame: NSMakeRect(0,0,f.size.width,f.size.height)];
1381     [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1382     [self addSubview:frameView];
1383     [frameView release];
1384
1385 #if PLATFORM(MAC)
1386     if (Class gestureClass = NSClassFromString(@"NSImmediateActionGestureRecognizer")) {
1387         RetainPtr<NSImmediateActionGestureRecognizer> recognizer = adoptNS([(NSImmediateActionGestureRecognizer *)[gestureClass alloc] init]);
1388         _private->immediateActionController = [[WebImmediateActionController alloc] initWithWebView:self recognizer:recognizer.get()];
1389         [recognizer setDelegate:_private->immediateActionController];
1390         [recognizer setDelaysPrimaryMouseButtonEvents:NO];
1391     }
1392 #endif
1393
1394     [self updateTouchBar];
1395
1396 #if !PLATFORM(IOS_FAMILY)
1397     static bool didOneTimeInitialization = false;
1398 #endif
1399     if (!didOneTimeInitialization) {
1400 #if !LOG_DISABLED || !RELEASE_LOG_DISABLED
1401         WebKitInitializeLogChannelsIfNecessary();
1402         WebCore::initializeLogChannelsIfNecessary();
1403 #endif
1404
1405         // Initialize our platform strategies first before invoking the rest
1406         // of the initialization code which may depend on the strategies.
1407         WebPlatformStrategies::initializeIfNecessary();
1408
1409         initializeDOMWrapperHooks();
1410
1411 #if PLATFORM(IOS_FAMILY)
1412         // Set the WebSQLiteDatabaseTrackerClient.
1413         SQLiteDatabaseTracker::setClient(&WebSQLiteDatabaseTrackerClient::sharedWebSQLiteDatabaseTrackerClient());
1414
1415         if ([standardPreferences databasesEnabled])
1416 #endif
1417         [WebDatabaseManager sharedWebDatabaseManager];
1418
1419 #if PLATFORM(IOS_FAMILY)        
1420         if ([standardPreferences storageTrackerEnabled])
1421 #endif
1422         WebKitInitializeStorageIfNecessary();
1423
1424 #if ENABLE(GAMEPAD)
1425         WebKitInitializeGamepadProviderIfNecessary();
1426 #endif
1427 #if PLATFORM(MAC)
1428         WebCore::SwitchingGPUClient::setSingleton(WebKit::WebSwitchingGPUClient::singleton());
1429 #endif
1430         DeprecatedGlobalSettings::setShouldRespectPriorityInCSSAttributeSetters(shouldRespectPriorityInCSSAttributeSetters());
1431
1432 #if PLATFORM(IOS_FAMILY)
1433         if (IOSApplication::isMobileSafari())
1434             DeprecatedGlobalSettings::setShouldManageAudioSessionCategory(true);
1435 #endif
1436
1437         didOneTimeInitialization = true;
1438     }
1439
1440     _private->group = WebViewGroup::getOrCreate(groupName, _private->preferences._localStorageDatabasePath);
1441     _private->group->addWebView(self);
1442
1443     PageConfiguration pageConfiguration(
1444         makeUniqueRef<WebEditorClient>(self),
1445         SocketProvider::create(),
1446         LibWebRTCProvider::create(),
1447         WebCore::CacheStorageProvider::create(),
1448         BackForwardList::create(self)
1449     );
1450 #if !PLATFORM(IOS_FAMILY)
1451     pageConfiguration.chromeClient = new WebChromeClient(self);
1452     pageConfiguration.contextMenuClient = new WebContextMenuClient(self);
1453     // FIXME: We should enable this on iOS as well.
1454     pageConfiguration.validationMessageClient = std::make_unique<WebValidationMessageClient>(self);
1455     pageConfiguration.inspectorClient = new WebInspectorClient(self);
1456 #else
1457     pageConfiguration.chromeClient = new WebChromeClientIOS(self);
1458     pageConfiguration.inspectorClient = new WebInspectorClient(self);
1459 #endif
1460
1461 #if ENABLE(DRAG_SUPPORT)
1462     pageConfiguration.dragClient = new WebDragClient(self);
1463 #endif
1464
1465 #if ENABLE(APPLE_PAY)
1466     pageConfiguration.paymentCoordinatorClient = new WebPaymentCoordinatorClient();
1467 #endif
1468
1469     pageConfiguration.alternativeTextClient = new WebAlternativeTextClient(self);
1470     pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
1471     pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(self);
1472     pageConfiguration.applicationCacheStorage = &webApplicationCacheStorage();
1473     pageConfiguration.databaseProvider = &WebDatabaseProvider::singleton();
1474     pageConfiguration.pluginInfoProvider = &WebPluginInfoProvider::singleton();
1475     pageConfiguration.storageNamespaceProvider = &_private->group->storageNamespaceProvider();
1476     pageConfiguration.userContentProvider = &_private->group->userContentController();
1477     pageConfiguration.visitedLinkStore = &_private->group->visitedLinkStore();
1478     _private->page = new Page(WTFMove(pageConfiguration));
1479
1480     _private->page->setGroupName(groupName);
1481
1482 #if ENABLE(GEOLOCATION)
1483     WebCore::provideGeolocationTo(_private->page, *new WebGeolocationClient(self));
1484 #endif
1485 #if ENABLE(NOTIFICATIONS)
1486     WebCore::provideNotification(_private->page, new WebNotificationClient(self));
1487 #endif
1488 #if ENABLE(DEVICE_ORIENTATION)
1489 #if !PLATFORM(IOS_FAMILY)
1490     WebCore::provideDeviceOrientationTo(_private->page, new WebDeviceOrientationClient(self));
1491 #endif
1492 #endif
1493
1494 #if ENABLE(REMOTE_INSPECTOR)
1495     _private->page->setRemoteInspectionAllowed(true);
1496 #endif
1497
1498     _private->page->setCanStartMedia([self window]);
1499     _private->page->settings().setLocalStorageDatabasePath([[self preferences] _localStorageDatabasePath]);
1500     _private->page->settings().setUseLegacyBackgroundSizeShorthandBehavior(shouldUseLegacyBackgroundSizeShorthandBehavior());
1501
1502 #if !PLATFORM(IOS_FAMILY)
1503     if (needsOutlookQuirksScript()) {
1504         _private->page->settings().setShouldInjectUserScriptsInInitialEmptyDocument(true);
1505         [self _injectOutlookQuirksScript];
1506     }
1507 #endif
1508
1509 #if PLATFORM(IOS_FAMILY)
1510     _private->page->settings().setPassiveTouchListenersAsDefaultOnDocument(linkedOnOrAfter(SDKVersion::FirstThatDefaultsToPassiveTouchListenersOnDocument));
1511 #endif
1512
1513 #if PLATFORM(IOS_FAMILY)
1514     // Preserve the behavior we had before <rdar://problem/7580867>
1515     // by enforcing a 5MB limit for session storage.
1516     _private->page->settings().setSessionStorageQuota(5 * 1024 * 1024);
1517
1518     [self _updateScreenScaleFromWindow];
1519     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
1520     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
1521     _private->_fixedPositionContent = [[WebFixedPositionContent alloc] initWithWebView:self];
1522 #if ENABLE(ORIENTATION_EVENTS)
1523     _private->deviceOrientation = [[self _UIKitDelegateForwarder] deviceOrientation];
1524 #endif
1525 #endif
1526
1527     if ([[NSUserDefaults standardUserDefaults] objectForKey:WebSmartInsertDeleteEnabled])
1528         [self setSmartInsertDeleteEnabled:[[NSUserDefaults standardUserDefaults] boolForKey:WebSmartInsertDeleteEnabled]];
1529
1530     [WebFrame _createMainFrameWithPage:_private->page frameName:frameName frameView:frameView];
1531
1532 #if PLATFORM(IOS_FAMILY)
1533     NSRunLoop *runLoop = WebThreadNSRunLoop();
1534 #else
1535     NSRunLoop *runLoop = [NSRunLoop mainRunLoop];
1536 #endif
1537
1538     if (WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOADING_DURING_COMMON_RUNLOOP_MODES))
1539         [self scheduleInRunLoop:runLoop forMode:(NSString *)kCFRunLoopCommonModes];
1540     else
1541         [self scheduleInRunLoop:runLoop forMode:NSDefaultRunLoopMode];
1542
1543     [self _addToAllWebViewsSet];
1544     
1545     // If there's already a next key view (e.g., from a nib), wire it up to our
1546     // contained frame view. In any case, wire our next key view up to the our
1547     // contained frame view. This works together with our becomeFirstResponder 
1548     // and setNextKeyView overrides.
1549     NSView *nextKeyView = [self nextKeyView];
1550     if (nextKeyView && nextKeyView != frameView)
1551         [frameView setNextKeyView:nextKeyView];
1552     [super setNextKeyView:frameView];
1553
1554     if ([[self class] shouldIncludeInWebKitStatistics])
1555         ++WebViewCount;
1556
1557 #if !PLATFORM(IOS_FAMILY)
1558     [self _registerDraggedTypes];
1559 #endif
1560
1561     [self _setIsVisible:[self _isViewVisible]];
1562
1563     WebPreferences *prefs = [self preferences];
1564     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_preferencesChangedNotification:)
1565                                                  name:WebPreferencesChangedInternalNotification object:prefs];
1566
1567 #if !PLATFORM(IOS_FAMILY)
1568     [self _preferencesChanged:[self preferences]];
1569     [[self preferences] _postPreferencesChangedAPINotification];
1570 #else
1571     // do this on the current thread on iOS, since the web thread could be blocked on the main thread,
1572     // and prefs need to be changed synchronously <rdar://problem/5841558>
1573     [self _preferencesChanged:prefs];
1574     _private->page->settings().setFontFallbackPrefersPictographs(true);
1575 #endif
1576
1577     WebInstallMemoryPressureHandler();
1578
1579 #if !PLATFORM(IOS_FAMILY)
1580     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
1581         // Originally, we allowed all local loads.
1582         SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForAll);
1583     } else if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_MORE_STRICT_LOCAL_RESOURCE_SECURITY_RESTRICTION)) {
1584         // Later, we allowed local loads for local URLs and documents loaded
1585         // with substitute data.
1586         SecurityPolicy::setLocalLoadPolicy(SecurityPolicy::AllowLocalLoadsForLocalAndSubstituteData);
1587     }
1588 #endif
1589
1590 #if PLATFORM(MAC)
1591     if (!WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_CONTENT_SNIFFING_FOR_FILE_URLS))
1592         ResourceHandle::forceContentSniffing();
1593
1594     _private->page->setDeviceScaleFactor([self _deviceScaleFactor]);
1595     _private->page->setUseDarkAppearance(self._effectiveAppearanceIsDark);
1596 #endif
1597
1598     _private->page->settings().setContentDispositionAttachmentSandboxEnabled(true);
1599 }
1600
1601 - (id)_initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName
1602 {
1603     self = [super initWithFrame:f];
1604     if (!self)
1605         return nil;
1606
1607 #ifdef ENABLE_WEBKIT_UNSET_DYLD_FRAMEWORK_PATH
1608     // DYLD_FRAMEWORK_PATH is used so Safari will load the development version of WebKit, which
1609     // may not work with other WebKit applications.  Unsetting DYLD_FRAMEWORK_PATH removes the
1610     // need for Safari to unset it to prevent it from being passed to applications it launches.
1611     // Unsetting it when a WebView is first created is as good a place as any.
1612     // See <http://bugs.webkit.org/show_bug.cgi?id=4286> for more details.
1613     if (getenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH")) {
1614         unsetenv("DYLD_FRAMEWORK_PATH");
1615         unsetenv("WEBKIT_UNSET_DYLD_FRAMEWORK_PATH");
1616     }
1617 #endif
1618
1619     _private = [[WebViewPrivate alloc] init];
1620     [self _commonInitializationWithFrameName:frameName groupName:groupName];
1621     [self setMaintainsBackForwardList: YES];
1622     return self;
1623 }
1624
1625 - (void)_viewWillDrawInternal
1626 {
1627     Frame* frame = [self _mainCoreFrame];
1628     if (frame && frame->view())
1629         frame->view()->updateLayoutAndStyleIfNeededRecursive();
1630 }
1631
1632 + (NSArray *)_supportedMIMETypes
1633 {
1634     // Load the plug-in DB allowing plug-ins to install types.
1635     [WebPluginDatabase sharedDatabase];
1636     return [[WebFrameView _viewTypesAllowImageTypeOmission:NO] allKeys];
1637 }
1638
1639 #if !PLATFORM(IOS_FAMILY)
1640 + (NSArray *)_supportedFileExtensions
1641 {
1642     NSMutableSet *extensions = [[NSMutableSet alloc] init];
1643     NSArray *MIMETypes = [self _supportedMIMETypes];
1644     NSEnumerator *enumerator = [MIMETypes objectEnumerator];
1645     NSString *MIMEType;
1646     while ((MIMEType = [enumerator nextObject]) != nil) {
1647         NSArray *extensionsForType = [[NSURLFileTypeMappings sharedMappings] extensionsForMIMEType:MIMEType];
1648         if (extensionsForType) {
1649             [extensions addObjectsFromArray:extensionsForType];
1650         }
1651     }
1652     NSArray *uniqueExtensions = [extensions allObjects];
1653     [extensions release];
1654     return uniqueExtensions;
1655 }
1656 #endif
1657
1658 #if PLATFORM(IOS_FAMILY)
1659 + (void)enableWebThread
1660 {
1661     static BOOL isWebThreadEnabled = NO;
1662     if (!isWebThreadEnabled) {
1663         WebCoreObjCDeallocOnWebThread([DOMObject class]);
1664         WebCoreObjCDeallocOnWebThread([WebBasePluginPackage class]);
1665         WebCoreObjCDeallocOnWebThread([WebDataSource class]);
1666         WebCoreObjCDeallocOnWebThread([WebFrame class]);
1667         WebCoreObjCDeallocOnWebThread([WebHTMLView class]);
1668         WebCoreObjCDeallocOnWebThread([WebHistoryItem class]);
1669         WebCoreObjCDeallocOnWebThread([WebPlainWhiteView class]);
1670         WebCoreObjCDeallocOnWebThread([WebPolicyDecisionListener class]);
1671         WebCoreObjCDeallocOnWebThread([WebView class]);
1672         WebCoreObjCDeallocOnWebThread([WebVisiblePosition class]);
1673         WebThreadEnable();
1674         isWebThreadEnabled = YES;
1675     }
1676 }
1677
1678 - (id)initSimpleHTMLDocumentWithStyle:(NSString *)style frame:(CGRect)frame preferences:(WebPreferences *)preferences groupName:(NSString *)groupName
1679 {
1680     self = [super initWithFrame:frame];
1681     if (!self)
1682         return nil;
1683     
1684     _private = [[WebViewPrivate alloc] init];
1685     
1686 #ifndef NDEBUG
1687     WTF::RefCountedLeakCounter::suppressMessages(webViewIsOpen);
1688 #endif
1689     
1690     if (!preferences)
1691         preferences = [WebPreferences standardPreferences];
1692     [preferences willAddToWebView];
1693     
1694     _private->preferences = [preferences retain];
1695     _private->mainFrameDocumentReady = NO;
1696     _private->drawsBackground = YES;
1697     _private->backgroundColor = CGColorRetain(cachedCGColor(Color::white));
1698
1699     WebFrameView *frameView = nil;
1700     frameView = [[WebFrameView alloc] initWithFrame: CGRectMake(0,0,frame.size.width,frame.size.height)];
1701     [frameView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1702     [self addSubview:frameView];
1703     [frameView release];
1704
1705     _private->group = WebViewGroup::getOrCreate(groupName, _private->preferences._localStorageDatabasePath);
1706     _private->group->addWebView(self);
1707
1708     PageConfiguration pageConfiguration(
1709         makeUniqueRef<WebEditorClient>(self),
1710         SocketProvider::create(),
1711         LibWebRTCProvider::create(),
1712         WebCore::CacheStorageProvider::create(),
1713         BackForwardList::create(self)
1714     );
1715     pageConfiguration.chromeClient = new WebChromeClientIOS(self);
1716 #if ENABLE(DRAG_SUPPORT)
1717     pageConfiguration.dragClient = new WebDragClient(self);
1718 #endif
1719
1720 #if ENABLE(APPLE_PAY)
1721     pageConfiguration.paymentCoordinatorClient = new WebPaymentCoordinatorClient();
1722 #endif
1723
1724     pageConfiguration.inspectorClient = new WebInspectorClient(self);
1725     pageConfiguration.loaderClientForMainFrame = new WebFrameLoaderClient;
1726     pageConfiguration.progressTrackerClient = new WebProgressTrackerClient(self);
1727     pageConfiguration.applicationCacheStorage = &webApplicationCacheStorage();
1728     pageConfiguration.databaseProvider = &WebDatabaseProvider::singleton();
1729     pageConfiguration.storageNamespaceProvider = &_private->group->storageNamespaceProvider();
1730     pageConfiguration.userContentProvider = &_private->group->userContentController();
1731     pageConfiguration.visitedLinkStore = &_private->group->visitedLinkStore();
1732     pageConfiguration.pluginInfoProvider = &WebPluginInfoProvider::singleton();
1733
1734     _private->page = new Page(WTFMove(pageConfiguration));
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().tryToBeginDataInteractionAtPoint(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)_didConcludeEditDataInteraction
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 + (void)_setIconLoadingEnabled:(BOOL)enabled
2494 {
2495     iconLoadingEnabled = enabled;
2496 }
2497
2498 + (BOOL)_isIconLoadingEnabled
2499 {
2500     return iconLoadingEnabled;
2501 }
2502
2503 - (WebInspector *)inspector
2504 {
2505     if (!_private->inspector)
2506         _private->inspector = [[WebInspector alloc] initWithInspectedWebView:self];
2507     return _private->inspector;
2508 }
2509
2510 #if ENABLE(REMOTE_INSPECTOR)
2511 + (void)_enableRemoteInspector
2512 {
2513     RemoteInspector::singleton().start();
2514 }
2515
2516 + (void)_disableRemoteInspector
2517 {
2518     RemoteInspector::singleton().stop();
2519 }
2520
2521 + (void)_disableAutoStartRemoteInspector
2522 {
2523     RemoteInspector::startDisabled();
2524 }
2525
2526 + (BOOL)_isRemoteInspectorEnabled
2527 {
2528     return RemoteInspector::singleton().enabled();
2529 }
2530
2531 + (BOOL)_hasRemoteInspectorSession
2532 {
2533     return RemoteInspector::singleton().hasActiveDebugSession();
2534 }
2535
2536 - (BOOL)allowsRemoteInspection
2537 {
2538     return _private->page->remoteInspectionAllowed();
2539 }
2540
2541 - (void)setAllowsRemoteInspection:(BOOL)allow
2542 {
2543     _private->page->setRemoteInspectionAllowed(allow);
2544 }
2545
2546 - (void)setShowingInspectorIndication:(BOOL)showing
2547 {
2548 #if PLATFORM(IOS_FAMILY)
2549     ASSERT(WebThreadIsLocked());
2550
2551     if (showing) {
2552         if (!_private->indicateLayer) {
2553             _private->indicateLayer = [[WebIndicateLayer alloc] initWithWebView:self];
2554             [_private->indicateLayer setNeedsLayout];
2555             [[[self window] hostLayer] addSublayer:_private->indicateLayer];
2556         }
2557     } else {
2558         [_private->indicateLayer removeFromSuperlayer];
2559         [_private->indicateLayer release];
2560         _private->indicateLayer = nil;
2561     }
2562 #else
2563     // Implemented in WebCore::InspectorOverlay.
2564 #endif
2565 }
2566
2567 #if PLATFORM(IOS_FAMILY)
2568 - (void)_setHostApplicationProcessIdentifier:(pid_t)pid auditToken:(audit_token_t)auditToken
2569 {
2570     RetainPtr<CFDataRef> auditData = adoptCF(CFDataCreate(nullptr, (const UInt8*)&auditToken, sizeof(auditToken)));
2571     RemoteInspector::singleton().setParentProcessInformation(pid, auditData);
2572 }
2573 #endif // PLATFORM(IOS_FAMILY)
2574 #endif // ENABLE(REMOTE_INSPECTOR)
2575
2576 - (WebCore::Page*)page
2577 {
2578     return _private->page;
2579 }
2580
2581 #if !PLATFORM(IOS_FAMILY)
2582 - (NSMenu *)_menuForElement:(NSDictionary *)element defaultItems:(NSArray *)items
2583 {
2584     NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate] webView:self contextMenuItemsForElement:element defaultMenuItems:items];
2585     NSArray *menuItems = defaultMenuItems;
2586
2587     // CallUIDelegate returns nil if UIDelegate is nil or doesn't respond to the selector. So we need to check that here
2588     // to distinguish between using defaultMenuItems or the delegate really returning nil to say "no context menu".
2589     SEL selector = @selector(webView:contextMenuItemsForElement:defaultMenuItems:);
2590     if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
2591         menuItems = CallUIDelegate(self, selector, element, defaultMenuItems);
2592         if (!menuItems)
2593             return nil;
2594     }
2595
2596     unsigned count = [menuItems count];
2597     if (!count)
2598         return nil;
2599
2600     NSMenu *menu = [[NSMenu alloc] init];
2601     for (unsigned i = 0; i < count; i++)
2602         [menu addItem:[menuItems objectAtIndex:i]];
2603
2604     return [menu autorelease];
2605 }
2606 #endif
2607
2608 - (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(NSUInteger)modifierFlags
2609 {
2610     // We originally intended to call this delegate method sometimes with a nil dictionary, but due to
2611     // a bug dating back to WebKit 1.0 this delegate was never called with nil! Unfortunately we can't
2612     // start calling this with nil since it will break Adobe Help Viewer, and possibly other clients.
2613     if (!dictionary)
2614         return;
2615     CallUIDelegate(self, @selector(webView:mouseDidMoveOverElement:modifierFlags:), dictionary, modifierFlags);
2616 }
2617
2618 - (void)_loadBackForwardListFromOtherView:(WebView *)otherView
2619 {
2620     if (!_private->page)
2621         return;
2622     
2623     if (!otherView->_private->page)
2624         return;
2625     
2626     // It turns out the right combination of behavior is done with the back/forward load
2627     // type.  (See behavior matrix at the top of WebFramePrivate.)  So we copy all the items
2628     // in the back forward list, and go to the current one.
2629
2630     BackForwardController& backForward = _private->page->backForward();
2631     ASSERT(!backForward.currentItem()); // destination list should be empty
2632
2633     BackForwardController& otherBackForward = otherView->_private->page->backForward();
2634     if (!otherBackForward.currentItem())
2635         return; // empty back forward list, bail
2636     
2637     HistoryItem* newItemToGoTo = nullptr;
2638
2639     int lastItemIndex = otherBackForward.forwardCount();
2640     for (int i = -otherBackForward.backCount(); i <= lastItemIndex; ++i) {
2641         if (i == 0) {
2642             // If this item is showing , save away its current scroll and form state,
2643             // since that might have changed since loading and it is normally not saved
2644             // until we leave that page.
2645             otherView->_private->page->mainFrame().loader().history().saveDocumentAndScrollState();
2646         }
2647         Ref<HistoryItem> newItem = otherBackForward.itemAtIndex(i)->copy();
2648         if (i == 0) 
2649             newItemToGoTo = newItem.ptr();
2650         backForward.client().addItem(WTFMove(newItem));
2651     }
2652
2653     ASSERT(newItemToGoTo);
2654     _private->page->goToItem(*newItemToGoTo, FrameLoadType::IndexedBackForward, ShouldTreatAsContinuingLoad::No);
2655 }
2656
2657 - (void)_setFormDelegate: (id<WebFormDelegate>)delegate
2658 {
2659     _private->formDelegate = delegate;
2660 #if PLATFORM(IOS_FAMILY)
2661     [_private->formDelegateForwarder clearTarget];
2662     [_private->formDelegateForwarder release];
2663     _private->formDelegateForwarder = nil;
2664 #endif
2665 }
2666
2667 - (id<WebFormDelegate>)_formDelegate
2668 {
2669     return _private->formDelegate;
2670 }
2671
2672 #if PLATFORM(IOS_FAMILY)
2673 - (id)_formDelegateForwarder
2674 {
2675     if (_private->closing)
2676         return nil;
2677
2678     if (!_private->formDelegateForwarder)
2679         _private->formDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:[self _formDelegate] defaultTarget:[WebDefaultFormDelegate sharedFormDelegate]];
2680     return _private->formDelegateForwarder;
2681 }
2682
2683 - (id)_formDelegateForSelector:(SEL)selector
2684 {
2685     id delegate = self->_private->formDelegate;
2686     if ([delegate respondsToSelector:selector])
2687         return delegate;
2688
2689     delegate = [WebDefaultFormDelegate sharedFormDelegate];
2690     if ([delegate respondsToSelector:selector])
2691         return delegate;
2692
2693     return nil;
2694 }
2695 #endif
2696
2697 #if !PLATFORM(IOS_FAMILY)
2698 - (BOOL)_needsAdobeFrameReloadingQuirk
2699 {
2700     static BOOL needsQuirk = _CFAppVersionCheckLessThan(CFSTR("com.adobe.Acrobat"), -1, 9.0)
2701         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.Acrobat.Pro"), -1, 9.0)
2702         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.Reader"), -1, 9.0)
2703         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.distiller"), -1, 9.0)
2704         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.Contribute"), -1, 4.2)
2705         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.dreamweaver-9.0"), -1, 9.1)
2706         || _CFAppVersionCheckLessThan(CFSTR("com.macromedia.fireworks"), -1, 9.1)
2707         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.InCopy"), -1, 5.1)
2708         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.InDesign"), -1, 5.1)
2709         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.Soundbooth"), -1, 2);
2710
2711     return needsQuirk;
2712 }
2713
2714 - (BOOL)_needsLinkElementTextCSSQuirk
2715 {
2716     static BOOL needsQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LINK_ELEMENT_TEXT_CSS_QUIRK)
2717         && _CFAppVersionCheckLessThan(CFSTR("com.e-frontier.shade10"), -1, 10.6);
2718     return needsQuirk;
2719 }
2720
2721 - (BOOL)_needsFrameNameFallbackToIdQuirk
2722 {
2723     static BOOL needsQuirk = _CFAppVersionCheckLessThan(CFSTR("info.colloquy"), -1, 2.5);
2724     return needsQuirk;
2725 }
2726
2727 - (BOOL)_needsIsLoadingInAPISenseQuirk
2728 {
2729     static BOOL needsQuirk = _CFAppVersionCheckLessThan(CFSTR("com.apple.iAdProducer"), -1, 2.1);
2730     
2731     return needsQuirk;
2732 }
2733
2734 - (BOOL)_needsKeyboardEventDisambiguationQuirks
2735 {
2736     static BOOL needsQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_IE_COMPATIBLE_KEYBOARD_EVENT_DISPATCH) && !MacApplication::isSafari();
2737     return needsQuirks;
2738 }
2739
2740 - (BOOL)_needsFrameLoadDelegateRetainQuirk
2741 {
2742     static BOOL needsQuirk = _CFAppVersionCheckLessThan(CFSTR("com.equinux.iSale5"), -1, 5.6);
2743     return needsQuirk;
2744 }
2745
2746 static bool needsSelfRetainWhileLoadingQuirk()
2747 {
2748     static bool needsQuirk = MacApplication::isAperture();
2749     return needsQuirk;
2750 }
2751 #endif // !PLATFORM(IOS_FAMILY)
2752
2753 - (BOOL)_needsPreHTML5ParserQuirks
2754 {    
2755 #if !PLATFORM(IOS_FAMILY)
2756     // AOL Instant Messenger and Microsoft My Day contain markup incompatible
2757     // with the new HTML5 parser. If these applications were linked against a
2758     // version of WebKit prior to the introduction of the HTML5 parser, enable
2759     // parser quirks to maintain compatibility. For details, see 
2760     // <https://bugs.webkit.org/show_bug.cgi?id=46134> and
2761     // <https://bugs.webkit.org/show_bug.cgi?id=46334>.
2762     static bool isApplicationNeedingParserQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
2763         && (MacApplication::isAOLInstantMessenger() || MacApplication::isMicrosoftMyDay());
2764     
2765     // Mail.app must continue to display HTML email that contains quirky markup.
2766     static bool isAppleMail = MacApplication::isAppleMail();
2767
2768     return isApplicationNeedingParserQuirks
2769         || isAppleMail
2770 #if ENABLE(DASHBOARD_SUPPORT)
2771         // Pre-HTML5 parser quirks are required to remain compatible with many
2772         // Dashboard widgets. See <rdar://problem/8175982>.
2773         || (_private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode())
2774 #endif
2775         || [[self preferences] usePreHTML5ParserQuirks];
2776 #else
2777     return [[self preferences] usePreHTML5ParserQuirks];
2778 #endif
2779 }
2780
2781 - (void)_preferencesChangedNotification:(NSNotification *)notification
2782 {
2783 #if PLATFORM(IOS_FAMILY)
2784     // For WebViews that load synchronously, preference changes need to be propagated
2785     // down to WebCore synchronously so that loads in that WebView have the correct
2786     // up-to-date settings.
2787     if (!WebThreadIsLocked())
2788         WebThreadLock();
2789     if ([[self mainFrame] _loadsSynchronously]) {
2790 #endif
2791
2792     WebPreferences *preferences = (WebPreferences *)[notification object];
2793     [self _preferencesChanged:preferences];
2794
2795 #if PLATFORM(IOS_FAMILY)
2796     } else {
2797         WebThreadRun(^{
2798             // It is possible that the prefs object has already changed before the invocation could be called
2799             // on the web thread. This is not possible on TOT which is why they have a simple ASSERT.
2800             WebPreferences *preferences = (WebPreferences *)[notification object];
2801             if (preferences != [self preferences])
2802                 return;
2803             [self _preferencesChanged:preferences];
2804         });
2805     }
2806 #endif
2807 }
2808
2809 - (void)_preferencesChanged:(WebPreferences *)preferences
2810 {    
2811     ASSERT(preferences == [self preferences]);
2812     if (!_private->userAgentOverridden)
2813         [self _invalidateUserAgentCache];
2814
2815     // Cache this value so we don't have to read NSUserDefaults on each page load
2816     _private->useSiteSpecificSpoofing = [preferences _useSiteSpecificSpoofing];
2817
2818     // Update corresponding WebCore Settings object.
2819     if (!_private->page)
2820         return;
2821
2822 #if PLATFORM(IOS_FAMILY)
2823     // iOS waits to call [WebDatabaseManager sharedWebDatabaseManager] until
2824     // didOneTimeInitialization is true so that we don't initialize databases
2825     // until the first WebView has been created. This is because database
2826     // initialization current requires disk access to populate the origins
2827     // quota map and we want to do this lazily by waiting until WebKit is
2828     // used to display web content in a WebView. The possible cases are:
2829     //   - on one time initialize (the first WebView creation) if databases are enabled (default)
2830     //   - when databases are dynamically enabled later, and they were disabled at startup (this case)
2831     if (didOneTimeInitialization) {
2832         if ([preferences databasesEnabled])
2833             [WebDatabaseManager sharedWebDatabaseManager];
2834         if ([preferences storageTrackerEnabled])
2835             WebKitInitializeStorageIfNecessary();
2836     }
2837 #endif
2838
2839     Settings& settings = _private->page->settings();
2840
2841     settings.setCursiveFontFamily([preferences cursiveFontFamily]);
2842     settings.setDefaultFixedFontSize([preferences defaultFixedFontSize]);
2843     settings.setDefaultFontSize([preferences defaultFontSize]);
2844     settings.setDefaultTextEncodingName([preferences defaultTextEncodingName]);
2845     settings.setUsesEncodingDetector([preferences usesEncodingDetector]);
2846     settings.setFantasyFontFamily([preferences fantasyFontFamily]);
2847     settings.setFixedFontFamily([preferences fixedFontFamily]);
2848     settings.setForceFTPDirectoryListings([preferences _forceFTPDirectoryListings]);
2849     settings.setFTPDirectoryTemplatePath([preferences _ftpDirectoryTemplatePath]);
2850     settings.setLocalStorageDatabasePath([preferences _localStorageDatabasePath]);
2851     settings.setJavaEnabled([preferences isJavaEnabled]);
2852     settings.setScriptEnabled([preferences isJavaScriptEnabled]);
2853     settings.setScriptMarkupEnabled([preferences javaScriptMarkupEnabled]);
2854     settings.setWebSecurityEnabled([preferences isWebSecurityEnabled]);
2855     settings.setAllowUniversalAccessFromFileURLs([preferences allowUniversalAccessFromFileURLs]);
2856     settings.setAllowFileAccessFromFileURLs([preferences allowFileAccessFromFileURLs]);
2857     settings.setAllowCrossOriginSubresourcesToAskForCredentials([preferences allowCrossOriginSubresourcesToAskForCredentials]);
2858     settings.setNeedsStorageAccessFromFileURLsQuirk([preferences needsStorageAccessFromFileURLsQuirk]);
2859     settings.setMinimumFontSize([preferences minimumFontSize]);
2860     settings.setMinimumLogicalFontSize([preferences minimumLogicalFontSize]);
2861     settings.setPictographFontFamily([preferences pictographFontFamily]);
2862     settings.setPluginsEnabled([preferences arePlugInsEnabled]);
2863     settings.setLocalStorageEnabled([preferences localStorageEnabled]);
2864
2865     _private->page->enableLegacyPrivateBrowsing([preferences privateBrowsingEnabled]);
2866     settings.setSansSerifFontFamily([preferences sansSerifFontFamily]);
2867     settings.setSerifFontFamily([preferences serifFontFamily]);
2868     settings.setStandardFontFamily([preferences standardFontFamily]);
2869     settings.setLoadsImagesAutomatically([preferences loadsImagesAutomatically]);
2870     settings.setLoadsSiteIconsIgnoringImageLoadingSetting([preferences loadsSiteIconsIgnoringImageLoadingPreference]);
2871 #if PLATFORM(IOS_FAMILY)
2872     settings.setShouldPrintBackgrounds(true);
2873 #else
2874     settings.setShouldPrintBackgrounds([preferences shouldPrintBackgrounds]);
2875 #endif
2876     settings.setShrinksStandaloneImagesToFit([preferences shrinksStandaloneImagesToFit]);
2877     settings.setEditableLinkBehavior(core([preferences editableLinkBehavior]));
2878     settings.setTextDirectionSubmenuInclusionBehavior(core([preferences textDirectionSubmenuInclusionBehavior]));
2879     settings.setDOMPasteAllowed([preferences isDOMPasteAllowed]);
2880     settings.setUsesPageCache([self usesPageCache]);
2881     settings.setPageCacheSupportsPlugins([preferences pageCacheSupportsPlugins]);
2882     settings.setBackForwardCacheExpirationInterval([preferences _backForwardCacheExpirationInterval]);
2883
2884     settings.setDeveloperExtrasEnabled([preferences developerExtrasEnabled]);
2885     settings.setJavaScriptRuntimeFlags(JSC::RuntimeFlags([preferences javaScriptRuntimeFlags]));
2886     settings.setAuthorAndUserStylesEnabled([preferences authorAndUserStylesEnabled]);
2887
2888     settings.setNeedsSiteSpecificQuirks(_private->useSiteSpecificSpoofing);
2889     settings.setDOMTimersThrottlingEnabled([preferences domTimersThrottlingEnabled]);
2890     settings.setWebArchiveDebugModeEnabled([preferences webArchiveDebugModeEnabled]);
2891     settings.setLocalFileContentSniffingEnabled([preferences localFileContentSniffingEnabled]);
2892     settings.setOfflineWebApplicationCacheEnabled([preferences offlineWebApplicationCacheEnabled]);
2893     settings.setJavaScriptCanAccessClipboard([preferences javaScriptCanAccessClipboard]);
2894     settings.setXSSAuditorEnabled([preferences isXSSAuditorEnabled]);
2895     settings.setDNSPrefetchingEnabled([preferences isDNSPrefetchingEnabled]);
2896
2897     settings.setAcceleratedCompositingEnabled([preferences acceleratedCompositingEnabled]);
2898     settings.setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
2899     settings.setDisplayListDrawingEnabled([preferences displayListDrawingEnabled]);
2900     settings.setCanvasUsesAcceleratedDrawing([preferences canvasUsesAcceleratedDrawing]);
2901     settings.setShowDebugBorders([preferences showDebugBorders]);
2902     settings.setSimpleLineLayoutEnabled([preferences simpleLineLayoutEnabled]);
2903     settings.setSimpleLineLayoutDebugBordersEnabled([preferences simpleLineLayoutDebugBordersEnabled]);
2904     settings.setShowRepaintCounter([preferences showRepaintCounter]);
2905     settings.setWebGLEnabled([preferences webGLEnabled]);
2906     settings.setSubpixelCSSOMElementMetricsEnabled([preferences subpixelCSSOMElementMetricsEnabled]);
2907     settings.setSubpixelAntialiasedLayerTextEnabled([preferences subpixelAntialiasedLayerTextEnabled]);
2908
2909     settings.setForceSoftwareWebGLRendering([preferences forceSoftwareWebGLRendering]);
2910     settings.setForceWebGLUsesLowPower([preferences forceLowPowerGPUForWebGL]);
2911     settings.setAccelerated2dCanvasEnabled([preferences accelerated2dCanvasEnabled]);
2912     settings.setLoadDeferringEnabled(shouldEnableLoadDeferring());
2913     settings.setWindowFocusRestricted(shouldRestrictWindowFocus());
2914     settings.setFrameFlattening((const WebCore::FrameFlattening)[preferences frameFlattening]);
2915     settings.setAsyncFrameScrollingEnabled([preferences asyncFrameScrollingEnabled]);
2916     settings.setSpatialNavigationEnabled([preferences isSpatialNavigationEnabled]);
2917     settings.setPaginateDuringLayoutEnabled([preferences paginateDuringLayoutEnabled]);
2918
2919     settings.setAsynchronousSpellCheckingEnabled([preferences asynchronousSpellCheckingEnabled]);
2920     settings.setHyperlinkAuditingEnabled([preferences hyperlinkAuditingEnabled]);
2921     settings.setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
2922     settings.setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
2923     settings.setValidationMessageTimerMagnification([self validationMessageTimerMagnification]);
2924
2925     BOOL mediaPlaybackRequiresUserGesture = [preferences mediaPlaybackRequiresUserGesture];
2926     settings.setVideoPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture || [preferences videoPlaybackRequiresUserGesture]);
2927     settings.setAudioPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture || [preferences audioPlaybackRequiresUserGesture]);
2928     settings.setRequiresUserGestureToLoadVideo(shouldRequireUserGestureToLoadVideo());
2929     settings.setMainContentUserGestureOverrideEnabled([preferences overrideUserGestureRequirementForMainContent]);
2930     settings.setAllowsInlineMediaPlayback([preferences mediaPlaybackAllowsInline]);
2931     settings.setAllowsInlineMediaPlaybackAfterFullscreen([preferences allowsInlineMediaPlaybackAfterFullscreen]);
2932     settings.setInlineMediaPlaybackRequiresPlaysInlineAttribute([preferences inlineMediaPlaybackRequiresPlaysInlineAttribute]);
2933     settings.setInvisibleAutoplayNotPermitted([preferences invisibleAutoplayNotPermitted]);
2934     settings.setAllowsPictureInPictureMediaPlayback([preferences allowsPictureInPictureMediaPlayback] && shouldAllowPictureInPictureMediaPlayback());
2935     settings.setMediaControlsScaleWithPageZoom([preferences mediaControlsScaleWithPageZoom]);
2936     settings.setSuppressesIncrementalRendering([preferences suppressesIncrementalRendering]);
2937     settings.setBackspaceKeyNavigationEnabled([preferences backspaceKeyNavigationEnabled]);
2938     settings.setWantsBalancedSetDefersLoadingBehavior([preferences wantsBalancedSetDefersLoadingBehavior]);
2939     DeprecatedGlobalSettings::setMockScrollbarsEnabled([preferences mockScrollbarsEnabled]);
2940
2941     settings.setShouldRespectImageOrientation([preferences shouldRespectImageOrientation]);
2942
2943     settings.setRequestAnimationFrameEnabled([preferences requestAnimationFrameEnabled]);
2944     settings.setDiagnosticLoggingEnabled([preferences diagnosticLoggingEnabled]);
2945     DeprecatedGlobalSettings::setLowPowerVideoAudioBufferSizeEnabled([preferences lowPowerVideoAudioBufferSizeEnabled]);
2946
2947     settings.setUseLegacyTextAlignPositionedElementBehavior([preferences useLegacyTextAlignPositionedElementBehavior]);
2948
2949     settings.setShouldConvertPositionStyleOnCopy([preferences shouldConvertPositionStyleOnCopy]);
2950     settings.setEnableInheritURIQueryComponent([preferences isInheritURIQueryComponentEnabled]);
2951
2952     settings.setAllowDisplayOfInsecureContent(shouldAllowDisplayAndRunningOfInsecureContent());
2953     settings.setAllowRunningOfInsecureContent(shouldAllowDisplayAndRunningOfInsecureContent());
2954
2955     settings.setJavaScriptCanOpenWindowsAutomatically([preferences javaScriptCanOpenWindowsAutomatically] || shouldAllowWindowOpenWithoutUserGesture());
2956
2957     settings.setVisualViewportEnabled([preferences visualViewportEnabled]);
2958     settings.setVisualViewportAPIEnabled([preferences visualViewportAPIEnabled]);
2959     settings.setCSSOMViewScrollingAPIEnabled([preferences CSSOMViewScrollingAPIEnabled]);
2960     settings.setMediaContentTypesRequiringHardwareSupport([preferences mediaContentTypesRequiringHardwareSupport]);
2961
2962     switch ([preferences storageBlockingPolicy]) {
2963     case WebAllowAllStorage:
2964         settings.setStorageBlockingPolicy(SecurityOrigin::AllowAllStorage);
2965         break;
2966     case WebBlockThirdPartyStorage:
2967         settings.setStorageBlockingPolicy(SecurityOrigin::BlockThirdPartyStorage);
2968         break;
2969     case WebBlockAllStorage:
2970         settings.setStorageBlockingPolicy(SecurityOrigin::BlockAllStorage);
2971         break;
2972     }
2973
2974     settings.setPlugInSnapshottingEnabled([preferences plugInSnapshottingEnabled]);
2975     settings.setHttpEquivEnabled([preferences httpEquivEnabled]);
2976     settings.setColorFilterEnabled([preferences colorFilterEnabled]);
2977     settings.setPunchOutWhiteBackgroundsInDarkMode([preferences punchOutWhiteBackgroundsInDarkMode]);
2978
2979 #if PLATFORM(MAC)
2980     settings.setAcceleratedCompositingForFixedPositionEnabled(true);
2981 #endif
2982
2983 #if ENABLE(RUBBER_BANDING)
2984     // FIXME: https://bugs.webkit.org/show_bug.cgi?id=136131
2985     settings.setRubberBandingForSubScrollableRegionsEnabled(false);
2986 #endif
2987
2988 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2989     settings.setAllowsAirPlayForMediaPlayback([preferences allowsAirPlayForMediaPlayback]);
2990 #endif
2991 #if PLATFORM(IOS_FAMILY)
2992     settings.setStandalone([preferences _standalone]);
2993     settings.setTelephoneNumberParsingEnabled([preferences _telephoneNumberParsingEnabled]);
2994     settings.setAllowMultiElementImplicitSubmission([preferences _allowMultiElementImplicitFormSubmission]);
2995     settings.setLayoutInterval(Seconds::fromMilliseconds([preferences _layoutInterval]));
2996     settings.setMaxParseDuration([preferences _maxParseDuration]);
2997     settings.setAlwaysUseAcceleratedOverflowScroll([preferences _alwaysUseAcceleratedOverflowScroll]);
2998     DeprecatedGlobalSettings::setAudioSessionCategoryOverride([preferences audioSessionCategoryOverride]);
2999     DeprecatedGlobalSettings::setNetworkDataUsageTrackingEnabled([preferences networkDataUsageTrackingEnabled]);
3000     DeprecatedGlobalSettings::setNetworkInterfaceName([preferences networkInterfaceName]);
3001 #if HAVE(AVKIT)
3002     DeprecatedGlobalSettings::setAVKitEnabled([preferences avKitEnabled]);
3003 #endif
3004
3005     settings.setPasswordEchoEnabled([preferences _allowPasswordEcho]);
3006     settings.setPasswordEchoDurationInSeconds([preferences _passwordEchoDuration]);
3007
3008     ASSERT_WITH_MESSAGE(settings.pageCacheSupportsPlugins(), "PageCacheSupportsPlugins should be enabled on iOS.");
3009     settings.setDelegatesPageScaling(true);
3010
3011 #if ENABLE(TEXT_AUTOSIZING)
3012     settings.setMinimumZoomFontSize([preferences _minimumZoomFontSize]);
3013     settings.setTextAutosizingEnabled([preferences _textAutosizingEnabled]);
3014 #endif
3015 #endif // PLATFORM(IOS_FAMILY)
3016
3017 #if PLATFORM(MAC)
3018     // This parses the user stylesheet synchronously so anything that may affect it should be done first.
3019     if ([preferences userStyleSheetEnabled]) {
3020         NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
3021         if ([location isEqualToString:@"apple-dashboard://stylesheet"])
3022             location = @"file:///System/Library/PrivateFrameworks/DashboardClient.framework/Resources/widget.css";
3023         settings.setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
3024     } else
3025         settings.setUserStyleSheetLocation([NSURL URLWithString:@""]);
3026
3027     settings.setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
3028     settings.setTreatsAnyTextCSSLinkAsStylesheet([self _needsLinkElementTextCSSQuirk]);
3029     settings.setNeedsFrameNameFallbackToIdQuirk([self _needsFrameNameFallbackToIdQuirk]);
3030     settings.setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
3031     settings.setEnforceCSSMIMETypeInNoQuirksMode(!_CFAppVersionCheckLessThan(CFSTR("com.apple.iWeb"), -1, 2.1));
3032     settings.setNeedsIsLoadingInAPISenseQuirk([self _needsIsLoadingInAPISenseQuirk]);
3033     settings.setTextAreasAreResizable([preferences textAreasAreResizable]);
3034     settings.setExperimentalNotificationsEnabled([preferences experimentalNotificationsEnabled]);
3035     settings.setShowsURLsInToolTips([preferences showsURLsInToolTips]);
3036     settings.setShowsToolTipOverTruncatedText([preferences showsToolTipOverTruncatedText]);
3037 #endif // PLATFORM(MAC)
3038
3039     DatabaseManager::singleton().setIsAvailable([preferences databasesEnabled]);
3040
3041 #if ENABLE(MEDIA_SOURCE)
3042     settings.setMediaSourceEnabled([preferences mediaSourceEnabled]);
3043     settings.setSourceBufferChangeTypeEnabled([preferences sourceBufferChangeTypeEnabled]);
3044 #endif
3045
3046 #if ENABLE(SERVICE_CONTROLS)
3047     settings.setImageControlsEnabled([preferences imageControlsEnabled]);
3048     settings.setServiceControlsEnabled([preferences serviceControlsEnabled]);
3049 #endif
3050
3051 #if ENABLE(VIDEO_TRACK)
3052     settings.setShouldDisplaySubtitles([preferences shouldDisplaySubtitles]);
3053     settings.setShouldDisplayCaptions([preferences shouldDisplayCaptions]);
3054     settings.setShouldDisplayTextDescriptions([preferences shouldDisplayTextDescriptions]);
3055 #endif
3056
3057 #if USE(AVFOUNDATION)
3058     DeprecatedGlobalSettings::setAVFoundationEnabled([preferences isAVFoundationEnabled]);
3059     DeprecatedGlobalSettings::setAVFoundationNSURLSessionEnabled([preferences isAVFoundationNSURLSessionEnabled]);
3060 #endif
3061
3062 #if ENABLE(MEDIA_STREAM)
3063     DeprecatedGlobalSettings::setMockCaptureDevicesEnabled(false);
3064     DeprecatedGlobalSettings::setMediaCaptureRequiresSecureConnection(true);
3065     RuntimeEnabledFeatures::sharedFeatures().setMediaStreamEnabled(false);
3066     RuntimeEnabledFeatures::sharedFeatures().setMediaDevicesEnabled(false);
3067     RuntimeEnabledFeatures::sharedFeatures().setMediaRecorderEnabled(preferences.mediaRecorderEnabled);
3068 #endif
3069
3070 #if ENABLE(WEB_RTC)
3071     RuntimeEnabledFeatures::sharedFeatures().setPeerConnectionEnabled([preferences peerConnectionEnabled]);
3072 #endif
3073
3074 #if ENABLE(WEB_AUDIO)
3075     settings.setWebAudioEnabled([preferences webAudioEnabled]);
3076 #endif
3077
3078 #if ENABLE(FULLSCREEN_API)
3079     settings.setFullScreenEnabled([preferences fullScreenEnabled]);
3080 #endif
3081
3082     settings.setHiddenPageDOMTimerThrottlingEnabled([preferences hiddenPageDOMTimerThrottlingEnabled]);
3083
3084     settings.setHiddenPageCSSAnimationSuspensionEnabled([preferences hiddenPageCSSAnimationSuspensionEnabled]);
3085
3086     DeprecatedGlobalSettings::setResourceLoadStatisticsEnabled([preferences resourceLoadStatisticsEnabled]);
3087
3088     settings.setViewportFitEnabled([preferences viewportFitEnabled]);
3089     settings.setConstantPropertiesEnabled([preferences constantPropertiesEnabled]);
3090
3091 #if ENABLE(GAMEPAD)
3092     RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled([preferences gamepadsEnabled]);
3093 #endif
3094
3095     RuntimeEnabledFeatures::sharedFeatures().setShadowDOMEnabled([preferences shadowDOMEnabled]);
3096     RuntimeEnabledFeatures::sharedFeatures().setCustomElementsEnabled([preferences customElementsEnabled]);
3097     RuntimeEnabledFeatures::sharedFeatures().setDataTransferItemsEnabled([preferences dataTransferItemsEnabled]);
3098     RuntimeEnabledFeatures::sharedFeatures().setCustomPasteboardDataEnabled([preferences customPasteboardDataEnabled]);
3099
3100 #if ENABLE(ATTACHMENT_ELEMENT)
3101     RuntimeEnabledFeatures::sharedFeatures().setAttachmentElementEnabled([preferences attachmentElementEnabled]);
3102 #endif
3103
3104     RuntimeEnabledFeatures::sharedFeatures().setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
3105     RuntimeEnabledFeatures::sharedFeatures().setModernMediaControlsEnabled([preferences modernMediaControlsEnabled]);
3106     RuntimeEnabledFeatures::sharedFeatures().setWebAnimationsCSSIntegrationEnabled([preferences webAnimationsCSSIntegrationEnabled]);
3107
3108     RuntimeEnabledFeatures::sharedFeatures().setCacheAPIEnabled([preferences cacheAPIEnabled]);
3109     RuntimeEnabledFeatures::sharedFeatures().setFetchAPIEnabled([preferences fetchAPIEnabled]);
3110
3111 #if ENABLE(STREAMS_API)
3112     RuntimeEnabledFeatures::sharedFeatures().setWritableStreamAPIEnabled([preferences writableStreamAPIEnabled]);
3113     RuntimeEnabledFeatures::sharedFeatures().setReadableByteStreamAPIEnabled([preferences readableByteStreamAPIEnabled]);
3114 #endif
3115
3116 #if ENABLE(WEBGL2)
3117     RuntimeEnabledFeatures::sharedFeatures().setWebGL2Enabled([preferences webGL2Enabled]);
3118 #endif
3119     
3120 #if ENABLE(WEBGPU)
3121     RuntimeEnabledFeatures::sharedFeatures().setWebGPUEnabled([preferences webGPUEnabled]);
3122 #endif
3123
3124 #if ENABLE(WEBMETAL)
3125     RuntimeEnabledFeatures::sharedFeatures().setWebMetalEnabled([preferences webMetalEnabled]);
3126 #endif
3127
3128 #if ENABLE(DOWNLOAD_ATTRIBUTE)
3129     RuntimeEnabledFeatures::sharedFeatures().setDownloadAttributeEnabled([preferences downloadAttributeEnabled]);
3130 #endif
3131
3132     RuntimeEnabledFeatures::sharedFeatures().setWebAnimationsEnabled([preferences webAnimationsEnabled]);
3133
3134 #if ENABLE(INTERSECTION_OBSERVER)
3135     RuntimeEnabledFeatures::sharedFeatures().setIntersectionObserverEnabled(preferences.intersectionObserverEnabled);
3136 #endif
3137     RuntimeEnabledFeatures::sharedFeatures().setDisplayContentsEnabled(preferences.displayContentsEnabled);
3138
3139     RuntimeEnabledFeatures::sharedFeatures().setUserTimingEnabled(preferences.userTimingEnabled);
3140     RuntimeEnabledFeatures::sharedFeatures().setResourceTimingEnabled(preferences.resourceTimingEnabled);
3141     RuntimeEnabledFeatures::sharedFeatures().setLinkPreloadEnabled(preferences.linkPreloadEnabled);
3142     RuntimeEnabledFeatures::sharedFeatures().setMediaPreloadingEnabled(preferences.mediaPreloadingEnabled);
3143     RuntimeEnabledFeatures::sharedFeatures().setIsSecureContextAttributeEnabled(preferences.isSecureContextAttributeEnabled);
3144     RuntimeEnabledFeatures::sharedFeatures().setDirectoryUploadEnabled([preferences directoryUploadEnabled]);
3145     RuntimeEnabledFeatures::sharedFeatures().setMenuItemElementEnabled([preferences menuItemElementEnabled]);
3146     RuntimeEnabledFeatures::sharedFeatures().setAccessibilityObjectModelEnabled([preferences accessibilityObjectModelEnabled]);
3147     RuntimeEnabledFeatures::sharedFeatures().setAriaReflectionEnabled([preferences ariaReflectionEnabled]);
3148     RuntimeEnabledFeatures::sharedFeatures().setFetchAPIKeepAliveEnabled([preferences fetchAPIKeepAliveEnabled]);
3149
3150 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
3151     RuntimeEnabledFeatures::sharedFeatures().setLegacyEncryptedMediaAPIEnabled(preferences.legacyEncryptedMediaAPIEnabled);
3152 #endif
3153
3154 #if ENABLE(ENCRYPTED_MEDIA)
3155     RuntimeEnabledFeatures::sharedFeatures().setEncryptedMediaAPIEnabled(preferences.encryptedMediaAPIEnabled);
3156 #endif
3157
3158     RuntimeEnabledFeatures::sharedFeatures().setInspectorAdditionsEnabled(preferences.inspectorAdditionsEnabled);
3159
3160     settings.setAllowMediaContentTypesRequiringHardwareSupportAsFallback(preferences.allowMediaContentTypesRequiringHardwareSupportAsFallback);
3161
3162     NSTimeInterval timeout = [preferences incrementalRenderingSuppressionTimeoutInSeconds];
3163     if (timeout > 0)
3164         settings.setIncrementalRenderingSuppressionTimeoutInSeconds(timeout);
3165
3166     // Application Cache Preferences are stored on the global cache storage manager, not in Settings.
3167     [WebApplicationCache setDefaultOriginQuota:[preferences applicationCacheDefaultOriginQuota]];
3168
3169     BOOL zoomsTextOnly = [preferences zoomsTextOnly];
3170     if (_private->zoomsTextOnly != zoomsTextOnly)
3171         [self _setZoomMultiplier:_private->zoomMultiplier isTextOnly:zoomsTextOnly];
3172
3173 #if PLATFORM(IOS_FAMILY)
3174     [[self window] setTileBordersVisible:[preferences showDebugBorders]];
3175     [[self window] setTilePaintCountsVisible:[preferences showRepaintCounter]];
3176     [[self window] setAcceleratedDrawingEnabled:[preferences acceleratedDrawingEnabled]];
3177     [WAKView _setInterpolationQuality:[preferences _interpolationQuality]];
3178 #endif
3179
3180 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
3181     settings.setMediaKeysStorageDirectory([preferences mediaKeysStorageDirectory]);
3182 #endif
3183
3184     settings.setMediaDataLoadsAutomatically([preferences mediaDataLoadsAutomatically]);
3185
3186     settings.setAllowContentSecurityPolicySourceStarToMatchAnyProtocol(shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol());
3187
3188     settings.setShouldConvertInvalidURLsToBlank(shouldConvertInvalidURLsToBlank());
3189
3190     settings.setLargeImageAsyncDecodingEnabled([preferences largeImageAsyncDecodingEnabled]);
3191     settings.setAnimatedImageAsyncDecodingEnabled([preferences animatedImageAsyncDecodingEnabled]);
3192     settings.setMediaCapabilitiesEnabled([preferences mediaCapabilitiesEnabled]);
3193
3194     RuntimeEnabledFeatures::sharedFeatures().setServerTimingEnabled([preferences serverTimingEnabled]);
3195
3196     settings.setSelectionAcrossShadowBoundariesEnabled(preferences.selectionAcrossShadowBoundariesEnabled);
3197 }
3198
3199 static inline IMP getMethod(id o, SEL s)
3200 {
3201     return [o respondsToSelector:s] ? [o methodForSelector:s] : 0;
3202 }
3203
3204 #if PLATFORM(IOS_FAMILY)
3205 - (id)_UIKitDelegateForwarder
3206 {
3207     if (_private->closing)
3208         return nil;
3209         
3210     if (!_private->UIKitDelegateForwarder)
3211         _private->UIKitDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIKitDelegate defaultTarget:[WebDefaultUIKitDelegate sharedUIKitDelegate]];
3212     return _private->UIKitDelegateForwarder;
3213 }
3214 #endif
3215
3216 - (void)_cacheResourceLoadDelegateImplementations
3217 {
3218     WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
3219     id delegate = _private->resourceProgressDelegate;
3220
3221     if (!delegate) {
3222         bzero(cache, sizeof(WebResourceDelegateImplementationCache));
3223         return;
3224     }
3225
3226     cache->didFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFailLoadingWithError:fromDataSource:));
3227     cache->didFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFinishLoadingFromDataSource:));
3228     cache->didLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
3229     cache->didReceiveAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
3230 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
3231     cache->canAuthenticateAgainstProtectionSpaceFunc = getMethod(delegate, @selector(webView:resource:canAuthenticateAgainstProtectionSpace:forDataSource:));
3232 #endif
3233
3234 #if PLATFORM(IOS_FAMILY)
3235     cache->connectionPropertiesFunc = getMethod(delegate, @selector(webView:connectionPropertiesForResource:dataSource:));
3236     cache->webThreadDidFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFinishLoadingFromDataSource:));
3237     cache->webThreadDidFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFailLoadingWithError:fromDataSource:));
3238     cache->webThreadIdentifierForRequestFunc = getMethod(delegate, @selector(webThreadWebView:identifierForInitialRequest:fromDataSource:));
3239     cache->webThreadDidLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webThreadWebView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
3240     cache->webThreadWillSendRequestFunc = getMethod(delegate, @selector(webThreadWebView:resource:willSendRequest:redirectResponse:fromDataSource:));
3241     cache->webThreadDidReceiveResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveResponse:fromDataSource:));
3242     cache->webThreadDidReceiveContentLengthFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveContentLength:fromDataSource:));
3243     cache->webThreadWillCacheResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:willCacheResponse:fromDataSource:));
3244 #endif
3245
3246     cache->didReceiveContentLengthFunc = getMethod(delegate, @selector(webView:resource:didReceiveContentLength:fromDataSource:));
3247     cache->didReceiveResponseFunc = getMethod(delegate, @selector(webView:resource:didReceiveResponse:fromDataSource:));
3248     cache->identifierForRequestFunc = getMethod(delegate, @selector(webView:identifierForInitialRequest:fromDataSource:));
3249     cache->plugInFailedWithErrorFunc = getMethod(delegate, @selector(webView:plugInFailedWithError:dataSource:));
3250     cache->willCacheResponseFunc = getMethod(delegate, @selector(webView:resource:willCacheResponse:fromDataSource:));
3251     cache->willSendRequestFunc = getMethod(delegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:));
3252     cache->shouldUseCredentialStorageFunc = getMethod(delegate, @selector(webView:resource:shouldUseCredentialStorageForDataSource:));
3253     cache->shouldPaintBrokenImageForURLFunc = getMethod(delegate, @selector(webView:shouldPaintBrokenImageForURL:));
3254 }
3255
3256 - (void)_cacheFrameLoadDelegateImplementations
3257 {
3258     WebFrameLoadDelegateImplementationCache *cache = &_private->frameLoadDelegateImplementations;
3259     id delegate = _private->frameLoadDelegate;
3260
3261     if (!delegate) {
3262         bzero(cache, sizeof(WebFrameLoadDelegateImplementationCache));
3263         return;
3264     }
3265
3266     cache->didCancelClientRedirectForFrameFunc = getMethod(delegate, @selector(webView:didCancelClientRedirectForFrame:));
3267     cache->didChangeLocationWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didChangeLocationWithinPageForFrame:));
3268     cache->didPushStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPushStateWithinPageForFrame:));
3269     cache->didReplaceStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didReplaceStateWithinPageForFrame:));
3270     cache->didPopStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPopStateWithinPageForFrame:));
3271 #if JSC_OBJC_API_ENABLED
3272     cache->didCreateJavaScriptContextForFrameFunc = getMethod(delegate, @selector(webView:didCreateJavaScriptContext:forFrame:));
3273 #endif
3274     cache->didClearWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearWindowObject:forFrame:));
3275     cache->didClearWindowObjectForFrameInScriptWorldFunc = getMethod(delegate, @selector(webView:didClearWindowObjectForFrame:inScriptWorld:));
3276     cache->didClearInspectorWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearInspectorWindowObject:forFrame:));
3277     cache->didCommitLoadForFrameFunc = getMethod(delegate, @selector(webView:didCommitLoadForFrame:));
3278     cache->didFailLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailLoadWithError:forFrame:));
3279     cache->didFailProvisionalLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailProvisionalLoadWithError:forFrame:));
3280     cache->didFinishDocumentLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishDocumentLoadForFrame:));
3281     cache->didFinishLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishLoadForFrame:));
3282     cache->didFirstLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstLayoutInFrame:));
3283     cache->didFirstVisuallyNonEmptyLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstVisuallyNonEmptyLayoutInFrame:));
3284     cache->didLayoutFunc = getMethod(delegate, @selector(webView:didLayout:));
3285     cache->didHandleOnloadEventsForFrameFunc = getMethod(delegate, @selector(webView:didHandleOnloadEventsForFrame:));
3286 #if ENABLE(ICONDATABASE)
3287     cache->didReceiveIconForFrameFunc = getMethod(delegate, @selector(webView:didReceiveIcon:forFrame:));
3288 #endif
3289     cache->didReceiveServerRedirectForProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didReceiveServerRedirectForProvisionalLoadForFrame:));
3290     cache->didReceiveTitleForFrameFunc = getMethod(delegate, @selector(webView:didReceiveTitle:forFrame:));
3291     cache->didStartProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didStartProvisionalLoadForFrame:));
3292     cache->willCloseFrameFunc = getMethod(delegate, @selector(webView:willCloseFrame:));
3293     cache->willPerformClientRedirectToURLDelayFireDateForFrameFunc = getMethod(delegate, @selector(webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:));
3294     cache->windowScriptObjectAvailableFunc = getMethod(delegate, @selector(webView:windowScriptObjectAvailable:));
3295     cache->didDisplayInsecureContentFunc = getMethod(delegate, @selector(webViewDidDisplayInsecureContent:));
3296     cache->didRunInsecureContentFunc = getMethod(delegate, @selector(webView:didRunInsecureContent:));
3297     cache->didDetectXSSFunc = getMethod(delegate, @selector(webView:didDetectXSS:));
3298     cache->didRemoveFrameFromHierarchyFunc = getMethod(delegate, @selector(webView:didRemoveFrameFromHierarchy:));
3299 #if PLATFORM(IOS_FAMILY)
3300     cache->webThreadDidLayoutFunc = getMethod(delegate, @selector(webThreadWebView:didLayout:));
3301 #endif
3302
3303     // It would be nice to get rid of this code and transition all clients to using didLayout instead of
3304     // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
3305     // for backwards compatibility.
3306     Page* page = core(self);
3307     if (page) {
3308         OptionSet<WebCore::LayoutMilestone> milestones { DidFirstLayout };
3309 #if PLATFORM(IOS_FAMILY)
3310         milestones.add(DidFirstVisuallyNonEmptyLayout);
3311 #else
3312         if (cache->didFirstVisuallyNonEmptyLayoutInFrameFunc)
3313             milestones.add(DidFirstVisuallyNonEmptyLayout);
3314 #endif
3315         page->addLayoutMilestones(milestones);
3316     }
3317 }
3318
3319 - (void)_cacheScriptDebugDelegateImplementations
3320 {
3321     WebScriptDebugDelegateImplementationCache *cache = &_private->scriptDebugDelegateImplementations;
3322     id delegate = _private->scriptDebugDelegate;
3323
3324     if (!delegate) {
3325         bzero(cache, sizeof(WebScriptDebugDelegateImplementationCache));
3326         return;
3327     }
3328
3329     cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:baseLineNumber:fromURL:sourceId:forWebFrame:));
3330     if (cache->didParseSourceFunc)
3331         cache->didParseSourceExpectsBaseLineNumber = YES;
3332     else {
3333         cache->didParseSourceExpectsBaseLineNumber = NO;
3334         cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:fromURL:sourceId:forWebFrame:));
3335     }
3336
3337     cache->failedToParseSourceFunc = getMethod(delegate, @selector(webView:failedToParseSource:baseLineNumber:fromURL:withError:forWebFrame:));
3338
3339     cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:hasHandler:sourceId:line:forWebFrame:));
3340     if (cache->exceptionWasRaisedFunc)
3341         cache->exceptionWasRaisedExpectsHasHandlerFlag = YES;
3342     else {
3343         cache->exceptionWasRaisedExpectsHasHandlerFlag = NO;
3344         cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:sourceId:line:forWebFrame:));
3345     }
3346 }
3347
3348 - (void)_cacheHistoryDelegateImplementations
3349 {
3350     WebHistoryDelegateImplementationCache *cache = &_private->historyDelegateImplementations;
3351     id delegate = _private->historyDelegate;
3352
3353     if (!delegate) {
3354         bzero(cache, sizeof(WebHistoryDelegateImplementationCache));
3355         return;
3356     }
3357
3358     cache->navigatedFunc = getMethod(delegate, @selector(webView:didNavigateWithNavigationData:inFrame:));
3359     cache->clientRedirectFunc = getMethod(delegate, @selector(webView:didPerformClientRedirectFromURL:toURL:inFrame:));
3360     cache->serverRedirectFunc = getMethod(delegate, @selector(webView:didPerformServerRedirectFromURL:toURL:inFrame:));
3361 IGNORE_WARNINGS_BEGIN("undeclared-selector")
3362     cache->deprecatedSetTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:));
3363 IGNORE_WARNINGS_END
3364     cache->setTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:inFrame:));
3365     cache->populateVisitedLinksFunc = getMethod(delegate, @selector(populateVisitedLinksForWebView:));
3366 }
3367
3368 - (id)_policyDelegateForwarder
3369 {
3370 #if PLATFORM(IOS_FAMILY)
3371     if (_private->closing)
3372         return nil;
3373 #endif
3374     if (!_private->policyDelegateForwarder)
3375         _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->policyDelegate defaultTarget:[WebDefaultPolicyDelegate sharedPolicyDelegate]];
3376     return _private->policyDelegateForwarder;
3377 }
3378
3379 - (id)_UIDelegateForwarder
3380 {
3381 #if PLATFORM(IOS_FAMILY)
3382     if (_private->closing)
3383         return nil;
3384 #endif
3385     if (!_private->UIDelegateForwarder)
3386         _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIDelegate defaultTarget:[WebDefaultUIDelegate sharedUIDelegate]];
3387     return _private->UIDelegateForwarder;
3388 }
3389
3390 #if PLATFORM(IOS_FAMILY)
3391 - (id)_UIDelegateForSelector:(SEL)selector
3392 {
3393     id delegate = self->_private->UIDelegate;
3394     if ([delegate respondsToSelector:selector])
3395         return delegate;
3396
3397     delegate = [WebDefaultUIDelegate sharedUIDelegate];
3398     if ([delegate respondsToSelector:selector])
3399         return delegate;
3400
3401     return nil;
3402 }
3403 #endif
3404
3405 - (id)_editingDelegateForwarder
3406 {
3407 #if PLATFORM(IOS_FAMILY)
3408     if (_private->closing)
3409         return nil;
3410 #endif    
3411     // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
3412     // Not sure if that is a bug or not.
3413     if (!_private)
3414         return nil;
3415
3416     if (!_private->editingDelegateForwarder)
3417         _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->editingDelegate defaultTarget:[WebDefaultEditingDelegate sharedEditingDelegate]];
3418     return _private->editingDelegateForwarder;
3419 }
3420
3421 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType
3422 {
3423     [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
3424     [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
3425     
3426     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
3427     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
3428     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
3429     MIMETypeRegistry::supportedNonImageMIMETypes().remove(MIMEType);
3430 }
3431
3432 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme
3433 {
3434     NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
3435     [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
3436
3437     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
3438     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
3439     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
3440     if ([viewClass class] == [WebHTMLView class])
3441         MIMETypeRegistry::supportedNonImageMIMETypes().add(MIMEType);
3442     
3443     // This is used to make _representationExistsForURLScheme faster.
3444     // Without this set, we'd have to create the MIME type each time.
3445     if (schemesWithRepresentationsSet == nil) {
3446         schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
3447     }
3448     [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
3449 }
3450
3451 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
3452 {
3453     return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
3454 }
3455
3456 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
3457 {
3458     return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
3459 }
3460
3461 + (BOOL)_canHandleRequest:(NSURLRequest *)request forMainFrame:(BOOL)forMainFrame
3462 {
3463     // FIXME: If <rdar://problem/5217309> gets fixed, this check can be removed.
3464     if (!request)
3465         return NO;
3466
3467     if ([NSURLConnection canHandleRequest:request])
3468         return YES;
3469
3470     NSString *scheme = [[request URL] scheme];
3471
3472     // Representations for URL schemes work at the top level.
3473     if (forMainFrame && [self _representationExistsForURLScheme:scheme])
3474         return YES;
3475
3476     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"applewebdata"])
3477         return YES;
3478
3479     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"blob"])
3480         return YES;
3481
3482     return NO;
3483 }
3484
3485 + (BOOL)_canHandleRequest:(NSURLRequest *)request
3486 {
3487     return [self _canHandleRequest:request forMainFrame:YES];
3488 }
3489
3490 + (NSString *)_decodeData:(NSData *)data
3491 {
3492     HTMLNames::init(); // this method is used for importing bookmarks at startup, so HTMLNames are likely to be uninitialized yet
3493     return TextResourceDecoder::create("text/html")->decodeAndFlush(static_cast<const char*>([data bytes]), [data length]); // bookmark files are HTML
3494 }
3495
3496 - (void)_pushPerformingProgrammaticFocus
3497 {
3498     _private->programmaticFocusCount++;
3499 }
3500
3501 - (void)_popPerformingProgrammaticFocus
3502 {
3503     _private->programmaticFocusCount--;
3504 }
3505
3506 - (BOOL)_isPerformingProgrammaticFocus
3507 {
3508     return _private->programmaticFocusCount != 0;
3509 }
3510
3511 #if !PLATFORM(IOS_FAMILY)
3512 - (void)_didChangeValueForKey: (NSString *)key
3513 {
3514     LOG (Bindings, "calling didChangeValueForKey: %@", key);
3515     [self didChangeValueForKey: key];
3516 }
3517
3518 - (void)_willChangeValueForKey: (NSString *)key
3519 {
3520     LOG (Bindings, "calling willChangeValueForKey: %@", key);
3521     [self willChangeValueForKey: key];
3522 }
3523
3524 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
3525     static NSSet *manualNotifyKeys = nil;
3526     if (!manualNotifyKeys)
3527         manualNotifyKeys = [[NSSet alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
3528             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey,
3529             nil];
3530     if ([manualNotifyKeys containsObject:key])
3531         return NO;
3532     return YES;
3533 }
3534
3535 - (NSArray *)_declaredKeys {
3536     static NSArray *declaredKeys = nil;
3537     if (!declaredKeys)
3538         declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
3539             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
3540     return declaredKeys;
3541 }
3542
3543 - (void)_willChangeBackForwardKeys
3544 {
3545     [self _willChangeValueForKey: _WebCanGoBackKey];
3546     [self _willChangeValueForKey: _WebCanGoForwardKey];
3547 }
3548
3549 - (void)_didChangeBackForwardKeys
3550 {
3551     [self _didChangeValueForKey: _WebCanGoBackKey];
3552     [self _didChangeValueForKey: _WebCanGoForwardKey];
3553 }
3554
3555 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
3556 {
3557     if (needsSelfRetainWhileLoadingQuirk())
3558         [self retain];
3559
3560     [self _willChangeBackForwardKeys];
3561     if (frame == [self mainFrame]){
3562         // Force an observer update by sending a will/did.
3563         [self _willChangeValueForKey: _WebIsLoadingKey];
3564         [self _didChangeValueForKey: _WebIsLoadingKey];
3565
3566         [self _willChangeValueForKey: _WebMainFrameURLKey];
3567
3568         [self hideFormValidationMessage];
3569     }
3570
3571     [NSApp setWindowsNeedUpdate:YES];
3572
3573 #if ENABLE(FULLSCREEN_API)
3574     Document* document = core([frame DOMDocument]);
3575     if (Element* element = document ? document->webkitCurrentFullScreenElement() : 0) {
3576         SEL selector = @selector(webView:closeFullScreenWithListener:);
3577         if ([_private->UIDelegate respondsToSelector:selector]) {
3578             WebKitFullScreenListener *listener = [[WebKitFullScreenListener alloc] initWithElement:element];
3579             CallUIDelegate(self, selector, listener);
3580             [listener release];
3581         } else if (_private->newFullscreenController && [_private->newFullscreenController isFullScreen]) {
3582             [_private->newFullscreenController close];
3583         }
3584     }
3585 #endif
3586 }
3587
3588 - (void)_checkDidPerformFirstNavigation
3589 {
3590     if (_private->_didPerformFirstNavigation)
3591         return;
3592
3593     Page* page = _private->page;
3594     if (!page)
3595         return;
3596
3597     auto& backForwardController = page->backForward();
3598
3599     if (!backForwardController.backItem())
3600         return;
3601
3602     _private->_didPerformFirstNavigation = YES;
3603
3604     if (_private->preferences.automaticallyDetectsCacheModel && _private->preferences.cacheModel < WebCacheModelDocumentBrowser)
3605         _private->preferences.cacheModel = WebCacheModelDocumentBrowser;
3606 }
3607
3608 - (void)_didCommitLoadForFrame:(WebFrame *)frame
3609 {
3610     if (frame == [self mainFrame])
3611         [self _didChangeValueForKey: _WebMainFrameURLKey];
3612
3613     [self _checkDidPerformFirstNavigation];
3614
3615     [NSApp setWindowsNeedUpdate:YES];
3616 }
3617
3618 - (void)_didFinishLoadForFrame:(WebFrame *)frame
3619 {
3620     if (needsSelfRetainWhileLoadingQuirk())
3621         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3622         
3623     [self _didChangeBackForwardKeys];
3624     if (frame == [self mainFrame]){
3625         // Force an observer update by sending a will/did.
3626         [self _willChangeValueForKey: _WebIsLoadingKey];
3627         [self _didChangeValueForKey: _WebIsLoadingKey];
3628     }
3629     [NSApp setWindowsNeedUpdate:YES];
3630 }
3631
3632 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
3633 {
3634     if (needsSelfRetainWhileLoadingQuirk())
3635         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3636
3637     [self _didChangeBackForwardKeys];
3638     if (frame == [self mainFrame]){
3639         // Force an observer update by sending a will/did.
3640         [self _willChangeValueForKey: _WebIsLoadingKey];
3641         [self _didChangeValueForKey: _WebIsLoadingKey];
3642     }
3643     [NSApp setWindowsNeedUpdate:YES];
3644 }
3645
3646 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
3647 {
3648     if (needsSelfRetainWhileLoadingQuirk())
3649         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3650
3651     [self _didChangeBackForwardKeys];
3652     if (frame == [self mainFrame]){
3653         // Force an observer update by sending a will/did.
3654         [self _willChangeValueForKey: _WebIsLoadingKey];
3655         [self _didChangeValueForKey: _WebIsLoadingKey];
3656         
3657         [self _didChangeValueForKey: _WebMainFrameURLKey];
3658     }
3659     [NSApp setWindowsNeedUpdate:YES];
3660 }
3661
3662 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
3663 {
3664     RetainPtr<NSMutableURLRequest> request = adoptNS([[NSMutableURLRequest alloc] initWithURL:URL]);
3665     [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
3666     NSCachedURLResponse *cachedResponse;
3667
3668     if (!_private->page)
3669         return nil;
3670
3671     if (auto storageSession = _private->page->mainFrame().loader().networkingContext()->storageSession()->platformSession())
3672         cachedResponse = cachedResponseForRequest(storageSession, request.get());
3673     else
3674         cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request.get()];
3675
3676     return cachedResponse;
3677 }
3678
3679 - (void)_writeImageForElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
3680 {
3681     NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
3682     DOMElement *domElement = [element objectForKey:WebElementDOMNodeKey];
3683     [pasteboard _web_writeImage:(NSImage *)(domElement ? nil : [element objectForKey:WebElementImageKey])
3684                         element:domElement
3685                             URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
3686                           title:[element objectForKey:WebElementImageAltStringKey] 
3687                         archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
3688                           types:types
3689                          source:nil];
3690 }
3691
3692 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
3693 {
3694     [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
3695                      andTitle:[element objectForKey:WebElementLinkLabelKey]
3696                         types:types];
3697 }
3698
3699 #if ENABLE(DRAG_SUPPORT)
3700 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
3701 {
3702     if (!_private->page)
3703         return;
3704     _private->page->dragController().setDidInitiateDrag(initiatedDrag);
3705 }
3706 #endif
3707
3708 #else
3709
3710 - (void)_didCommitLoadForFrame:(WebFrame *)frame
3711 {
3712     if (frame == [self mainFrame])
3713         _private->didDrawTiles = 0;
3714 }
3715
3716 #endif // PLATFORM(IOS_FAMILY)
3717
3718 #if ENABLE(DASHBOARD_SUPPORT)
3719
3720 #define DASHBOARD_CONTROL_LABEL @"control"
3721
3722 - (void)_addControlRect:(NSRect)bounds clip:(NSRect)clip fromView:(NSView *)view toDashboardRegions:(NSMutableDictionary *)regions
3723 {
3724     NSRect adjustedBounds = bounds;
3725     adjustedBounds.origin = [self convertPoint:bounds.origin fromView:view];
3726     adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
3727     adjustedBounds.size = bounds.size;
3728
3729     NSRect adjustedClip;
3730     adjustedClip.origin = [self convertPoint:clip.origin fromView:view];
3731     adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
3732     adjustedClip.size = clip.size;
3733
3734     WebDashboardRegion *region = [[WebDashboardRegion alloc] initWithRect:adjustedBounds 
3735         clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle];
3736     NSMutableArray *scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
3737     if (!scrollerRegions) {
3738         scrollerRegions = [[NSMutableArray alloc] init];
3739         [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
3740         [scrollerRegions release];
3741     }
3742     [scrollerRegions addObject:region];
3743     [region release];
3744 }
3745
3746 - (void)_addScrollerDashboardRegionsForFrameView:(FrameView*)frameView dashboardRegions:(NSMutableDictionary *)regions
3747 {    
3748     NSView *documentView = [[kit(&frameView->frame()) frameView] documentView];
3749
3750     for (const auto& widget: frameView->children()) {
3751         if (is<FrameView>(widget)) {
3752             [self _addScrollerDashboardRegionsForFrameView:&downcast<FrameView>(widget.get()) dashboardRegions:regions];
3753             continue;
3754         }
3755
3756         if (!widget->isScrollbar())
3757             continue;
3758
3759         // FIXME: This should really pass an appropriate clip, but our first try got it wrong, and
3760         // it's not common to need this to be correct in Dashboard widgets.
3761         NSRect bounds = widget->frameRect();
3762         [self _addControlRect:bounds clip:bounds fromView:documentView toDashboardRegions:regions];
3763     }
3764 }
3765
3766 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
3767 {
3768     // Add scroller regions for NSScroller and WebCore scrollbars
3769     NSUInteger count = [views count];
3770     for (NSUInteger i = 0; i < count; i++) {
3771         NSView *view = [views objectAtIndex:i];
3772         
3773         if ([view isKindOfClass:[WebHTMLView class]]) {
3774             if (Frame* coreFrame = core([(WebHTMLView*)view _frame])) {
3775                 if (FrameView* coreView = coreFrame->view())
3776                     [self _addScrollerDashboardRegionsForFrameView:coreView dashboardRegions:regions];
3777             }
3778         } else if ([view isKindOfClass:[NSScroller class]]) {
3779             // AppKit places absent scrollers at -100,-100
3780             if ([view frame].origin.y < 0)
3781                 continue;
3782             [self _addControlRect:[view bounds] clip:[view visibleRect] fromView:view toDashboardRegions:regions];
3783         }
3784         [self _addScrollerDashboardRegions:regions from:[view subviews]];
3785     }
3786 }
3787
3788 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
3789 {
3790     [self _addScrollerDashboardRegions:regions from:[self subviews]];
3791 }
3792
3793 - (NSDictionary *)_dashboardRegions
3794 {
3795     // Only return regions from main frame.
3796     Frame* mainFrame = [self _mainCoreFrame];
3797     if (!mainFrame)
3798         return nil;
3799
3800     const Vector<AnnotatedRegionValue>& regions = mainFrame->document()->annotatedRegions();
3801     size_t size = regions.size();
3802
3803     NSMutableDictionary *webRegions = [NSMutableDictionary dictionaryWithCapacity:size];
3804     for (size_t i = 0; i < size; i++) {
3805         const AnnotatedRegionValue& region = regions[i];
3806
3807         if (region.type == StyleDashboardRegion::None)
3808             continue;
3809
3810         NSString *label = region.label;
3811         WebDashboardRegionType type = WebDashboardRegionTypeNone;
3812         if (region.type == StyleDashboardRegion::Circle)
3813             type = WebDashboardRegionTypeCircle;
3814         else if (region.type == StyleDashboardRegion::Rectangle)
3815             type = WebDashboardRegionTypeRectangle;
3816         NSMutableArray *regionValues = [webRegions objectForKey:label];
3817         if (!regionValues) {
3818             regionValues = [[NSMutableArray alloc] initWithCapacity:1];
3819             [webRegions setObject:regionValues forKey:label];
3820             [regionValues release];
3821         }
3822
3823         WebDashboardRegion *webRegion = [[WebDashboardRegion alloc] initWithRect:snappedIntRect(region.bounds) clip:snappedIntRect(region.clip) type:type];
3824         [regionValues addObject:webRegion];
3825         [webRegion release];
3826     }
3827
3828     [self _addScrollerDashboardRegions:webRegions];
3829
3830     return webRegions;
3831 }
3832
3833 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag
3834 {
3835     // FIXME: Remove this blanket assignment once Dashboard and Dashcode implement 
3836     // specific support for the backward compatibility mode flag.
3837     if (behavior == WebDashboardBehaviorAllowWheelScrolling && flag == NO && _private->page)
3838         _private->page->settings().setUsesDashboardBackwardCompatibilityMode(true);
3839     
3840     switch (behavior) {
3841         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3842             _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
3843             break;
3844         }
3845         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3846             _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
3847             break;
3848         }
3849         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3850             _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
3851             break;
3852         }
3853         case WebDashboardBehaviorAllowWheelScrolling: {
3854             _private->dashboardBehaviorAllowWheelScrolling = flag;
3855             break;
3856         }
3857         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3858             if (_private->page)
3859                 _private->page->settings().setUsesDashboardBackwardCompatibilityMode(flag);
3860 #if ENABLE(LEGACY_CSS_VENDOR_PREFIXES)
3861             RuntimeEnabledFeatures::sharedFeatures().setLegacyCSSVendorPrefixesEnabled(flag);
3862 #endif
3863             break;
3864         }
3865     }
3866
3867     // Pre-HTML5 parser quirks should be enabled if Dashboard is in backward
3868     // compatibility mode. See <rdar://problem/8175982>.
3869     if (_private->page)
3870         _private->page->settings().setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
3871 }
3872
3873 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
3874 {
3875     switch (behavior) {
3876         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3877             return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
3878         }
3879         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3880             return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
3881         }
3882         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3883             return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
3884         }
3885         case WebDashboardBehaviorAllowWheelScrolling: {
3886             return _private->dashboardBehaviorAllowWheelScrolling;
3887         }
3888         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3889             return _private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode();
3890         }
3891     }
3892     return NO;
3893 }
3894
3895 #endif /* ENABLE(DASHBOARD_SUPPORT) */
3896
3897 + (void)_setShouldUseFontSmoothing:(BOOL)f
3898 {
3899     FontCascade::setShouldUseSmoothing(f);
3900 }
3901
3902 + (BOOL)_shouldUseFontSmoothing
3903 {
3904     return FontCascade::shouldUseSmoothing();
3905 }
3906
3907 #if !PLATFORM(IOS_FAMILY)
3908 + (void)_setUsesTestModeFocusRingColor:(BOOL)f
3909 {
3910     setUsesTestModeFocusRingColor(f);
3911 }
3912
3913 + (BOOL)_usesTestModeFocusRingColor
3914 {
3915     return usesTestModeFocusRingColor();
3916 }
3917 #endif
3918
3919 #if PLATFORM(IOS_FAMILY)
3920 - (void)_setUIKitDelegate:(id)delegate
3921 {
3922     _private->UIKitDelegate = delegate;
3923     [_private->UIKitDelegateForwarder clearTarget];
3924     [_private->UIKitDelegateForwarder release];
3925     _private->UIKitDelegateForwarder = nil;
3926 }
3927
3928 - (id)_UIKitDelegate
3929 {
3930     return _private->UIKitDelegate;
3931 }
3932
3933 - (void)setWebMailDelegate:(id)delegate
3934 {
3935     _private->WebMailDelegate = delegate;
3936 }
3937
3938 - (id)_webMailDelegate
3939 {
3940     return _private->WebMailDelegate;
3941 }
3942
3943 - (id <WebCaretChangeListener>)caretChangeListener
3944 {
3945     return _private->_caretChangeListener;
3946 }
3947
3948 - (void)setCaretChangeListener:(id <WebCaretChangeListener>)listener
3949 {
3950     _private->_caretChangeListener = listener;
3951 }
3952
3953 - (NSSet *)caretChangeListeners
3954 {
3955     return _private->_caretChangeListeners;
3956 }
3957
3958 - (void)addCaretChangeListener:(id <WebCaretChangeListener>)listener
3959 {
3960     if (_private->_caretChangeListeners == nil) {
3961         _private->_caretChangeListeners = [[NSMutableSet alloc] init];
3962     }
3963     
3964     [_private->_caretChangeListeners addObject:listener];
3965 }
3966
3967 - (void)removeCaretChangeListener:(id <WebCaretChangeListener>)listener
3968 {
3969     [_private->_caretChangeListeners removeObject:listener];
3970 }
3971
3972 - (void)removeAllCaretChangeListeners
3973 {
3974     [_private->_caretChangeListeners removeAllObjects];
3975 }
3976
3977 - (void)caretChanged
3978 {
3979     [_private->_caretChangeListener caretChanged];
3980     NSSet *copy = [_private->_caretChangeListeners copy];
3981     for (id <WebCaretChangeListener> listener in copy) {
3982         [listener caretChanged];
3983     }
3984     [copy release];
3985 }
3986
3987 - (void)_clearDelegates
3988 {
3989     ASSERT(WebThreadIsLocked() || !WebThreadIsEnabled());
3990     
3991     [self _setFormDelegate:nil];
3992     [self _setUIKitDelegate:nil];
3993     [self setCaretChangeListener:nil];
3994     [self removeAllCaretChangeListeners];
3995     [self setWebMailDelegate:nil];
3996     
3997     [self setDownloadDelegate:nil];
3998     [self setEditingDelegate:nil]; 
3999     [self setFrameLoadDelegate:nil];
4000     [self setPolicyDelegate:nil];
4001     [self setResourceLoadDelegate:nil];
4002     [self setScriptDebugDelegate:nil];
4003     [self setUIDelegate:nil];     
4004 }
4005
4006 - (NSURL *)_displayURL
4007 {
4008     WebThreadLock();
4009     WebFrame *frame = [self mainFrame];
4010     // FIXME: <rdar://problem/6362369> We used to get provisionalDataSource here if in provisional state; how do we tell that now? Is this right?
4011     WebDataSource *dataSource = [frame provisionalDataSource];
4012     if (!dataSource)
4013         dataSource = [frame dataSource];
4014     NSURL *unreachableURL = [dataSource unreachableURL];
4015     NSURL *URL = unreachableURL != nil ? unreachableURL : [[dataSource request] URL];
4016     [[URL retain] autorelease];
4017     return URL;
4018 }
4019 #endif // PLATFORM(IOS_FAMILY)
4020
4021 #if !PLATFORM(IOS_FAMILY)
4022 - (void)setAlwaysShowVerticalScroller:(BOOL)flag
4023 {
4024     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
4025     if (flag) {
4026         [scrollview setVerticalScrollingMode:ScrollbarAlwaysOn andLock:YES];
4027     } else {
4028         [scrollview setVerticalScrollingModeLocked:NO];
4029         [scrollview setVerticalScrollingMode:ScrollbarAuto andLock:NO];
4030     }
4031 }
4032
4033 - (BOOL)alwaysShowVerticalScroller
4034 {
4035     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
4036     return [scrollview verticalScrollingModeLocked] && [scrollview verticalScrollingMode] == ScrollbarAlwaysOn;
4037 }
4038
4039 - (void)setAlwaysShowHorizontalScroller:(BOOL)flag
4040 {
4041     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
4042     if (flag) {
4043         [scrollview setHorizontalScrollingMode:ScrollbarAlwaysOn andLock:YES];
4044     } else {
4045         [scrollview setHorizontalScrollingModeLocked:NO];
4046         [scrollview setHorizontalScrollingMode:ScrollbarAuto andLock:NO];
4047     }
4048 }
4049
4050 - (void)setProhibitsMainFrameScrolling:(BOOL)prohibits
4051 {
4052     if (Frame* mainFrame = [self _mainCoreFrame])
4053         mainFrame->view()->setProhibitsScrolling(prohibits);
4054 }
4055
4056 - (BOOL)alwaysShowHorizontalScroller
4057 {
4058     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
4059     return [scrollview horizontalScrollingModeLocked] && [scrollview horizontalScrollingMode] == ScrollbarAlwaysOn;
4060 }
4061 #endif // !PLATFORM(IOS_FAMILY)
4062
4063 - (void)_setUseFastImageScalingMode:(BOOL)flag
4064 {
4065     if (_private->page && _private->page->inLowQualityImageInterpolationMode() != flag) {
4066         _private->page->setInLowQualityImageInterpolationMode(flag);
4067         [self setNeedsDisplay:YES];
4068     }
4069 }
4070
4071 - (BOOL)_inFastImageScalingMode
4072 {
4073     if (_private->page)
4074         return _private->page->inLowQualityImageInterpolationMode();
4075     return NO;
4076 }
4077
4078 - (BOOL)_cookieEnabled
4079 {
4080     if (_private->page)
4081         return _private->page->settings().cookieEnabled();
4082     return YES;
4083 }
4084
4085 - (void)_setCookieEnabled:(BOOL)enable
4086 {
4087     if (_private->page)
4088         _private->page->settings().setCookieEnabled(enable);
4089 }
4090
4091 #if !PLATFORM(IOS_FAMILY)
4092 - (void)_setAdditionalWebPlugInPaths:(NSArray *)newPaths
4093 {
4094     if (!_private->pluginDatabase)
4095         _private->pluginDatabase = [[WebPluginDatabase alloc] init];
4096         
4097     [_private->pluginDatabase setPlugInPaths:newPaths];
4098     [_private->pluginDatabase refresh];
4099 }
4100 #endif
4101
4102 #if PLATFORM(IOS_FAMILY)
4103 - (BOOL)_locked_plugInsAreRunningInFrame:(WebFrame *)frame
4104 {
4105     // Ask plug-ins in this frame
4106     id <WebDocumentView> documentView = [[frame frameView] documentView];
4107     if (documentView && [documentView isKindOfClass:[WebHTMLView class]]) {
4108         if ([[(WebHTMLView *)documentView _pluginController] plugInsAreRunning])
4109             return YES;
4110     }
4111
4112     // Ask plug-ins in child frames
4113     NSArray *childFrames = [frame childFrames];
4114     unsigned childCount = [childFrames count];
4115     unsigned childIndex;
4116     for (childIndex = 0; childIndex < childCount; childIndex++) {
4117         if ([self _locked_plugInsAreRunningInFrame:[childFrames objectAtIndex:childIndex]])
4118             return YES;
4119     }
4120     
4121     return NO;
4122 }
4123
4124 - (BOOL)_pluginsAreRunning
4125 {
4126     WebThreadLock();
4127     return [self _locked_plugInsAreRunningInFrame:[self mainFrame]];
4128 }
4129
4130 - (void)_locked_recursivelyPerformPlugInSelector:(SEL)selector inFrame:(WebFrame *)frame
4131 {
4132     // Send the message to plug-ins in this frame
4133     id <WebDocumentView> documentView = [[frame frameView] documentView];
4134     if (documentView && [documentView isKindOfClass:[WebHTMLView class]])
4135         [[(WebHTMLView *)documentView _pluginController] performSelector:selector];
4136
4137     // Send the message to plug-ins in child frames
4138     NSArray *childFrames = [frame childFrames];
4139     unsigned childCount = [childFrames count];
4140     unsigned childIndex;
4141     for (childIndex = 0; childIndex < childCount; childIndex++) {
4142         [self _locked_recursivelyPerformPlugInSelector:selector inFrame:[childFrames objectAtIndex:childIndex]];
4143     }
4144 }
4145
4146 - (void)_destroyAllPlugIns
4147 {
4148     WebThreadLock();
4149     [self _locked_recursivelyPerformPlugInSelector:@selector(destroyAllPlugins) inFrame:[self mainFrame]];
4150 }
4151
4152 - (void)_startAllPlugIns
4153 {
4154     WebThreadLock();