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