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