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