ed0e0df79b03da66e8a29bced9ceaa93cd665e8c
[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     WebThreadRun(^{
1787         WebCore::releaseMemory(Critical::Yes, Synchronous::Yes);
1788     });
1789 }
1790
1791 - (void)_replaceCurrentHistoryItem:(WebHistoryItem *)item
1792 {
1793     Frame* frame = [self _mainCoreFrame];
1794     if (frame)
1795         frame->loader().history().replaceCurrentItem(core(item));
1796 }
1797
1798 + (void)willEnterBackgroundWithCompletionHandler:(void(^)(void))handler
1799 {
1800     WebThreadRun(^{
1801         [WebView _releaseMemoryNow];
1802         dispatch_async(dispatch_get_main_queue(), handler);
1803     });
1804 }
1805
1806 + (BOOL)isCharacterSmartReplaceExempt:(unichar)character isPreviousCharacter:(BOOL)b
1807 {
1808     return WebCore::isCharacterSmartReplaceExempt(character, b);
1809 }
1810
1811 - (void)updateLayoutIgnorePendingStyleSheets
1812 {
1813     WebThreadRun(^{
1814         for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext()) {
1815             Document *document = frame->document();
1816             if (document)
1817                 document->updateLayoutIgnorePendingStylesheets();
1818         }
1819     });
1820 }
1821 #endif
1822
1823 #if PLATFORM(IOS_FAMILY)
1824
1825 #if ENABLE(DRAG_SUPPORT)
1826
1827 - (BOOL)_requestStartDataInteraction:(CGPoint)clientPosition globalPosition:(CGPoint)globalPosition
1828 {
1829     WebThreadLock();
1830     return _private->page->mainFrame().eventHandler().tryToBeginDataInteractionAtPoint(IntPoint(clientPosition), IntPoint(globalPosition));
1831 }
1832
1833 - (void)_startDrag:(const DragItem&)dragItem
1834 {
1835     auto& dragImage = dragItem.image;
1836     auto image = dragImage.get().get();
1837     auto indicatorData = dragImage.indicatorData();
1838
1839     if (indicatorData)
1840         _private->textIndicatorData = adoptNS([[WebUITextIndicatorData alloc] initWithImage:image textIndicatorData:indicatorData.value() scale:_private->page->deviceScaleFactor()]);
1841     else
1842         _private->textIndicatorData = adoptNS([[WebUITextIndicatorData alloc] initWithImage:image scale:_private->page->deviceScaleFactor()]);
1843     _private->draggedLinkURL = dragItem.url.isEmpty() ? nil : (NSURL *)dragItem.url;
1844     _private->draggedLinkTitle = dragItem.title.isEmpty() ? nil : (NSString *)dragItem.title;
1845     _private->dragPreviewFrameInRootViewCoordinates = dragItem.dragPreviewFrameInRootViewCoordinates;
1846     _private->dragSourceAction = static_cast<WebDragSourceAction>(dragItem.sourceAction);
1847 }
1848
1849 - (CGRect)_dataInteractionCaretRect
1850 {
1851     WebThreadLock();
1852     if (auto* page = _private->page)
1853         return page->dragCaretController().caretRectInRootViewCoordinates();
1854
1855     return { };
1856 }
1857
1858 - (WebUITextIndicatorData *)_dataOperationTextIndicator
1859 {
1860     return _private->dataOperationTextIndicator.get();
1861 }
1862
1863 - (WebDragSourceAction)_dragSourceAction
1864 {
1865     return _private->dragSourceAction;
1866 }
1867
1868 - (NSString *)_draggedLinkTitle
1869 {
1870     return _private->draggedLinkTitle.get();
1871 }
1872
1873 - (NSURL *)_draggedLinkURL
1874 {
1875     return _private->draggedLinkURL.get();
1876 }
1877
1878 - (CGRect)_draggedElementBounds
1879 {
1880     return _private->dragPreviewFrameInRootViewCoordinates;
1881 }
1882
1883 - (WebUITextIndicatorData *)_getDataInteractionData
1884 {
1885     return _private->textIndicatorData.get();
1886 }
1887
1888 - (WebDragDestinationAction)dragDestinationActionMaskForSession:(id <UIDropSession>)session
1889 {
1890     return [self._UIDelegateForwarder webView:self dragDestinationActionMaskForSession:session];
1891 }
1892
1893 - (DragData)dragDataForSession:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1894 {
1895     auto dragOperationMask = static_cast<DragOperation>(operation);
1896     auto dragDestinationMask = static_cast<DragDestinationAction>([self dragDestinationActionMaskForSession:session]);
1897     return { session, roundedIntPoint(clientPosition), roundedIntPoint(globalPosition), dragOperationMask, DragApplicationNone, dragDestinationMask };
1898 }
1899
1900 - (uint64_t)_enteredDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1901 {
1902     WebThreadLock();
1903     auto dragData = [self dragDataForSession:session client:clientPosition global:globalPosition operation:operation];
1904     return _private->page->dragController().dragEntered(dragData);
1905 }
1906
1907 - (uint64_t)_updatedDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1908 {
1909     WebThreadLock();
1910     auto dragData = [self dragDataForSession:session client:clientPosition global:globalPosition operation:operation];
1911     return _private->page->dragController().dragUpdated(dragData);
1912 }
1913 - (void)_exitedDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1914 {
1915     WebThreadLock();
1916     auto dragData = [self dragDataForSession:session client:clientPosition global:globalPosition operation:operation];
1917     _private->page->dragController().dragExited(dragData);
1918 }
1919 - (void)_performDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1920 {
1921     [self _tryToPerformDataInteraction:session client:clientPosition global:globalPosition operation:operation];
1922 }
1923
1924 - (BOOL)_tryToPerformDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1925 {
1926     WebThreadLock();
1927     auto dragData = [self dragDataForSession:session client:clientPosition global:globalPosition operation:operation];
1928     return _private->page->dragController().performDragOperation(dragData);
1929 }
1930
1931 - (void)_endedDataInteraction:(CGPoint)clientPosition global:(CGPoint)globalPosition
1932 {
1933     WebThreadLock();
1934     _private->page->dragController().dragEnded();
1935     _private->dataOperationTextIndicator = nullptr;
1936     _private->dragPreviewFrameInRootViewCoordinates = CGRectNull;
1937     _private->dragSourceAction = WebDragSourceActionNone;
1938     _private->draggedLinkTitle = nil;
1939     _private->draggedLinkURL = nil;
1940 }
1941
1942 - (void)_didConcludeEditDataInteraction
1943 {
1944     _private->dataOperationTextIndicator = nullptr;
1945     auto* page = _private->page;
1946     if (!page)
1947         return;
1948
1949     static auto defaultEditDragTextIndicatorOptions = TextIndicatorOptionIncludeSnapshotOfAllVisibleContentWithoutSelection | TextIndicatorOptionExpandClipBeyondVisibleRect | TextIndicatorOptionPaintAllContent | TextIndicatorOptionIncludeMarginIfRangeMatchesSelection | TextIndicatorOptionPaintBackgrounds | TextIndicatorOptionUseSelectionRectForSizing | TextIndicatorOptionIncludeSnapshotWithSelectionHighlight | TextIndicatorOptionRespectTextColor;
1950     auto& frame = page->focusController().focusedOrMainFrame();
1951     if (auto range = frame.selection().selection().toNormalizedRange()) {
1952         if (auto textIndicator = TextIndicator::createWithRange(*range, defaultEditDragTextIndicatorOptions, TextIndicatorPresentationTransition::None, FloatSize()))
1953             _private->dataOperationTextIndicator = adoptNS([[WebUITextIndicatorData alloc] initWithImage:nil textIndicatorData:textIndicator->data() scale:page->deviceScaleFactor()]);
1954     }
1955 }
1956
1957 #elif __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000
1958
1959 - (BOOL)_requestStartDataInteraction:(CGPoint)clientPosition globalPosition:(CGPoint)globalPosition
1960 {
1961     return NO;
1962 }
1963
1964 - (WebUITextIndicatorData *)_getDataInteractionData
1965 {
1966     return nil;
1967 }
1968
1969 - (WebUITextIndicatorData *)_dataOperationTextIndicator
1970 {
1971     return nil;
1972 }
1973
1974 - (NSUInteger)_dragSourceAction
1975 {
1976     return 0;
1977 }
1978
1979 - (NSString *)_draggedLinkTitle
1980 {
1981     return nil;
1982 }
1983
1984 - (NSURL *)_draggedLinkURL
1985 {
1986     return nil;
1987 }
1988
1989 - (CGRect)_draggedElementBounds
1990 {
1991     return CGRectNull;
1992 }
1993
1994 - (uint64_t)_enteredDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
1995 {
1996     return 0;
1997 }
1998
1999 - (uint64_t)_updatedDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
2000 {
2001     return 0;
2002 }
2003
2004 - (void)_exitedDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
2005 {
2006 }
2007
2008 - (void)_performDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
2009 {
2010 }
2011
2012 - (BOOL)_tryToPerformDataInteraction:(id <UIDropSession>)session client:(CGPoint)clientPosition global:(CGPoint)globalPosition operation:(uint64_t)operation
2013 {
2014     return NO;
2015 }
2016
2017 - (void)_endedDataInteraction:(CGPoint)clientPosition global:(CGPoint)globalPosition
2018 {
2019 }
2020
2021 - (CGRect)_dataInteractionCaretRect
2022 {
2023     return CGRectNull;
2024 }
2025
2026 #endif
2027 #endif // PLATFORM(IOS_FAMILY)
2028
2029 static NSMutableSet *knownPluginMIMETypes()
2030 {
2031     static NSMutableSet *mimeTypes = [[NSMutableSet alloc] init];
2032     
2033     return mimeTypes;
2034 }
2035
2036 + (void)_registerPluginMIMEType:(NSString *)MIMEType
2037 {
2038     [WebView registerViewClass:[WebHTMLView class] representationClass:[WebHTMLRepresentation class] forMIMEType:MIMEType];
2039     [knownPluginMIMETypes() addObject:MIMEType];
2040 }
2041
2042 + (void)_unregisterPluginMIMEType:(NSString *)MIMEType
2043 {
2044     [self _unregisterViewClassAndRepresentationClassForMIMEType:MIMEType];
2045     [knownPluginMIMETypes() removeObject:MIMEType];
2046 }
2047
2048 + (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType allowingPlugins:(BOOL)allowPlugins
2049 {
2050     MIMEType = [MIMEType lowercaseString];
2051     Class viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
2052     Class repClass = [[WebDataSource _repTypesAllowImageTypeOmission:YES] _webkit_objectForMIMEType:MIMEType];
2053
2054 #if PLATFORM(IOS_FAMILY)
2055 #define WebPDFView ([WebView _getPDFViewClass])
2056 #endif
2057     if (!viewClass || !repClass || [[WebPDFView supportedMIMETypes] containsObject:MIMEType]) {
2058 #if PLATFORM(IOS_FAMILY)
2059 #undef WebPDFView
2060 #endif
2061         // Our optimization to avoid loading the plug-in DB and image types for the HTML case failed.
2062
2063         if (allowPlugins) {
2064             // Load the plug-in DB allowing plug-ins to install types.
2065             [WebPluginDatabase sharedDatabase];
2066         }
2067
2068         // Load the image types and get the view class and rep class. This should be the fullest picture of all handled types.
2069         viewClass = [[WebFrameView _viewTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
2070         repClass = [[WebDataSource _repTypesAllowImageTypeOmission:NO] _webkit_objectForMIMEType:MIMEType];
2071     }
2072     
2073     if (viewClass && repClass) {
2074         if (viewClass == [WebHTMLView class] && repClass == [WebHTMLRepresentation class]) {
2075             // Special-case WebHTMLView for text types that shouldn't be shown.
2076             if ([[WebHTMLView unsupportedTextMIMETypes] containsObject:MIMEType])
2077                 return NO;
2078
2079             // If the MIME type is a known plug-in we might not want to load it.
2080             if (!allowPlugins && [knownPluginMIMETypes() containsObject:MIMEType]) {
2081                 BOOL isSupportedByWebKit = [[WebHTMLView supportedNonImageMIMETypes] containsObject:MIMEType] ||
2082                     [[WebHTMLView supportedMIMETypes] containsObject:MIMEType];
2083                 
2084                 // If this is a known plug-in MIME type and WebKit can't show it natively, we don't want to show it.
2085                 if (!isSupportedByWebKit)
2086                     return NO;
2087             }
2088         }
2089         if (vClass)
2090             *vClass = viewClass;
2091         if (rClass)
2092             *rClass = repClass;
2093         return YES;
2094     }
2095     
2096     return NO;
2097 }
2098
2099 - (BOOL)_viewClass:(Class *)vClass andRepresentationClass:(Class *)rClass forMIMEType:(NSString *)MIMEType
2100 {
2101     if ([[self class] _viewClass:vClass andRepresentationClass:rClass forMIMEType:MIMEType allowingPlugins:[_private->preferences arePlugInsEnabled]])
2102         return YES;
2103 #if !PLATFORM(IOS_FAMILY)
2104     if (_private->pluginDatabase) {
2105         WebBasePluginPackage *pluginPackage = [_private->pluginDatabase pluginForMIMEType:MIMEType];
2106         if (pluginPackage) {
2107             if (vClass)
2108                 *vClass = [WebHTMLView class];
2109             if (rClass)
2110                 *rClass = [WebHTMLRepresentation class];
2111             return YES;
2112         }
2113     }
2114 #endif
2115     return NO;
2116 }
2117
2118 + (void)_setAlwaysUsesComplexTextCodePath:(BOOL)f
2119 {
2120     FontCascade::setCodePath(f ? FontCascade::Complex : FontCascade::Auto);
2121 }
2122
2123 + (BOOL)canCloseAllWebViews
2124 {
2125     return DOMWindow::dispatchAllPendingBeforeUnloadEvents();
2126 }
2127
2128 + (void)closeAllWebViews
2129 {
2130     DOMWindow::dispatchAllPendingUnloadEvents();
2131
2132     // This will close the WebViews in a random order. Change this if close order is important.
2133     for (WebView *webView in [(__bridge NSSet *)allWebViewsSet allObjects])
2134         [webView close];
2135 }
2136
2137 + (BOOL)canShowFile:(NSString *)path
2138 {
2139     return [[self class] canShowMIMEType:[WebView _MIMETypeForFile:path]];
2140 }
2141
2142 #if !PLATFORM(IOS_FAMILY)
2143 + (NSString *)suggestedFileExtensionForMIMEType:(NSString *)type
2144 {
2145     return [[NSURLFileTypeMappings sharedMappings] preferredExtensionForMIMEType:type];
2146 }
2147 #endif
2148
2149 - (BOOL)_isClosed
2150 {
2151     return !_private || _private->closed;
2152 }
2153
2154 #if PLATFORM(IOS_FAMILY)
2155
2156 - (void)_dispatchUnloadEvent
2157 {
2158     WebThreadRun(^{
2159         WebFrame *mainFrame = [self mainFrame];
2160         Frame *coreMainFrame = core(mainFrame);
2161         if (coreMainFrame) {
2162             Document *document = coreMainFrame->document();
2163             if (document)
2164                 document->dispatchWindowEvent(Event::create(eventNames().unloadEvent, Event::CanBubble::No, Event::IsCancelable::No));
2165         }
2166     });
2167 }
2168
2169 - (DOMCSSStyleDeclaration *)styleAtSelectionStart
2170 {
2171     auto* mainFrame = [self _mainCoreFrame];
2172     if (!mainFrame)
2173         return nil;
2174     RefPtr<EditingStyle> editingStyle = EditingStyle::styleAtSelectionStart(mainFrame->selection().selection());
2175     if (!editingStyle)
2176         return nil;
2177     auto* style = editingStyle->style();
2178     if (!style)
2179         return nil;
2180     return kit(&style->ensureCSSStyleDeclaration());
2181 }
2182
2183 - (NSUInteger)_renderTreeSize
2184 {
2185     if (!_private->page)
2186         return 0;
2187     return _private->page->renderTreeSize();
2188 }
2189
2190 - (void)_dispatchTileDidDraw:(CALayer*)tile
2191 {
2192     id mailDelegate = [self _webMailDelegate];
2193     if ([mailDelegate respondsToSelector:@selector(_webthread_webView:tileDidDraw:)]) {
2194         [mailDelegate _webthread_webView:self tileDidDraw:tile];
2195         return;
2196     }
2197
2198     ALLOW_DEPRECATED_DECLARATIONS_BEGIN
2199     if (!OSAtomicCompareAndSwap32(0, 1, &_private->didDrawTiles))
2200         return;
2201     ALLOW_DEPRECATED_DECLARATIONS_END
2202
2203     WebThreadLock();
2204
2205     [[[self _UIKitDelegateForwarder] asyncForwarder] webViewDidDrawTiles:self];
2206 }
2207
2208 - (void)_willStartScrollingOrZooming
2209 {
2210     // Pause timers during top level interaction
2211     if (_private->mainViewIsScrollingOrZooming)
2212         return;
2213     _private->mainViewIsScrollingOrZooming = YES;
2214
2215     [self hideFormValidationMessage];
2216
2217     // This suspends active DOM objects like timers, but not media.
2218     [[self mainFrame] setTimeoutsPaused:YES];
2219
2220     // This defers loading callbacks only.
2221     // WARNING: This behavior could change if Bug 49401 lands in open source WebKit again.
2222     [self setDefersCallbacks:YES];
2223 }
2224
2225 - (void)_didFinishScrollingOrZooming
2226 {
2227     if (!_private->mainViewIsScrollingOrZooming)
2228         return;
2229     _private->mainViewIsScrollingOrZooming = NO;
2230     [self setDefersCallbacks:NO];
2231     [[self mainFrame] setTimeoutsPaused:NO];
2232     if (FrameView* view = [self _mainCoreFrame]->view())
2233         view->resumeVisibleImageAnimationsIncludingSubframes();
2234 }
2235
2236 - (void)_setResourceLoadSchedulerSuspended:(BOOL)suspend
2237 {
2238     if (suspend)
2239         webResourceLoadScheduler().suspendPendingRequests();
2240     else
2241         webResourceLoadScheduler().resumePendingRequests();
2242 }
2243
2244 + (BOOL)_isUnderMemoryPressure
2245 {
2246     return MemoryPressureHandler::singleton().isUnderMemoryPressure();
2247 }
2248
2249 #endif // PLATFORM(IOS_FAMILY)
2250
2251 - (void)_closePluginDatabases
2252 {
2253     pluginDatabaseClientCount--;
2254
2255     // Close both sets of plug-in databases because plug-ins need an opportunity to clean up files, etc.
2256
2257 #if !PLATFORM(IOS_FAMILY)
2258     // Unload the WebView local plug-in database. 
2259     if (_private->pluginDatabase) {
2260         [_private->pluginDatabase destroyAllPluginInstanceViews];
2261         [_private->pluginDatabase close];
2262         [_private->pluginDatabase release];
2263         _private->pluginDatabase = nil;
2264     }
2265 #endif
2266     
2267     // Keep the global plug-in database active until the app terminates to avoid having to reload plug-in bundles.
2268     if (!pluginDatabaseClientCount && applicationIsTerminating)
2269         [WebPluginDatabase closeSharedDatabase];
2270 }
2271
2272 - (void)_closeWithFastTeardown 
2273 {
2274 #ifndef NDEBUG
2275     WTF::RefCountedLeakCounter::suppressMessages("At least one WebView was closed with fast teardown.");
2276 #endif
2277
2278 #if !PLATFORM(IOS_FAMILY)
2279     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
2280 #endif
2281     [[NSNotificationCenter defaultCenter] removeObserver:self];
2282
2283     [self _closePluginDatabases];
2284 }
2285
2286 static bool fastDocumentTeardownEnabled()
2287 {
2288 #ifdef NDEBUG
2289     static bool enabled = ![[NSUserDefaults standardUserDefaults] boolForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
2290 #else
2291     static bool initialized = false;
2292     static bool enabled = false;
2293     if (!initialized) {
2294         // This allows debug builds to default to not have fast teardown, so leak checking still works.
2295         // But still allow the WebKitEnableFullDocumentTeardown default to override it if present.
2296         NSNumber *setting = [[NSUserDefaults standardUserDefaults] objectForKey:WebKitEnableFullDocumentTeardownPreferenceKey];
2297         if (setting)
2298             enabled = ![setting boolValue];
2299         initialized = true;
2300     }
2301 #endif
2302     return enabled;
2303 }
2304
2305 // _close is here only for backward compatibility; clients and subclasses should use
2306 // public method -close instead.
2307 - (void)_close
2308 {
2309 #if PLATFORM(IOS_FAMILY)
2310     // Always clear delegates on calling thread, becasue caller can deallocate delegates right after calling -close
2311     // (and could in fact already be in delegate's -dealloc method, as seen in <rdar://problem/11540972>).
2312
2313     [self _clearDelegates];
2314
2315     // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
2316     WebThreadRun(^{
2317 #endif            
2318
2319     if (!_private || _private->closed)
2320         return;
2321
2322     [[NSNotificationCenter defaultCenter] postNotificationName:WebViewWillCloseNotification object:self];
2323
2324     _private->closed = YES;
2325     [self _removeFromAllWebViewsSet];
2326
2327 #ifndef NDEBUG
2328     WTF::RefCountedLeakCounter::cancelMessageSuppression(webViewIsOpen);
2329 #endif
2330
2331     // To quit the apps fast we skip document teardown, except plugins
2332     // need to be destroyed and unloaded.
2333     if (applicationIsTerminating && fastDocumentTeardownEnabled()) {
2334         [self _closeWithFastTeardown];
2335         return;
2336     }
2337
2338 #if ENABLE(VIDEO) && !PLATFORM(IOS_FAMILY)
2339     [self _exitVideoFullscreen];
2340 #endif
2341
2342 #if PLATFORM(IOS_FAMILY)
2343     _private->closing = YES;
2344 #endif
2345
2346     if (Frame* mainFrame = [self _mainCoreFrame])
2347         mainFrame->loader().detachFromParent();
2348
2349     [self setHostWindow:nil];
2350
2351 #if !PLATFORM(IOS_FAMILY)
2352     [self setDownloadDelegate:nil];
2353     [self setEditingDelegate:nil];
2354     [self setFrameLoadDelegate:nil];
2355     [self setPolicyDelegate:nil];
2356     [self setResourceLoadDelegate:nil];
2357     [self setScriptDebugDelegate:nil];
2358     [self setUIDelegate:nil];
2359
2360     [_private->inspector inspectedWebViewClosed];
2361 #endif
2362 #if PLATFORM(MAC)
2363     [_private->immediateActionController webViewClosed];
2364 #endif
2365
2366 #if !PLATFORM(IOS_FAMILY)
2367     // To avoid leaks, call removeDragCaret in case it wasn't called after moveDragCaretToPoint.
2368     [self removeDragCaret];
2369 #endif
2370
2371     _private->group->removeWebView(self);
2372
2373     // Deleteing the WebCore::Page will clear the page cache so we call destroy on
2374     // all the plug-ins in the page cache to break any retain cycles.
2375     // See comment in HistoryItem::releaseAllPendingPageCaches() for more information.
2376     Page* page = _private->page;
2377     _private->page = nullptr;
2378     WebKit::DeferredPageDestructor::createDeferredPageDestructor(std::unique_ptr<Page>(page));
2379
2380 #if !PLATFORM(IOS_FAMILY)
2381     if (_private->hasSpellCheckerDocumentTag) {
2382         [[NSSpellChecker sharedSpellChecker] closeSpellDocumentWithTag:_private->spellCheckerDocumentTag];
2383         _private->hasSpellCheckerDocumentTag = NO;
2384     }
2385 #endif
2386
2387     if (_private->layerFlushController) {
2388         _private->layerFlushController->invalidate();
2389         _private->layerFlushController = nullptr;
2390     }
2391
2392     [[self _notificationProvider] unregisterWebView:self];
2393
2394 #if !PLATFORM(IOS_FAMILY)
2395     [[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
2396 #endif
2397     [[NSNotificationCenter defaultCenter] removeObserver:self];
2398
2399     [WebPreferences _removeReferenceForIdentifier:[self preferencesIdentifier]];
2400
2401     WebPreferences *preferences = _private->preferences;
2402     _private->preferences = nil;
2403     [preferences didRemoveFromWebView];
2404     [preferences release];
2405
2406     [self _closePluginDatabases];
2407
2408 #if ENABLE(WIRELESS_PLAYBACK_TARGET) && !PLATFORM(IOS_FAMILY)
2409     if (_private->m_playbackTargetPicker) {
2410         _private->m_playbackTargetPicker->invalidate();
2411         _private->m_playbackTargetPicker = nullptr;
2412     }
2413 #endif
2414
2415 #ifndef NDEBUG
2416     // Need this to make leak messages accurate.
2417     if (applicationIsTerminating) {
2418         WebCore::GCController::singleton().garbageCollectNow();
2419         [WebCache setDisabled:YES];
2420     }
2421 #endif
2422 #if PLATFORM(IOS_FAMILY)
2423     // Fix for problems such as <rdar://problem/5774587> Crash closing tab in WebCore::Frame::page() from -[WebCoreFrameBridge pauseTimeouts]
2424     });
2425 #endif            
2426 }
2427
2428 // Indicates if the WebView is in the midst of a user gesture.
2429 - (BOOL)_isProcessingUserGesture
2430 {
2431     return UserGestureIndicator::processingUserGesture();
2432 }
2433
2434 + (NSString *)_MIMETypeForFile:(NSString *)path
2435 {
2436 #if !PLATFORM(IOS_FAMILY)
2437     NSString *extension = [path pathExtension];
2438 #endif
2439     NSString *MIMEType = nil;
2440
2441 #if !PLATFORM(IOS_FAMILY)
2442     // Get the MIME type from the extension.
2443     if ([extension length] != 0) {
2444         MIMEType = [[NSURLFileTypeMappings sharedMappings] MIMETypeForExtension:extension];
2445     }
2446 #endif
2447
2448     // If we can't get a known MIME type from the extension, sniff.
2449     if ([MIMEType length] == 0 || [MIMEType isEqualToString:@"application/octet-stream"]) {
2450         NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
2451         NSData *data = [handle readDataOfLength:WEB_GUESS_MIME_TYPE_PEEK_LENGTH];
2452         [handle closeFile];
2453         if ([data length] != 0) {
2454             MIMEType = [data _webkit_guessedMIMEType];
2455         }
2456         if ([MIMEType length] == 0) {
2457             MIMEType = @"application/octet-stream";
2458         }
2459     }
2460
2461     return MIMEType;
2462 }
2463
2464 - (WebDownload *)_downloadURL:(NSURL *)URL
2465 {
2466     ASSERT(URL);
2467     
2468     NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
2469 ALLOW_DEPRECATED_DECLARATIONS_BEGIN
2470     WebDownload *download = [WebDownload _downloadWithRequest:request delegate:_private->downloadDelegate directory:nil];
2471 ALLOW_DEPRECATED_DECLARATIONS_END
2472     [request release];
2473
2474     return download;
2475 }
2476
2477 - (WebView *)_openNewWindowWithRequest:(NSURLRequest *)request
2478 {
2479     NSDictionary *features = [[NSDictionary alloc] init];
2480     WebView *newWindowWebView = [[self _UIDelegateForwarder] webView:self
2481                                             createWebViewWithRequest:nil
2482                                                       windowFeatures:features];
2483     [features release];
2484     if (!newWindowWebView)
2485         return nil;
2486
2487     CallUIDelegate(newWindowWebView, @selector(webViewShow:));
2488     return newWindowWebView;
2489 }
2490
2491 + (void)_setIconLoadingEnabled:(BOOL)enabled
2492 {
2493     iconLoadingEnabled = enabled;
2494 }
2495
2496 + (BOOL)_isIconLoadingEnabled
2497 {
2498     return iconLoadingEnabled;
2499 }
2500
2501 - (WebInspector *)inspector
2502 {
2503     if (!_private->inspector)
2504         _private->inspector = [[WebInspector alloc] initWithInspectedWebView:self];
2505     return _private->inspector;
2506 }
2507
2508 #if ENABLE(REMOTE_INSPECTOR)
2509 + (void)_enableRemoteInspector
2510 {
2511     RemoteInspector::singleton().start();
2512 }
2513
2514 + (void)_disableRemoteInspector
2515 {
2516     RemoteInspector::singleton().stop();
2517 }
2518
2519 + (void)_disableAutoStartRemoteInspector
2520 {
2521     RemoteInspector::startDisabled();
2522 }
2523
2524 + (BOOL)_isRemoteInspectorEnabled
2525 {
2526     return RemoteInspector::singleton().enabled();
2527 }
2528
2529 + (BOOL)_hasRemoteInspectorSession
2530 {
2531     return RemoteInspector::singleton().hasActiveDebugSession();
2532 }
2533
2534 - (BOOL)allowsRemoteInspection
2535 {
2536     return _private->page->remoteInspectionAllowed();
2537 }
2538
2539 - (void)setAllowsRemoteInspection:(BOOL)allow
2540 {
2541     _private->page->setRemoteInspectionAllowed(allow);
2542 }
2543
2544 - (void)setShowingInspectorIndication:(BOOL)showing
2545 {
2546 #if PLATFORM(IOS_FAMILY)
2547     ASSERT(WebThreadIsLocked());
2548
2549     if (showing) {
2550         if (!_private->indicateLayer) {
2551             _private->indicateLayer = [[WebIndicateLayer alloc] initWithWebView:self];
2552             [_private->indicateLayer setNeedsLayout];
2553             [[[self window] hostLayer] addSublayer:_private->indicateLayer];
2554         }
2555     } else {
2556         [_private->indicateLayer removeFromSuperlayer];
2557         [_private->indicateLayer release];
2558         _private->indicateLayer = nil;
2559     }
2560 #else
2561     // Implemented in WebCore::InspectorOverlay.
2562 #endif
2563 }
2564
2565 #if PLATFORM(IOS_FAMILY)
2566 - (void)_setHostApplicationProcessIdentifier:(pid_t)pid auditToken:(audit_token_t)auditToken
2567 {
2568     RetainPtr<CFDataRef> auditData = adoptCF(CFDataCreate(nullptr, (const UInt8*)&auditToken, sizeof(auditToken)));
2569     RemoteInspector::singleton().setParentProcessInformation(pid, auditData);
2570 }
2571 #endif // PLATFORM(IOS_FAMILY)
2572 #endif // ENABLE(REMOTE_INSPECTOR)
2573
2574 - (WebCore::Page*)page
2575 {
2576     return _private->page;
2577 }
2578
2579 #if !PLATFORM(IOS_FAMILY)
2580 - (NSMenu *)_menuForElement:(NSDictionary *)element defaultItems:(NSArray *)items
2581 {
2582     NSArray *defaultMenuItems = [[WebDefaultUIDelegate sharedUIDelegate] webView:self contextMenuItemsForElement:element defaultMenuItems:items];
2583     NSArray *menuItems = defaultMenuItems;
2584
2585     // CallUIDelegate returns nil if UIDelegate is nil or doesn't respond to the selector. So we need to check that here
2586     // to distinguish between using defaultMenuItems or the delegate really returning nil to say "no context menu".
2587     SEL selector = @selector(webView:contextMenuItemsForElement:defaultMenuItems:);
2588     if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
2589         menuItems = CallUIDelegate(self, selector, element, defaultMenuItems);
2590         if (!menuItems)
2591             return nil;
2592     }
2593
2594     unsigned count = [menuItems count];
2595     if (!count)
2596         return nil;
2597
2598     NSMenu *menu = [[NSMenu alloc] init];
2599     for (unsigned i = 0; i < count; i++)
2600         [menu addItem:[menuItems objectAtIndex:i]];
2601
2602     return [menu autorelease];
2603 }
2604 #endif
2605
2606 - (void)_mouseDidMoveOverElement:(NSDictionary *)dictionary modifierFlags:(NSUInteger)modifierFlags
2607 {
2608     // We originally intended to call this delegate method sometimes with a nil dictionary, but due to
2609     // a bug dating back to WebKit 1.0 this delegate was never called with nil! Unfortunately we can't
2610     // start calling this with nil since it will break Adobe Help Viewer, and possibly other clients.
2611     if (!dictionary)
2612         return;
2613     CallUIDelegate(self, @selector(webView:mouseDidMoveOverElement:modifierFlags:), dictionary, modifierFlags);
2614 }
2615
2616 - (void)_loadBackForwardListFromOtherView:(WebView *)otherView
2617 {
2618     if (!_private->page)
2619         return;
2620     
2621     if (!otherView->_private->page)
2622         return;
2623     
2624     // It turns out the right combination of behavior is done with the back/forward load
2625     // type.  (See behavior matrix at the top of WebFramePrivate.)  So we copy all the items
2626     // in the back forward list, and go to the current one.
2627
2628     BackForwardController& backForward = _private->page->backForward();
2629     ASSERT(!backForward.currentItem()); // destination list should be empty
2630
2631     BackForwardController& otherBackForward = otherView->_private->page->backForward();
2632     if (!otherBackForward.currentItem())
2633         return; // empty back forward list, bail
2634     
2635     HistoryItem* newItemToGoTo = nullptr;
2636
2637     int lastItemIndex = otherBackForward.forwardCount();
2638     for (int i = -otherBackForward.backCount(); i <= lastItemIndex; ++i) {
2639         if (i == 0) {
2640             // If this item is showing , save away its current scroll and form state,
2641             // since that might have changed since loading and it is normally not saved
2642             // until we leave that page.
2643             otherView->_private->page->mainFrame().loader().history().saveDocumentAndScrollState();
2644         }
2645         Ref<HistoryItem> newItem = otherBackForward.itemAtIndex(i)->copy();
2646         if (i == 0) 
2647             newItemToGoTo = newItem.ptr();
2648         backForward.client().addItem(WTFMove(newItem));
2649     }
2650
2651     ASSERT(newItemToGoTo);
2652     _private->page->goToItem(*newItemToGoTo, FrameLoadType::IndexedBackForward, ShouldTreatAsContinuingLoad::No);
2653 }
2654
2655 - (void)_setFormDelegate: (id<WebFormDelegate>)delegate
2656 {
2657     _private->formDelegate = delegate;
2658 #if PLATFORM(IOS_FAMILY)
2659     [_private->formDelegateForwarder clearTarget];
2660     [_private->formDelegateForwarder release];
2661     _private->formDelegateForwarder = nil;
2662 #endif
2663 }
2664
2665 - (id<WebFormDelegate>)_formDelegate
2666 {
2667     return _private->formDelegate;
2668 }
2669
2670 #if PLATFORM(IOS_FAMILY)
2671 - (id)_formDelegateForwarder
2672 {
2673     if (_private->closing)
2674         return nil;
2675
2676     if (!_private->formDelegateForwarder)
2677         _private->formDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:[self _formDelegate] defaultTarget:[WebDefaultFormDelegate sharedFormDelegate]];
2678     return _private->formDelegateForwarder;
2679 }
2680
2681 - (id)_formDelegateForSelector:(SEL)selector
2682 {
2683     id delegate = self->_private->formDelegate;
2684     if ([delegate respondsToSelector:selector])
2685         return delegate;
2686
2687     delegate = [WebDefaultFormDelegate sharedFormDelegate];
2688     if ([delegate respondsToSelector:selector])
2689         return delegate;
2690
2691     return nil;
2692 }
2693 #endif
2694
2695 #if !PLATFORM(IOS_FAMILY)
2696 - (BOOL)_needsAdobeFrameReloadingQuirk
2697 {
2698     static BOOL needsQuirk = _CFAppVersionCheckLessThan(CFSTR("com.adobe.Acrobat"), -1, 9.0)
2699         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.Acrobat.Pro"), -1, 9.0)
2700         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.Reader"), -1, 9.0)
2701         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.distiller"), -1, 9.0)
2702         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.Contribute"), -1, 4.2)
2703         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.dreamweaver-9.0"), -1, 9.1)
2704         || _CFAppVersionCheckLessThan(CFSTR("com.macromedia.fireworks"), -1, 9.1)
2705         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.InCopy"), -1, 5.1)
2706         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.InDesign"), -1, 5.1)
2707         || _CFAppVersionCheckLessThan(CFSTR("com.adobe.Soundbooth"), -1, 2);
2708
2709     return needsQuirk;
2710 }
2711
2712 - (BOOL)_needsLinkElementTextCSSQuirk
2713 {
2714     static BOOL needsQuirk = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITHOUT_LINK_ELEMENT_TEXT_CSS_QUIRK)
2715         && _CFAppVersionCheckLessThan(CFSTR("com.e-frontier.shade10"), -1, 10.6);
2716     return needsQuirk;
2717 }
2718
2719 - (BOOL)_needsFrameNameFallbackToIdQuirk
2720 {
2721     static BOOL needsQuirk = _CFAppVersionCheckLessThan(CFSTR("info.colloquy"), -1, 2.5);
2722     return needsQuirk;
2723 }
2724
2725 - (BOOL)_needsIsLoadingInAPISenseQuirk
2726 {
2727     static BOOL needsQuirk = _CFAppVersionCheckLessThan(CFSTR("com.apple.iAdProducer"), -1, 2.1);
2728     
2729     return needsQuirk;
2730 }
2731
2732 - (BOOL)_needsKeyboardEventDisambiguationQuirks
2733 {
2734     static BOOL needsQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_IE_COMPATIBLE_KEYBOARD_EVENT_DISPATCH) && !MacApplication::isSafari();
2735     return needsQuirks;
2736 }
2737
2738 - (BOOL)_needsFrameLoadDelegateRetainQuirk
2739 {
2740     static BOOL needsQuirk = _CFAppVersionCheckLessThan(CFSTR("com.equinux.iSale5"), -1, 5.6);
2741     return needsQuirk;
2742 }
2743
2744 static bool needsSelfRetainWhileLoadingQuirk()
2745 {
2746     static bool needsQuirk = MacApplication::isAperture();
2747     return needsQuirk;
2748 }
2749 #endif // !PLATFORM(IOS_FAMILY)
2750
2751 - (BOOL)_needsPreHTML5ParserQuirks
2752 {    
2753 #if !PLATFORM(IOS_FAMILY)
2754     // AOL Instant Messenger and Microsoft My Day contain markup incompatible
2755     // with the new HTML5 parser. If these applications were linked against a
2756     // version of WebKit prior to the introduction of the HTML5 parser, enable
2757     // parser quirks to maintain compatibility. For details, see 
2758     // <https://bugs.webkit.org/show_bug.cgi?id=46134> and
2759     // <https://bugs.webkit.org/show_bug.cgi?id=46334>.
2760     static bool isApplicationNeedingParserQuirks = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_HTML5_PARSER)
2761         && (MacApplication::isAOLInstantMessenger() || MacApplication::isMicrosoftMyDay());
2762     
2763     // Mail.app must continue to display HTML email that contains quirky markup.
2764     static bool isAppleMail = MacApplication::isAppleMail();
2765
2766     return isApplicationNeedingParserQuirks
2767         || isAppleMail
2768 #if ENABLE(DASHBOARD_SUPPORT)
2769         // Pre-HTML5 parser quirks are required to remain compatible with many
2770         // Dashboard widgets. See <rdar://problem/8175982>.
2771         || (_private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode())
2772 #endif
2773         || [[self preferences] usePreHTML5ParserQuirks];
2774 #else
2775     return [[self preferences] usePreHTML5ParserQuirks];
2776 #endif
2777 }
2778
2779 - (void)_preferencesChangedNotification:(NSNotification *)notification
2780 {
2781 #if PLATFORM(IOS_FAMILY)
2782     // For WebViews that load synchronously, preference changes need to be propagated
2783     // down to WebCore synchronously so that loads in that WebView have the correct
2784     // up-to-date settings.
2785     if (!WebThreadIsLocked())
2786         WebThreadLock();
2787     if ([[self mainFrame] _loadsSynchronously]) {
2788 #endif
2789
2790     WebPreferences *preferences = (WebPreferences *)[notification object];
2791     [self _preferencesChanged:preferences];
2792
2793 #if PLATFORM(IOS_FAMILY)
2794     } else {
2795         WebThreadRun(^{
2796             // It is possible that the prefs object has already changed before the invocation could be called
2797             // on the web thread. This is not possible on TOT which is why they have a simple ASSERT.
2798             WebPreferences *preferences = (WebPreferences *)[notification object];
2799             if (preferences != [self preferences])
2800                 return;
2801             [self _preferencesChanged:preferences];
2802         });
2803     }
2804 #endif
2805 }
2806
2807 - (void)_preferencesChanged:(WebPreferences *)preferences
2808 {    
2809     ASSERT(preferences == [self preferences]);
2810     if (!_private->userAgentOverridden)
2811         [self _invalidateUserAgentCache];
2812
2813     // Cache this value so we don't have to read NSUserDefaults on each page load
2814     _private->useSiteSpecificSpoofing = [preferences _useSiteSpecificSpoofing];
2815
2816     // Update corresponding WebCore Settings object.
2817     if (!_private->page)
2818         return;
2819
2820 #if PLATFORM(IOS_FAMILY)
2821     // iOS waits to call [WebDatabaseManager sharedWebDatabaseManager] until
2822     // didOneTimeInitialization is true so that we don't initialize databases
2823     // until the first WebView has been created. This is because database
2824     // initialization current requires disk access to populate the origins
2825     // quota map and we want to do this lazily by waiting until WebKit is
2826     // used to display web content in a WebView. The possible cases are:
2827     //   - on one time initialize (the first WebView creation) if databases are enabled (default)
2828     //   - when databases are dynamically enabled later, and they were disabled at startup (this case)
2829     if (didOneTimeInitialization) {
2830         if ([preferences databasesEnabled])
2831             [WebDatabaseManager sharedWebDatabaseManager];
2832         if ([preferences storageTrackerEnabled])
2833             WebKitInitializeStorageIfNecessary();
2834     }
2835 #endif
2836
2837     Settings& settings = _private->page->settings();
2838
2839     settings.setCursiveFontFamily([preferences cursiveFontFamily]);
2840     settings.setDefaultFixedFontSize([preferences defaultFixedFontSize]);
2841     settings.setDefaultFontSize([preferences defaultFontSize]);
2842     settings.setDefaultTextEncodingName([preferences defaultTextEncodingName]);
2843     settings.setUsesEncodingDetector([preferences usesEncodingDetector]);
2844     settings.setFantasyFontFamily([preferences fantasyFontFamily]);
2845     settings.setFixedFontFamily([preferences fixedFontFamily]);
2846     settings.setForceFTPDirectoryListings([preferences _forceFTPDirectoryListings]);
2847     settings.setFTPDirectoryTemplatePath([preferences _ftpDirectoryTemplatePath]);
2848     settings.setLocalStorageDatabasePath([preferences _localStorageDatabasePath]);
2849     settings.setJavaEnabled([preferences isJavaEnabled]);
2850     settings.setScriptEnabled([preferences isJavaScriptEnabled]);
2851     settings.setScriptMarkupEnabled([preferences javaScriptMarkupEnabled]);
2852     settings.setWebSecurityEnabled([preferences isWebSecurityEnabled]);
2853     settings.setAllowUniversalAccessFromFileURLs([preferences allowUniversalAccessFromFileURLs]);
2854     settings.setAllowFileAccessFromFileURLs([preferences allowFileAccessFromFileURLs]);
2855     settings.setAllowCrossOriginSubresourcesToAskForCredentials([preferences allowCrossOriginSubresourcesToAskForCredentials]);
2856     settings.setNeedsStorageAccessFromFileURLsQuirk([preferences needsStorageAccessFromFileURLsQuirk]);
2857     settings.setMinimumFontSize([preferences minimumFontSize]);
2858     settings.setMinimumLogicalFontSize([preferences minimumLogicalFontSize]);
2859     settings.setPictographFontFamily([preferences pictographFontFamily]);
2860     settings.setPluginsEnabled([preferences arePlugInsEnabled]);
2861     settings.setLocalStorageEnabled([preferences localStorageEnabled]);
2862
2863     _private->page->enableLegacyPrivateBrowsing([preferences privateBrowsingEnabled]);
2864     settings.setSansSerifFontFamily([preferences sansSerifFontFamily]);
2865     settings.setSerifFontFamily([preferences serifFontFamily]);
2866     settings.setStandardFontFamily([preferences standardFontFamily]);
2867     settings.setLoadsImagesAutomatically([preferences loadsImagesAutomatically]);
2868     settings.setLoadsSiteIconsIgnoringImageLoadingSetting([preferences loadsSiteIconsIgnoringImageLoadingPreference]);
2869 #if PLATFORM(IOS_FAMILY)
2870     settings.setShouldPrintBackgrounds(true);
2871 #else
2872     settings.setShouldPrintBackgrounds([preferences shouldPrintBackgrounds]);
2873 #endif
2874     settings.setShrinksStandaloneImagesToFit([preferences shrinksStandaloneImagesToFit]);
2875     settings.setEditableLinkBehavior(core([preferences editableLinkBehavior]));
2876     settings.setTextDirectionSubmenuInclusionBehavior(core([preferences textDirectionSubmenuInclusionBehavior]));
2877     settings.setDOMPasteAllowed([preferences isDOMPasteAllowed]);
2878     settings.setUsesPageCache([self usesPageCache]);
2879     settings.setPageCacheSupportsPlugins([preferences pageCacheSupportsPlugins]);
2880     settings.setBackForwardCacheExpirationInterval([preferences _backForwardCacheExpirationInterval]);
2881
2882     settings.setDeveloperExtrasEnabled([preferences developerExtrasEnabled]);
2883     settings.setJavaScriptRuntimeFlags(JSC::RuntimeFlags([preferences javaScriptRuntimeFlags]));
2884     settings.setAuthorAndUserStylesEnabled([preferences authorAndUserStylesEnabled]);
2885
2886     settings.setNeedsSiteSpecificQuirks(_private->useSiteSpecificSpoofing);
2887     settings.setDOMTimersThrottlingEnabled([preferences domTimersThrottlingEnabled]);
2888     settings.setWebArchiveDebugModeEnabled([preferences webArchiveDebugModeEnabled]);
2889     settings.setLocalFileContentSniffingEnabled([preferences localFileContentSniffingEnabled]);
2890     settings.setOfflineWebApplicationCacheEnabled([preferences offlineWebApplicationCacheEnabled]);
2891     settings.setJavaScriptCanAccessClipboard([preferences javaScriptCanAccessClipboard]);
2892     settings.setXSSAuditorEnabled([preferences isXSSAuditorEnabled]);
2893     settings.setDNSPrefetchingEnabled([preferences isDNSPrefetchingEnabled]);
2894
2895     settings.setAcceleratedCompositingEnabled([preferences acceleratedCompositingEnabled]);
2896     settings.setAcceleratedDrawingEnabled([preferences acceleratedDrawingEnabled]);
2897     settings.setDisplayListDrawingEnabled([preferences displayListDrawingEnabled]);
2898     settings.setCanvasUsesAcceleratedDrawing([preferences canvasUsesAcceleratedDrawing]);
2899     settings.setShowDebugBorders([preferences showDebugBorders]);
2900     settings.setSimpleLineLayoutEnabled([preferences simpleLineLayoutEnabled]);
2901     settings.setSimpleLineLayoutDebugBordersEnabled([preferences simpleLineLayoutDebugBordersEnabled]);
2902     settings.setShowRepaintCounter([preferences showRepaintCounter]);
2903     settings.setWebGLEnabled([preferences webGLEnabled]);
2904     settings.setSubpixelCSSOMElementMetricsEnabled([preferences subpixelCSSOMElementMetricsEnabled]);
2905     settings.setSubpixelAntialiasedLayerTextEnabled([preferences subpixelAntialiasedLayerTextEnabled]);
2906
2907     settings.setForceSoftwareWebGLRendering([preferences forceSoftwareWebGLRendering]);
2908     settings.setForceWebGLUsesLowPower([preferences forceLowPowerGPUForWebGL]);
2909     settings.setAccelerated2dCanvasEnabled([preferences accelerated2dCanvasEnabled]);
2910     settings.setLoadDeferringEnabled(shouldEnableLoadDeferring());
2911     settings.setWindowFocusRestricted(shouldRestrictWindowFocus());
2912     settings.setFrameFlattening((const WebCore::FrameFlattening)[preferences frameFlattening]);
2913     settings.setAsyncFrameScrollingEnabled([preferences asyncFrameScrollingEnabled]);
2914     settings.setSpatialNavigationEnabled([preferences isSpatialNavigationEnabled]);
2915     settings.setPaginateDuringLayoutEnabled([preferences paginateDuringLayoutEnabled]);
2916
2917     settings.setAsynchronousSpellCheckingEnabled([preferences asynchronousSpellCheckingEnabled]);
2918     settings.setHyperlinkAuditingEnabled([preferences hyperlinkAuditingEnabled]);
2919     settings.setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
2920     settings.setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
2921     settings.setValidationMessageTimerMagnification([self validationMessageTimerMagnification]);
2922
2923     BOOL mediaPlaybackRequiresUserGesture = [preferences mediaPlaybackRequiresUserGesture];
2924     settings.setVideoPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture || [preferences videoPlaybackRequiresUserGesture]);
2925     settings.setAudioPlaybackRequiresUserGesture(mediaPlaybackRequiresUserGesture || [preferences audioPlaybackRequiresUserGesture]);
2926     settings.setRequiresUserGestureToLoadVideo(shouldRequireUserGestureToLoadVideo());
2927     settings.setMainContentUserGestureOverrideEnabled([preferences overrideUserGestureRequirementForMainContent]);
2928     settings.setAllowsInlineMediaPlayback([preferences mediaPlaybackAllowsInline]);
2929     settings.setAllowsInlineMediaPlaybackAfterFullscreen([preferences allowsInlineMediaPlaybackAfterFullscreen]);
2930     settings.setInlineMediaPlaybackRequiresPlaysInlineAttribute([preferences inlineMediaPlaybackRequiresPlaysInlineAttribute]);
2931     settings.setInvisibleAutoplayNotPermitted([preferences invisibleAutoplayNotPermitted]);
2932     settings.setAllowsPictureInPictureMediaPlayback([preferences allowsPictureInPictureMediaPlayback] && shouldAllowPictureInPictureMediaPlayback());
2933     settings.setMediaControlsScaleWithPageZoom([preferences mediaControlsScaleWithPageZoom]);
2934     settings.setSuppressesIncrementalRendering([preferences suppressesIncrementalRendering]);
2935     settings.setBackspaceKeyNavigationEnabled([preferences backspaceKeyNavigationEnabled]);
2936     settings.setWantsBalancedSetDefersLoadingBehavior([preferences wantsBalancedSetDefersLoadingBehavior]);
2937     DeprecatedGlobalSettings::setMockScrollbarsEnabled([preferences mockScrollbarsEnabled]);
2938
2939     settings.setShouldRespectImageOrientation([preferences shouldRespectImageOrientation]);
2940
2941     settings.setRequestAnimationFrameEnabled([preferences requestAnimationFrameEnabled]);
2942     settings.setDiagnosticLoggingEnabled([preferences diagnosticLoggingEnabled]);
2943     DeprecatedGlobalSettings::setLowPowerVideoAudioBufferSizeEnabled([preferences lowPowerVideoAudioBufferSizeEnabled]);
2944
2945     settings.setUseLegacyTextAlignPositionedElementBehavior([preferences useLegacyTextAlignPositionedElementBehavior]);
2946
2947     settings.setShouldConvertPositionStyleOnCopy([preferences shouldConvertPositionStyleOnCopy]);
2948     settings.setEnableInheritURIQueryComponent([preferences isInheritURIQueryComponentEnabled]);
2949
2950     settings.setAllowDisplayOfInsecureContent(shouldAllowDisplayAndRunningOfInsecureContent());
2951     settings.setAllowRunningOfInsecureContent(shouldAllowDisplayAndRunningOfInsecureContent());
2952
2953     settings.setJavaScriptCanOpenWindowsAutomatically([preferences javaScriptCanOpenWindowsAutomatically] || shouldAllowWindowOpenWithoutUserGesture());
2954
2955     settings.setVisualViewportEnabled([preferences visualViewportEnabled]);
2956     settings.setVisualViewportAPIEnabled([preferences visualViewportAPIEnabled]);
2957     settings.setCSSOMViewScrollingAPIEnabled([preferences CSSOMViewScrollingAPIEnabled]);
2958     settings.setMediaContentTypesRequiringHardwareSupport([preferences mediaContentTypesRequiringHardwareSupport]);
2959
2960     switch ([preferences storageBlockingPolicy]) {
2961     case WebAllowAllStorage:
2962         settings.setStorageBlockingPolicy(SecurityOrigin::AllowAllStorage);
2963         break;
2964     case WebBlockThirdPartyStorage:
2965         settings.setStorageBlockingPolicy(SecurityOrigin::BlockThirdPartyStorage);
2966         break;
2967     case WebBlockAllStorage:
2968         settings.setStorageBlockingPolicy(SecurityOrigin::BlockAllStorage);
2969         break;
2970     }
2971
2972     settings.setPlugInSnapshottingEnabled([preferences plugInSnapshottingEnabled]);
2973     settings.setHttpEquivEnabled([preferences httpEquivEnabled]);
2974     settings.setColorFilterEnabled([preferences colorFilterEnabled]);
2975     settings.setPunchOutWhiteBackgroundsInDarkMode([preferences punchOutWhiteBackgroundsInDarkMode]);
2976
2977 #if PLATFORM(MAC)
2978     settings.setAcceleratedCompositingForFixedPositionEnabled(true);
2979 #endif
2980
2981 #if ENABLE(RUBBER_BANDING)
2982     // FIXME: https://bugs.webkit.org/show_bug.cgi?id=136131
2983     settings.setRubberBandingForSubScrollableRegionsEnabled(false);
2984 #endif
2985
2986 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2987     settings.setAllowsAirPlayForMediaPlayback([preferences allowsAirPlayForMediaPlayback]);
2988 #endif
2989 #if PLATFORM(IOS_FAMILY)
2990     settings.setStandalone([preferences _standalone]);
2991     settings.setTelephoneNumberParsingEnabled([preferences _telephoneNumberParsingEnabled]);
2992     settings.setAllowMultiElementImplicitSubmission([preferences _allowMultiElementImplicitFormSubmission]);
2993     settings.setLayoutInterval(Seconds::fromMilliseconds([preferences _layoutInterval]));
2994     settings.setMaxParseDuration([preferences _maxParseDuration]);
2995     settings.setAlwaysUseAcceleratedOverflowScroll([preferences _alwaysUseAcceleratedOverflowScroll]);
2996     DeprecatedGlobalSettings::setAudioSessionCategoryOverride([preferences audioSessionCategoryOverride]);
2997     DeprecatedGlobalSettings::setNetworkDataUsageTrackingEnabled([preferences networkDataUsageTrackingEnabled]);
2998     DeprecatedGlobalSettings::setNetworkInterfaceName([preferences networkInterfaceName]);
2999 #if HAVE(AVKIT)
3000     DeprecatedGlobalSettings::setAVKitEnabled([preferences avKitEnabled]);
3001 #endif
3002
3003     settings.setPasswordEchoEnabled([preferences _allowPasswordEcho]);
3004     settings.setPasswordEchoDurationInSeconds([preferences _passwordEchoDuration]);
3005
3006     ASSERT_WITH_MESSAGE(settings.pageCacheSupportsPlugins(), "PageCacheSupportsPlugins should be enabled on iOS.");
3007     settings.setDelegatesPageScaling(true);
3008
3009 #if ENABLE(TEXT_AUTOSIZING)
3010     settings.setMinimumZoomFontSize([preferences _minimumZoomFontSize]);
3011     settings.setTextAutosizingEnabled([preferences _textAutosizingEnabled]);
3012 #endif
3013 #endif // PLATFORM(IOS_FAMILY)
3014
3015 #if PLATFORM(MAC)
3016     // This parses the user stylesheet synchronously so anything that may affect it should be done first.
3017     if ([preferences userStyleSheetEnabled]) {
3018         NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
3019         if ([location isEqualToString:@"apple-dashboard://stylesheet"])
3020             location = @"file:///System/Library/PrivateFrameworks/DashboardClient.framework/Resources/widget.css";
3021         settings.setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
3022     } else
3023         settings.setUserStyleSheetLocation([NSURL URLWithString:@""]);
3024
3025     settings.setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
3026     settings.setTreatsAnyTextCSSLinkAsStylesheet([self _needsLinkElementTextCSSQuirk]);
3027     settings.setNeedsFrameNameFallbackToIdQuirk([self _needsFrameNameFallbackToIdQuirk]);
3028     settings.setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
3029     settings.setEnforceCSSMIMETypeInNoQuirksMode(!_CFAppVersionCheckLessThan(CFSTR("com.apple.iWeb"), -1, 2.1));
3030     settings.setNeedsIsLoadingInAPISenseQuirk([self _needsIsLoadingInAPISenseQuirk]);
3031     settings.setTextAreasAreResizable([preferences textAreasAreResizable]);
3032     settings.setExperimentalNotificationsEnabled([preferences experimentalNotificationsEnabled]);
3033     settings.setShowsURLsInToolTips([preferences showsURLsInToolTips]);
3034     settings.setShowsToolTipOverTruncatedText([preferences showsToolTipOverTruncatedText]);
3035 #endif // PLATFORM(MAC)
3036
3037     DatabaseManager::singleton().setIsAvailable([preferences databasesEnabled]);
3038
3039 #if ENABLE(MEDIA_SOURCE)
3040     settings.setMediaSourceEnabled([preferences mediaSourceEnabled]);
3041     settings.setSourceBufferChangeTypeEnabled([preferences sourceBufferChangeTypeEnabled]);
3042 #endif
3043
3044 #if ENABLE(SERVICE_CONTROLS)
3045     settings.setImageControlsEnabled([preferences imageControlsEnabled]);
3046     settings.setServiceControlsEnabled([preferences serviceControlsEnabled]);
3047 #endif
3048
3049 #if ENABLE(VIDEO_TRACK)
3050     settings.setShouldDisplaySubtitles([preferences shouldDisplaySubtitles]);
3051     settings.setShouldDisplayCaptions([preferences shouldDisplayCaptions]);
3052     settings.setShouldDisplayTextDescriptions([preferences shouldDisplayTextDescriptions]);
3053 #endif
3054
3055 #if USE(AVFOUNDATION)
3056     DeprecatedGlobalSettings::setAVFoundationEnabled([preferences isAVFoundationEnabled]);
3057     DeprecatedGlobalSettings::setAVFoundationNSURLSessionEnabled([preferences isAVFoundationNSURLSessionEnabled]);
3058 #endif
3059
3060 #if ENABLE(MEDIA_STREAM)
3061     DeprecatedGlobalSettings::setMockCaptureDevicesEnabled(false);
3062     DeprecatedGlobalSettings::setMediaCaptureRequiresSecureConnection(true);
3063     RuntimeEnabledFeatures::sharedFeatures().setMediaStreamEnabled(false);
3064     RuntimeEnabledFeatures::sharedFeatures().setMediaDevicesEnabled(false);
3065     RuntimeEnabledFeatures::sharedFeatures().setMediaRecorderEnabled(preferences.mediaRecorderEnabled);
3066 #endif
3067
3068 #if ENABLE(WEB_RTC)
3069     RuntimeEnabledFeatures::sharedFeatures().setPeerConnectionEnabled([preferences peerConnectionEnabled]);
3070 #endif
3071
3072 #if ENABLE(WEB_AUDIO)
3073     settings.setWebAudioEnabled([preferences webAudioEnabled]);
3074 #endif
3075
3076 #if ENABLE(FULLSCREEN_API)
3077     settings.setFullScreenEnabled([preferences fullScreenEnabled]);
3078 #endif
3079
3080     RuntimeEnabledFeatures::sharedFeatures().setCSSLogicalEnabled([preferences cssLogicalEnabled]);
3081
3082     settings.setHiddenPageDOMTimerThrottlingEnabled([preferences hiddenPageDOMTimerThrottlingEnabled]);
3083
3084     settings.setHiddenPageCSSAnimationSuspensionEnabled([preferences hiddenPageCSSAnimationSuspensionEnabled]);
3085
3086     DeprecatedGlobalSettings::setResourceLoadStatisticsEnabled([preferences resourceLoadStatisticsEnabled]);
3087
3088     settings.setViewportFitEnabled([preferences viewportFitEnabled]);
3089     settings.setConstantPropertiesEnabled([preferences constantPropertiesEnabled]);
3090
3091 #if ENABLE(GAMEPAD)
3092     RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled([preferences gamepadsEnabled]);
3093 #endif
3094
3095     RuntimeEnabledFeatures::sharedFeatures().setShadowDOMEnabled([preferences shadowDOMEnabled]);
3096     RuntimeEnabledFeatures::sharedFeatures().setCustomElementsEnabled([preferences customElementsEnabled]);
3097     RuntimeEnabledFeatures::sharedFeatures().setDataTransferItemsEnabled([preferences dataTransferItemsEnabled]);
3098     RuntimeEnabledFeatures::sharedFeatures().setCustomPasteboardDataEnabled([preferences customPasteboardDataEnabled]);
3099
3100 #if ENABLE(ATTACHMENT_ELEMENT)
3101     RuntimeEnabledFeatures::sharedFeatures().setAttachmentElementEnabled([preferences attachmentElementEnabled]);
3102 #endif
3103
3104     RuntimeEnabledFeatures::sharedFeatures().setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
3105     RuntimeEnabledFeatures::sharedFeatures().setModernMediaControlsEnabled([preferences modernMediaControlsEnabled]);
3106     RuntimeEnabledFeatures::sharedFeatures().setWebAnimationsCSSIntegrationEnabled([preferences webAnimationsCSSIntegrationEnabled]);
3107
3108     RuntimeEnabledFeatures::sharedFeatures().setCacheAPIEnabled([preferences cacheAPIEnabled]);
3109     RuntimeEnabledFeatures::sharedFeatures().setFetchAPIEnabled([preferences fetchAPIEnabled]);
3110
3111 #if ENABLE(STREAMS_API)
3112     RuntimeEnabledFeatures::sharedFeatures().setWritableStreamAPIEnabled([preferences writableStreamAPIEnabled]);
3113     RuntimeEnabledFeatures::sharedFeatures().setReadableByteStreamAPIEnabled([preferences readableByteStreamAPIEnabled]);
3114 #endif
3115
3116 #if ENABLE(WEBGL2)
3117     RuntimeEnabledFeatures::sharedFeatures().setWebGL2Enabled([preferences webGL2Enabled]);
3118 #endif
3119     
3120 #if ENABLE(WEBGPU)
3121     RuntimeEnabledFeatures::sharedFeatures().setWebGPUEnabled([preferences webGPUEnabled]);
3122 #endif
3123
3124 #if ENABLE(WEBMETAL)
3125     RuntimeEnabledFeatures::sharedFeatures().setWebMetalEnabled([preferences webMetalEnabled]);
3126 #endif
3127
3128 #if ENABLE(DOWNLOAD_ATTRIBUTE)
3129     RuntimeEnabledFeatures::sharedFeatures().setDownloadAttributeEnabled([preferences downloadAttributeEnabled]);
3130 #endif
3131
3132     RuntimeEnabledFeatures::sharedFeatures().setWebAnimationsEnabled([preferences webAnimationsEnabled]);
3133
3134 #if ENABLE(INTERSECTION_OBSERVER)
3135     RuntimeEnabledFeatures::sharedFeatures().setIntersectionObserverEnabled(preferences.intersectionObserverEnabled);
3136 #endif
3137     RuntimeEnabledFeatures::sharedFeatures().setDisplayContentsEnabled(preferences.displayContentsEnabled);
3138
3139     RuntimeEnabledFeatures::sharedFeatures().setUserTimingEnabled(preferences.userTimingEnabled);
3140     RuntimeEnabledFeatures::sharedFeatures().setResourceTimingEnabled(preferences.resourceTimingEnabled);
3141     RuntimeEnabledFeatures::sharedFeatures().setLinkPreloadEnabled(preferences.linkPreloadEnabled);
3142     RuntimeEnabledFeatures::sharedFeatures().setMediaPreloadingEnabled(preferences.mediaPreloadingEnabled);
3143     RuntimeEnabledFeatures::sharedFeatures().setIsSecureContextAttributeEnabled(preferences.isSecureContextAttributeEnabled);
3144     RuntimeEnabledFeatures::sharedFeatures().setDirectoryUploadEnabled([preferences directoryUploadEnabled]);
3145     RuntimeEnabledFeatures::sharedFeatures().setMenuItemElementEnabled([preferences menuItemElementEnabled]);
3146     RuntimeEnabledFeatures::sharedFeatures().setAccessibilityObjectModelEnabled([preferences accessibilityObjectModelEnabled]);
3147     RuntimeEnabledFeatures::sharedFeatures().setAriaReflectionEnabled([preferences ariaReflectionEnabled]);
3148     RuntimeEnabledFeatures::sharedFeatures().setFetchAPIKeepAliveEnabled([preferences fetchAPIKeepAliveEnabled]);
3149
3150 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
3151     RuntimeEnabledFeatures::sharedFeatures().setLegacyEncryptedMediaAPIEnabled(preferences.legacyEncryptedMediaAPIEnabled);
3152 #endif
3153
3154 #if ENABLE(ENCRYPTED_MEDIA)
3155     RuntimeEnabledFeatures::sharedFeatures().setEncryptedMediaAPIEnabled(preferences.encryptedMediaAPIEnabled);
3156 #endif
3157
3158     RuntimeEnabledFeatures::sharedFeatures().setInspectorAdditionsEnabled(preferences.inspectorAdditionsEnabled);
3159
3160     settings.setAllowMediaContentTypesRequiringHardwareSupportAsFallback(preferences.allowMediaContentTypesRequiringHardwareSupportAsFallback);
3161
3162     NSTimeInterval timeout = [preferences incrementalRenderingSuppressionTimeoutInSeconds];
3163     if (timeout > 0)
3164         settings.setIncrementalRenderingSuppressionTimeoutInSeconds(timeout);
3165
3166     // Application Cache Preferences are stored on the global cache storage manager, not in Settings.
3167     [WebApplicationCache setDefaultOriginQuota:[preferences applicationCacheDefaultOriginQuota]];
3168
3169     BOOL zoomsTextOnly = [preferences zoomsTextOnly];
3170     if (_private->zoomsTextOnly != zoomsTextOnly)
3171         [self _setZoomMultiplier:_private->zoomMultiplier isTextOnly:zoomsTextOnly];
3172
3173 #if PLATFORM(IOS_FAMILY)
3174     [[self window] setTileBordersVisible:[preferences showDebugBorders]];
3175     [[self window] setTilePaintCountsVisible:[preferences showRepaintCounter]];
3176     [[self window] setAcceleratedDrawingEnabled:[preferences acceleratedDrawingEnabled]];
3177     [WAKView _setInterpolationQuality:[preferences _interpolationQuality]];
3178 #endif
3179
3180 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
3181     settings.setMediaKeysStorageDirectory([preferences mediaKeysStorageDirectory]);
3182 #endif
3183
3184     settings.setMediaDataLoadsAutomatically([preferences mediaDataLoadsAutomatically]);
3185
3186     settings.setAllowContentSecurityPolicySourceStarToMatchAnyProtocol(shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol());
3187
3188     settings.setShouldConvertInvalidURLsToBlank(shouldConvertInvalidURLsToBlank());
3189
3190     settings.setLargeImageAsyncDecodingEnabled([preferences largeImageAsyncDecodingEnabled]);
3191     settings.setAnimatedImageAsyncDecodingEnabled([preferences animatedImageAsyncDecodingEnabled]);
3192     settings.setMediaCapabilitiesEnabled([preferences mediaCapabilitiesEnabled]);
3193
3194     RuntimeEnabledFeatures::sharedFeatures().setServerTimingEnabled([preferences serverTimingEnabled]);
3195
3196     settings.setSelectionAcrossShadowBoundariesEnabled(preferences.selectionAcrossShadowBoundariesEnabled);
3197 }
3198
3199 static inline IMP getMethod(id o, SEL s)
3200 {
3201     return [o respondsToSelector:s] ? [o methodForSelector:s] : 0;
3202 }
3203
3204 #if PLATFORM(IOS_FAMILY)
3205 - (id)_UIKitDelegateForwarder
3206 {
3207     if (_private->closing)
3208         return nil;
3209         
3210     if (!_private->UIKitDelegateForwarder)
3211         _private->UIKitDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIKitDelegate defaultTarget:[WebDefaultUIKitDelegate sharedUIKitDelegate]];
3212     return _private->UIKitDelegateForwarder;
3213 }
3214 #endif
3215
3216 - (void)_cacheResourceLoadDelegateImplementations
3217 {
3218     WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
3219     id delegate = _private->resourceProgressDelegate;
3220
3221     if (!delegate) {
3222         bzero(cache, sizeof(WebResourceDelegateImplementationCache));
3223         return;
3224     }
3225
3226     cache->didFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFailLoadingWithError:fromDataSource:));
3227     cache->didFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFinishLoadingFromDataSource:));
3228     cache->didLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
3229     cache->didReceiveAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
3230 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
3231     cache->canAuthenticateAgainstProtectionSpaceFunc = getMethod(delegate, @selector(webView:resource:canAuthenticateAgainstProtectionSpace:forDataSource:));
3232 #endif
3233
3234 #if PLATFORM(IOS_FAMILY)
3235     cache->connectionPropertiesFunc = getMethod(delegate, @selector(webView:connectionPropertiesForResource:dataSource:));
3236     cache->webThreadDidFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFinishLoadingFromDataSource:));
3237     cache->webThreadDidFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFailLoadingWithError:fromDataSource:));
3238     cache->webThreadIdentifierForRequestFunc = getMethod(delegate, @selector(webThreadWebView:identifierForInitialRequest:fromDataSource:));
3239     cache->webThreadDidLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webThreadWebView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
3240     cache->webThreadWillSendRequestFunc = getMethod(delegate, @selector(webThreadWebView:resource:willSendRequest:redirectResponse:fromDataSource:));
3241     cache->webThreadDidReceiveResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveResponse:fromDataSource:));
3242     cache->webThreadDidReceiveContentLengthFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveContentLength:fromDataSource:));
3243     cache->webThreadWillCacheResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:willCacheResponse:fromDataSource:));
3244 #endif
3245
3246     cache->didReceiveContentLengthFunc = getMethod(delegate, @selector(webView:resource:didReceiveContentLength:fromDataSource:));
3247     cache->didReceiveResponseFunc = getMethod(delegate, @selector(webView:resource:didReceiveResponse:fromDataSource:));
3248     cache->identifierForRequestFunc = getMethod(delegate, @selector(webView:identifierForInitialRequest:fromDataSource:));
3249     cache->plugInFailedWithErrorFunc = getMethod(delegate, @selector(webView:plugInFailedWithError:dataSource:));
3250     cache->willCacheResponseFunc = getMethod(delegate, @selector(webView:resource:willCacheResponse:fromDataSource:));
3251     cache->willSendRequestFunc = getMethod(delegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:));
3252     cache->shouldUseCredentialStorageFunc = getMethod(delegate, @selector(webView:resource:shouldUseCredentialStorageForDataSource:));
3253     cache->shouldPaintBrokenImageForURLFunc = getMethod(delegate, @selector(webView:shouldPaintBrokenImageForURL:));
3254 }
3255
3256 - (void)_cacheFrameLoadDelegateImplementations
3257 {
3258     WebFrameLoadDelegateImplementationCache *cache = &_private->frameLoadDelegateImplementations;
3259     id delegate = _private->frameLoadDelegate;
3260
3261     if (!delegate) {
3262         bzero(cache, sizeof(WebFrameLoadDelegateImplementationCache));
3263         return;
3264     }
3265
3266     cache->didCancelClientRedirectForFrameFunc = getMethod(delegate, @selector(webView:didCancelClientRedirectForFrame:));
3267     cache->didChangeLocationWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didChangeLocationWithinPageForFrame:));
3268     cache->didPushStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPushStateWithinPageForFrame:));
3269     cache->didReplaceStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didReplaceStateWithinPageForFrame:));
3270     cache->didPopStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPopStateWithinPageForFrame:));
3271 #if JSC_OBJC_API_ENABLED
3272     cache->didCreateJavaScriptContextForFrameFunc = getMethod(delegate, @selector(webView:didCreateJavaScriptContext:forFrame:));
3273 #endif
3274     cache->didClearWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearWindowObject:forFrame:));
3275     cache->didClearWindowObjectForFrameInScriptWorldFunc = getMethod(delegate, @selector(webView:didClearWindowObjectForFrame:inScriptWorld:));
3276     cache->didClearInspectorWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearInspectorWindowObject:forFrame:));
3277     cache->didCommitLoadForFrameFunc = getMethod(delegate, @selector(webView:didCommitLoadForFrame:));
3278     cache->didFailLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailLoadWithError:forFrame:));
3279     cache->didFailProvisionalLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailProvisionalLoadWithError:forFrame:));
3280     cache->didFinishDocumentLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishDocumentLoadForFrame:));
3281     cache->didFinishLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishLoadForFrame:));
3282     cache->didFirstLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstLayoutInFrame:));
3283     cache->didFirstVisuallyNonEmptyLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstVisuallyNonEmptyLayoutInFrame:));
3284     cache->didLayoutFunc = getMethod(delegate, @selector(webView:didLayout:));
3285     cache->didHandleOnloadEventsForFrameFunc = getMethod(delegate, @selector(webView:didHandleOnloadEventsForFrame:));
3286 #if ENABLE(ICONDATABASE)
3287     cache->didReceiveIconForFrameFunc = getMethod(delegate, @selector(webView:didReceiveIcon:forFrame:));
3288 #endif
3289     cache->didReceiveServerRedirectForProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didReceiveServerRedirectForProvisionalLoadForFrame:));
3290     cache->didReceiveTitleForFrameFunc = getMethod(delegate, @selector(webView:didReceiveTitle:forFrame:));
3291     cache->didStartProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didStartProvisionalLoadForFrame:));
3292     cache->willCloseFrameFunc = getMethod(delegate, @selector(webView:willCloseFrame:));
3293     cache->willPerformClientRedirectToURLDelayFireDateForFrameFunc = getMethod(delegate, @selector(webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:));
3294     cache->windowScriptObjectAvailableFunc = getMethod(delegate, @selector(webView:windowScriptObjectAvailable:));
3295     cache->didDisplayInsecureContentFunc = getMethod(delegate, @selector(webViewDidDisplayInsecureContent:));
3296     cache->didRunInsecureContentFunc = getMethod(delegate, @selector(webView:didRunInsecureContent:));
3297     cache->didDetectXSSFunc = getMethod(delegate, @selector(webView:didDetectXSS:));
3298     cache->didRemoveFrameFromHierarchyFunc = getMethod(delegate, @selector(webView:didRemoveFrameFromHierarchy:));
3299 #if PLATFORM(IOS_FAMILY)
3300     cache->webThreadDidLayoutFunc = getMethod(delegate, @selector(webThreadWebView:didLayout:));
3301 #endif
3302
3303     // It would be nice to get rid of this code and transition all clients to using didLayout instead of
3304     // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
3305     // for backwards compatibility.
3306     Page* page = core(self);
3307     if (page) {
3308         OptionSet<WebCore::LayoutMilestone> milestones { DidFirstLayout };
3309 #if PLATFORM(IOS_FAMILY)
3310         milestones.add(DidFirstVisuallyNonEmptyLayout);
3311 #else
3312         if (cache->didFirstVisuallyNonEmptyLayoutInFrameFunc)
3313             milestones.add(DidFirstVisuallyNonEmptyLayout);
3314 #endif
3315         page->addLayoutMilestones(milestones);
3316     }
3317 }
3318
3319 - (void)_cacheScriptDebugDelegateImplementations
3320 {
3321     WebScriptDebugDelegateImplementationCache *cache = &_private->scriptDebugDelegateImplementations;
3322     id delegate = _private->scriptDebugDelegate;
3323
3324     if (!delegate) {
3325         bzero(cache, sizeof(WebScriptDebugDelegateImplementationCache));
3326         return;
3327     }
3328
3329     cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:baseLineNumber:fromURL:sourceId:forWebFrame:));
3330     if (cache->didParseSourceFunc)
3331         cache->didParseSourceExpectsBaseLineNumber = YES;
3332     else {
3333         cache->didParseSourceExpectsBaseLineNumber = NO;
3334         cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:fromURL:sourceId:forWebFrame:));
3335     }
3336
3337     cache->failedToParseSourceFunc = getMethod(delegate, @selector(webView:failedToParseSource:baseLineNumber:fromURL:withError:forWebFrame:));
3338
3339     cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:hasHandler:sourceId:line:forWebFrame:));
3340     if (cache->exceptionWasRaisedFunc)
3341         cache->exceptionWasRaisedExpectsHasHandlerFlag = YES;
3342     else {
3343         cache->exceptionWasRaisedExpectsHasHandlerFlag = NO;
3344         cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:sourceId:line:forWebFrame:));
3345     }
3346 }
3347
3348 - (void)_cacheHistoryDelegateImplementations
3349 {
3350     WebHistoryDelegateImplementationCache *cache = &_private->historyDelegateImplementations;
3351     id delegate = _private->historyDelegate;
3352
3353     if (!delegate) {
3354         bzero(cache, sizeof(WebHistoryDelegateImplementationCache));
3355         return;
3356     }
3357
3358     cache->navigatedFunc = getMethod(delegate, @selector(webView:didNavigateWithNavigationData:inFrame:));
3359     cache->clientRedirectFunc = getMethod(delegate, @selector(webView:didPerformClientRedirectFromURL:toURL:inFrame:));
3360     cache->serverRedirectFunc = getMethod(delegate, @selector(webView:didPerformServerRedirectFromURL:toURL:inFrame:));
3361 IGNORE_WARNINGS_BEGIN("undeclared-selector")
3362     cache->deprecatedSetTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:));
3363 IGNORE_WARNINGS_END
3364     cache->setTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:inFrame:));
3365     cache->populateVisitedLinksFunc = getMethod(delegate, @selector(populateVisitedLinksForWebView:));
3366 }
3367
3368 - (id)_policyDelegateForwarder
3369 {
3370 #if PLATFORM(IOS_FAMILY)
3371     if (_private->closing)
3372         return nil;
3373 #endif
3374     if (!_private->policyDelegateForwarder)
3375         _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->policyDelegate defaultTarget:[WebDefaultPolicyDelegate sharedPolicyDelegate]];
3376     return _private->policyDelegateForwarder;
3377 }
3378
3379 - (id)_UIDelegateForwarder
3380 {
3381 #if PLATFORM(IOS_FAMILY)
3382     if (_private->closing)
3383         return nil;
3384 #endif
3385     if (!_private->UIDelegateForwarder)
3386         _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIDelegate defaultTarget:[WebDefaultUIDelegate sharedUIDelegate]];
3387     return _private->UIDelegateForwarder;
3388 }
3389
3390 #if PLATFORM(IOS_FAMILY)
3391 - (id)_UIDelegateForSelector:(SEL)selector
3392 {
3393     id delegate = self->_private->UIDelegate;
3394     if ([delegate respondsToSelector:selector])
3395         return delegate;
3396
3397     delegate = [WebDefaultUIDelegate sharedUIDelegate];
3398     if ([delegate respondsToSelector:selector])
3399         return delegate;
3400
3401     return nil;
3402 }
3403 #endif
3404
3405 - (id)_editingDelegateForwarder
3406 {
3407 #if PLATFORM(IOS_FAMILY)
3408     if (_private->closing)
3409         return nil;
3410 #endif    
3411     // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
3412     // Not sure if that is a bug or not.
3413     if (!_private)
3414         return nil;
3415
3416     if (!_private->editingDelegateForwarder)
3417         _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->editingDelegate defaultTarget:[WebDefaultEditingDelegate sharedEditingDelegate]];
3418     return _private->editingDelegateForwarder;
3419 }
3420
3421 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType
3422 {
3423     [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
3424     [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
3425     
3426     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
3427     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
3428     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
3429     MIMETypeRegistry::supportedNonImageMIMETypes().remove(MIMEType);
3430 }
3431
3432 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme
3433 {
3434     NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
3435     [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
3436
3437     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
3438     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
3439     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
3440     if ([viewClass class] == [WebHTMLView class])
3441         MIMETypeRegistry::supportedNonImageMIMETypes().add(MIMEType);
3442     
3443     // This is used to make _representationExistsForURLScheme faster.
3444     // Without this set, we'd have to create the MIME type each time.
3445     if (schemesWithRepresentationsSet == nil) {
3446         schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
3447     }
3448     [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
3449 }
3450
3451 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
3452 {
3453     return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
3454 }
3455
3456 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
3457 {
3458     return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
3459 }
3460
3461 + (BOOL)_canHandleRequest:(NSURLRequest *)request forMainFrame:(BOOL)forMainFrame
3462 {
3463     // FIXME: If <rdar://problem/5217309> gets fixed, this check can be removed.
3464     if (!request)
3465         return NO;
3466
3467     if ([NSURLConnection canHandleRequest:request])
3468         return YES;
3469
3470     NSString *scheme = [[request URL] scheme];
3471
3472     // Representations for URL schemes work at the top level.
3473     if (forMainFrame && [self _representationExistsForURLScheme:scheme])
3474         return YES;
3475
3476     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"applewebdata"])
3477         return YES;
3478
3479     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"blob"])
3480         return YES;
3481
3482     return NO;
3483 }
3484
3485 + (BOOL)_canHandleRequest:(NSURLRequest *)request
3486 {
3487     return [self _canHandleRequest:request forMainFrame:YES];
3488 }
3489
3490 + (NSString *)_decodeData:(NSData *)data
3491 {
3492     HTMLNames::init(); // this method is used for importing bookmarks at startup, so HTMLNames are likely to be uninitialized yet
3493     return TextResourceDecoder::create("text/html")->decodeAndFlush(static_cast<const char*>([data bytes]), [data length]); // bookmark files are HTML
3494 }
3495
3496 - (void)_pushPerformingProgrammaticFocus
3497 {
3498     _private->programmaticFocusCount++;
3499 }
3500
3501 - (void)_popPerformingProgrammaticFocus
3502 {
3503     _private->programmaticFocusCount--;
3504 }
3505
3506 - (BOOL)_isPerformingProgrammaticFocus
3507 {
3508     return _private->programmaticFocusCount != 0;
3509 }
3510
3511 #if !PLATFORM(IOS_FAMILY)
3512 - (void)_didChangeValueForKey: (NSString *)key
3513 {
3514     LOG (Bindings, "calling didChangeValueForKey: %@", key);
3515     [self didChangeValueForKey: key];
3516 }
3517
3518 - (void)_willChangeValueForKey: (NSString *)key
3519 {
3520     LOG (Bindings, "calling willChangeValueForKey: %@", key);
3521     [self willChangeValueForKey: key];
3522 }
3523
3524 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
3525     static NSSet *manualNotifyKeys = nil;
3526     if (!manualNotifyKeys)
3527         manualNotifyKeys = [[NSSet alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
3528             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey,
3529             nil];
3530     if ([manualNotifyKeys containsObject:key])
3531         return NO;
3532     return YES;
3533 }
3534
3535 - (NSArray *)_declaredKeys {
3536     static NSArray *declaredKeys = nil;
3537     if (!declaredKeys)
3538         declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
3539             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
3540     return declaredKeys;
3541 }
3542
3543 - (void)_willChangeBackForwardKeys
3544 {
3545     [self _willChangeValueForKey: _WebCanGoBackKey];
3546     [self _willChangeValueForKey: _WebCanGoForwardKey];
3547 }
3548
3549 - (void)_didChangeBackForwardKeys
3550 {
3551     [self _didChangeValueForKey: _WebCanGoBackKey];
3552     [self _didChangeValueForKey: _WebCanGoForwardKey];
3553 }
3554
3555 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
3556 {
3557     if (needsSelfRetainWhileLoadingQuirk())
3558         [self retain];
3559
3560     [self _willChangeBackForwardKeys];
3561     if (frame == [self mainFrame]){
3562         // Force an observer update by sending a will/did.
3563         [self _willChangeValueForKey: _WebIsLoadingKey];
3564         [self _didChangeValueForKey: _WebIsLoadingKey];
3565
3566         [self _willChangeValueForKey: _WebMainFrameURLKey];
3567
3568         [self hideFormValidationMessage];
3569     }
3570
3571     [NSApp setWindowsNeedUpdate:YES];
3572
3573 #if ENABLE(FULLSCREEN_API)
3574     Document* document = core([frame DOMDocument]);
3575     if (Element* element = document ? document->webkitCurrentFullScreenElement() : 0) {
3576         SEL selector = @selector(webView:closeFullScreenWithListener:);
3577         if ([_private->UIDelegate respondsToSelector:selector]) {
3578             WebKitFullScreenListener *listener = [[WebKitFullScreenListener alloc] initWithElement:element];
3579             CallUIDelegate(self, selector, listener);
3580             [listener release];
3581         } else if (_private->newFullscreenController && [_private->newFullscreenController isFullScreen]) {
3582             [_private->newFullscreenController close];
3583         }
3584     }
3585 #endif
3586 }
3587
3588 - (void)_checkDidPerformFirstNavigation
3589 {
3590     if (_private->_didPerformFirstNavigation)
3591         return;
3592
3593     Page* page = _private->page;
3594     if (!page)
3595         return;
3596
3597     auto& backForwardController = page->backForward();
3598
3599     if (!backForwardController.backItem())
3600         return;
3601
3602     _private->_didPerformFirstNavigation = YES;
3603
3604     if (_private->preferences.automaticallyDetectsCacheModel && _private->preferences.cacheModel < WebCacheModelDocumentBrowser)
3605         _private->preferences.cacheModel = WebCacheModelDocumentBrowser;
3606 }
3607
3608 - (void)_didCommitLoadForFrame:(WebFrame *)frame
3609 {
3610     if (frame == [self mainFrame])
3611         [self _didChangeValueForKey: _WebMainFrameURLKey];
3612
3613     [self _checkDidPerformFirstNavigation];
3614
3615     [NSApp setWindowsNeedUpdate:YES];
3616 }
3617
3618 - (void)_didFinishLoadForFrame:(WebFrame *)frame
3619 {
3620     if (needsSelfRetainWhileLoadingQuirk())
3621         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3622         
3623     [self _didChangeBackForwardKeys];
3624     if (frame == [self mainFrame]){
3625         // Force an observer update by sending a will/did.
3626         [self _willChangeValueForKey: _WebIsLoadingKey];
3627         [self _didChangeValueForKey: _WebIsLoadingKey];
3628     }
3629     [NSApp setWindowsNeedUpdate:YES];
3630 }
3631
3632 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
3633 {
3634     if (needsSelfRetainWhileLoadingQuirk())
3635         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3636
3637     [self _didChangeBackForwardKeys];
3638     if (frame == [self mainFrame]){
3639         // Force an observer update by sending a will/did.
3640         [self _willChangeValueForKey: _WebIsLoadingKey];
3641         [self _didChangeValueForKey: _WebIsLoadingKey];
3642     }
3643     [NSApp setWindowsNeedUpdate:YES];
3644 }
3645
3646 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
3647 {
3648     if (needsSelfRetainWhileLoadingQuirk())
3649         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3650
3651     [self _didChangeBackForwardKeys];
3652     if (frame == [self mainFrame]){
3653         // Force an observer update by sending a will/did.
3654         [self _willChangeValueForKey: _WebIsLoadingKey];
3655         [self _didChangeValueForKey: _WebIsLoadingKey];
3656         
3657         [self _didChangeValueForKey: _WebMainFrameURLKey];
3658     }
3659     [NSApp setWindowsNeedUpdate:YES];
3660 }
3661
3662 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
3663 {
3664     RetainPtr<NSMutableURLRequest> request = adoptNS([[NSMutableURLRequest alloc] initWithURL:URL]);
3665     [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
3666     NSCachedURLResponse *cachedResponse;
3667
3668     if (!_private->page)
3669         return nil;
3670
3671     if (auto storageSession = _private->page->mainFrame().loader().networkingContext()->storageSession()->platformSession())
3672         cachedResponse = cachedResponseForRequest(storageSession, request.get());
3673     else
3674         cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request.get()];
3675
3676     return cachedResponse;
3677 }
3678
3679 - (void)_writeImageForElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
3680 {
3681     NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
3682     DOMElement *domElement = [element objectForKey:WebElementDOMNodeKey];
3683     [pasteboard _web_writeImage:(NSImage *)(domElement ? nil : [element objectForKey:WebElementImageKey])
3684                         element:domElement
3685                             URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
3686                           title:[element objectForKey:WebElementImageAltStringKey] 
3687                         archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
3688                           types:types
3689                          source:nil];
3690 }
3691
3692 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
3693 {
3694     [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
3695                      andTitle:[element objectForKey:WebElementLinkLabelKey]
3696                         types:types];
3697 }
3698
3699 #if ENABLE(DRAG_SUPPORT)
3700 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
3701 {
3702     if (!_private->page)
3703         return;
3704     _private->page->dragController().setDidInitiateDrag(initiatedDrag);
3705 }
3706 #endif
3707
3708 #else
3709
3710 - (void)_didCommitLoadForFrame:(WebFrame *)frame
3711 {
3712     if (frame == [self mainFrame])
3713         _private->didDrawTiles = 0;
3714 }
3715
3716 #endif // PLATFORM(IOS_FAMILY)
3717
3718 #if ENABLE(DASHBOARD_SUPPORT)
3719
3720 #define DASHBOARD_CONTROL_LABEL @"control"
3721
3722 - (void)_addControlRect:(NSRect)bounds clip:(NSRect)clip fromView:(NSView *)view toDashboardRegions:(NSMutableDictionary *)regions
3723 {
3724     NSRect adjustedBounds = bounds;
3725     adjustedBounds.origin = [self convertPoint:bounds.origin fromView:view];
3726     adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
3727     adjustedBounds.size = bounds.size;
3728
3729     NSRect adjustedClip;
3730     adjustedClip.origin = [self convertPoint:clip.origin fromView:view];
3731     adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
3732     adjustedClip.size = clip.size;
3733
3734     WebDashboardRegion *region = [[WebDashboardRegion alloc] initWithRect:adjustedBounds 
3735         clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle];
3736     NSMutableArray *scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
3737     if (!scrollerRegions) {
3738         scrollerRegions = [[NSMutableArray alloc] init];
3739         [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
3740         [scrollerRegions release];
3741     }
3742     [scrollerRegions addObject:region];
3743     [region release];
3744 }
3745
3746 - (void)_addScrollerDashboardRegionsForFrameView:(FrameView*)frameView dashboardRegions:(NSMutableDictionary *)regions
3747 {    
3748     NSView *documentView = [[kit(&frameView->frame()) frameView] documentView];
3749
3750     for (const auto& widget: frameView->children()) {
3751         if (is<FrameView>(widget)) {
3752             [self _addScrollerDashboardRegionsForFrameView:&downcast<FrameView>(widget.get()) dashboardRegions:regions];
3753             continue;
3754         }
3755
3756         if (!widget->isScrollbar())
3757             continue;
3758
3759         // FIXME: This should really pass an appropriate clip, but our first try got it wrong, and
3760         // it's not common to need this to be correct in Dashboard widgets.
3761         NSRect bounds = widget->frameRect();
3762         [self _addControlRect:bounds clip:bounds fromView:documentView toDashboardRegions:regions];
3763     }
3764 }
3765
3766 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
3767 {
3768     // Add scroller regions for NSScroller and WebCore scrollbars
3769     NSUInteger count = [views count];
3770     for (NSUInteger i = 0; i < count; i++) {
3771         NSView *view = [views objectAtIndex:i];
3772         
3773         if ([view isKindOfClass:[WebHTMLView class]]) {
3774             if (Frame* coreFrame = core([(WebHTMLView*)view _frame])) {
3775                 if (FrameView* coreView = coreFrame->view())
3776                     [self _addScrollerDashboardRegionsForFrameView:coreView dashboardRegions:regions];
3777             }
3778         } else if ([view isKindOfClass:[NSScroller class]]) {
3779             // AppKit places absent scrollers at -100,-100
3780             if ([view frame].origin.y < 0)
3781                 continue;
3782             [self _addControlRect:[view bounds] clip:[view visibleRect] fromView:view toDashboardRegions:regions];
3783         }
3784         [self _addScrollerDashboardRegions:regions from:[view subviews]];
3785     }
3786 }
3787
3788 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
3789 {
3790     [self _addScrollerDashboardRegions:regions from:[self subviews]];
3791 }
3792
3793 - (NSDictionary *)_dashboardRegions
3794 {
3795     // Only return regions from main frame.
3796     Frame* mainFrame = [self _mainCoreFrame];
3797     if (!mainFrame)
3798         return nil;
3799
3800     const Vector<AnnotatedRegionValue>& regions = mainFrame->document()->annotatedRegions();
3801     size_t size = regions.size();
3802
3803     NSMutableDictionary *webRegions = [NSMutableDictionary dictionaryWithCapacity:size];
3804     for (size_t i = 0; i < size; i++) {
3805         const AnnotatedRegionValue& region = regions[i];
3806
3807         if (region.type == StyleDashboardRegion::None)
3808             continue;
3809
3810         NSString *label = region.label;
3811         WebDashboardRegionType type = WebDashboardRegionTypeNone;
3812         if (region.type == StyleDashboardRegion::Circle)
3813             type = WebDashboardRegionTypeCircle;
3814         else if (region.type == StyleDashboardRegion::Rectangle)
3815             type = WebDashboardRegionTypeRectangle;
3816         NSMutableArray *regionValues = [webRegions objectForKey:label];
3817         if (!regionValues) {
3818             regionValues = [[NSMutableArray alloc] initWithCapacity:1];
3819             [webRegions setObject:regionValues forKey:label];
3820             [regionValues release];
3821         }
3822
3823         WebDashboardRegion *webRegion = [[WebDashboardRegion alloc] initWithRect:snappedIntRect(region.bounds) clip:snappedIntRect(region.clip) type:type];
3824         [regionValues addObject:webRegion];
3825         [webRegion release];
3826     }
3827
3828     [self _addScrollerDashboardRegions:webRegions];
3829
3830     return webRegions;
3831 }
3832
3833 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag
3834 {
3835     // FIXME: Remove this blanket assignment once Dashboard and Dashcode implement 
3836     // specific support for the backward compatibility mode flag.
3837     if (behavior == WebDashboardBehaviorAllowWheelScrolling && flag == NO && _private->page)
3838         _private->page->settings().setUsesDashboardBackwardCompatibilityMode(true);
3839     
3840     switch (behavior) {
3841         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3842             _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
3843             break;
3844         }
3845         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3846             _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
3847             break;
3848         }
3849         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3850             _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
3851             break;
3852         }
3853         case WebDashboardBehaviorAllowWheelScrolling: {
3854             _private->dashboardBehaviorAllowWheelScrolling = flag;
3855             break;
3856         }
3857         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3858             if (_private->page)
3859                 _private->page->settings().setUsesDashboardBackwardCompatibilityMode(flag);
3860 #if ENABLE(LEGACY_CSS_VENDOR_PREFIXES)
3861             RuntimeEnabledFeatures::sharedFeatures().setLegacyCSSVendorPrefixesEnabled(flag);
3862 #endif
3863             break;
3864         }
3865     }
3866
3867     // Pre-HTML5 parser quirks should be enabled if Dashboard is in backward
3868     // compatibility mode. See <rdar://problem/8175982>.
3869     if (_private->page)
3870         _private->page->settings().setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
3871 }
3872
3873 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
3874 {
3875     switch (behavior) {
3876         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3877             return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
3878         }
3879         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3880             return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
3881         }
3882         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3883             return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
3884         }
3885         case WebDashboardBehaviorAllowWheelScrolling: {
3886             return _private->dashboardBehaviorAllowWheelScrolling;
3887         }
3888         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3889             return _private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode();
3890         }
3891     }
3892     return NO;
3893 }
3894
3895 #endif /* ENABLE(DASHBOARD_SUPPORT) */
3896
3897 + (void)_setShouldUseFontSmoothing:(BOOL)f
3898 {
3899     FontCascade::setShouldUseSmoothing(f);
3900 }
3901
3902 + (BOOL)_shouldUseFontSmoothing
3903 {
3904     return FontCascade::shouldUseSmoothing();
3905 }
3906
3907 #if !PLATFORM(IOS_FAMILY)
3908 + (void)_setUsesTestModeFocusRingColor:(BOOL)f
3909 {
3910     setUsesTestModeFocusRingColor(f);
3911 }
3912
3913 + (BOOL)_usesTestModeFocusRingColor
3914 {
3915     return usesTestModeFocusRingColor();
3916 }
3917 #endif
3918
3919 #if PLATFORM(IOS_FAMILY)
3920 - (void)_setUIKitDelegate:(id)delegate
3921 {
3922     _private->UIKitDelegate = delegate;
3923     [_private->UIKitDelegateForwarder clearTarget];
3924     [_private->UIKitDelegateForwarder release];
3925     _private->UIKitDelegateForwarder = nil;
3926 }
3927
3928 - (id)_UIKitDelegate
3929 {
3930     return _private->UIKitDelegate;
3931 }
3932
3933 - (void)setWebMailDelegate:(id)delegate
3934 {
3935     _private->WebMailDelegate = delegate;
3936 }
3937
3938 - (id)_webMailDelegate
3939 {
3940     return _private->WebMailDelegate;
3941 }
3942
3943 - (id <WebCaretChangeListener>)caretChangeListener
3944 {
3945     return _private->_caretChangeListener;
3946 }
3947
3948 - (void)setCaretChangeListener:(id <WebCaretChangeListener>)listener
3949 {
3950     _private->_caretChangeListener = listener;
3951 }
3952
3953 - (NSSet *)caretChangeListeners
3954 {
3955     return _private->_caretChangeListeners;
3956 }
3957
3958 - (void)addCaretChangeListener:(id <WebCaretChangeListener>)listener
3959 {
3960     if (_private->_caretChangeListeners == nil) {
3961         _private->_caretChangeListeners = [[NSMutableSet alloc] init];
3962     }
3963     
3964     [_private->_caretChangeListeners addObject:listener];
3965 }
3966
3967 - (void)removeCaretChangeListener:(id <WebCaretChangeListener>)listener
3968 {
3969     [_private->_caretChangeListeners removeObject:listener];
3970 }
3971
3972 - (void)removeAllCaretChangeListeners
3973 {
3974     [_private->_caretChangeListeners removeAllObjects];
3975 }
3976
3977 - (void)caretChanged
3978 {
3979     [_private->_caretChangeListener caretChanged];
3980     NSSet *copy = [_private->_caretChangeListeners copy];
3981     for (id <WebCaretChangeListener> listener in copy) {
3982         [listener caretChanged];
3983     }
3984     [copy release];
3985 }
3986
3987 - (void)_clearDelegates
3988 {
3989     ASSERT(WebThreadIsLocked() || !WebThreadIsEnabled());
3990     
3991     [self _setFormDelegate:nil];
3992     [self _setUIKitDelegate:nil];
3993     [self setCaretChangeListener:nil];
3994     [self removeAllCaretChangeListeners];
3995     [self setWebMailDelegate:nil];
3996     
3997     [self setDownloadDelegate:nil];
3998     [self setEditingDelegate:nil]; 
3999     [self setFrameLoadDelegate:nil];
4000     [self setPolicyDelegate:nil];
4001     [self setResourceLoadDelegate:nil];
4002     [self setScriptDebugDelegate:nil];
4003     [self setUIDelegate:nil];     
4004 }
4005
4006 - (NSURL *)_displayURL
4007 {
4008     WebThreadLock();
4009     WebFrame *frame = [self mainFrame];
4010     // FIXME: <rdar://problem/6362369> We used to get provisionalDataSource here if in provisional state; how do we tell that now? Is this right?
4011     WebDataSource *dataSource = [frame provisionalDataSource];
4012     if (!dataSource)
4013         dataSource = [frame dataSource];
4014     NSURL *unreachableURL = [dataSource unreachableURL];
4015     NSURL *URL = unreachableURL != nil ? unreachableURL : [[dataSource request] URL];
4016     [[URL retain] autorelease];
4017     return URL;
4018 }
4019 #endif // PLATFORM(IOS_FAMILY)
4020
4021 #if !PLATFORM(IOS_FAMILY)
4022 - (void)setAlwaysShowVerticalScroller:(BOOL)flag
4023 {
4024     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
4025     if (flag) {
4026         [scrollview setVerticalScrollingMode:ScrollbarAlwaysOn andLock:YES];
4027     } else {
4028         [scrollview setVerticalScrollingModeLocked:NO];
4029         [scrollview setVerticalScrollingMode:ScrollbarAuto andLock:NO];
4030     }
4031 }
4032
4033 - (BOOL)alwaysShowVerticalScroller
4034 {
4035     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
4036     return [scrollview verticalScrollingModeLocked] && [scrollview verticalScrollingMode] == ScrollbarAlwaysOn;
4037 }
4038
4039 - (void)setAlwaysShowHorizontalScroller:(BOOL)flag
4040 {
4041     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
4042     if (flag) {
4043         [scrollview setHorizontalScrollingMode:ScrollbarAlwaysOn andLock:YES];
4044     } else {
4045         [scrollview setHorizontalScrollingModeLocked:NO];
4046         [scrollview setHorizontalScrollingMode:ScrollbarAuto andLock:NO];
4047     }
4048 }
4049
4050 - (void)setProhibitsMainFrameScrolling:(BOOL)prohibits
4051 {
4052     if (Frame* mainFrame = [self _mainCoreFrame])
4053         mainFrame->view()->setProhibitsScrolling(prohibits);
4054 }
4055
4056 - (BOOL)alwaysShowHorizontalScroller
4057 {
4058     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
4059     return [scrollview horizontalScrollingModeLocked] && [scrollview horizontalScrollingMode] == ScrollbarAlwaysOn;
4060 }
4061 #endif // !PLATFORM(IOS_FAMILY)
4062
4063 - (void)_setUseFastImageScalingMode:(BOOL)flag
4064 {
4065     if (_private->page && _private->page->inLowQualityImageInterpolationMode() != flag) {
4066         _private->page->setInLowQualityImageInterpolationMode(flag);
4067         [self setNeedsDisplay:YES];
4068     }
4069 }
4070
4071 - (BOOL)_inFastImageScalingMode
4072 {
4073     if (_private->page)
4074         return _private->page->inLowQualityImageInterpolationMode();
4075     return NO;
4076 }
4077
4078 - (BOOL)_cookieEnabled
4079 {
4080     if (_private->page)
4081         return _private->page->settings().cookieEnabled();
4082     return YES;
4083 }
4084
4085 - (void)_setCookieEnabled:(BOOL)enable
4086 {
4087     if (_private->page)
4088         _private->page->settings().setCookieEnabled(enable);
4089 }
4090
4091 #if !PLATFORM(IOS_FAMILY)
4092 - (void)_setAdditionalWebPlugInPaths:(NSArray *)newPaths
4093 {
4094     if (!_private->pluginDatabase)
4095         _private->pluginDatabase = [[WebPluginDatabase alloc] init];
4096         
4097     [_private->pluginDatabase setPlugInPaths:newPaths];
4098     [_private->pluginDatabase refresh];
4099 }
4100 #endif
4101
4102 #if PLATFORM(IOS_FAMILY)
4103 - (BOOL)_locked_plugInsAreRunningInFrame:(WebFrame *)frame
4104 {
4105     // Ask plug-ins in this frame
4106     id <WebDocumentView> documentView = [[frame frameView] documentView];
4107     if (documentView && [documentView isKindOfClass:[WebHTMLView class]]) {
4108         if ([[(WebHTMLView *)documentView _pluginController] plugInsAreRunning])
4109             return YES;
4110     }
4111
4112     // Ask plug-ins in child frames
4113     NSArray *childFrames = [frame childFrames];
4114     unsigned childCount = [childFrames count];
4115     unsigned childIndex;
4116     for (childIndex = 0; childIndex < childCount; childIndex++) {
4117         if ([self _locked_plugInsAreRunningInFrame:[childFrames objectAtIndex:childIndex]])
4118             return YES;
4119     }
4120     
4121     return NO;
4122 }
4123
4124 - (BOOL)_pluginsAreRunning
4125 {
4126     WebThreadLock();
4127     return [self _locked_plugInsAreRunningInFrame:[self mainFrame]];
4128 }
4129
4130 - (void)_locked_recursivelyPerformPlugInSelector:(SEL)selector inFrame:(WebFrame *)frame
4131 {
4132     // Send the message to plug-ins in this frame
4133     id <WebDocumentView> documentView = [[frame frameView] documentView];
4134     if (documentView && [documentView isKindOfClass:[WebHTMLView class]])
4135         [[(WebHTMLView *)documentView _pluginController] performSelector:selector];
4136
4137     // Send the message to plug-ins in child frames
4138     NSArray *childFrames = [frame childFrames];
4139     unsigned childCount = [childFrames count];
4140     unsigned childIndex;
4141     for (childIndex = 0; childIndex < childCount; childIndex++) {
4142         [self _locked_recursivelyPerformPlugInSelector:selector inFrame:[childFrames objectAtIndex:childIndex]];
4143     }
4144 }
4145
4146 - (void)_destroyAllPlugIns
4147 {
4148     WebThreadLock();
4149     [self _locked_recursivelyPerformPlugInSelector:@selector(destroyAllPlugins) inFrame:[self mainFrame]];
4150 }
4151
4152 - (void)_startAllPlugIns
4153 {
4154     WebThreadLock();
4155     [self _locked_recursivelyPerformPlugInSelector:@selector(startAllPlugins) inFrame:[self mainFrame]];
4156 }
4157
4158 - (void)_stopAllPlugIns
4159 {
4160     WebThreadLock();
4161     [self _locked_recursivelyPerformPlugInSelector:@selector(stopAllPlugins) inFrame:[self mainFrame]];
4162 }
4163
4164 - (void)_stopAllPlugInsForPageCache
4165 {
4166     WebThreadLock();
4167     [self _locked_recursivelyPerformPlugInSelector:@selector(stopPluginsForPageCache) inFrame:[self mainFrame]];
4168 }
4169
4170 - (void)_restorePlugInsFromCache
4171 {
4172     WebThreadLock();
4173     [self _locked_recursivelyPerformPlugInSelector:@selector(restorePluginsFromCache) inFrame:[self mainFrame]];
4174 }
4175
4176 - (BOOL)_setMediaLayer:(CALayer*)layer forPluginView:(NSView*)pluginView
4177 {