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