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