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