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