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