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