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