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