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