Make memoryCache() return a reference
[WebKit-https.git] / Source / WebKit / mac / WebView / WebView.mm
index f4fb1bc..290c111 100644 (file)
@@ -12,7 +12,7 @@
  * 2.  Redistributions in binary form must reproduce the above copyright
  *     notice, this list of conditions and the following disclaimer in the
  *     documentation and/or other materials provided with the distribution. 
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
  *     its contributors may be used to endorse or promote products derived
  *     from this software without specific prior written permission. 
  *
@@ -97,6 +97,7 @@
 #import "WebProgressTrackerClient.h"
 #import "WebScriptDebugDelegate.h"
 #import "WebScriptWorldInternal.h"
+#import "WebSelectionServiceController.h"
 #import "WebStorageManagerInternal.h"
 #import "WebSystemInterface.h"
 #import "WebTextCompletionController.h"
 #import <WebCore/ApplicationCacheStorage.h>
 #import <WebCore/BackForwardController.h>
 #import <WebCore/BackForwardList.h>
-#import <WebCore/MemoryCache.h>
+#import <WebCore/CFNetworkSPI.h>
 #import <WebCore/Chrome.h>
 #import <WebCore/ColorMac.h>
 #import <WebCore/Cursor.h>
 #import <WebCore/DocumentLoader.h>
 #import <WebCore/DragController.h>
 #import <WebCore/DragData.h>
-#import <WebCore/DragSession.h>
 #import <WebCore/Editor.h>
 #import <WebCore/EventHandler.h>
 #import <WebCore/ExceptionHandlers.h>
 #import <WebCore/GCController.h>
 #import <WebCore/GeolocationController.h>
 #import <WebCore/GeolocationError.h>
-#import <WebCore/HTMLMediaElement.h>
 #import <WebCore/HTMLNames.h>
+#import <WebCore/HTMLVideoElement.h>
 #import <WebCore/HistoryController.h>
 #import <WebCore/HistoryItem.h>
 #import <WebCore/IconDatabase.h>
 #import <WebCore/Logging.h>
 #import <WebCore/MIMETypeRegistry.h>
 #import <WebCore/MainFrame.h>
+#import <WebCore/MemoryCache.h>
 #import <WebCore/MemoryPressureHandler.h>
+#import <WebCore/NSURLFileTypeMappingsSPI.h>
 #import <WebCore/NodeList.h>
 #import <WebCore/Notification.h>
 #import <WebCore/NotificationController.h>
 #import <WebCore/WebCoreObjCExtras.h>
 #import <WebCore/WebCoreView.h>
 #import <WebCore/Widget.h>
-#import <WebKit/DOM.h>
-#import <WebKit/DOMExtensions.h>
-#import <WebKit/DOMPrivate.h>
+#import <WebKitLegacy/DOM.h>
+#import <WebKitLegacy/DOMExtensions.h>
+#import <WebKitLegacy/DOMPrivate.h>
 #import <WebKitSystemInterface.h>
 #import <bindings/ScriptValue.h>
 #import <mach-o/dyld.h>
 #import <runtime/ArrayPrototype.h>
 #import <runtime/DateInstance.h>
 #import <runtime/InitializeThreading.h>
-#import <runtime/JSLock.h>
 #import <runtime/JSCJSValue.h>
+#import <runtime/JSLock.h>
 #import <wtf/Assertions.h>
 #import <wtf/HashTraits.h>
 #import <wtf/MainThread.h>
 #import <wtf/StdLibExtras.h>
 
 #if !PLATFORM(IOS)
+#import "WebActionMenuController.h"
 #import "WebContextMenuClient.h"
 #import "WebFullScreenController.h"
 #import "WebNSEventExtras.h"
 #import "WebNSPasteboardExtras.h"
 #import "WebNSPrintOperationExtras.h"
 #import "WebPDFView.h"
+#import <WebCore/NSViewSPI.h>
 #import <WebCore/WebVideoFullscreenController.h>
 #else
 #import "MemoryMeasure.h"
 #import "WebStorageManagerPrivate.h"
 #import "WebUIKitSupport.h"
 #import "WebVisiblePosition.h"
-#import <CFNetwork/CFURLCachePriv.h>
-#import <MobileGestalt.h>
+#import <WebCore/DispatchSPI.h>
 #import <WebCore/EventNames.h>
 #import <WebCore/FontCache.h>
 #import <WebCore/GraphicsLayer.h>
 #import <WebCore/IconController.h>
+#import <WebCore/LegacyTileCache.h>
+#import <WebCore/MobileGestaltSPI.h>
 #import <WebCore/NetworkStateNotifier.h>
 #import <WebCore/RuntimeApplicationChecksIOS.h>
 #import <WebCore/SQLiteDatabaseTracker.h>
 #import <WebCore/SmartReplace.h>
 #import <WebCore/TextRun.h>
-#import <WebCore/TileCache.h>
 #import <WebCore/TileControllerMemoryHandlerIOS.h>
 #import <WebCore/WAKWindow.h>
+#import <WebCore/WKView.h>
 #import <WebCore/WebCoreThread.h>
 #import <WebCore/WebCoreThreadMessage.h>
 #import <WebCore/WebCoreThreadRun.h>
 #import <WebCore/WebEvent.h>
 #import <WebCore/WebVideoFullscreenControllerAVKit.h>
-#import <dispatch/private.h>
 #import <wtf/FastMalloc.h>
 #endif // !PLATFORM(IOS)
 
 #if ENABLE(DASHBOARD_SUPPORT)
-#import <WebKit/WebDashboardRegion.h>
-#endif
-
-#if ENABLE(DISK_IMAGE_CACHE) && PLATFORM(IOS)
-#import "WebDiskImageCacheClientIOS.h"
-#import <WebCore/DiskImageCacheIOS.h>
+#import <WebKitLegacy/WebDashboardRegion.h>
 #endif
 
 #if ENABLE(REMOTE_INSPECTOR)
 #include <WebCore/QuickLook.h>
 #endif
 
-#if ENABLE(TOUCH_EVENTS)
+#if ENABLE(IOS_TOUCH_EVENTS)
 #import <WebCore/WebEventRegion.h>
 #endif
 
-#if ENABLE(DISK_IMAGE_CACHE)
-#import "WebDiskImageCacheClientIOS.h"
-#import <WebCore/DiskImageCacheIOS.h>
+#if ENABLE(GAMEPAD)
+#import <WebCore/HIDGamepadProvider.h>
 #endif
 
 #if !PLATFORM(IOS)
@@ -674,22 +672,14 @@ static CFMutableSetRef allWebViewsSet;
 
 @implementation WebView (WebPrivate)
 
-static String userVisibleWebKitVersionString()
+static String webKitBundleVersionString()
 {
-    // If the version is longer than 3 digits then the leading digits represent the version of the OS. Our user agent
-    // string should not include the leading digits, so strip them off and report the rest as the version. <rdar://problem/4997547>
-    NSString *fullVersion = [[NSBundle bundleForClass:[WebView class]] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
-    NSRange nonDigitRange = [fullVersion rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
-    if (nonDigitRange.location == NSNotFound && fullVersion.length > 3)
-        return [fullVersion substringFromIndex:fullVersion.length - 3];
-    if (nonDigitRange.location != NSNotFound && nonDigitRange.location > 3)
-        return [fullVersion substringFromIndex:nonDigitRange.location - 3];
-    return fullVersion;
+    return [[NSBundle bundleForClass:[WebView class]] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey];
 }
 
 + (NSString *)_standardUserAgentWithApplicationName:(NSString *)applicationName
 {
-    return standardUserAgentWithApplicationName(applicationName, userVisibleWebKitVersionString());
+    return standardUserAgentWithApplicationName(applicationName, webKitBundleVersionString());
 }
 
 #if PLATFORM(IOS)
@@ -839,6 +829,18 @@ static bool shouldUseLegacyBackgroundSizeShorthandBehavior()
     return shouldUseLegacyBackgroundSizeShorthandBehavior;
 }
 
+#if ENABLE(GAMEPAD)
+static void WebKitInitializeGamepadProviderIfNecessary()
+{
+    static bool initialized = false;
+    if (initialized)
+        return;
+
+    GamepadProvider::shared().setSharedProvider(HIDGamepadProvider::shared());
+    initialized = true;
+}
+#endif
+
 - (void)_commonInitializationWithFrameName:(NSString *)frameName groupName:(NSString *)groupName
 {
     WebCoreThreadViolationCheckRoundTwo();
@@ -867,6 +869,12 @@ static bool shouldUseLegacyBackgroundSizeShorthandBehavior()
     [frameView release];
 
 #if !PLATFORM(IOS)
+    if ([self respondsToSelector:@selector(setActionMenu:)]) {
+        RetainPtr<NSMenu> actionMenu = adoptNS([[NSMenu alloc] init]);
+        self.actionMenu = actionMenu.get();
+        _private->actionMenuController = [[WebActionMenuController alloc] initWithWebView:self];
+    }
+
     static bool didOneTimeInitialization = false;
 #endif
     if (!didOneTimeInitialization) {
@@ -894,14 +902,19 @@ static bool shouldUseLegacyBackgroundSizeShorthandBehavior()
 #endif
         WebKitInitializeStorageIfNecessary();
         WebKitInitializeApplicationCachePathIfNecessary();
-#if ENABLE(DISK_IMAGE_CACHE) && PLATFORM(IOS)
-        WebKitInitializeWebDiskImageCache();
+#if ENABLE(GAMEPAD)
+        WebKitInitializeGamepadProviderIfNecessary();
 #endif
         
         Settings::setDefaultMinDOMTimerInterval(0.004);
         
         Settings::setShouldRespectPriorityInCSSAttributeSetters(shouldRespectPriorityInCSSAttributeSetters());
 
+#if PLATFORM(IOS)
+        if (applicationIsMobileSafari())
+            Settings::setShouldManageAudioSessionCategory(true);
+#endif
+
         didOneTimeInitialization = true;
     }
 
@@ -1033,12 +1046,8 @@ static bool shouldUseLegacyBackgroundSizeShorthandBehavior()
 #endif
 }
 
-- (id)_initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName usesDocumentViews:(BOOL)usesDocumentViews
+- (id)_initWithFrame:(NSRect)f frameName:(NSString *)frameName groupName:(NSString *)groupName
 {
-    // FIXME: Remove the usesDocumentViews parameter; it's only here for compatibility with WebKit nightly builds
-    // running against Safari 5 on Leopard.
-    ASSERT(usesDocumentViews);
-
     self = [super initWithFrame:f];
     if (!self)
         return nil;
@@ -1086,7 +1095,7 @@ static bool shouldUseLegacyBackgroundSizeShorthandBehavior()
     NSEnumerator *enumerator = [MIMETypes objectEnumerator];
     NSString *MIMEType;
     while ((MIMEType = [enumerator nextObject]) != nil) {
-        NSArray *extensionsForType = WKGetExtensionsForMIMEType(MIMEType);
+        NSArray *extensionsForType = [[NSURLFileTypeMappings sharedMappings] extensionsForMIMEType:MIMEType];
         if (extensionsForType) {
             [extensions addObjectsFromArray:extensionsForType];
         }
@@ -1185,15 +1194,12 @@ static bool shouldUseLegacyBackgroundSizeShorthandBehavior()
     [self setGroupName:groupName];
 
 #if ENABLE(REMOTE_INSPECTOR)
-    // Production installs always disallow debugging simple HTML documents.
-    // Internal installs allow debugging simple HTML documents (TextFields) if the Internal Setting is enabled.
-    if (!isInternalInstall())
-        _private->page->setRemoteInspectionAllowed(false);
-    else {
-        static BOOL textFieldInspectionEnabled = [[NSUserDefaults standardUserDefaults] boolForKey:WebKitTextFieldRemoteInspectionEnabledPreferenceKey];
-        _private->page->setRemoteInspectionAllowed(textFieldInspectionEnabled);
-    }
+    _private->page->setRemoteInspectionAllowed(isInternalInstall());
 #endif
+    
+    [self _updateScreenScaleFromWindow];
+    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowScreenScaleChanged:) name:WAKWindowScreenScaleDidChangeNotification object:nil];
+    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_wakWindowVisibilityChanged:) name:WAKWindowVisibilityDidChangeNotification object:nil];
 
     [WebFrame _createMainFrameWithSimpleHTMLDocumentWithPage:_private->page frameView:frameView style:style];
     
@@ -1220,13 +1226,6 @@ static bool shouldUseLegacyBackgroundSizeShorthandBehavior()
 
     tileControllerMemoryHandler().trimUnparentedTilesToTarget(0);
 
-#if ENABLE(DISK_IMAGE_CACHE)
-    {
-        WebKit::MemoryMeasure measurer("Memory warning: flushing images to disk.");
-        WebCore::memoryCache()->flushCachedImagesToDisk();
-    }
-#endif
-
     [WebStorageManager closeIdleLocalStorageDatabases];
 
     [WebView _releaseMemoryNow];
@@ -1323,14 +1322,14 @@ static bool shouldUseLegacyBackgroundSizeShorthandBehavior()
 {
     ASSERT(WebThreadIsCurrent());
     WebKit::MemoryMeasure measurer("Memory warning: Purging inactive font data.");
-    fontCache()->purgeInactiveFontData();
+    fontCache().purgeInactiveFontData();
 }
 
 + (void)drainLayerPool
 {
     ASSERT(WebThreadIsCurrent());
     WebKit::MemoryMeasure measurer("Memory warning: Draining layer pool.");
-    WebCore::TileCache::drainLayerPool();
+    WebCore::LegacyTileCache::drainLayerPool();
 }
 
 + (void)discardAllCompiledCode
@@ -1446,13 +1445,6 @@ static NSMutableSet *knownPluginMIMETypes()
     return NO;
 }
 
-#if !PLATFORM(IOS)
-+ (void)_setAlwaysUseATSU:(BOOL)f
-{
-    [self _setAlwaysUsesComplexTextCodePath:f];
-}
-#endif
-
 + (void)_setAlwaysUsesComplexTextCodePath:(BOOL)f
 {
     Font::setCodePath(f ? Font::Complex : Font::Auto);
@@ -1493,7 +1485,7 @@ static NSMutableSet *knownPluginMIMETypes()
 #if !PLATFORM(IOS)
 + (NSString *)suggestedFileExtensionForMIMEType:(NSString *)type
 {
-    return WKGetPreferredExtensionForMIMEType(type);
+    return [[NSURLFileTypeMappings sharedMappings] preferredExtensionForMIMEType:type];
 }
 #endif
 
@@ -1570,6 +1562,8 @@ static NSMutableSet *knownPluginMIMETypes()
     _private->mainViewIsScrollingOrZooming = NO;
     [self setDefersCallbacks:NO];
     [[self mainFrame] setTimeoutsPaused:NO];
+    if (FrameView* view = [self _mainCoreFrame]->view())
+        view->resumeVisibleImageAnimationsIncludingSubframes();
 }
 
 - (void)_setResourceLoadSchedulerSuspended:(BOOL)suspend
@@ -1580,16 +1574,6 @@ static NSMutableSet *knownPluginMIMETypes()
         resourceLoadScheduler()->resumePendingRequests();
 }
 
-+ (void)_setAcceleratedImageDecoding:(BOOL)enabled
-{
-    ImageSource::setAcceleratedImageDecodingEnabled(enabled);
-}
-
-+ (BOOL)_acceleratedImageDecoding
-{
-    return ImageSource::acceleratedImageDecodingEnabled();
-}
-
 + (void)_setAllowCookies:(BOOL)allow
 {
     ResourceRequestBase::setDefaultAllowCookies(allow);
@@ -1602,7 +1586,7 @@ static NSMutableSet *knownPluginMIMETypes()
 
 + (BOOL)_isUnderMemoryPressure
 {
-    return memoryPressureHandler().hasReceivedMemoryPressure();
+    return memoryPressureHandler().isUnderMemoryPressure();
 }
 
 + (void)_clearMemoryPressure
@@ -1704,7 +1688,7 @@ static bool fastDocumentTeardownEnabled()
     }
 
 #if ENABLE(VIDEO) && !PLATFORM(IOS)
-    [self _exitFullscreen];
+    [self _exitVideoFullscreen];
 #endif
 
 #if PLATFORM(IOS)
@@ -1726,6 +1710,7 @@ static bool fastDocumentTeardownEnabled()
     [self setUIDelegate:nil];
 
     [_private->inspector webViewClosed];
+    [_private->actionMenuController webViewClosed];
 #endif
 
 #if !PLATFORM(IOS)
@@ -1803,7 +1788,7 @@ static bool fastDocumentTeardownEnabled()
 #if !PLATFORM(IOS)
     // Get the MIME type from the extension.
     if ([extension length] != 0) {
-        MIMEType = WKGetMIMETypeForExtension(extension);
+        MIMEType = [[NSURLFileTypeMappings sharedMappings] MIMETypeForExtension:extension];
     }
 #endif
 
@@ -1893,12 +1878,12 @@ static bool fastDocumentTeardownEnabled()
     _private->page->setRemoteInspectionAllowed(allow);
 }
 
-- (void)setIndicatingForRemoteInspector:(BOOL)enabled
+- (void)setShowingInspectorIndication:(BOOL)showing
 {
 #if PLATFORM(IOS)
     ASSERT(WebThreadIsLocked());
 
-    if (enabled) {
+    if (showing) {
         if (!_private->indicateLayer) {
             _private->indicateLayer = [[WebIndicateLayer alloc] initWithWebView:self];
             [_private->indicateLayer setNeedsLayout];
@@ -1910,34 +1895,15 @@ static bool fastDocumentTeardownEnabled()
         _private->indicateLayer = nil;
     }
 #else
-    // FIXME: Needs implementation or put an implementation in WebCore::InspectorOverlay.
+    // Implemented in WebCore::InspectorOverlay.
 #endif
 }
 
 #if PLATFORM(IOS)
-- (void)setHostApplicationBundleId:(NSString *)bundleId name:(NSString *)name
+- (void)_setHostApplicationProcessIdentifier:(pid_t)pid auditToken:(audit_token_t)auditToken
 {
-    if (![_private->hostApplicationBundleId isEqualToString:bundleId]) {
-        [_private->hostApplicationBundleId release];
-        _private->hostApplicationBundleId = [bundleId copy];
-    }
-
-    if (![_private->hostApplicationName isEqualToString:name]) {
-        [_private->hostApplicationName release];
-        _private->hostApplicationName = [name copy];
-    }
-
-    // FIXME: This has not yet been ported to Inspector::RemoteInspectorServer.
-}
-
-- (NSString *)hostApplicationBundleId
-{
-    return _private->hostApplicationBundleId;
-}
-
-- (NSString *)hostApplicationName
-{
-    return _private->hostApplicationName;
+    RetainPtr<CFDataRef> auditData = adoptCF(CFDataCreate(nullptr, (const UInt8*)&auditToken, sizeof(auditToken)));
+    RemoteInspector::shared().setParentProcessInformation(pid, auditData);
 }
 #endif // PLATFORM(IOS)
 #endif // ENABLE(REMOTE_INSPECTOR)
@@ -2020,7 +1986,7 @@ static bool fastDocumentTeardownEnabled()
     }
     
     ASSERT(newItemToGoTo);
-    _private->page->goToItem(newItemToGoTo, FrameLoadTypeIndexedBackForward);
+    _private->page->goToItem(newItemToGoTo, FrameLoadType::IndexedBackForward);
 }
 
 - (void)_setFormDelegate: (id<WebFormDelegate>)delegate
@@ -2142,17 +2108,6 @@ static bool needsSelfRetainWhileLoadingQuirk()
 #endif
 }
 
-- (BOOL)_needsUnrestrictedGetMatchedCSSRules
-{
-#if !PLATFORM(IOS)
-    static bool needsUnrestrictedGetMatchedCSSRules = !WebKitLinkedOnOrAfter(WEBKIT_FIRST_VERSION_WITH_GET_MATCHED_CSS_RULES_RESTRICTIONS) && applicationIsSafari();
-    return needsUnrestrictedGetMatchedCSSRules;
-#else
-    // FIXME: <rdar://problem/8963684> Implement linked-on-or-after check for needsUnrestrictedGetMatchedCSSRules
-    return NO;
-#endif
-}
-
 - (void)_preferencesChangedNotification:(NSNotification *)notification
 {
 #if PLATFORM(IOS)
@@ -2240,14 +2195,9 @@ static bool needsSelfRetainWhileLoadingQuirk()
     settings.setMinimumLogicalFontSize([preferences minimumLogicalFontSize]);
     settings.setPictographFontFamily([preferences pictographFontFamily]);
     settings.setPluginsEnabled([preferences arePlugInsEnabled]);
-#if ENABLE(SQL_DATABASE)
-    DatabaseManager::manager().setIsAvailable([preferences databasesEnabled]);
-#endif
     settings.setLocalStorageEnabled([preferences localStorageEnabled]);
-#if !PLATFORM(IOS)
-    settings.setExperimentalNotificationsEnabled([preferences experimentalNotificationsEnabled]);
-#endif
-    settings.setPrivateBrowsingEnabled([preferences privateBrowsingEnabled]);
+
+    _private->page->enableLegacyPrivateBrowsing([preferences privateBrowsingEnabled]);
     settings.setSansSerifFontFamily([preferences sansSerifFontFamily]);
     settings.setSerifFontFamily([preferences serifFontFamily]);
     settings.setStandardFontFamily([preferences standardFontFamily]);
@@ -2257,7 +2207,6 @@ static bool needsSelfRetainWhileLoadingQuirk()
     settings.setShouldPrintBackgrounds(true);
 #else
     settings.setShouldPrintBackgrounds([preferences shouldPrintBackgrounds]);
-    settings.setTextAreasAreResizable([preferences textAreasAreResizable]);
 #endif
     settings.setShrinksStandaloneImagesToFit([preferences shrinksStandaloneImagesToFit]);
     settings.setEditableLinkBehavior(core([preferences editableLinkBehavior]));
@@ -2266,45 +2215,19 @@ static bool needsSelfRetainWhileLoadingQuirk()
     settings.setUsesPageCache([self usesPageCache]);
     settings.setPageCacheSupportsPlugins([preferences pageCacheSupportsPlugins]);
     settings.setBackForwardCacheExpirationInterval([preferences _backForwardCacheExpirationInterval]);
-#if !PLATFORM(IOS)
-    settings.setShowsURLsInToolTips([preferences showsURLsInToolTips]);
-    settings.setShowsToolTipOverTruncatedText([preferences showsToolTipOverTruncatedText]);
-#endif
+
     settings.setDeveloperExtrasEnabled([preferences developerExtrasEnabled]);
     settings.setJavaScriptExperimentsEnabled([preferences javaScriptExperimentsEnabled]);
     settings.setAuthorAndUserStylesEnabled([preferences authorAndUserStylesEnabled]);
     settings.setApplicationChromeMode([preferences applicationChromeModeEnabled]);
-#if !PLATFORM(IOS)
-    if ([preferences userStyleSheetEnabled]) {
-        NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
-        if ([location isEqualToString:@"apple-dashboard://stylesheet"])
-            location = @"file:///System/Library/PrivateFrameworks/DashboardClient.framework/Resources/widget.css";
-        settings.setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
-    } else
-        settings.setUserStyleSheetLocation([NSURL URLWithString:@""]);
-    settings.setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
-    settings.setTreatsAnyTextCSSLinkAsStylesheet([self _needsLinkElementTextCSSQuirk]);
-    settings.setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
-#else
-    // iOS-specific settings
-    settings.setStandalone([preferences _standalone]);
-    settings.setMaximumDecodedImageSize([preferences _maximumImageSize]);
-    settings.setTelephoneNumberParsingEnabled([preferences _telephoneNumberParsingEnabled]);
-    settings.setAlwaysUseBaselineOfPrimaryFont([preferences _alwaysUseBaselineOfPrimaryFont]);
-    settings.setAllowMultiElementImplicitSubmission([preferences _allowMultiElementImplicitFormSubmission]);
-    settings.setLayoutInterval(std::chrono::milliseconds([preferences _layoutInterval]));
-    settings.setMaxParseDuration([preferences _maxParseDuration]);
-    settings.setAlwaysUseAcceleratedOverflowScroll([preferences _alwaysUseAcceleratedOverflowScroll]);
-#endif
+
     settings.setNeedsSiteSpecificQuirks(_private->useSiteSpecificSpoofing);
+    settings.setDOMTimersThrottlingEnabled([preferences domTimersThrottlingEnabled]);
     settings.setWebArchiveDebugModeEnabled([preferences webArchiveDebugModeEnabled]);
     settings.setLocalFileContentSniffingEnabled([preferences localFileContentSniffingEnabled]);
     settings.setOfflineWebApplicationCacheEnabled([preferences offlineWebApplicationCacheEnabled]);
     settings.setJavaScriptCanAccessClipboard([preferences javaScriptCanAccessClipboard]);
     settings.setXSSAuditorEnabled([preferences isXSSAuditorEnabled]);
-#if !PLATFORM(IOS)
-    settings.setEnforceCSSMIMETypeInNoQuirksMode(!WKAppVersionCheckLessThan(@"com.apple.iWeb", -1, 2.1));
-#endif
     settings.setDNSPrefetchingEnabled([preferences isDNSPrefetchingEnabled]);
     
     // FIXME: Enabling accelerated compositing when WebGL is enabled causes tests to fail on Leopard which expect HW compositing to be disabled.
@@ -2315,10 +2238,8 @@ static bool needsSelfRetainWhileLoadingQuirk()
     settings.setShowDebugBorders([preferences showDebugBorders]);
     settings.setShowRepaintCounter([preferences showRepaintCounter]);
     settings.setWebGLEnabled([preferences webGLEnabled]);
-#if !PLATFORM(IOS)
-    // FIXME: Should we enable this following <rdar://problem/15290404>?
-    settings.setMultithreadedWebGLEnabled([preferences multithreadedWebGLEnabled]);
-#endif
+    settings.setSubpixelCSSOMElementMetricsEnabled([preferences subpixelCSSOMElementMetricsEnabled]);
+
     settings.setForceSoftwareWebGLRendering([preferences forceSoftwareWebGLRendering]);
     settings.setAccelerated2dCanvasEnabled([preferences accelerated2dCanvasEnabled]);
     settings.setLoadDeferringEnabled(shouldEnableLoadDeferring());
@@ -2328,69 +2249,31 @@ static bool needsSelfRetainWhileLoadingQuirk()
     settings.setPaginateDuringLayoutEnabled([preferences paginateDuringLayoutEnabled]);
     RuntimeEnabledFeatures::sharedFeatures().setCSSRegionsEnabled([preferences cssRegionsEnabled]);
     RuntimeEnabledFeatures::sharedFeatures().setCSSCompositingEnabled([preferences cssCompositingEnabled]);
-#if ENABLE(WEB_AUDIO)
-    settings.setWebAudioEnabled([preferences webAudioEnabled]);
-#endif
-    settings.setCSSGridLayoutEnabled([preferences cssGridLayoutEnabled]);
-#if ENABLE(FULLSCREEN_API)
-    settings.setFullScreenEnabled([preferences fullScreenEnabled]);
-#endif
+
     settings.setAsynchronousSpellCheckingEnabled([preferences asynchronousSpellCheckingEnabled]);
     settings.setHyperlinkAuditingEnabled([preferences hyperlinkAuditingEnabled]);
     settings.setUsePreHTML5ParserQuirks([self _needsPreHTML5ParserQuirks]);
-    settings.setCrossOriginCheckInGetMatchedCSSRulesDisabled([self _needsUnrestrictedGetMatchedCSSRules]);
     settings.setInteractiveFormValidationEnabled([self interactiveFormValidationEnabled]);
     settings.setValidationMessageTimerMagnification([self validationMessageTimerMagnification]);
-#if USE(AVFOUNDATION)
-    settings.setAVFoundationEnabled([preferences isAVFoundationEnabled]);
-#endif
-#if PLATFORM(MAC)
-    settings.setQTKitEnabled([preferences isQTKitEnabled]);
-#endif
-#if PLATFORM(IOS)
-    settings.setMediaPlaybackAllowsAirPlay([preferences mediaPlaybackAllowsAirPlay]);
-    settings.setAudioSessionCategoryOverride([preferences audioSessionCategoryOverride]);
-    settings.setNetworkDataUsageTrackingEnabled([preferences networkDataUsageTrackingEnabled]);
-    settings.setNetworkInterfaceName([preferences networkInterfaceName]);
-    settings.setAVKitEnabled([preferences avKitEnabled]);
-#endif
+
     settings.setMediaPlaybackRequiresUserGesture([preferences mediaPlaybackRequiresUserGesture]);
     settings.setMediaPlaybackAllowsInline([preferences mediaPlaybackAllowsInline]);
+    settings.setAllowsAlternateFullscreen([preferences allowsAlternateFullscreen]);
     settings.setSuppressesIncrementalRendering([preferences suppressesIncrementalRendering]);
-    settings.setRegionBasedColumnsEnabled([preferences regionBasedColumnsEnabled]);
     settings.setBackspaceKeyNavigationEnabled([preferences backspaceKeyNavigationEnabled]);
     settings.setWantsBalancedSetDefersLoadingBehavior([preferences wantsBalancedSetDefersLoadingBehavior]);
     settings.setMockScrollbarsEnabled([preferences mockScrollbarsEnabled]);
 
-#if ENABLE(VIDEO_TRACK)
-    settings.setShouldDisplaySubtitles([preferences shouldDisplaySubtitles]);
-    settings.setShouldDisplayCaptions([preferences shouldDisplayCaptions]);
-    settings.setShouldDisplayTextDescriptions([preferences shouldDisplayTextDescriptions]);
-#endif
-
     settings.setShouldRespectImageOrientation([preferences shouldRespectImageOrientation]);
-#if !PLATFORM(IOS)
-    settings.setNeedsIsLoadingInAPISenseQuirk([self _needsIsLoadingInAPISenseQuirk]);
-#endif
+
     settings.setRequestAnimationFrameEnabled([preferences requestAnimationFrameEnabled]);
     settings.setDiagnosticLoggingEnabled([preferences diagnosticLoggingEnabled]);
     settings.setLowPowerVideoAudioBufferSizeEnabled([preferences lowPowerVideoAudioBufferSizeEnabled]);
 
     settings.setUseLegacyTextAlignPositionedElementBehavior([preferences useLegacyTextAlignPositionedElementBehavior]);
 
-#if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
-    settings.setVideoPluginProxyEnabled([preferences isVideoPluginProxyEnabled]);
-#endif
-
-#if ENABLE(MEDIA_SOURCE)
-    settings.setMediaSourceEnabled([preferences mediaSourceEnabled]);
-#endif
-
-#if ENABLE(IMAGE_CONTROLS)
-    settings.setImageControlsEnabled([preferences imageControlsEnabled]);
-#endif
-
     settings.setShouldConvertPositionStyleOnCopy([preferences shouldConvertPositionStyleOnCopy]);
+    settings.setEnableInheritURIQueryComponent([preferences isInheritURIQueryComponentEnabled]);
 
     switch ([preferences storageBlockingPolicy]) {
     case WebAllowAllStorage:
@@ -2406,18 +2289,105 @@ static bool needsSelfRetainWhileLoadingQuirk()
 
     settings.setPlugInSnapshottingEnabled([preferences plugInSnapshottingEnabled]);
 
+    settings.setFixedPositionCreatesStackingContext(true);
+#if PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
+    settings.setAcceleratedCompositingForFixedPositionEnabled(true);
+#endif
+
+#if ENABLE(RUBBER_BANDING)
+    // FIXME: https://bugs.webkit.org/show_bug.cgi?id=136131
+    settings.setRubberBandingForSubScrollableRegionsEnabled(false);
+#endif
+
+#if PLATFORM(IOS)
+    settings.setStandalone([preferences _standalone]);
+    settings.setTelephoneNumberParsingEnabled([preferences _telephoneNumberParsingEnabled]);
+    settings.setAlwaysUseBaselineOfPrimaryFont([preferences _alwaysUseBaselineOfPrimaryFont]);
+    settings.setAllowMultiElementImplicitSubmission([preferences _allowMultiElementImplicitFormSubmission]);
+    settings.setLayoutInterval(std::chrono::milliseconds([preferences _layoutInterval]));
+    settings.setMaxParseDuration([preferences _maxParseDuration]);
+    settings.setAlwaysUseAcceleratedOverflowScroll([preferences _alwaysUseAcceleratedOverflowScroll]);
+    settings.setMediaPlaybackAllowsAirPlay([preferences mediaPlaybackAllowsAirPlay]);
+    settings.setAudioSessionCategoryOverride([preferences audioSessionCategoryOverride]);
+    settings.setNetworkDataUsageTrackingEnabled([preferences networkDataUsageTrackingEnabled]);
+    settings.setNetworkInterfaceName([preferences networkInterfaceName]);
+    settings.setAVKitEnabled([preferences avKitEnabled]);
+    settings.setShouldTransformsAffectOverflow(shouldTransformsAffectOverflow());
+    settings.setShouldDispatchJavaScriptWindowOnErrorEvents(shouldDispatchJavaScriptWindowOnErrorEvents());
+
+    settings.setPasswordEchoEnabled([preferences _allowPasswordEcho]);
+    settings.setPasswordEchoDurationInSeconds([preferences _passwordEchoDuration]);
+
+    ASSERT_WITH_MESSAGE(settings.pageCacheSupportsPlugins(), "PageCacheSupportsPlugins should be enabled on iOS.");
+    settings.setDelegatesPageScaling(true);
+
+#if ENABLE(IOS_TEXT_AUTOSIZING)
+    settings.setMinimumZoomFontSize([preferences _minimumZoomFontSize]);
+#endif
+#endif // PLATFORM(IOS)
+
+#if PLATFORM(MAC)
+    if ([preferences userStyleSheetEnabled]) {
+        NSString* location = [[preferences userStyleSheetLocation] _web_originalDataAsString];
+        if ([location isEqualToString:@"apple-dashboard://stylesheet"])
+            location = @"file:///System/Library/PrivateFrameworks/DashboardClient.framework/Resources/widget.css";
+        settings.setUserStyleSheetLocation([NSURL URLWithString:(location ? location : @"")]);
+    } else
+        settings.setUserStyleSheetLocation([NSURL URLWithString:@""]);
+
+    settings.setNeedsAdobeFrameReloadingQuirk([self _needsAdobeFrameReloadingQuirk]);
+    settings.setTreatsAnyTextCSSLinkAsStylesheet([self _needsLinkElementTextCSSQuirk]);
+    settings.setNeedsKeyboardEventDisambiguationQuirks([self _needsKeyboardEventDisambiguationQuirks]);
+    settings.setEnforceCSSMIMETypeInNoQuirksMode(!WKAppVersionCheckLessThan(@"com.apple.iWeb", -1, 2.1));
+    settings.setNeedsIsLoadingInAPISenseQuirk([self _needsIsLoadingInAPISenseQuirk]);
+    settings.setTextAreasAreResizable([preferences textAreasAreResizable]);
+    settings.setExperimentalNotificationsEnabled([preferences experimentalNotificationsEnabled]);
+    settings.setShowsURLsInToolTips([preferences showsURLsInToolTips]);
+    settings.setShowsToolTipOverTruncatedText([preferences showsToolTipOverTruncatedText]);
+    settings.setQTKitEnabled([preferences isQTKitEnabled]);
+#endif // PLATFORM(MAC)
+
+#if ENABLE(SQL_DATABASE)
+    DatabaseManager::manager().setIsAvailable([preferences databasesEnabled]);
+#endif
+
+#if ENABLE(MEDIA_SOURCE)
+    settings.setMediaSourceEnabled([preferences mediaSourceEnabled]);
+#endif
+
+#if ENABLE(SERVICE_CONTROLS)
+    settings.setImageControlsEnabled([preferences imageControlsEnabled]);
+    settings.setServiceControlsEnabled([preferences serviceControlsEnabled]);
+#endif
+
+#if ENABLE(VIDEO_TRACK)
+    settings.setShouldDisplaySubtitles([preferences shouldDisplaySubtitles]);
+    settings.setShouldDisplayCaptions([preferences shouldDisplayCaptions]);
+    settings.setShouldDisplayTextDescriptions([preferences shouldDisplayTextDescriptions]);
+#endif
+
+#if USE(AVFOUNDATION)
+    settings.setAVFoundationEnabled([preferences isAVFoundationEnabled]);
+#endif
+
+#if ENABLE(WEB_AUDIO)
+    settings.setWebAudioEnabled([preferences webAudioEnabled]);
+#endif
+
+#if ENABLE(FULLSCREEN_API)
+    settings.setFullScreenEnabled([preferences fullScreenEnabled]);
+#endif
+
 #if ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING)
     settings.setHiddenPageDOMTimerThrottlingEnabled([preferences hiddenPageDOMTimerThrottlingEnabled]);
 #endif
-#if ENABLE(PAGE_VISIBILITY_API)
+
     settings.setHiddenPageCSSAnimationSuspensionEnabled([preferences hiddenPageCSSAnimationSuspensionEnabled]);
+
+#if ENABLE(GAMEPAD)
+    RuntimeEnabledFeatures::sharedFeatures().setGamepadsEnabled([preferences gamepadsEnabled]);
 #endif
 
-    // We have enabled this setting in WebKit2 for the sake of some ScrollingCoordinator work.
-    // To avoid possible rendering differences, we should enable it for WebKit1 too. We also
-    // want to keep this setting enabled for iOS. See <rdar://problem/9813262> for more details.
-    settings.setFixedPositionCreatesStackingContext(true);
-    
     NSTimeInterval timeout = [preferences incrementalRenderingSuppressionTimeoutInSeconds];
     if (timeout > 0)
         settings.setIncrementalRenderingSuppressionTimeoutInSeconds(timeout);
@@ -2429,31 +2399,15 @@ static bool needsSelfRetainWhileLoadingQuirk()
     if (_private->zoomsTextOnly != zoomsTextOnly)
         [self _setZoomMultiplier:_private->zoomMultiplier isTextOnly:zoomsTextOnly];
 
-#if ENABLE(IOS_TEXT_AUTOSIZING)
-    settings.setMinimumZoomFontSize([preferences _minimumZoomFontSize]);
-#endif
-
-#if ENABLE(DISK_IMAGE_CACHE) && PLATFORM(IOS)
-    DiskImageCache& diskImageCache = WebCore::diskImageCache();
-    diskImageCache.setEnabled([preferences diskImageCacheEnabled]);
-    diskImageCache.setMinimumImageSize([preferences diskImageCacheMinimumImageSize]);
-    diskImageCache.setMaximumCacheSize([preferences diskImageCacheMaximumCacheSize]);
-#endif
-
 #if PLATFORM(IOS)
     [[self window] setTileBordersVisible:[preferences showDebugBorders]];
     [[self window] setTilePaintCountsVisible:[preferences showRepaintCounter]];
     [[self window] setAcceleratedDrawingEnabled:[preferences acceleratedDrawingEnabled]];
     [WAKView _setInterpolationQuality:[preferences _interpolationQuality]];
-    settings.setDelegatesPageScaling(true);
-    
-    settings.setShouldTransformsAffectOverflow(shouldTransformsAffectOverflow());
-    settings.setShouldDispatchJavaScriptWindowOnErrorEvents(shouldDispatchJavaScriptWindowOnErrorEvents());
-    ASSERT_WITH_MESSAGE(settings.pageCacheSupportsPlugins(), "PageCacheSupportsPlugins should be enabled on iOS.");
+#endif
 
-    // Password echo
-    settings.setPasswordEchoEnabled([preferences _allowPasswordEcho]);
-    settings.setPasswordEchoDurationInSeconds([preferences _passwordEchoDuration]);
+#if ENABLE(ENCRYPTED_MEDIA_V2)
+    settings.setMediaKeysStorageDirectory([preferences mediaKeysStorageDirectory]);
 #endif
 }
 
@@ -2741,10 +2695,8 @@ static inline IMP getMethod(id o, SEL s)
     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"applewebdata"])
         return YES;
 
-#if ENABLE(BLOB)
     if ([scheme _webkit_isCaseInsensitiveEqualToString:@"blob"])
         return YES;
-#endif
 
     return NO;
 }
@@ -2757,10 +2709,7 @@ static inline IMP getMethod(id o, SEL s)
 + (NSString *)_decodeData:(NSData *)data
 {
     HTMLNames::init(); // this method is used for importing bookmarks at startup, so HTMLNames are likely to be uninitialized yet
-    RefPtr<TextResourceDecoder> decoder = TextResourceDecoder::create("text/html"); // bookmark files are HTML
-    String result = decoder->decode(static_cast<const char*>([data bytes]), [data length]);
-    result.append(decoder->flush());
-    return result;
+    return TextResourceDecoder::create("text/html")->decodeAndFlush(static_cast<const char*>([data bytes]), [data length]); // bookmark files are HTML
 }
 
 - (void)_pushPerformingProgrammaticFocus
@@ -3026,8 +2975,8 @@ static inline IMP getMethod(id o, SEL s)
     NSView *documentView = [[kit(&frameView->frame()) frameView] documentView];
 
     for (const auto& widget: frameView->children()) {
-        if (widget->isFrameView()) {
-            [self _addScrollerDashboardRegionsForFrameView:toFrameView(widget.get()) dashboardRegions:regions];
+        if (is<FrameView>(*widget)) {
+            [self _addScrollerDashboardRegionsForFrameView:downcast<FrameView>(widget.get()) dashboardRegions:regions];
             continue;
         }
 
@@ -3098,7 +3047,7 @@ static inline IMP getMethod(id o, SEL s)
             [regionValues release];
         }
 
-        WebDashboardRegion *webRegion = [[WebDashboardRegion alloc] initWithRect:pixelSnappedIntRect(region.bounds) clip:pixelSnappedIntRect(region.clip) type:type];
+        WebDashboardRegion *webRegion = [[WebDashboardRegion alloc] initWithRect:snappedIntRect(region.bounds) clip:snappedIntRect(region.clip) type:type];
         [regionValues addObject:webRegion];
         [webRegion release];
     }
@@ -3481,7 +3430,7 @@ static inline IMP getMethod(id o, SEL s)
             continue;
         
         if (layerForWidget->contentsLayerForMedia() != layer) {
-            layerForWidget->setContentsToMedia(layer);
+            layerForWidget->setContentsToPlatformLayer(layer, GraphicsLayer::ContentsLayerForMedia);
             // We need to make sure the layer hierachy change is applied immediately.
             if (mainCoreFrame->view())
                 mainCoreFrame->view()->flushCompositingStateIncludingSubframes();
@@ -3607,11 +3556,6 @@ static inline IMP getMethod(id o, SEL s)
     return _private->allowsMessaging;
 }
 
-// FIXME: Remove once this is no longer necessary for UIKit binary compatibility.
-- (void)_setNetworkStateIsOnline:(BOOL)isOnLine
-{
-}
-
 - (void)_setFixedLayoutSize:(CGSize)size
 {
     ASSERT(WebThreadIsLocked());
@@ -3730,6 +3674,11 @@ static inline IMP getMethod(id o, SEL s)
         if (rect.isEmpty())
             continue;
 
+        // Note that these rectangles are in the coordinate system of the document (inside the WebHTMLView), which is not
+        // the same as the coordinate system of the WebView. If you want to do comparisons with locations in the WebView,
+        // you must convert between the two using WAKView's convertRect:toView: selector. This will take care of scaling
+        // and translations (which are relevant for right-to-left column layout).
+
         // The event region wants this points in this order:
         //  p2------p3
         //  |       |
@@ -3956,7 +3905,7 @@ static inline IMP getMethod(id o, SEL s)
     NSMutableArray* rectsArray = [[NSMutableArray alloc] initWithCapacity:repaintRects.size()];
     
     for (unsigned i = 0; i < repaintRects.size(); ++i)
-        [rectsArray addObject:[NSValue valueWithRect:pixelSnappedIntRect(LayoutRect(repaintRects[i]))]];
+        [rectsArray addObject:[NSValue valueWithRect:snappedIntRect(LayoutRect(repaintRects[i]))]];
 
     return [rectsArray autorelease];
 }
@@ -4358,10 +4307,8 @@ static Vector<String> toStringVector(NSArray* patterns)
 
 - (WebPageVisibilityState)_visibilityState
 {
-#if ENABLE(PAGE_VISIBILITY_API) || ENABLE(HIDDEN_PAGE_DOM_TIMER_THROTTLING)
     if (_private->page)
         return kit(_private->page->visibilityState());
-#endif
     return WebPageVisibilityStateVisible;
 }
 
@@ -4546,7 +4493,7 @@ static Vector<String> toStringVector(NSArray* patterns)
 
 + (void)_setTileCacheLayerPoolCapacity:(unsigned)capacity
 {
-    TileCache::setLayerPoolCapacity(capacity);
+    LegacyTileCache::setLayerPoolCapacity(capacity);
 }
 #endif // PLATFORM(IOS)
 
@@ -4850,22 +4797,6 @@ static Vector<String> toStringVector(NSArray* patterns)
     return nil;
 }
 
-#if ENABLE(PLUGIN_PROXY_FOR_VIDEO)
-- (WebBasePluginPackage *)_videoProxyPluginForMIMEType:(NSString *)MIMEType
-{
-    WebBasePluginPackage *pluginPackage = [[WebPluginDatabase sharedDatabase] pluginForMIMEType:MIMEType];
-    if (pluginPackage)
-        return pluginPackage;
-
-#if !PLATFORM(IOS)
-    if (_private->pluginDatabase)
-        return [_private->pluginDatabase pluginForMIMEType:MIMEType];
-#endif
-
-    return nil;
-}
-#endif
-
 - (WebBasePluginPackage *)_pluginForExtension:(NSString *)extension
 {
     if (![_private->preferences arePlugInsEnabled])
@@ -5050,7 +4981,7 @@ static bool needsWebViewInitThreadWorkaround()
 #endif
 
     WebCoreThreadViolationCheckRoundTwo();
-    return [self _initWithFrame:f frameName:frameName groupName:groupName usesDocumentViews:YES];
+    return [self _initWithFrame:f frameName:frameName groupName:groupName];
 }
 
 #if !PLATFORM(IOS)
@@ -5156,26 +5087,32 @@ static bool needsWebViewInitThreadWorkaround()
     if (WebCoreObjCScheduleDeallocateOnMainThread([WebView class], self))
         return;
 
+    // Because the machinations of the view's shutdown may cause self to be added to
+    // active autorelease pool, we capture any such releases here to ensure they are
+    // carried out before we are dealloc'd.
+    @autoreleasepool {
+
 #if PLATFORM(IOS)
-    if (_private)
-        [_private->_geolocationProvider stopTrackingWebView:self];
+        if (_private)
+            [_private->_geolocationProvider stopTrackingWebView:self];
 #endif
 
-    // call close to ensure we tear-down completely
-    // this maintains our old behavior for existing applications
-    [self close];
+        // call close to ensure we tear-down completely
+        // this maintains our old behavior for existing applications
+        [self close];
 
-    if ([[self class] shouldIncludeInWebKitStatistics])
-        --WebViewCount;
+        if ([[self class] shouldIncludeInWebKitStatistics])
+            --WebViewCount;
 
 #if !PLATFORM(IOS)
-    if ([self _needsFrameLoadDelegateRetainQuirk])
-        [_private->frameLoadDelegate release];
+        if ([self _needsFrameLoadDelegateRetainQuirk])
+            [_private->frameLoadDelegate release];
 #endif
-        
-    [_private release];
-    // [super dealloc] can end up dispatching against _private (3466082)
-    _private = nil;
+
+        [_private release];
+        // [super dealloc] can end up dispatching against _private (3466082)
+        _private = nil;
+    }
 
     [super dealloc];
 }
@@ -5220,6 +5157,10 @@ static NSString * const backingPropertyOldScaleFactorKey = @"NSBackingPropertyOl
 - (void)addWindowObserversForWindow:(NSWindow *)window
 {
     if (window) {
+        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowKeyStateChanged:)
+            name:NSWindowDidBecomeKeyNotification object:window];
+        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowKeyStateChanged:)
+            name:NSWindowDidResignKeyNotification object:window];
         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowWillOrderOnScreen:)
             name:WKWindowWillOrderOnScreenNotification() object:window];
         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_windowWillOrderOffScreen:)
@@ -5244,6 +5185,10 @@ static NSString * const backingPropertyOldScaleFactorKey = @"NSBackingPropertyOl
     NSWindow *window = [self window];
     if (window) {
         [[NSNotificationCenter defaultCenter] removeObserver:self
+            name:NSWindowDidBecomeKeyNotification object:window];
+        [[NSNotificationCenter defaultCenter] removeObserver:self
+            name:NSWindowDidResignKeyNotification object:window];
+        [[NSNotificationCenter defaultCenter] removeObserver:self
             name:WKWindowWillOrderOnScreenNotification() object:window];
         [[NSNotificationCenter defaultCenter] removeObserver:self
             name:WKWindowWillOrderOffScreenNotification() object:window];
@@ -5314,7 +5259,11 @@ static NSString * const backingPropertyOldScaleFactorKey = @"NSBackingPropertyOl
         [window setAcceleratedDrawingEnabled:[preferences acceleratedDrawingEnabled]];
 #endif
     }
-    
+#if PLATFORM(IOS)
+    else
+        [_private->fullscreenController requestHideAndExitFullscreen];
+#endif
+
 #if !PLATFORM(IOS)
     _private->page->setDeviceScaleFactor([self _deviceScaleFactor]);
 #endif
@@ -5333,10 +5282,24 @@ static NSString * const backingPropertyOldScaleFactorKey = @"NSBackingPropertyOl
 - (void)_windowChangedKeyState
 {
     [self _updateActiveState];
-
     [super _windowChangedKeyState];
 }
 
+- (void)windowKeyStateChanged:(NSNotification *)notification
+{
+    [self _updateActiveState];
+}
+
+- (void)viewDidHide
+{
+    [self _updateVisibilityState];
+}
+
+- (void)viewDidUnhide
+{
+    [self _updateVisibilityState];
+}
+
 - (void)_windowWillOrderOnScreen:(NSNotification *)notification
 {
     if (![self shouldUpdateWhileOffscreen])
@@ -5648,7 +5611,7 @@ static NSString * const backingPropertyOldScaleFactorKey = @"NSBackingPropertyOl
     if (!_private->page)
         return NO;
 
-    _private->page->goToItem(core(item), FrameLoadTypeIndexedBackForward);
+    _private->page->goToItem(core(item), FrameLoadType::IndexedBackForward);
     return YES;
 }
 
@@ -5978,7 +5941,7 @@ static NSString * const backingPropertyOldScaleFactorKey = @"NSBackingPropertyOl
     IntPoint client([draggingInfo draggingLocation]);
     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
     DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
-    return core(self)->dragController().dragEntered(dragData).operation;
+    return core(self)->dragController().dragEntered(dragData);
 }
 
 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo
@@ -5990,7 +5953,7 @@ static NSString * const backingPropertyOldScaleFactorKey = @"NSBackingPropertyOl
     IntPoint client([draggingInfo draggingLocation]);
     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
     DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
-    return page->dragController().dragUpdated(dragData).operation;
+    return page->dragController().dragUpdated(dragData);
 }
 
 - (void)draggingExited:(id <NSDraggingInfo>)draggingInfo
@@ -6015,7 +5978,7 @@ static NSString * const backingPropertyOldScaleFactorKey = @"NSBackingPropertyOl
     IntPoint client([draggingInfo draggingLocation]);
     IntPoint global(globalPoint([draggingInfo draggingLocation], [self window]));
     DragData dragData(draggingInfo, client, global, static_cast<DragOperation>([draggingInfo draggingSourceOperationMask]), [self applicationFlags:draggingInfo]);
-    return core(self)->dragController().performDrag(dragData);
+    return core(self)->dragController().performDragOperation(dragData);
 }
 
 - (NSView *)_hitTest:(NSPoint *)point dragTypes:(NSSet *)types
@@ -6791,7 +6754,7 @@ static NSAppleEventDescriptor* aeDescFromJSValue(ExecState* exec, JSC::JSValue j
             }
         }
         else if (object->inherits(JSArray::info())) {
-            DEFINE_STATIC_LOCAL(HashSet<JSObject*>, visitedElems, ());
+            DEPRECATED_DEFINE_STATIC_LOCAL(HashSet<JSObject*>, visitedElems, ());
             if (!visitedElems.contains(object)) {
                 visitedElems.add(object);
                 
@@ -7585,7 +7548,7 @@ static NSAppleEventDescriptor* aeDescFromJSValue(ExecState* exec, JSC::JSValue j
     if (Frame* coreFrame = core(webFrame)) {
         // FIXME: We shouldn't have to make a copy here.
         Ref<MutableStyleProperties> properties(core(style)->copyProperties());
-        coreFrame->editor().applyStyle(&properties.get());
+        coreFrame->editor().applyStyle(properties.ptr());
     }
 }
 
@@ -7744,7 +7707,7 @@ static inline uint64_t roundUpToPowerOf2(uint64_t num)
     unsigned cacheTotalCapacity = 0;
     unsigned cacheMinDeadCapacity = 0;
     unsigned cacheMaxDeadCapacity = 0;
-    double deadDecodedDataDeletionInterval = 0;
+    auto deadDecodedDataDeletionInterval = std::chrono::seconds { 0 };
 
     unsigned pageCacheCapacity = 0;
 
@@ -7845,10 +7808,6 @@ static inline uint64_t roundUpToPowerOf2(uint64_t num)
         break;
     }
     case WebCacheModelPrimaryWebBrowser: {
-#if PLATFORM(IOS)
-        WebPreferences *preferences = [WebPreferences standardPreferences];
-        int prefValue;
-#endif
         // Page cache capacity (in pages)
         // (Research indicates that value / page drops substantially after 3 pages.)
         if (memSize >= 2048)
@@ -7868,9 +7827,6 @@ static inline uint64_t roundUpToPowerOf2(uint64_t num)
         // Reducing the capacity by 1 reduces overall back-forward performance.
         if (pageCacheCapacity > 0)
             pageCacheCapacity -= 1;
-        prefValue = [preferences _pageCacheSize];
-        if (prefValue >= 0)
-            pageCacheCapacity = prefValue;
 #endif
 
         // Object cache capacities (in bytes)
@@ -7886,12 +7842,6 @@ static inline uint64_t roundUpToPowerOf2(uint64_t num)
         else if (memSize >= 512)
             cacheTotalCapacity = 32 * 1024 * 1024;
 
-#if PLATFORM(IOS)
-        prefValue = [preferences _objectCacheSize];
-        if (prefValue >= 0)
-            cacheTotalCapacity = prefValue;
-#endif
-
         cacheMinDeadCapacity = cacheTotalCapacity / 4;
         cacheMaxDeadCapacity = cacheTotalCapacity / 2;
 
@@ -7899,17 +7849,13 @@ static inline uint64_t roundUpToPowerOf2(uint64_t num)
         // can prove that the overall system gain would justify the regression.
         cacheMaxDeadCapacity = std::max<unsigned>(24, cacheMaxDeadCapacity);
 
-        deadDecodedDataDeletionInterval = 60;
+        deadDecodedDataDeletionInterval = std::chrono::seconds { 60 };
 
 #if PLATFORM(IOS)
         if (memSize >= 1024)
             nsurlCacheMemoryCapacity = 16 * 1024 * 1024;
         else
             nsurlCacheMemoryCapacity = 8 * 1024 * 1024;
-        
-        prefValue = [preferences _NSURLMemoryCacheSize];
-        if (prefValue >= 0)
-            nsurlCacheMemoryCapacity = prefValue;
 #else
         // Foundation memory cache capacity (in bytes)
         // (These values are small because WebCore does most caching itself.)
@@ -7938,10 +7884,6 @@ static inline uint64_t roundUpToPowerOf2(uint64_t num)
             nsurlCacheDiskCapacity = 50 * 1024 * 1024;
 
 #if PLATFORM(IOS)
-        prefValue = [preferences _NSURLDiskCacheSize];
-        if (prefValue >= 0)
-            nsurlCacheDiskCapacity = prefValue;
-
         // TileCache layer pool capacity, in bytes.
         if (memSize >= 1024)
             tileLayerPoolCapacity = 48 * 1024 * 1024;
@@ -7958,8 +7900,8 @@ static inline uint64_t roundUpToPowerOf2(uint64_t num)
     // Don't shrink a big disk cache, since that would cause churn.
     nsurlCacheDiskCapacity = std::max(nsurlCacheDiskCapacity, [nsurlCache diskCapacity]);
 
-    memoryCache()->setCapacities(cacheMinDeadCapacity, cacheMaxDeadCapacity, cacheTotalCapacity);
-    memoryCache()->setDeadDecodedDataDeletionInterval(deadDecodedDataDeletionInterval);
+    memoryCache().setCapacities(cacheMinDeadCapacity, cacheMaxDeadCapacity, cacheTotalCapacity);
+    memoryCache().setDeadDecodedDataDeletionInterval(deadDecodedDataDeletionInterval);
     pageCache()->setCapacity(pageCacheCapacity);
 #if PLATFORM(IOS)
     pageCache()->setShouldClearBackingStores(true);
@@ -8334,15 +8276,6 @@ static inline uint64_t roundUpToPowerOf2(uint64_t num)
     _private->needsOneShotDrawingSynchronization = needsSynchronization;
 }
 
-- (BOOL)_flushCompositingChanges
-{
-    Frame* frame = [self _mainCoreFrame];
-    if (frame && frame->view())
-        return frame->view()->flushCompositingStateIncludingSubframes();
-
-    return YES;
-}
-
 /*
     The order of events with compositing updates is this:
     
@@ -8407,8 +8340,6 @@ bool LayerFlushController::flushLayers()
 
     [m_webView _viewWillDrawInternal];
 
-    [m_webView _viewWillDrawInternal];
-
     if ([m_webView _flushCompositingChanges]) {
 #if !PLATFORM(IOS)
         // AppKit may have disabled screen updates, thinking an upcoming window flush will re-enable them.
@@ -8436,6 +8367,15 @@ bool LayerFlushController::flushLayers()
     _private->layerFlushController->scheduleLayerFlush();
 }
 
+- (BOOL)_flushCompositingChanges
+{
+    Frame* frame = [self _mainCoreFrame];
+    if (frame && frame->view())
+        return frame->view()->flushCompositingStateIncludingSubframes();
+
+    return YES;
+}
+
 #if PLATFORM(IOS)
 - (void)_scheduleLayerFlushForPendingTileCacheRepaint
 {
@@ -8446,39 +8386,36 @@ bool LayerFlushController::flushLayers()
 #endif
 
 #if ENABLE(VIDEO)
-- (void)_enterFullscreenForNode:(WebCore::Node*)node
+- (void)_enterVideoFullscreenForVideoElement:(WebCore::HTMLVideoElement*)videoElement mode:(WebCore::HTMLMediaElement::VideoFullscreenMode)mode
 {
-    ASSERT(isHTMLVideoElement(node));
-    HTMLMediaElement* videoElement = toHTMLMediaElement(node);
-
     if (_private->fullscreenController) {
-        if ([_private->fullscreenController mediaElement] == videoElement) {
+        if ([_private->fullscreenController videoElement] == videoElement) {
             // The backend may just warn us that the underlaying plaftormMovie()
             // has changed. Just force an update.
-            [_private->fullscreenController setMediaElement:videoElement];
+            [_private->fullscreenController setVideoElement:videoElement];
             return; // No more to do.
         }
 
-        // First exit Fullscreen for the old mediaElement.
-        [_private->fullscreenController mediaElement]->exitFullscreen();
+        // First exit Fullscreen for the old videoElement.
+        [_private->fullscreenController videoElement]->exitFullscreen();
         // This previous call has to trigger _exitFullscreen,
         // which has to clear _private->fullscreenController.
         ASSERT(!_private->fullscreenController);
     }
     if (!_private->fullscreenController) {
         _private->fullscreenController = [[WebVideoFullscreenController alloc] init];
-        [_private->fullscreenController setMediaElement:videoElement];
+        [_private->fullscreenController setVideoElement:videoElement];
 #if PLATFORM(IOS)
-        [_private->fullscreenController enterFullscreen:nil];
+        [_private->fullscreenController enterFullscreen:(UIView *)[[[self window] hostLayer] delegate] mode:mode];
 #else
         [_private->fullscreenController enterFullscreen:[[self window] screen]];
 #endif
     }
     else
-        [_private->fullscreenController setMediaElement:videoElement];
+        [_private->fullscreenController setVideoElement:videoElement];
 }
 
-- (void)_exitFullscreen
+- (void)_exitVideoFullscreen
 {
     if (!_private->fullscreenController)
         return;
@@ -8487,7 +8424,7 @@ bool LayerFlushController::flushLayers()
     _private->fullscreenController = nil;
 }
 
-#endif // ENABLE(VIDEO) && !PLATFORM(IOS)
+#endif // ENABLE(VIDEO)
 
 #if ENABLE(FULLSCREEN_API) && !PLATFORM(IOS)
 - (BOOL)_supportsFullScreenForElement:(const WebCore::Element*)element withKeyboard:(BOOL)withKeyboard
@@ -8581,6 +8518,15 @@ static void glibContextIterationCallback(CFRunLoopObserverRef, CFRunLoopActivity
 }
 #endif
 
+#if ENABLE(SERVICE_CONTROLS)
+- (WebSelectionServiceController&)_selectionServiceController
+{
+    if (!_private->_selectionServiceController)
+        _private->_selectionServiceController = std::make_unique<WebSelectionServiceController>(self);
+    return *_private->_selectionServiceController;
+}
+#endif
+
 - (NSPoint)_convertPointFromRootView:(NSPoint)point
 {
     return NSMakePoint(point.x, [self bounds].size.height - point.y);
@@ -8591,6 +8537,32 @@ static void glibContextIterationCallback(CFRunLoopObserverRef, CFRunLoopActivity
     return NSMakeRect(rect.origin.x, [self bounds].size.height - rect.origin.y - rect.size.height, rect.size.width, rect.size.height);
 }
 
+#if !PLATFORM(IOS)
+- (void)prepareForMenu:(NSMenu *)menu withEvent:(NSEvent *)event
+{
+    if (menu != self.actionMenu)
+        return;
+
+    [_private->actionMenuController prepareForMenu:menu withEvent:event];
+}
+
+- (void)willOpenMenu:(NSMenu *)menu withEvent:(NSEvent *)event
+{
+    if (menu != self.actionMenu)
+        return;
+
+    [_private->actionMenuController willOpenMenu:menu withEvent:event];
+}
+
+- (void)didCloseMenu:(NSMenu *)menu withEvent:(NSEvent *)event
+{
+    if (menu != self.actionMenu)
+        return;
+
+    [_private->actionMenuController didCloseMenu:menu withEvent:event];
+}
+#endif
+
 @end
 
 @implementation WebView (WebViewDeviceOrientation)
@@ -8709,7 +8681,7 @@ static void glibContextIterationCallback(CFRunLoopObserverRef, CFRunLoopActivity
 {
 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
     JSContextRef context = [[self mainFrame] globalContext];
-    WebCore::Notification* notification = toNotification(toJS(toJS(context), jsNotification));
+    WebCore::Notification* notification = JSNotification::toWrapped(toJS(toJS(context), jsNotification));
     return static_cast<WebNotificationClient*>(NotificationController::clientFrom(_private->page))->notificationIDForTesting(notification);
 #else
     return 0;