[MediaStream] restrict media capture secure connections
[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     settings.setVisualViewportEnabled([preferences visualViewportEnabled]);
2414
2415     switch ([preferences storageBlockingPolicy]) {
2416     case WebAllowAllStorage:
2417         settings.setStorageBlockingPolicy(SecurityOrigin::AllowAllStorage);
2418         break;
2419     case WebBlockThirdPartyStorage:
2420         settings.setStorageBlockingPolicy(SecurityOrigin::BlockThirdPartyStorage);
2421         break;
2422     case WebBlockAllStorage:
2423         settings.setStorageBlockingPolicy(SecurityOrigin::BlockAllStorage);
2424         break;
2425     }
2426
2427     settings.setPlugInSnapshottingEnabled([preferences plugInSnapshottingEnabled]);
2428     settings.setHttpEquivEnabled([preferences httpEquivEnabled]);
2429
2430     settings.setFixedPositionCreatesStackingContext(true);
2431 #if PLATFORM(MAC)
2432     settings.setAcceleratedCompositingForFixedPositionEnabled(true);
2433 #endif
2434
2435 #if ENABLE(RUBBER_BANDING)
2436     // FIXME: https://bugs.webkit.org/show_bug.cgi?id=136131
2437     settings.setRubberBandingForSubScrollableRegionsEnabled(false);
2438 #endif
2439
2440 #if ENABLE(WIRELESS_PLAYBACK_TARGET)
2441     settings.setAllowsAirPlayForMediaPlayback([preferences allowsAirPlayForMediaPlayback]);
2442 #endif
2443 #if PLATFORM(IOS)
2444     settings.setStandalone([preferences _standalone]);
2445     settings.setTelephoneNumberParsingEnabled([preferences _telephoneNumberParsingEnabled]);
2446     settings.setAllowMultiElementImplicitSubmission([preferences _allowMultiElementImplicitFormSubmission]);
2447     settings.setLayoutInterval(std::chrono::milliseconds([preferences _layoutInterval]));
2448     settings.setMaxParseDuration([preferences _maxParseDuration]);
2449     settings.setAlwaysUseAcceleratedOverflowScroll([preferences _alwaysUseAcceleratedOverflowScroll]);
2450     settings.setAudioSessionCategoryOverride([preferences audioSessionCategoryOverride]);
2451     settings.setNetworkDataUsageTrackingEnabled([preferences networkDataUsageTrackingEnabled]);
2452     settings.setNetworkInterfaceName([preferences networkInterfaceName]);
2453 #if HAVE(AVKIT)
2454     settings.setAVKitEnabled([preferences avKitEnabled]);
2455 #endif
2456     settings.setShouldTransformsAffectOverflow(shouldTransformsAffectOverflow());
2457     settings.setShouldDispatchJavaScriptWindowOnErrorEvents(shouldDispatchJavaScriptWindowOnErrorEvents());
2458
2459     settings.setPasswordEchoEnabled([preferences _allowPasswordEcho]);
2460     settings.setPasswordEchoDurationInSeconds([preferences _passwordEchoDuration]);
2461
2462     ASSERT_WITH_MESSAGE(settings.pageCacheSupportsPlugins(), "PageCacheSupportsPlugins should be enabled on iOS.");
2463     settings.setDelegatesPageScaling(true);
2464
2465 #if ENABLE(TEXT_AUTOSIZING)
2466     settings.setMinimumZoomFontSize([preferences _minimumZoomFontSize]);
2467     settings.setTextAutosizingEnabled([preferences _textAutosizingEnabled]);
2468 #endif
2469 #endif // PLATFORM(IOS)
2470
2471 #if PLATFORM(MAC)
2472     if ([preferences userStyleSheetEnabled]) {
2473         NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
2474         if ([location isEqualToString:@"apple-dashboard://stylesheet"])
2475             location = @"file:///System/Library/PrivateFrameworks/DashboardClient.framework/Resources/widget.css";
2476         settings.setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
2477     } else
2478         settings.setUserStyleSheetLocation([NSURL URLWithString:@""]);
2479
2480     settings.setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
2481     settings.setTreatsAnyTextCSSLinkAsStylesheet([self _needsLinkElementTextCSSQuirk]);
2482     settings.setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
2483     settings.setEnforceCSSMIMETypeInNoQuirksMode(!WKAppVersionCheckLessThan(@"com.apple.iWeb", -1, 2.1));
2484     settings.setNeedsIsLoadingInAPISenseQuirk([self _needsIsLoadingInAPISenseQuirk]);
2485     settings.setTextAreasAreResizable([preferences textAreasAreResizable]);
2486     settings.setExperimentalNotificationsEnabled([preferences experimentalNotificationsEnabled]);
2487     settings.setShowsURLsInToolTips([preferences showsURLsInToolTips]);
2488     settings.setShowsToolTipOverTruncatedText([preferences showsToolTipOverTruncatedText]);
2489     settings.setQTKitEnabled([preferences isQTKitEnabled]);
2490 #endif // PLATFORM(MAC)
2491
2492     DatabaseManager::singleton().setIsAvailable([preferences databasesEnabled]);
2493
2494 #if ENABLE(MEDIA_SOURCE)
2495     settings.setMediaSourceEnabled([preferences mediaSourceEnabled]);
2496 #endif
2497
2498 #if ENABLE(SERVICE_CONTROLS)
2499     settings.setImageControlsEnabled([preferences imageControlsEnabled]);
2500     settings.setServiceControlsEnabled([preferences serviceControlsEnabled]);
2501 #endif
2502
2503 #if ENABLE(VIDEO_TRACK)
2504     settings.setShouldDisplaySubtitles([preferences shouldDisplaySubtitles]);
2505     settings.setShouldDisplayCaptions([preferences shouldDisplayCaptions]);
2506     settings.setShouldDisplayTextDescriptions([preferences shouldDisplayTextDescriptions]);
2507 #endif
2508
2509 #if USE(AVFOUNDATION)
2510     settings.setAVFoundationEnabled([preferences isAVFoundationEnabled]);
2511     settings.setAVFoundationNSURLSessionEnabled([preferences isAVFoundationNSURLSessionEnabled]);
2512 #endif
2513
2514 #if ENABLE(MEDIA_STREAM)
2515     settings.setMockCaptureDevicesEnabled([preferences mockCaptureDevicesEnabled]);
2516     settings.setMediaCaptureRequiresSecureConnection([preferences mediaCaptureRequiresSecureConnection]);
2517 #endif
2518
2519 #if ENABLE(WEB_AUDIO)
2520     settings.setWebAudioEnabled([preferences webAudioEnabled]);
2521 #endif
2522
2523 #if ENABLE(FULLSCREEN_API)
2524     settings.setFullScreenEnabled([preferences fullScreenEnabled]);
2525 #endif
2526
2527     settings.setHiddenPageDOMTimerThrottlingEnabled([preferences hiddenPageDOMTimerThrottlingEnabled]);
2528
2529     settings.setHiddenPageCSSAnimationSuspensionEnabled([preferences hiddenPageCSSAnimationSuspensionEnabled]);
2530
2531     settings.setResourceLoadStatisticsEnabled([preferences resourceLoadStatisticsEnabled]);
2532
2533 #if ENABLE(GAMEPAD)
2534     RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled([preferences gamepadsEnabled]);
2535 #endif
2536
2537 #if ENABLE(INDEXED_DATABASE)
2538     RuntimeEnabledFeatures::sharedFeatures().setWebkitIndexedDBEnabled(true);
2539 #endif
2540
2541     RuntimeEnabledFeatures::sharedFeatures().setShadowDOMEnabled([preferences shadowDOMEnabled]);
2542
2543     RuntimeEnabledFeatures::sharedFeatures().setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
2544
2545     RuntimeEnabledFeatures::sharedFeatures().setDOMIteratorEnabled([preferences DOMIteratorEnabled]);
2546
2547     RuntimeEnabledFeatures::sharedFeatures().setModernMediaControlsEnabled([preferences modernMediaControlsEnabled]);
2548
2549 #if ENABLE(CUSTOM_ELEMENTS)
2550     RuntimeEnabledFeatures::sharedFeatures().setCustomElementsEnabled([preferences customElementsEnabled]);
2551 #endif
2552
2553 #if ENABLE(FETCH_API)
2554     RuntimeEnabledFeatures::sharedFeatures().setFetchAPIEnabled([preferences fetchAPIEnabled]);
2555 #endif
2556
2557 #if ENABLE(WEBGL2)
2558     RuntimeEnabledFeatures::sharedFeatures().setWebGL2Enabled([preferences webGL2Enabled]);
2559 #endif
2560
2561 #if ENABLE(DOWNLOAD_ATTRIBUTE)
2562     RuntimeEnabledFeatures::sharedFeatures().setDownloadAttributeEnabled([preferences downloadAttributeEnabled]);
2563 #endif
2564
2565 #if ENABLE(CSS_GRID_LAYOUT)
2566     RuntimeEnabledFeatures::sharedFeatures().setCSSGridLayoutEnabled([preferences isCSSGridLayoutEnabled]);
2567 #endif
2568
2569 #if ENABLE(WEB_ANIMATIONS)
2570     RuntimeEnabledFeatures::sharedFeatures().setWebAnimationsEnabled([preferences webAnimationsEnabled]);
2571 #endif
2572
2573     NSTimeInterval timeout = [preferences incrementalRenderingSuppressionTimeoutInSeconds];
2574     if (timeout > 0)
2575         settings.setIncrementalRenderingSuppressionTimeoutInSeconds(timeout);
2576
2577     // Application Cache Preferences are stored on the global cache storage manager, not in Settings.
2578     [WebApplicationCache setDefaultOriginQuota:[preferences applicationCacheDefaultOriginQuota]];
2579
2580     BOOL zoomsTextOnly = [preferences zoomsTextOnly];
2581     if (_private->zoomsTextOnly != zoomsTextOnly)
2582         [self _setZoomMultiplier:_private->zoomMultiplier isTextOnly:zoomsTextOnly];
2583
2584 #if PLATFORM(IOS)
2585     [[self window] setTileBordersVisible:[preferences showDebugBorders]];
2586     [[self window] setTilePaintCountsVisible:[preferences showRepaintCounter]];
2587     [[self window] setAcceleratedDrawingEnabled:[preferences acceleratedDrawingEnabled]];
2588     [WAKView _setInterpolationQuality:[preferences _interpolationQuality]];
2589 #endif
2590
2591 #if ENABLE(LEGACY_ENCRYPTED_MEDIA)
2592     settings.setMediaKeysStorageDirectory([preferences mediaKeysStorageDirectory]);
2593 #endif
2594
2595     settings.setMediaDataLoadsAutomatically([preferences mediaDataLoadsAutomatically]);
2596
2597 #if ENABLE(ATTACHMENT_ELEMENT)
2598     settings.setAttachmentElementEnabled([preferences attachmentElementEnabled]);
2599 #endif
2600
2601     settings.setAllowContentSecurityPolicySourceStarToMatchAnyProtocol(shouldAllowContentSecurityPolicySourceStarToMatchAnyProtocol());
2602
2603     settings.setAllowWindowOpenWithoutUserGesture(shouldAllowWindowOpenWithoutUserGesture());
2604
2605     settings.setShouldConvertInvalidURLsToBlank(shouldConvertInvalidURLsToBlank());
2606 }
2607
2608 static inline IMP getMethod(id o, SEL s)
2609 {
2610     return [o respondsToSelector:s] ? [o methodForSelector:s] : 0;
2611 }
2612
2613 #if PLATFORM(IOS)
2614 - (id)_UIKitDelegateForwarder
2615 {
2616     if (_private->closing)
2617         return nil;
2618         
2619     if (!_private->UIKitDelegateForwarder)
2620         _private->UIKitDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIKitDelegate defaultTarget:[WebDefaultUIKitDelegate sharedUIKitDelegate]];
2621     return _private->UIKitDelegateForwarder;
2622 }
2623 #endif
2624
2625 - (void)_cacheResourceLoadDelegateImplementations
2626 {
2627     WebResourceDelegateImplementationCache *cache = &_private->resourceLoadDelegateImplementations;
2628     id delegate = _private->resourceProgressDelegate;
2629
2630     if (!delegate) {
2631         bzero(cache, sizeof(WebResourceDelegateImplementationCache));
2632         return;
2633     }
2634
2635     cache->didFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFailLoadingWithError:fromDataSource:));
2636     cache->didFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webView:resource:didFinishLoadingFromDataSource:));
2637     cache->didLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
2638     cache->didReceiveAuthenticationChallengeFunc = getMethod(delegate, @selector(webView:resource:didReceiveAuthenticationChallenge:fromDataSource:));
2639 #if USE(PROTECTION_SPACE_AUTH_CALLBACK)
2640     cache->canAuthenticateAgainstProtectionSpaceFunc = getMethod(delegate, @selector(webView:resource:canAuthenticateAgainstProtectionSpace:forDataSource:));
2641 #endif
2642
2643 #if PLATFORM(IOS)
2644     cache->connectionPropertiesFunc = getMethod(delegate, @selector(webView:connectionPropertiesForResource:dataSource:));
2645     cache->webThreadDidFinishLoadingFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFinishLoadingFromDataSource:));
2646     cache->webThreadDidFailLoadingWithErrorFromDataSourceFunc = getMethod(delegate, @selector(webThreadWebView:resource:didFailLoadingWithError:fromDataSource:));
2647     cache->webThreadIdentifierForRequestFunc = getMethod(delegate, @selector(webThreadWebView:identifierForInitialRequest:fromDataSource:));
2648     cache->webThreadDidLoadResourceFromMemoryCacheFunc = getMethod(delegate, @selector(webThreadWebView:didLoadResourceFromMemoryCache:response:length:fromDataSource:));
2649     cache->webThreadWillSendRequestFunc = getMethod(delegate, @selector(webThreadWebView:resource:willSendRequest:redirectResponse:fromDataSource:));
2650     cache->webThreadDidReceiveResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveResponse:fromDataSource:));
2651     cache->webThreadDidReceiveContentLengthFunc = getMethod(delegate, @selector(webThreadWebView:resource:didReceiveContentLength:fromDataSource:));
2652     cache->webThreadWillCacheResponseFunc = getMethod(delegate, @selector(webThreadWebView:resource:willCacheResponse:fromDataSource:));
2653 #endif
2654
2655     cache->didReceiveContentLengthFunc = getMethod(delegate, @selector(webView:resource:didReceiveContentLength:fromDataSource:));
2656     cache->didReceiveResponseFunc = getMethod(delegate, @selector(webView:resource:didReceiveResponse:fromDataSource:));
2657     cache->identifierForRequestFunc = getMethod(delegate, @selector(webView:identifierForInitialRequest:fromDataSource:));
2658     cache->plugInFailedWithErrorFunc = getMethod(delegate, @selector(webView:plugInFailedWithError:dataSource:));
2659     cache->willCacheResponseFunc = getMethod(delegate, @selector(webView:resource:willCacheResponse:fromDataSource:));
2660     cache->willSendRequestFunc = getMethod(delegate, @selector(webView:resource:willSendRequest:redirectResponse:fromDataSource:));
2661     cache->shouldUseCredentialStorageFunc = getMethod(delegate, @selector(webView:resource:shouldUseCredentialStorageForDataSource:));
2662     cache->shouldPaintBrokenImageForURLFunc = getMethod(delegate, @selector(webView:shouldPaintBrokenImageForURL:));
2663 }
2664
2665 - (void)_cacheFrameLoadDelegateImplementations
2666 {
2667     WebFrameLoadDelegateImplementationCache *cache = &_private->frameLoadDelegateImplementations;
2668     id delegate = _private->frameLoadDelegate;
2669
2670     if (!delegate) {
2671         bzero(cache, sizeof(WebFrameLoadDelegateImplementationCache));
2672         return;
2673     }
2674
2675     cache->didCancelClientRedirectForFrameFunc = getMethod(delegate, @selector(webView:didCancelClientRedirectForFrame:));
2676     cache->didChangeLocationWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didChangeLocationWithinPageForFrame:));
2677     cache->didPushStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPushStateWithinPageForFrame:));
2678     cache->didReplaceStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didReplaceStateWithinPageForFrame:));
2679     cache->didPopStateWithinPageForFrameFunc = getMethod(delegate, @selector(webView:didPopStateWithinPageForFrame:));
2680 #if JSC_OBJC_API_ENABLED
2681     cache->didCreateJavaScriptContextForFrameFunc = getMethod(delegate, @selector(webView:didCreateJavaScriptContext:forFrame:));
2682 #endif
2683     cache->didClearWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearWindowObject:forFrame:));
2684     cache->didClearWindowObjectForFrameInScriptWorldFunc = getMethod(delegate, @selector(webView:didClearWindowObjectForFrame:inScriptWorld:));
2685     cache->didClearInspectorWindowObjectForFrameFunc = getMethod(delegate, @selector(webView:didClearInspectorWindowObject:forFrame:));
2686     cache->didCommitLoadForFrameFunc = getMethod(delegate, @selector(webView:didCommitLoadForFrame:));
2687     cache->didFailLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailLoadWithError:forFrame:));
2688     cache->didFailProvisionalLoadWithErrorForFrameFunc = getMethod(delegate, @selector(webView:didFailProvisionalLoadWithError:forFrame:));
2689     cache->didFinishDocumentLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishDocumentLoadForFrame:));
2690     cache->didFinishLoadForFrameFunc = getMethod(delegate, @selector(webView:didFinishLoadForFrame:));
2691     cache->didFirstLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstLayoutInFrame:));
2692     cache->didFirstVisuallyNonEmptyLayoutInFrameFunc = getMethod(delegate, @selector(webView:didFirstVisuallyNonEmptyLayoutInFrame:));
2693     cache->didLayoutFunc = getMethod(delegate, @selector(webView:didLayout:));
2694     cache->didHandleOnloadEventsForFrameFunc = getMethod(delegate, @selector(webView:didHandleOnloadEventsForFrame:));
2695 #if ENABLE(ICONDATABASE)
2696     cache->didReceiveIconForFrameFunc = getMethod(delegate, @selector(webView:didReceiveIcon:forFrame:));
2697 #endif
2698     cache->didReceiveServerRedirectForProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didReceiveServerRedirectForProvisionalLoadForFrame:));
2699     cache->didReceiveTitleForFrameFunc = getMethod(delegate, @selector(webView:didReceiveTitle:forFrame:));
2700     cache->didStartProvisionalLoadForFrameFunc = getMethod(delegate, @selector(webView:didStartProvisionalLoadForFrame:));
2701     cache->willCloseFrameFunc = getMethod(delegate, @selector(webView:willCloseFrame:));
2702     cache->willPerformClientRedirectToURLDelayFireDateForFrameFunc = getMethod(delegate, @selector(webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:));
2703     cache->windowScriptObjectAvailableFunc = getMethod(delegate, @selector(webView:windowScriptObjectAvailable:));
2704     cache->didDisplayInsecureContentFunc = getMethod(delegate, @selector(webViewDidDisplayInsecureContent:));
2705     cache->didRunInsecureContentFunc = getMethod(delegate, @selector(webView:didRunInsecureContent:));
2706     cache->didDetectXSSFunc = getMethod(delegate, @selector(webView:didDetectXSS:));
2707     cache->didRemoveFrameFromHierarchyFunc = getMethod(delegate, @selector(webView:didRemoveFrameFromHierarchy:));
2708 #if PLATFORM(IOS)
2709     cache->webThreadDidLayoutFunc = getMethod(delegate, @selector(webThreadWebView:didLayout:));
2710 #endif
2711
2712     // It would be nice to get rid of this code and transition all clients to using didLayout instead of
2713     // didFirstLayoutInFrame and didFirstVisuallyNonEmptyLayoutInFrame. In the meantime, this is required
2714     // for backwards compatibility.
2715     Page* page = core(self);
2716     if (page) {
2717         unsigned milestones = DidFirstLayout;
2718 #if PLATFORM(IOS)
2719         milestones |= DidFirstVisuallyNonEmptyLayout;
2720 #else
2721         if (cache->didFirstVisuallyNonEmptyLayoutInFrameFunc)
2722             milestones |= DidFirstVisuallyNonEmptyLayout;
2723 #endif
2724         page->addLayoutMilestones(static_cast<LayoutMilestones>(milestones));
2725     }
2726 }
2727
2728 - (void)_cacheScriptDebugDelegateImplementations
2729 {
2730     WebScriptDebugDelegateImplementationCache *cache = &_private->scriptDebugDelegateImplementations;
2731     id delegate = _private->scriptDebugDelegate;
2732
2733     if (!delegate) {
2734         bzero(cache, sizeof(WebScriptDebugDelegateImplementationCache));
2735         return;
2736     }
2737
2738     cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:baseLineNumber:fromURL:sourceId:forWebFrame:));
2739     if (cache->didParseSourceFunc)
2740         cache->didParseSourceExpectsBaseLineNumber = YES;
2741     else {
2742         cache->didParseSourceExpectsBaseLineNumber = NO;
2743         cache->didParseSourceFunc = getMethod(delegate, @selector(webView:didParseSource:fromURL:sourceId:forWebFrame:));
2744     }
2745
2746     cache->failedToParseSourceFunc = getMethod(delegate, @selector(webView:failedToParseSource:baseLineNumber:fromURL:withError:forWebFrame:));
2747
2748     cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:hasHandler:sourceId:line:forWebFrame:));
2749     if (cache->exceptionWasRaisedFunc)
2750         cache->exceptionWasRaisedExpectsHasHandlerFlag = YES;
2751     else {
2752         cache->exceptionWasRaisedExpectsHasHandlerFlag = NO;
2753         cache->exceptionWasRaisedFunc = getMethod(delegate, @selector(webView:exceptionWasRaised:sourceId:line:forWebFrame:));
2754     }
2755 }
2756
2757 - (void)_cacheHistoryDelegateImplementations
2758 {
2759     WebHistoryDelegateImplementationCache *cache = &_private->historyDelegateImplementations;
2760     id delegate = _private->historyDelegate;
2761
2762     if (!delegate) {
2763         bzero(cache, sizeof(WebHistoryDelegateImplementationCache));
2764         return;
2765     }
2766
2767     cache->navigatedFunc = getMethod(delegate, @selector(webView:didNavigateWithNavigationData:inFrame:));
2768     cache->clientRedirectFunc = getMethod(delegate, @selector(webView:didPerformClientRedirectFromURL:toURL:inFrame:));
2769     cache->serverRedirectFunc = getMethod(delegate, @selector(webView:didPerformServerRedirectFromURL:toURL:inFrame:));
2770     cache->deprecatedSetTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:));
2771     cache->setTitleFunc = getMethod(delegate, @selector(webView:updateHistoryTitle:forURL:inFrame:));
2772     cache->populateVisitedLinksFunc = getMethod(delegate, @selector(populateVisitedLinksForWebView:));
2773 }
2774
2775 - (id)_policyDelegateForwarder
2776 {
2777 #if PLATFORM(IOS)
2778     if (_private->closing)
2779         return nil;
2780 #endif
2781     if (!_private->policyDelegateForwarder)
2782         _private->policyDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->policyDelegate defaultTarget:[WebDefaultPolicyDelegate sharedPolicyDelegate]];
2783     return _private->policyDelegateForwarder;
2784 }
2785
2786 - (id)_UIDelegateForwarder
2787 {
2788 #if PLATFORM(IOS)
2789     if (_private->closing)
2790         return nil;
2791 #endif
2792     if (!_private->UIDelegateForwarder)
2793         _private->UIDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->UIDelegate defaultTarget:[WebDefaultUIDelegate sharedUIDelegate]];
2794     return _private->UIDelegateForwarder;
2795 }
2796
2797 #if PLATFORM(IOS)
2798 - (id)_UIDelegateForSelector:(SEL)selector
2799 {
2800     id delegate = self->_private->UIDelegate;
2801     if ([delegate respondsToSelector:selector])
2802         return delegate;
2803
2804     delegate = [WebDefaultUIDelegate sharedUIDelegate];
2805     if ([delegate respondsToSelector:selector])
2806         return delegate;
2807
2808     return nil;
2809 }
2810 #endif
2811
2812 - (id)_editingDelegateForwarder
2813 {
2814 #if PLATFORM(IOS)
2815     if (_private->closing)
2816         return nil;
2817 #endif    
2818     // This can be called during window deallocation by QTMovieView in the QuickTime Cocoa Plug-in.
2819     // Not sure if that is a bug or not.
2820     if (!_private)
2821         return nil;
2822
2823     if (!_private->editingDelegateForwarder)
2824         _private->editingDelegateForwarder = [[_WebSafeForwarder alloc] initWithTarget:_private->editingDelegate defaultTarget:[WebDefaultEditingDelegate sharedEditingDelegate]];
2825     return _private->editingDelegateForwarder;
2826 }
2827
2828 - (void)_closeWindow
2829 {
2830     [[self _UIDelegateForwarder] webViewClose:self];
2831 }
2832
2833 + (void)_unregisterViewClassAndRepresentationClassForMIMEType:(NSString *)MIMEType
2834 {
2835     [[WebFrameView _viewTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
2836     [[WebDataSource _repTypesAllowImageTypeOmission:NO] removeObjectForKey:MIMEType];
2837     
2838     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
2839     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
2840     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
2841     MIMETypeRegistry::getSupportedNonImageMIMETypes().remove(MIMEType);
2842 }
2843
2844 + (void)_registerViewClass:(Class)viewClass representationClass:(Class)representationClass forURLScheme:(NSString *)URLScheme
2845 {
2846     NSString *MIMEType = [self _generatedMIMETypeForURLScheme:URLScheme];
2847     [self registerViewClass:viewClass representationClass:representationClass forMIMEType:MIMEType];
2848
2849     // FIXME: We also need to maintain MIMEType registrations (which can be dynamically changed)
2850     // in the WebCore MIMEType registry.  For now we're doing this in a safe, limited manner
2851     // to fix <rdar://problem/5372989> - a future revamping of the entire system is neccesary for future robustness
2852     if ([viewClass class] == [WebHTMLView class])
2853         MIMETypeRegistry::getSupportedNonImageMIMETypes().add(MIMEType);
2854     
2855     // This is used to make _representationExistsForURLScheme faster.
2856     // Without this set, we'd have to create the MIME type each time.
2857     if (schemesWithRepresentationsSet == nil) {
2858         schemesWithRepresentationsSet = [[NSMutableSet alloc] init];
2859     }
2860     [schemesWithRepresentationsSet addObject:[[[URLScheme lowercaseString] copy] autorelease]];
2861 }
2862
2863 + (NSString *)_generatedMIMETypeForURLScheme:(NSString *)URLScheme
2864 {
2865     return [@"x-apple-web-kit/" stringByAppendingString:[URLScheme lowercaseString]];
2866 }
2867
2868 + (BOOL)_representationExistsForURLScheme:(NSString *)URLScheme
2869 {
2870     return [schemesWithRepresentationsSet containsObject:[URLScheme lowercaseString]];
2871 }
2872
2873 + (BOOL)_canHandleRequest:(NSURLRequest *)request forMainFrame:(BOOL)forMainFrame
2874 {
2875     // FIXME: If <rdar://problem/5217309> gets fixed, this check can be removed.
2876     if (!request)
2877         return NO;
2878
2879     if ([NSURLConnection canHandleRequest:request])
2880         return YES;
2881
2882     NSString *scheme = [[request URL] scheme];
2883
2884     // Representations for URL schemes work at the top level.
2885     if (forMainFrame && [self _representationExistsForURLScheme:scheme])
2886         return YES;
2887
2888     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"applewebdata"])
2889         return YES;
2890
2891     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"blob"])
2892         return YES;
2893
2894     return NO;
2895 }
2896
2897 + (BOOL)_canHandleRequest:(NSURLRequest *)request
2898 {
2899     return [self _canHandleRequest:request forMainFrame:YES];
2900 }
2901
2902 + (NSString *)_decodeData:(NSData *)data
2903 {
2904     HTMLNames::init(); // this method is used for importing bookmarks at startup, so HTMLNames are likely to be uninitialized yet
2905     return TextResourceDecoder::create("text/html")->decodeAndFlush(static_cast<const char*>([data bytes]), [data length]); // bookmark files are HTML
2906 }
2907
2908 - (void)_pushPerformingProgrammaticFocus
2909 {
2910     _private->programmaticFocusCount++;
2911 }
2912
2913 - (void)_popPerformingProgrammaticFocus
2914 {
2915     _private->programmaticFocusCount--;
2916 }
2917
2918 - (BOOL)_isPerformingProgrammaticFocus
2919 {
2920     return _private->programmaticFocusCount != 0;
2921 }
2922
2923 #if !PLATFORM(IOS)
2924 - (void)_didChangeValueForKey: (NSString *)key
2925 {
2926     LOG (Bindings, "calling didChangeValueForKey: %@", key);
2927     [self didChangeValueForKey: key];
2928 }
2929
2930 - (void)_willChangeValueForKey: (NSString *)key
2931 {
2932     LOG (Bindings, "calling willChangeValueForKey: %@", key);
2933     [self willChangeValueForKey: key];
2934 }
2935
2936 + (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
2937     static NSSet *manualNotifyKeys = nil;
2938     if (!manualNotifyKeys)
2939         manualNotifyKeys = [[NSSet alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
2940             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey,
2941             nil];
2942     if ([manualNotifyKeys containsObject:key])
2943         return NO;
2944     return YES;
2945 }
2946
2947 - (NSArray *)_declaredKeys {
2948     static NSArray *declaredKeys = nil;
2949     if (!declaredKeys)
2950         declaredKeys = [[NSArray alloc] initWithObjects:_WebMainFrameURLKey, _WebIsLoadingKey, _WebEstimatedProgressKey,
2951             _WebCanGoBackKey, _WebCanGoForwardKey, _WebMainFrameTitleKey, _WebMainFrameIconKey, _WebMainFrameDocumentKey, nil];
2952     return declaredKeys;
2953 }
2954
2955 - (void)_willChangeBackForwardKeys
2956 {
2957     [self _willChangeValueForKey: _WebCanGoBackKey];
2958     [self _willChangeValueForKey: _WebCanGoForwardKey];
2959 }
2960
2961 - (void)_didChangeBackForwardKeys
2962 {
2963     [self _didChangeValueForKey: _WebCanGoBackKey];
2964     [self _didChangeValueForKey: _WebCanGoForwardKey];
2965 }
2966
2967 - (void)_didStartProvisionalLoadForFrame:(WebFrame *)frame
2968 {
2969     if (needsSelfRetainWhileLoadingQuirk())
2970         [self retain];
2971
2972     [self _willChangeBackForwardKeys];
2973     if (frame == [self mainFrame]){
2974         // Force an observer update by sending a will/did.
2975         [self _willChangeValueForKey: _WebIsLoadingKey];
2976         [self _didChangeValueForKey: _WebIsLoadingKey];
2977
2978         [self _willChangeValueForKey: _WebMainFrameURLKey];
2979     }
2980
2981     [NSApp setWindowsNeedUpdate:YES];
2982
2983 #if ENABLE(FULLSCREEN_API)
2984     Document* document = core([frame DOMDocument]);
2985     if (Element* element = document ? document->webkitCurrentFullScreenElement() : 0) {
2986         SEL selector = @selector(webView:closeFullScreenWithListener:);
2987         if (_private->UIDelegate && [_private->UIDelegate respondsToSelector:selector]) {
2988             WebKitFullScreenListener *listener = [[WebKitFullScreenListener alloc] initWithElement:element];
2989             CallUIDelegate(self, selector, listener);
2990             [listener release];
2991         } else if (_private->newFullscreenController && [_private->newFullscreenController isFullScreen]) {
2992             [_private->newFullscreenController close];
2993         }
2994     }
2995 #endif
2996 }
2997
2998 - (void)_checkDidPerformFirstNavigation
2999 {
3000     if (_private->_didPerformFirstNavigation)
3001         return;
3002
3003     Page* page = _private->page;
3004     if (!page)
3005         return;
3006
3007     auto& backForwardController = page->backForward();
3008
3009     if (!backForwardController.backItem())
3010         return;
3011
3012     _private->_didPerformFirstNavigation = YES;
3013
3014     if (_private->preferences.automaticallyDetectsCacheModel && _private->preferences.cacheModel < WebCacheModelDocumentBrowser)
3015         _private->preferences.cacheModel = WebCacheModelDocumentBrowser;
3016 }
3017
3018 - (void)_didCommitLoadForFrame:(WebFrame *)frame
3019 {
3020     if (frame == [self mainFrame])
3021         [self _didChangeValueForKey: _WebMainFrameURLKey];
3022
3023     [self _checkDidPerformFirstNavigation];
3024
3025     [NSApp setWindowsNeedUpdate:YES];
3026 }
3027
3028 - (void)_didFinishLoadForFrame:(WebFrame *)frame
3029 {
3030     if (needsSelfRetainWhileLoadingQuirk())
3031         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3032         
3033     [self _didChangeBackForwardKeys];
3034     if (frame == [self mainFrame]){
3035         // Force an observer update by sending a will/did.
3036         [self _willChangeValueForKey: _WebIsLoadingKey];
3037         [self _didChangeValueForKey: _WebIsLoadingKey];
3038     }
3039     [NSApp setWindowsNeedUpdate:YES];
3040 }
3041
3042 - (void)_didFailLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
3043 {
3044     if (needsSelfRetainWhileLoadingQuirk())
3045         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3046
3047     [self _didChangeBackForwardKeys];
3048     if (frame == [self mainFrame]){
3049         // Force an observer update by sending a will/did.
3050         [self _willChangeValueForKey: _WebIsLoadingKey];
3051         [self _didChangeValueForKey: _WebIsLoadingKey];
3052     }
3053     [NSApp setWindowsNeedUpdate:YES];
3054 }
3055
3056 - (void)_didFailProvisionalLoadWithError:(NSError *)error forFrame:(WebFrame *)frame
3057 {
3058     if (needsSelfRetainWhileLoadingQuirk())
3059         [self performSelector:@selector(release) withObject:nil afterDelay:0];
3060
3061     [self _didChangeBackForwardKeys];
3062     if (frame == [self mainFrame]){
3063         // Force an observer update by sending a will/did.
3064         [self _willChangeValueForKey: _WebIsLoadingKey];
3065         [self _didChangeValueForKey: _WebIsLoadingKey];
3066         
3067         [self _didChangeValueForKey: _WebMainFrameURLKey];
3068     }
3069     [NSApp setWindowsNeedUpdate:YES];
3070 }
3071
3072 - (NSCachedURLResponse *)_cachedResponseForURL:(NSURL *)URL
3073 {
3074     RetainPtr<NSMutableURLRequest *> request = adoptNS([[NSMutableURLRequest alloc] initWithURL:URL]);
3075     [request _web_setHTTPUserAgent:[self userAgentForURL:URL]];
3076     NSCachedURLResponse *cachedResponse;
3077
3078     if (!_private->page)
3079         return nil;
3080
3081     if (CFURLStorageSessionRef storageSession = _private->page->mainFrame().loader().networkingContext()->storageSession().platformSession())
3082         cachedResponse = WKCachedResponseForRequest(storageSession, request.get());
3083     else
3084         cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request.get()];
3085
3086     return cachedResponse;
3087 }
3088
3089 - (void)_writeImageForElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
3090 {
3091     NSURL *linkURL = [element objectForKey:WebElementLinkURLKey];
3092     DOMElement *domElement = [element objectForKey:WebElementDOMNodeKey];
3093     [pasteboard _web_writeImage:(NSImage *)(domElement ? nil : [element objectForKey:WebElementImageKey])
3094                         element:domElement
3095                             URL:linkURL ? linkURL : (NSURL *)[element objectForKey:WebElementImageURLKey]
3096                           title:[element objectForKey:WebElementImageAltStringKey] 
3097                         archive:[[element objectForKey:WebElementDOMNodeKey] webArchive]
3098                           types:types
3099                          source:nil];
3100 }
3101
3102 - (void)_writeLinkElement:(NSDictionary *)element withPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
3103 {
3104     [pasteboard _web_writeURL:[element objectForKey:WebElementLinkURLKey]
3105                      andTitle:[element objectForKey:WebElementLinkLabelKey]
3106                         types:types];
3107 }
3108
3109 #if ENABLE(DRAG_SUPPORT)
3110 - (void)_setInitiatedDrag:(BOOL)initiatedDrag
3111 {
3112     if (!_private->page)
3113         return;
3114     _private->page->dragController().setDidInitiateDrag(initiatedDrag);
3115 }
3116 #endif
3117
3118 #else
3119
3120 - (void)_didCommitLoadForFrame:(WebFrame *)frame
3121 {
3122     if (frame == [self mainFrame])
3123         _private->didDrawTiles = 0;
3124 }
3125
3126 #endif // PLATFORM(IOS)
3127
3128 #if ENABLE(DASHBOARD_SUPPORT)
3129
3130 #define DASHBOARD_CONTROL_LABEL @"control"
3131
3132 - (void)_addControlRect:(NSRect)bounds clip:(NSRect)clip fromView:(NSView *)view toDashboardRegions:(NSMutableDictionary *)regions
3133 {
3134     NSRect adjustedBounds = bounds;
3135     adjustedBounds.origin = [self convertPoint:bounds.origin fromView:view];
3136     adjustedBounds.origin.y = [self bounds].size.height - adjustedBounds.origin.y;
3137     adjustedBounds.size = bounds.size;
3138
3139     NSRect adjustedClip;
3140     adjustedClip.origin = [self convertPoint:clip.origin fromView:view];
3141     adjustedClip.origin.y = [self bounds].size.height - adjustedClip.origin.y;
3142     adjustedClip.size = clip.size;
3143
3144     WebDashboardRegion *region = [[WebDashboardRegion alloc] initWithRect:adjustedBounds 
3145         clip:adjustedClip type:WebDashboardRegionTypeScrollerRectangle];
3146     NSMutableArray *scrollerRegions = [regions objectForKey:DASHBOARD_CONTROL_LABEL];
3147     if (!scrollerRegions) {
3148         scrollerRegions = [[NSMutableArray alloc] init];
3149         [regions setObject:scrollerRegions forKey:DASHBOARD_CONTROL_LABEL];
3150         [scrollerRegions release];
3151     }
3152     [scrollerRegions addObject:region];
3153     [region release];
3154 }
3155
3156 - (void)_addScrollerDashboardRegionsForFrameView:(FrameView*)frameView dashboardRegions:(NSMutableDictionary *)regions
3157 {    
3158     NSView *documentView = [[kit(&frameView->frame()) frameView] documentView];
3159
3160     for (const auto& widget: frameView->children()) {
3161         if (is<FrameView>(*widget)) {
3162             [self _addScrollerDashboardRegionsForFrameView:downcast<FrameView>(widget.get()) dashboardRegions:regions];
3163             continue;
3164         }
3165
3166         if (!widget->isScrollbar())
3167             continue;
3168
3169         // FIXME: This should really pass an appropriate clip, but our first try got it wrong, and
3170         // it's not common to need this to be correct in Dashboard widgets.
3171         NSRect bounds = widget->frameRect();
3172         [self _addControlRect:bounds clip:bounds fromView:documentView toDashboardRegions:regions];
3173     }
3174 }
3175
3176 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions from:(NSArray *)views
3177 {
3178     // Add scroller regions for NSScroller and WebCore scrollbars
3179     NSUInteger count = [views count];
3180     for (NSUInteger i = 0; i < count; i++) {
3181         NSView *view = [views objectAtIndex:i];
3182         
3183         if ([view isKindOfClass:[WebHTMLView class]]) {
3184             if (Frame* coreFrame = core([(WebHTMLView*)view _frame])) {
3185                 if (FrameView* coreView = coreFrame->view())
3186                     [self _addScrollerDashboardRegionsForFrameView:coreView dashboardRegions:regions];
3187             }
3188         } else if ([view isKindOfClass:[NSScroller class]]) {
3189             // AppKit places absent scrollers at -100,-100
3190             if ([view frame].origin.y < 0)
3191                 continue;
3192             [self _addControlRect:[view bounds] clip:[view visibleRect] fromView:view toDashboardRegions:regions];
3193         }
3194         [self _addScrollerDashboardRegions:regions from:[view subviews]];
3195     }
3196 }
3197
3198 - (void)_addScrollerDashboardRegions:(NSMutableDictionary *)regions
3199 {
3200     [self _addScrollerDashboardRegions:regions from:[self subviews]];
3201 }
3202
3203 - (NSDictionary *)_dashboardRegions
3204 {
3205     // Only return regions from main frame.
3206     Frame* mainFrame = [self _mainCoreFrame];
3207     if (!mainFrame)
3208         return nil;
3209
3210     const Vector<AnnotatedRegionValue>& regions = mainFrame->document()->annotatedRegions();
3211     size_t size = regions.size();
3212
3213     NSMutableDictionary *webRegions = [NSMutableDictionary dictionaryWithCapacity:size];
3214     for (size_t i = 0; i < size; i++) {
3215         const AnnotatedRegionValue& region = regions[i];
3216
3217         if (region.type == StyleDashboardRegion::None)
3218             continue;
3219
3220         NSString *label = region.label;
3221         WebDashboardRegionType type = WebDashboardRegionTypeNone;
3222         if (region.type == StyleDashboardRegion::Circle)
3223             type = WebDashboardRegionTypeCircle;
3224         else if (region.type == StyleDashboardRegion::Rectangle)
3225             type = WebDashboardRegionTypeRectangle;
3226         NSMutableArray *regionValues = [webRegions objectForKey:label];
3227         if (!regionValues) {
3228             regionValues = [[NSMutableArray alloc] initWithCapacity:1];
3229             [webRegions setObject:regionValues forKey:label];
3230             [regionValues release];
3231         }
3232
3233         WebDashboardRegion *webRegion = [[WebDashboardRegion alloc] initWithRect:snappedIntRect(region.bounds) clip:snappedIntRect(region.clip) type:type];
3234         [regionValues addObject:webRegion];
3235         [webRegion release];
3236     }
3237
3238     [self _addScrollerDashboardRegions:webRegions];
3239
3240     return webRegions;
3241 }
3242
3243 - (void)_setDashboardBehavior:(WebDashboardBehavior)behavior to:(BOOL)flag
3244 {
3245     // FIXME: Remove this blanket assignment once Dashboard and Dashcode implement 
3246     // specific support for the backward compatibility mode flag.
3247     if (behavior == WebDashboardBehaviorAllowWheelScrolling && flag == NO && _private->page)
3248         _private->page->settings().setUsesDashboardBackwardCompatibilityMode(true);
3249     
3250     switch (behavior) {
3251         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3252             _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows = flag;
3253             break;
3254         }
3255         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3256             _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns = flag;
3257             break;
3258         }
3259         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3260             _private->dashboardBehaviorAlwaysAcceptsFirstMouse = flag;
3261             break;
3262         }
3263         case WebDashboardBehaviorAllowWheelScrolling: {
3264             _private->dashboardBehaviorAllowWheelScrolling = flag;
3265             break;
3266         }
3267         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3268             if (_private->page)
3269                 _private->page->settings().setUsesDashboardBackwardCompatibilityMode(flag);
3270 #if ENABLE(LEGACY_CSS_VENDOR_PREFIXES)
3271             RuntimeEnabledFeatures::sharedFeatures().setLegacyCSSVendorPrefixesEnabled(flag);
3272 #endif
3273             break;
3274         }
3275     }
3276
3277     // Pre-HTML5 parser quirks should be enabled if Dashboard is in backward
3278     // compatibility mode. See <rdar://problem/8175982>.
3279     if (_private->page)
3280         _private->page->settings().setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
3281 }
3282
3283 - (BOOL)_dashboardBehavior:(WebDashboardBehavior)behavior
3284 {
3285     switch (behavior) {
3286         case WebDashboardBehaviorAlwaysSendMouseEventsToAllWindows: {
3287             return _private->dashboardBehaviorAlwaysSendMouseEventsToAllWindows;
3288         }
3289         case WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns: {
3290             return _private->dashboardBehaviorAlwaysSendActiveNullEventsToPlugIns;
3291         }
3292         case WebDashboardBehaviorAlwaysAcceptsFirstMouse: {
3293             return _private->dashboardBehaviorAlwaysAcceptsFirstMouse;
3294         }
3295         case WebDashboardBehaviorAllowWheelScrolling: {
3296             return _private->dashboardBehaviorAllowWheelScrolling;
3297         }
3298         case WebDashboardBehaviorUseBackwardCompatibilityMode: {
3299             return _private->page && _private->page->settings().usesDashboardBackwardCompatibilityMode();
3300         }
3301     }
3302     return NO;
3303 }
3304
3305 #endif /* ENABLE(DASHBOARD_SUPPORT) */
3306
3307 + (void)_setShouldUseFontSmoothing:(BOOL)f
3308 {
3309     FontCascade::setShouldUseSmoothing(f);
3310 }
3311
3312 + (BOOL)_shouldUseFontSmoothing
3313 {
3314     return FontCascade::shouldUseSmoothing();
3315 }
3316
3317 #if !PLATFORM(IOS)
3318 + (void)_setUsesTestModeFocusRingColor:(BOOL)f
3319 {
3320     setUsesTestModeFocusRingColor(f);
3321 }
3322
3323 + (BOOL)_usesTestModeFocusRingColor
3324 {
3325     return usesTestModeFocusRingColor();
3326 }
3327 #endif
3328
3329 #if PLATFORM(IOS)
3330 - (void)_setUIKitDelegate:(id)delegate
3331 {
3332     _private->UIKitDelegate = delegate;
3333     [_private->UIKitDelegateForwarder clearTarget];
3334     [_private->UIKitDelegateForwarder release];
3335     _private->UIKitDelegateForwarder = nil;
3336 }
3337
3338 - (id)_UIKitDelegate
3339 {
3340     return _private->UIKitDelegate;
3341 }
3342
3343 - (void)setWebMailDelegate:(id)delegate
3344 {
3345     _private->WebMailDelegate = delegate;
3346 }
3347
3348 - (id)_webMailDelegate
3349 {
3350     return _private->WebMailDelegate;
3351 }
3352
3353 - (id <WebCaretChangeListener>)caretChangeListener
3354 {
3355     return _private->_caretChangeListener;
3356 }
3357
3358 - (void)setCaretChangeListener:(id <WebCaretChangeListener>)listener
3359 {
3360     _private->_caretChangeListener = listener;
3361 }
3362
3363 - (NSSet *)caretChangeListeners
3364 {
3365     return _private->_caretChangeListeners;
3366 }
3367
3368 - (void)addCaretChangeListener:(id <WebCaretChangeListener>)listener
3369 {
3370     if (_private->_caretChangeListeners == nil) {
3371         _private->_caretChangeListeners = [[NSMutableSet alloc] init];
3372     }
3373     
3374     [_private->_caretChangeListeners addObject:listener];
3375 }
3376
3377 - (void)removeCaretChangeListener:(id <WebCaretChangeListener>)listener
3378 {
3379     [_private->_caretChangeListeners removeObject:listener];
3380 }
3381
3382 - (void)removeAllCaretChangeListeners
3383 {
3384     [_private->_caretChangeListeners removeAllObjects];
3385 }
3386
3387 - (void)caretChanged
3388 {
3389     [_private->_caretChangeListener caretChanged];
3390     NSSet *copy = [_private->_caretChangeListeners copy];
3391     for (id <WebCaretChangeListener> listener in copy) {
3392         [listener caretChanged];
3393     }
3394     [copy release];
3395 }
3396
3397 - (void)_clearDelegates
3398 {
3399     ASSERT(WebThreadIsLocked() || !WebThreadIsEnabled());
3400     
3401     [self _setFormDelegate:nil];
3402     [self _setUIKitDelegate:nil];
3403     [self setCaretChangeListener:nil];
3404     [self removeAllCaretChangeListeners];
3405     [self setWebMailDelegate:nil];
3406     
3407     [self setDownloadDelegate:nil];
3408     [self setEditingDelegate:nil]; 
3409     [self setFrameLoadDelegate:nil];
3410     [self setPolicyDelegate:nil];
3411     [self setResourceLoadDelegate:nil];
3412     [self setScriptDebugDelegate:nil];
3413     [self setUIDelegate:nil];     
3414 }
3415
3416 - (NSURL *)_displayURL
3417 {
3418     WebThreadLock();
3419     WebFrame *frame = [self mainFrame];
3420     // FIXME: <rdar://problem/6362369> We used to get provisionalDataSource here if in provisional state; how do we tell that now? Is this right?
3421     WebDataSource *dataSource = [frame provisionalDataSource];
3422     if (!dataSource)
3423         dataSource = [frame dataSource];
3424     NSURL *unreachableURL = [dataSource unreachableURL];
3425     NSURL *URL = unreachableURL != nil ? unreachableURL : [[dataSource request] URL];
3426     [[URL retain] autorelease];
3427     return URL;
3428 }
3429 #endif // PLATFORM(IOS)
3430
3431 #if !PLATFORM(IOS)
3432 - (void)setAlwaysShowVerticalScroller:(BOOL)flag
3433 {
3434     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3435     if (flag) {
3436         [scrollview setVerticalScrollingMode:ScrollbarAlwaysOn andLock:YES];
3437     } else {
3438         [scrollview setVerticalScrollingModeLocked:NO];
3439         [scrollview setVerticalScrollingMode:ScrollbarAuto andLock:NO];
3440     }
3441 }
3442
3443 - (BOOL)alwaysShowVerticalScroller
3444 {
3445     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3446     return [scrollview verticalScrollingModeLocked] && [scrollview verticalScrollingMode] == ScrollbarAlwaysOn;
3447 }
3448
3449 - (void)setAlwaysShowHorizontalScroller:(BOOL)flag
3450 {
3451     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3452     if (flag) {
3453         [scrollview setHorizontalScrollingMode:ScrollbarAlwaysOn andLock:YES];
3454     } else {
3455         [scrollview setHorizontalScrollingModeLocked:NO];
3456         [scrollview setHorizontalScrollingMode:ScrollbarAuto andLock:NO];
3457     }
3458 }
3459
3460 - (void)setProhibitsMainFrameScrolling:(BOOL)prohibits
3461 {
3462     if (Frame* mainFrame = [self _mainCoreFrame])
3463         mainFrame->view()->setProhibitsScrolling(prohibits);
3464 }
3465
3466 - (BOOL)alwaysShowHorizontalScroller
3467 {
3468     WebDynamicScrollBarsView *scrollview = [[[self mainFrame] frameView] _scrollView];
3469     return [scrollview horizontalScrollingModeLocked] && [scrollview horizontalScrollingMode] == ScrollbarAlwaysOn;
3470 }
3471 #endif // !PLATFORM(IOS)
3472
3473 - (void)_setUseFastImageScalingMode:(BOOL)flag
3474 {
3475     if (_private->page && _private->page->inLowQualityImageInterpolationMode() != flag) {
3476         _private->page->setInLowQualityImageInterpolationMode(flag);
3477         [self setNeedsDisplay:YES];
3478     }
3479 }
3480
3481 - (BOOL)_inFastImageScalingMode
3482 {
3483     if (_private->page)
3484         return _private->page->inLowQualityImageInterpolationMode();
3485     return NO;
3486 }
3487
3488 - (BOOL)_cookieEnabled
3489 {
3490     if (_private->page)
3491         return _private->page->settings().cookieEnabled();
3492     return YES;
3493 }
3494
3495 - (void)_setCookieEnabled:(BOOL)enable
3496 {
3497     if (_private->page)
3498         _private->page->settings().setCookieEnabled(enable);
3499 }
3500
3501 #if !PLATFORM(IOS)
3502 - (void)_setAdditionalWebPlugInPaths:(NSArray *)newPaths
3503 {
3504     if (!_private->pluginDatabase)
3505         _private->pluginDatabase = [[WebPluginDatabase alloc] init];
3506         
3507     [_private->pluginDatabase setPlugInPaths:newPaths];
3508     [_private->pluginDatabase refresh];
3509 }
3510 #endif
3511
3512 #if PLATFORM(IOS)
3513 - (BOOL)_locked_plugInsAreRunningInFrame:(WebFrame *)frame
3514 {
3515     // Ask plug-ins in this frame
3516     id <WebDocumentView> documentView = [[frame frameView] documentView];
3517     if (documentView && [documentView isKindOfClass:[WebHTMLView class]]) {
3518         if ([[(WebHTMLView *)documentView _pluginController] plugInsAreRunning])
3519             return YES;
3520     }
3521
3522     // Ask plug-ins in child frames
3523     NSArray *childFrames = [frame childFrames];
3524     unsigned childCount = [childFrames count];
3525     unsigned childIndex;
3526     for (childIndex = 0; childIndex < childCount; childIndex++) {
3527         if ([self _locked_plugInsAreRunningInFrame:[childFrames objectAtIndex:childIndex]])
3528             return YES;
3529     }
3530     
3531     return NO;
3532 }
3533
3534 - (BOOL)_pluginsAreRunning
3535 {
3536     WebThreadLock();
3537     return [self _locked_plugInsAreRunningInFrame:[self mainFrame]];
3538 }
3539
3540 - (void)_locked_recursivelyPerformPlugInSelector:(SEL)selector inFrame:(WebFrame *)frame
3541 {
3542     // Send the message to plug-ins in this frame
3543     id <WebDocumentView> documentView = [[frame frameView] documentView];
3544     if (documentView && [documentView isKindOfClass:[WebHTMLView class]])
3545         [[(WebHTMLView *)documentView _pluginController] performSelector:selector];
3546
3547     // Send the message to plug-ins in child frames
3548     NSArray *childFrames = [frame childFrames];
3549     unsigned childCount = [childFrames count];
3550     unsigned childIndex;
3551     for (childIndex = 0; childIndex < childCount; childIndex++) {
3552         [self _locked_recursivelyPerformPlugInSelector:selector inFrame:[childFrames objectAtIndex:childIndex]];
3553     }
3554 }
3555
3556 - (void)_destroyAllPlugIns
3557 {
3558     WebThreadLock();
3559     [self _locked_recursivelyPerformPlugInSelector:@selector(destroyAllPlugins) inFrame:[self mainFrame]];
3560 }
3561
3562 - (void)_startAllPlugIns
3563 {
3564     WebThreadLock();
3565     [self _locked_recursivelyPerformPlugInSelector:@selector(startAllPlugins) inFrame:[self mainFrame]];
3566 }
3567
3568 - (void)_stopAllPlugIns
3569 {
3570     WebThreadLock();
3571     [self _locked_recursivelyPerformPlugInSelector:@selector(stopAllPlugins) inFrame:[self mainFrame]];
3572 }
3573
3574 - (void)_stopAllPlugInsForPageCache
3575 {
3576     WebThreadLock();
3577     [self _locked_recursivelyPerformPlugInSelector:@selector(stopPluginsForPageCache) inFrame:[self mainFrame]];
3578 }
3579
3580 - (void)_restorePlugInsFromCache
3581 {
3582     WebThreadLock();
3583     [self _locked_recursivelyPerformPlugInSelector:@selector(restorePluginsFromCache) inFrame:[self mainFrame]];
3584 }
3585
3586 - (BOOL)_setMediaLayer:(CALayer*)layer forPluginView:(NSView*)pluginView
3587 {
3588     WebThreadLock();
3589
3590     Frame* mainCoreFrame = [self _mainCoreFrame];
3591     for (Frame* frame = mainCoreFrame; frame; frame = frame->tree().traverseNext()) {
3592         FrameView* coreView = frame ? frame->view() : 0;
3593         if (!coreView)
3594             continue;
3595
3596         // Get the GraphicsLayer for this widget.
3597         GraphicsLayer* layerForWidget = coreView->graphicsLayerForPlatformWidget(pluginView);
3598         if (!layerForWidget)
3599             continue;
3600         
3601         if (layerForWidget->contentsLayerForMedia() != layer) {
3602             layerForWidget->setContentsToPlatformLayer(layer, GraphicsLayer::ContentsLayerForMedia);
3603             // We need to make sure the layer hierachy change is applied immediately.
3604             if (mainCoreFrame->view())
3605                 mainCoreFrame->view()->flushCompositingStateIncludingSubframes();
3606             return YES;
3607         }
3608     }
3609
3610     return NO;
3611 }
3612
3613 - (void)_setNeedsUnrestrictedGetMatchedCSSRules:(BOOL)flag
3614 {
3615     if (_private->page)
3616         _private->page->settings().setCrossOriginCheckInGetMatchedCSSRulesDisabled(flag);
3617 }
3618 #endif // PLATFORM(IOS)
3619
3620 - (void)_attachScriptDebuggerToAllFrames
3621 {
3622     for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext())
3623         [kit(frame) _attachScriptDebugger];
3624 }
3625
3626 - (void)_detachScriptDebuggerFromAllFrames
3627 {
3628     for (Frame* frame = [self _mainCoreFrame]; frame; frame = frame->tree().traverseNext())
3629         [kit(frame) _detachScriptDebugger];
3630 }
3631
3632 #if !PLATFORM(IOS)
3633 - (void)setBackgroundColor:(NSColor *)backgroundColor
3634 {
3635     if ([_private->backgroundColor isEqual:backgroundColor])
3636         return;
3637
3638     id old = _private->backgroundColor;
3639     _private->backgroundColor = [backgroundColor retain];
3640     [old release];
3641
3642     [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
3643 }
3644
3645 - (NSColor *)backgroundColor
3646 {
3647     return _private->backgroundColor;
3648 }
3649 #else
3650 - (void)setBackgroundColor:(CGColorRef)backgroundColor
3651 {
3652    if (!backgroundColor || CFEqual(_private->backgroundColor, backgroundColor))
3653         return;
3654
3655     CFTypeRef old = _private->backgroundColor;
3656     CFRetain(backgroundColor);
3657     _private->backgroundColor = backgroundColor;
3658     CFRelease(old);
3659
3660     [[self mainFrame] _updateBackgroundAndUpdatesWhileOffscreen];
3661 }
3662
3663 - (CGColorRef)backgroundColor
3664 {
3665     return _private->backgroundColor;
3666 }
3667 #endif
3668
3669 - (BOOL)defersCallbacks
3670 {
3671     if (!_private->page)
3672         return NO;
3673     return _private->page->defersLoading();
3674 }
3675
3676 - (void)setDefersCallbacks:(BOOL)defer
3677 {
3678     if (!_private->page)
3679         return;
3680     return _private->page->setDefersLoading(defer);
3681 }
3682
3683 #if PLATFORM(IOS)
3684 - (NSDictionary *)quickLookContentForURL:(NSURL *)url
3685 {
3686 #if USE(QUICK_LOOK)
3687     NSString *uti = qlPreviewConverterUTIForURL(url);
3688     if (!uti)
3689         return nil;
3690
3691     NSString *fileName = qlPreviewConverterFileNameForURL(url);
3692     if (!fileName)
3693         return nil;
3694
3695     return [NSDictionary dictionaryWithObjectsAndKeys: fileName, WebQuickLookFileNameKey, uti, WebQuickLookUTIKey, nil];
3696 #else
3697     return nil;
3698 #endif
3699 }
3700
3701 - (BOOL)_isStopping
3702 {
3703     return _private->isStopping;
3704 }
3705
3706 - (BOOL)_isClosing
3707 {
3708     return _private->closing;
3709 }
3710
3711 + (NSArray *)_productivityDocumentMIMETypes
3712 {
3713 #if USE(QUICK_LOOK)
3714     return [QLPreviewGetSupportedMIMETypesSet() allObjects];
3715 #else
3716     return nil;
3717 #endif
3718 }
3719
3720 - (void)_setAllowsMessaging:(BOOL)aFlag
3721 {
3722     _private->allowsMessaging = aFlag;
3723 }
3724
3725 - (BOOL)_allowsMessaging
3726 {
3727     return _private->allowsMessaging;
3728 }
3729
3730 - (void)_setFixedLayoutSize:(CGSize)size
3731 {
3732     ASSERT(WebThreadIsLocked());
3733     _private->fixedLayoutSize = size;
3734     if (Frame* mainFrame = core([self mainFrame])) {
3735         IntSize newSize(size);
3736         mainFrame->view()->setFixedLayoutSize(newSize);
3737         mainFrame->view()->setUseFixedLayout(!newSize.isEmpty());
3738         [self setNeedsDisplay:YES];
3739     }
3740 }
3741
3742 - (CGSize)_fixedLayoutSize
3743 {
3744     return _private->fixedLayoutSize;
3745 }
3746
3747 - (void)_synchronizeCustomFixedPositionLayoutRect
3748 {
3749     ASSERT(WebThreadIsLocked());
3750
3751     IntRect newRect;
3752     {
3753         LockHolder locker(_private->pendingFixedPositionLayoutRectMutex);
3754         if (CGRectIsNull(_private->pendingFixedPositionLayoutRect))
3755             return;
3756         newRect = enclosingIntRect(_private->pendingFixedPositionLayoutRect);
3757         _private->pendingFixedPositionLayoutRect = CGRectNull;
3758     }
3759
3760     if (Frame* mainFrame = core([self mainFrame]))
3761         mainFrame->view()->setCustomFixedPositionLayoutRect(newRect);
3762 }
3763
3764 - (void)_setCustomFixedPositionLayoutRectInWebThread:(CGRect)rect synchronize:(BOOL)synchronize
3765 {
3766     {
3767         LockHolder locker(_private->pendingFixedPositionLayoutRectMutex);
3768         _private->pendingFixedPositionLayoutRect = rect;
3769     }
3770     if (!synchronize)
3771         return;
3772     WebThreadRun(^{
3773         [self _synchronizeCustomFixedPositionLayoutRect];
3774     });
3775 }
3776
3777 - (void)_setCustomFixedPositionLayoutRect:(CGRect)rect
3778 {
3779     ASSERT(WebThreadIsLocked());
3780     {
3781         LockHolder locker(_private->pendingFixedPositionLayoutRectMutex);
3782         _private->pendingFixedPositionLayoutRect = rect;
3783     }
3784     [self _synchronizeCustomFixedPositionLayoutRect];
3785 }
3786
3787 - (BOOL)_fetchCustomFixedPositionLayoutRect:(NSRect*)rect
3788 {
3789     LockHolder locker(_private->pendingFixedPositionLayoutRectMutex);
3790     if (CGRectIsNull(_private->pendingFixedPositionLayoutRect))
3791         return false;
3792
3793     *rect = _private->pendingFixedPositionLayoutRect;
3794     _private->pendingFixedPositionLayoutRect = CGRectNull;
3795     return true;
3796 }
3797
3798 - (void)_viewGeometryDidChange
3799 {
3800     ASSERT(WebThreadIsLocked());
3801     
3802     if (Frame* coreFrame = [self _mainCoreFrame])
3803         coreFrame->viewportOffsetChanged(Frame::IncrementalScrollOffset);
3804 }
3805
3806 - (void)_overflowScrollPositionChangedTo:(CGPoint)offset forNode:(DOMNode *)domNode isUserScroll:(BOOL)userScroll
3807 {
3808     // Find the frame
3809     Node* node = core(domNode);
3810     Frame* frame = node->document().frame();
3811     if (!frame)
3812         return;
3813
3814     frame->overflowScrollPositionChangedForNode(roundedIntPoint(offset), node, userScroll);
3815 }
3816
3817 + (void)_doNotStartObservingNetworkReachability
3818 {
3819     Settings::setShouldOptOutOfNetworkStateObservation(true);
3820 }
3821 #endif // PLATFORM(IOS)
3822
3823 #if ENABLE(TOUCH_EVENTS)
3824 - (NSArray *)_touchEventRegions
3825 {
3826     Frame* frame = [self _mainCoreFrame];
3827     if (!frame)
3828         return nil;
3829     
3830     Document* document = frame->document();
3831     if (!document)
3832         return nil;
3833
3834     Vector<IntRect> rects;
3835     document->getTouchRects(rects);
3836
3837     if (rects.size() == 0)
3838         return nil;
3839
3840     NSMutableArray *eventRegionArray = [[[NSMutableArray alloc] initWithCapacity:rects.size()] autorelease];
3841
3842     NSView <WebDocumentView> *documentView = [[[self mainFrame] frameView] documentView];
3843     Vector<IntRect>::const_iterator end = rects.end();
3844     for (Vector<IntRect>::const_iterator it = rects.begin(); it != end; ++it) {
3845         const IntRect& rect = *it;
3846         if (rect.isEmpty())
3847             continue;
3848
3849         // The touch rectangles are in the coordinate system of the document (inside the WebHTMLView), which is not
3850         // the same as the coordinate system of the WebView. UIWebView currently expects view coordinates, so we'll
3851         // convert them here now.
3852         IntRect viewRect = IntRect([documentView convertRect:rect toView:self]);
3853
3854         // The event region wants this points in this order:
3855         //  p2------p3
3856         //  |       |
3857         //  p1------p4
3858         //
3859         WebEventRegion *eventRegion = [[WebEventRegion alloc] initWithPoints:FloatPoint(viewRect.x(), viewRect.maxY())
3860                                                                             :FloatPoint(viewRect.x(), viewRect.y())
3861                                                                             :FloatPoint(viewRect.maxX(), viewRect.y())
3862                                                                             :FloatPoint(viewRect.maxX(), viewRect.maxY())];
3863         if (eventRegion) {
3864             [eventRegionArray addObject:eventRegion];
3865             [eventRegion release];
3866         }
3867     }
3868
3869     return eventRegionArray;
3870 }
3871 #endif // ENABLE(TOUCH_EVENTS)
3872
3873 // For backwards compatibility with the WebBackForwardList API, we honor both
3874 // a per-WebView and a per-preferences setting for whether to use the page cache.
3875
3876 - (BOOL)usesPageCache
3877 {
3878     return _private->usesPageCache && [[self preferences] usesPageCache];
3879 }
3880
3881 - (void)setUsesPageCache:(BOOL)usesPageCache
3882 {
3883     _private->usesPageCache = usesPageCache;
3884
3885     // Update our own settings and post the public notification only
3886     [self _preferencesChanged:[self preferences]];
3887     [[self preferences] _postPreferencesChangedAPINotification];
3888 }
3889
3890 - (WebHistoryItem *)_globalHistoryItem
3891 {
3892     if (!_private)
3893         return nil;
3894
3895     return kit(_private->_globalHistoryItem.get());
3896 }
3897
3898 - (void)_setGlobalHistoryItem:(HistoryItem*)historyItem
3899 {
3900     _private->_globalHistoryItem = historyItem;
3901 }
3902
3903 - (WebTextIterator *)textIteratorForRect:(NSRect)rect
3904 {
3905     IntPoint rectStart(rect.origin.x, rect.origin.y);
3906     IntPoint rectEnd(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height);
3907     
3908     Frame* coreFrame = [self _mainCoreFrame];
3909     if (!coreFrame)
3910         return nil;
3911     
3912     VisibleSelection selectionInsideRect(coreFrame->visiblePositionForPoint(rectStart), coreFrame->visiblePositionForPoint(rectEnd));
3913     
3914     return [[[WebTextIterator alloc] initWithRange:kit(selectionInsideRect.toNormalizedRange().get())] autorelease];
3915 }
3916
3917 #if !PLATFORM(IOS)
3918 - (void)_clearUndoRedoOperations
3919 {
3920     if (!_private->page)
3921         return;
3922     _private->page->clearUndoRedoOperations();
3923 }
3924 #endif
3925
3926 - (void)_executeCoreCommandByName:(NSString *)name value:(NSString *)value
3927 {
3928     Frame* coreFrame = [self _mainCoreFrame];
3929     if (!coreFrame)
3930         return;
3931     coreFrame->editor().command(name).execute(value);
3932 }
3933
3934 - (void)_clearMainFrameName
3935 {
3936     _private->page->mainFrame().tree().clearName();
3937 }
3938
3939 - (void)setSelectTrailingWhitespaceEnabled:(BOOL)flag
3940 {
3941     if (_private->page->settings().selectTrailingWhitespaceEnabled() != flag) {
3942         _private->page->settings().setSelectTrailingWhitespaceEnabled(flag);
3943         [self setSmartInsertDeleteEnabled:!flag];
3944     }
3945 }
3946
3947 - (BOOL)isSelectTrailingWhitespaceEnabled
3948 {
3949     return _private->page->settings().selectTrailingWhitespaceEnabled();
3950 }
3951
3952 - (void)setMemoryCacheDelegateCallsEnabled:(BOOL)enabled
3953 {
3954     _private->page->setMemoryCacheClientCallsEnabled(enabled);
3955 }
3956
3957 - (BOOL)areMemoryCacheDelegateCallsEnabled
3958 {
3959     return _private->page->areMemoryCacheClientCallsEnabled();
3960 }
3961
3962 - (BOOL)_postsAcceleratedCompositingNotifications
3963 {
3964     return _private->postsAcceleratedCompositingNotifications;
3965 }
3966 - (void)_setPostsAcceleratedCompositingNotifications:(BOOL)flag
3967 {
3968     _private->postsAcceleratedCompositingNotifications = flag;
3969 }
3970
3971 - (BOOL)_isUsingAcceleratedCompositing
3972 {
3973     Frame* coreFrame = [self _mainCoreFrame];
3974     for (Frame* frame = coreFrame; frame; frame = frame->tree().traverseNext(coreFrame)) {
3975         NSView *documentView = [[kit(frame) frameView] documentView];
3976         if ([documentView isKindOfClass:[WebHTMLView class]] && [(WebHTMLView *)documentView _isUsingAcceleratedCompositing])
3977             return YES;
3978     }
3979
3980     return NO;
3981 }
3982
3983 - (void)_setBaseCTM:(CGAffineTransform)transform forContext:(CGContextRef)context
3984 {
3985     CGContextSetBaseCTM(context, transform);
3986 }
3987
3988 - (BOOL)interactiveFormValidationEnabled
3989 {
3990     return _private->interactiveFormValidationEnabled;
3991 }
3992
3993 - (void)setInteractiveFormValidationEnabled:(BOOL)enabled
3994 {
3995     _private->interactiveFormValidationEnabled = enabled;
3996 }
3997
3998 - (int)validationMessageTimerMagnification
3999 {
4000     return _private->validationMessageTimerMagnification;
4001 }
4002
4003 - (void)setValidationMessageTimerMagnification:(int)newValue
4004 {
4005     _private->validationMessageTimerMagnification = newValue;
4006 }
4007
4008 - (BOOL)_isSoftwareRenderable
4009 {
4010     Frame* coreFrame = [self _mainCoreFrame];
4011     for (Frame* frame = coreFrame; frame; frame = frame->tree().traverseNext(coreFrame)) {
4012         if (FrameView* view = frame->view()) {
4013             if (!view->isSoftwareRenderable())
4014                 return NO;
4015         }
4016     }
4017
4018     return YES;
4019 }
4020
4021 - (void)_setIncludesFlattenedCompositingLayersWhenDrawingToBitmap:(BOOL)flag
4022 {
4023     _private->includesFlattenedCompositingLayersWhenDrawingToBitmap = flag;
4024 }
4025
4026 - (BOOL)_includesFlattenedCompositingLayersWhenDrawingToBitmap
4027 {
4028     return _private->includesFlattenedCompositingLayersWhenDrawingToBitmap;
4029 }
4030
4031 - (void)setTracksRepaints:(BOOL)flag
4032 {
4033     Frame* coreFrame = [self _mainCoreFrame];
4034     if (FrameView* view = coreFrame->view())
4035         view->setTracksRepaints(flag);
4036 }
4037
4038 - (BOOL)isTrackingRepaints
4039 {
4040     Frame* coreFrame = [self _mainCoreFrame];
4041     if (FrameView* view = coreFrame->view())
4042         return view->isTrackingRepaints();
4043     
4044     return NO;
4045 }
4046
4047 - (void)resetTrackedRepaints
4048 {
4049     Frame* coreFrame = [self _mainCoreFrame];
4050     if (FrameView* view = coreFrame->view())
4051         view->resetTrackedRepaints();
4052 }
4053
4054 - (NSArray*)trackedRepaintRects
4055 {
4056     Frame* coreFrame = [self _mainCoreFrame];
4057     FrameView* view = coreFrame->view();
4058     if (!view || !view->isTrackingRepaints())
4059         return nil;
4060
4061     const Vector<FloatRect>& repaintRects = view->trackedRepaintRects();
4062     NSMutableArray* rectsArray = [[NSMutableArray alloc] initWithCapacity:repaintRects.size()];
4063     
4064     for (unsigned i = 0; i < repaintRects.size(); ++i)
4065         [rectsArray addObject:[NSValue valueWithRect:snappedIntRect(LayoutRect(repaintRects[i]))]];
4066
4067     return [rectsArray autorelease];
4068 }
4069
4070 #if !PLATFORM(IOS)
4071 - (NSPasteboard *)_insertionPasteboard
4072 {
4073     return _private ? _private->insertionPasteboard : nil;
4074 }
4075 #endif
4076
4077 + (void)_addOriginAccessWhitelistEntryWithSourceOrigin:(NSString *)sourceOrigin destinationProtocol:(NSString *)destinationProtocol destinationHost:(NSString *)destinationHost allowDestinationSubdomains:(BOOL)allowDestinationSubdomains
4078 {
4079     SecurityPolicy::addOriginAccessWhitelistEntry(SecurityOrigin::createFromString(sourceOrigin).get(), destinationProtocol, destinationHost, allowDestinationSubdomains);
4080 }
4081
4082 + (void)_removeOriginAccessWhitelistEntryWithSourceOrigin:(NSString *)sourceOrigin destinationProtocol:(NSString *)destinationProtocol destinationHost:(NSString *)destinationHost allowDestinationSubdomains:(BOOL)allowDestinationSubdomains
4083 {
4084     SecurityPolicy::removeOriginAccessWhitelistEntry(SecurityOrigin::createFromString(sourceOrigin).get(), destinationProtocol, destinationHost, allowDestinationSubdomains);
4085 }
4086
4087 + (void)_resetOriginAccessWhitelists
4088 {
4089     SecurityPolicy::resetOriginAccessWhitelists();
4090 }
4091
4092 - (BOOL)_isViewVisible
4093 {
4094     if (![self window])
4095         return false;
4096
4097     if (![[self window] isVisible])
4098         return false;
4099
4100     if ([self isHiddenOrHasHiddenAncestor])
4101         return false;
4102
4103     return true;
4104 }
4105
4106 - (void)_updateVisibilityState
4107 {
4108     if (_private && _private->page)
4109         [self _setIsVisible:[self _isViewVisible]];
4110 }
4111
4112 - (void)_updateActiveState
4113 {
4114     if (_private && _private->page)
4115 #if PLATFORM(IOS)
4116         _private->page->focusController().setActive([[self window] isKeyWindow]);
4117 #else
4118         _private->page->focusController().setActive([[self window] _hasKeyAppearance]);
4119 #endif
4120 }
4121
4122 static Vector<String> toStringVector(NSArray* patterns)
4123 {
4124     Vector<String> patternsVector;
4125
4126     NSUInteger count = [patterns count];
4127     if (!count)
4128         return patternsVector;
4129
4130     for (NSUInteger i = 0; i < count; ++i) {
4131         id entry = [patterns objectAtIndex:i];
4132         if ([entry isKindOfClass:[NSString class]])
4133             patternsVector.append(String((NSString *)entry));
4134     }
4135     return patternsVector;
4136 }
4137
4138 + (void)_addUserScriptToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
4139                     whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
4140                 injectionTime:(WebUserScriptInjectionTime)injectionTime
4141 {
4142     [WebView _addUserScriptToGroup:groupName world:world source:source url:url whitelist:whitelist blacklist:blacklist injectionTime:injectionTime injectedFrames:WebInjectInAllFrames];
4143 }
4144
4145 + (void)_addUserScriptToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
4146                     whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
4147                 injectionTime:(WebUserScriptInjectionTime)injectionTime
4148                injectedFrames:(WebUserContentInjectedFrames)injectedFrames
4149 {
4150     String group(groupName);
4151     if (group.isEmpty())
4152         return;
4153
4154     auto viewGroup = WebViewGroup::getOrCreate(groupName, String());
4155     if (!viewGroup)
4156         return;
4157
4158     if (!world)
4159         return;
4160
4161     auto userScript = std::make_unique<UserScript>(source, url, toStringVector(whitelist), toStringVector(blacklist), injectionTime == WebInjectAtDocumentStart ? InjectAtDocumentStart : InjectAtDocumentEnd, injectedFrames == WebInjectInAllFrames ? InjectInAllFrames : InjectInTopFrameOnly);
4162     viewGroup->userContentController().addUserScript(*core(world), WTFMove(userScript));
4163 }
4164
4165 + (void)_addUserStyleSheetToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
4166                         whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
4167 {
4168     [WebView _addUserStyleSheetToGroup:groupName world:world source:source url:url whitelist:whitelist blacklist:blacklist injectedFrames:WebInjectInAllFrames];
4169 }
4170
4171 + (void)_addUserStyleSheetToGroup:(NSString *)groupName world:(WebScriptWorld *)world source:(NSString *)source url:(NSURL *)url
4172                         whitelist:(NSArray *)whitelist blacklist:(NSArray *)blacklist
4173                    injectedFrames:(WebUserContentInjectedFrames)injectedFrames
4174 {
4175     String group(groupName);
4176     if (group.isEmpty())
4177         return;
4178
4179     auto viewGroup = WebViewGroup::getOrCreate(groupName, String());
4180     if (!viewGroup)
4181         return;
4182
4183     if (!world)
4184         return;
4185
4186     auto styleSheet = std::make_unique<UserStyleSheet>(source, url, toStringVector(whitelist), toStringVector(blacklist), injectedFrames == WebInjectInAllFrames ? InjectInAllFrames : InjectInTopFrameOnly, UserStyleUserLevel);
4187     viewGroup->userContentController().addUserStyleSheet(*core(world), WTFMove(styleSheet), InjectInExistingDocuments);
4188 }
4189
4190 + (void)_removeUserScriptFromGroup:(NSString *)groupName world:(WebScriptWorld *)world url:(NSURL *)url
4191 {
4192     String group(groupName);
4193     if (group.isEmpty())
4194         return;
4195
4196     auto* viewGroup = WebViewGroup::get(group);
4197     if (!viewGroup)
4198         return;
4199
4200     if (!world)
4201         return;
4202
4203     viewGroup->userContentController().removeUserScript(*core(world), url);
4204 }
4205
4206 + (void)_removeUserStyleSheetFromGroup:(NSString *)groupName world:(WebScriptWorld *)world url:(NSURL *)url
4207 {
4208     String group(groupName);
4209     if (group.isEmpty())
4210         return;
4211
4212     auto* viewGroup = WebViewGroup::get(group);
4213     if (!viewGroup)
4214         return;
4215
4216     if (!world)
4217         return;
4218
4219     viewGroup->userContentController().removeUserStyleSheet(*core(world), url);
4220 }
4221
4222 + (void)_removeUserScriptsFromGroup:(NSString *)groupName world:(WebScriptWorld *)world
4223 {
4224     String group(groupName);
4225     if (group.isEmpty())
4226         return;
4227
4228     auto* viewGroup = WebViewGroup::get(group);
4229     if (!viewGroup)
4230         return;
4231
4232     if (!world)
4233         return;
4234
4235     viewGroup->userContentController().removeUserScripts(*core(world));
4236 }
4237
4238 + (void)_removeUserStyleSheetsFromGroup:(NSString *)groupName world:(WebScriptWorld *)world
4239 {
4240     String group(groupName);
4241     if (group.isEmpty())
4242         return;
4243
4244     auto* viewGroup = WebViewGroup::get(group);
4245     if (!viewGroup)
4246         return;
4247
4248     if (!world)
4249         return;
4250
4251     viewGroup->userContentController().removeUserStyleSheets(*core(world));
4252 }
4253
4254 + (void)_removeAllUserContentFromGroup:(NSString *)groupName
4255 {
4256     String group(groupName);
4257     if (group.isEmpty())
4258         return;
4259
4260     auto* viewGroup = WebViewGroup::get(group);
4261     if (!viewGroup)
4262         return;
4263
4264     viewGroup->userContentController().removeAllUserContent();
4265 }
4266
4267 - (BOOL)allowsNewCSSAnimationsWhileSuspended
4268 {
4269     Frame* frame =