[Mac] Regression: WebContent process's display name is no longer set
[WebKit-https.git] / Source / WebKit / WebProcess / cocoa / WebProcessCocoa.mm
index 7cdf287..ce2e48e 100644 (file)
 #import <WebCore/AVFoundationMIMETypeCache.h>
 #import <WebCore/AXObjectCache.h>
 #import <WebCore/CPUMonitor.h>
+#import <WebCore/DisplayRefreshMonitorManager.h>
 #import <WebCore/FileSystem.h>
 #import <WebCore/FontCache.h>
 #import <WebCore/FontCascade.h>
+#import <WebCore/HistoryController.h>
+#import <WebCore/HistoryItem.h>
 #import <WebCore/LocalizedStrings.h>
 #import <WebCore/LogInitialization.h>
 #import <WebCore/MemoryRelease.h>
@@ -64,6 +67,7 @@
 #import <algorithm>
 #import <dispatch/dispatch.h>
 #import <objc/runtime.h>
+#import <pal/spi/cg/CoreGraphicsSPI.h>
 #import <pal/spi/cocoa/LaunchServicesSPI.h>
 #import <pal/spi/cocoa/QuartzCoreSPI.h>
 #import <pal/spi/cocoa/pthreadSPI.h>
 #import <pal/spi/mac/NSApplicationSPI.h>
 #import <stdio.h>
 
-#if PLATFORM(IOS)
+#if PLATFORM(IOS_FAMILY)
+#import "WKAccessibilityWebPageObjectIOS.h"
 #import <UIKit/UIAccessibility.h>
 #import <pal/spi/ios/GraphicsServicesSPI.h>
+#endif
 
-#if USE(APPLE_INTERNAL_SDK)
+#if PLATFORM(IOS_FAMILY) && USE(APPLE_INTERNAL_SDK)
 #import <AXRuntime/AXDefines.h>
 #import <AXRuntime/AXNotificationConstants.h>
-#else
-#define kAXPidStatusChangedNotification 0
 #endif
 
+#if PLATFORM(IOS_FAMILY) && !USE(APPLE_INTERNAL_SDK)
+#define kAXPidStatusChangedNotification 0
 #endif
 
 #if PLATFORM(MAC)
+#import "WKAccessibilityWebPageObjectMac.h"
+#import "WebSwitchingGPUClient.h"
+#import <WebCore/GraphicsContext3DManager.h>
 #import <WebCore/ScrollbarThemeMac.h>
+#import <pal/spi/mac/NSScrollerImpSPI.h>
 #endif
 
 #if USE(OS_STATE)
 #import <os/state_private.h>
 #endif
 
-using namespace WebCore;
-
 namespace WebKit {
+using namespace WebCore;
 
 #if PLATFORM(MAC)
 static const Seconds cpuMonitoringInterval { 8_min };
@@ -123,6 +132,8 @@ void WebProcess::platformInitializeWebProcess(WebProcessCreationParameters&& par
 #endif
 
     WebCore::setApplicationBundleIdentifier(parameters.uiProcessBundleIdentifier);
+    WebCore::setApplicationSDKVersion(parameters.uiProcessSDKVersion);
+
     SessionTracker::setIdentifierBase(parameters.uiProcessBundleIdentifier);
 
 #if ENABLE(SANDBOX_EXTENSIONS)
@@ -135,7 +146,7 @@ void WebProcess::platformInitializeWebProcess(WebProcessCreationParameters&& par
 #if ENABLE(MEDIA_STREAM)
     SandboxExtension::consumePermanently(parameters.audioCaptureExtensionHandle);
 #endif
-#if PLATFORM(IOS)
+#if PLATFORM(IOS_FAMILY)
     SandboxExtension::consumePermanently(parameters.cookieStorageDirectoryExtensionHandle);
     SandboxExtension::consumePermanently(parameters.containerCachesDirectoryExtensionHandle);
     SandboxExtension::consumePermanently(parameters.containerTemporaryDirectoryExtensionHandle);
@@ -194,12 +205,15 @@ void WebProcess::platformInitializeWebProcess(WebProcessCreationParameters&& par
 
 #if PLATFORM(MAC)
     WebCore::setScreenProperties(parameters.screenProperties);
+#if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
+    scrollerStylePreferenceChanged(parameters.useOverlayScrollbars);
+#endif
 #endif
 }
 
 void WebProcess::initializeProcessName(const ChildProcessInitializationParameters& parameters)
 {
-#if !PLATFORM(IOS)
+#if !PLATFORM(IOS_FAMILY)
     NSString *applicationName;
     if (parameters.extraInitializationData.get("inspector-process"_s) == "1")
         applicationName = [NSString stringWithFormat:WEB_UI_STRING("%@ Web Inspector", "Visible name of Web Inspector's web process. The argument is the application name."), (NSString *)parameters.uiProcessName];
@@ -209,7 +223,21 @@ void WebProcess::initializeProcessName(const ChildProcessInitializationParameter
 #endif
     else
         applicationName = [NSString stringWithFormat:WEB_UI_STRING("%@ Web Content", "Visible name of the web process. The argument is the application name."), (NSString *)parameters.uiProcessName];
-    _LSSetApplicationInformationItem(kLSDefaultSessionID, _LSGetCurrentApplicationASN(), _kLSDisplayNameKey, (CFStringRef)applicationName, nullptr);
+
+    dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), ^{
+        // Note that it is important for _RegisterApplication() to have been called before setting the display name.
+        auto error = _LSSetApplicationInformationItem(kLSDefaultSessionID, _LSGetCurrentApplicationASN(), _kLSDisplayNameKey, (CFStringRef)applicationName, nullptr);
+        ASSERT(!error);
+        if (error) {
+            RELEASE_LOG_ERROR(Process, "Failed to set the display name of the WebContent process, error code: %ld", static_cast<long>(error));
+            return;
+        }
+#if !ASSERT_DISABLED
+        // It is possible for _LSSetApplicationInformationItem() to return 0 and yet fail to set the display name so we make sure the display name has actually been set.
+        String actualApplicationName = adoptCF((CFStringRef)_LSCopyApplicationInformationItem(kLSDefaultSessionID, _LSGetCurrentApplicationASN(), _kLSDisplayNameKey)).get();
+        ASSERT(!actualApplicationName.isEmpty());
+#endif
+    });
 #endif
 }
 
@@ -218,7 +246,7 @@ static void registerWithAccessibility()
 #if USE(APPKIT)
     [NSAccessibilityRemoteUIElement setRemoteUIApp:YES];
 #endif
-#if PLATFORM(IOS)
+#if PLATFORM(IOS_FAMILY)
     NSString *accessibilityBundlePath = [(NSString *)GSSystemRootDirectory() stringByAppendingString:@"/System/Library/AccessibilityBundles/WebProcessLoader.axbundle"];
     NSError *error = nil;
     if (![[NSBundle bundleWithPath:accessibilityBundlePath] loadAndReturnError:&error])
@@ -316,10 +344,18 @@ void WebProcess::platformInitializeProcess(const ChildProcessInitializationParam
 #if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
     // Deny the WebContent process access to the WindowServer.
     // This call will not succeed if there are open WindowServer connections at this point.
-    CGSSetDenyWindowServerConnections(true);
+    auto retval = CGSSetDenyWindowServerConnections(true);
+    RELEASE_ASSERT(retval == kCGErrorSuccess);
     // Make sure that we close any WindowServer connections after checking in with Launch Services.
     CGSShutdownServerConnections();
+
+    SwitchingGPUClient::setSingleton(WebSwitchingGPUClient::singleton());
+
+    // This is necessary so that we are able to set the process' display name.
+    _RegisterApplication(nullptr, nullptr);
+
 #else
+
     if (![NSApp isRunning]) {
         // This call is needed when the WebProcess is not running the NSApplication event loop.
         // Otherwise, calling enableSandboxStyleFileQuarantine() will fail.
@@ -353,7 +389,7 @@ void WebProcess::platformTerminate()
 
 RetainPtr<CFDataRef> WebProcess::sourceApplicationAuditData() const
 {
-#if PLATFORM(IOS)
+#if PLATFORM(IOS_FAMILY)
     audit_token_t auditToken;
     ASSERT(parentProcessConnection());
     if (!parentProcessConnection() || !parentProcessConnection()->getAuditToken(auditToken))
@@ -374,7 +410,7 @@ void WebProcess::initializeSandbox(const ChildProcessInitializationParameters& p
 #else
     NSBundle *webKit2Bundle = [NSBundle bundleForClass:NSClassFromString(@"WKView")];
 #endif
-#if PLATFORM(IOS) && !PLATFORM(IOSMAC)
+#if PLATFORM(IOS_FAMILY) && !PLATFORM(IOSMAC)
     sandboxParameters.setOverrideSandboxProfilePath([webKit2Bundle pathForResource:@"com.apple.WebKit.WebContent" ofType:@"sb"]);
 #else
     sandboxParameters.setOverrideSandboxProfilePath([webKit2Bundle pathForResource:@"com.apple.WebProcess" ofType:@"sb"]);
@@ -395,7 +431,15 @@ static NSURL *origin(WebPage& page)
     if (!mainFrame)
         return nil;
 
-    URL mainFrameURL(URL(), mainFrame->url());
+    URL mainFrameURL = { URL(), mainFrame->url() };
+    if (page.isSuspended()) {
+        // Suspended page are navigated to about:blank upon suspension so we really want to report the previous URL.
+        if (auto* coreFrame = mainFrame->coreFrame()) {
+            if (auto* backHistoryItem = coreFrame->loader().history().previousItem())
+                mainFrameURL = { URL(), backHistoryItem->urlString() };
+        }
+    }
+
     Ref<SecurityOrigin> mainFrameOrigin = SecurityOrigin::create(mainFrameURL);
     String mainFrameOriginString;
     if (!mainFrameOrigin->isUnique())
@@ -412,25 +456,46 @@ static NSURL *origin(WebPage& page)
 
 #endif
 
-void WebProcess::updateActivePages()
-{
 #if PLATFORM(MAC)
-    auto activePageURLs = adoptNS([[NSMutableArray alloc] init]);
+static RetainPtr<NSArray<NSString *>> activePagesOrigins(const HashMap<uint64_t, RefPtr<WebPage>>& pageMap)
+{
+    RetainPtr<NSMutableArray<NSString *>> activeOrigins = adoptNS([[NSMutableArray alloc] init]);
 
-    for (auto& page : m_pageMap.values()) {
-        if (page->usesEphemeralSession() || page->isSuspended())
+    for (auto& page : pageMap.values()) {
+        if (page->usesEphemeralSession())
             continue;
 
         if (NSURL *originAsURL = origin(*page))
-            [activePageURLs addObject:userVisibleString(originAsURL)];
+            [activeOrigins addObject:userVisibleString(originAsURL)];
     }
 
-    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), [activePageURLs] {
-        _LSSetApplicationInformationItem(kLSDefaultSessionID, _LSGetCurrentApplicationASN(), CFSTR("LSActivePageUserVisibleOriginsKey"), (__bridge CFArrayRef)activePageURLs.get(), nullptr);
+    return activeOrigins;
+}
+#endif
+
+void WebProcess::updateActivePages()
+{
+#if PLATFORM(MAC)
+    auto activeOrigins = activePagesOrigins(m_pageMap);
+
+    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), [activeOrigins = WTFMove(activeOrigins)] {
+        _LSSetApplicationInformationItem(kLSDefaultSessionID, _LSGetCurrentApplicationASN(), CFSTR("LSActivePageUserVisibleOriginsKey"), (__bridge CFArrayRef)activeOrigins.get(), nullptr);
     });
 #endif
 }
 
+void WebProcess::getActivePagesOriginsForTesting(Vector<String>& activeOrigins)
+{
+#if PLATFORM(MAC)
+    auto activeOriginsAsNSStrings = activePagesOrigins(m_pageMap);
+    activeOrigins.reserveCapacity([activeOriginsAsNSStrings count]);
+    for (NSString* activeOrigin in activeOriginsAsNSStrings.get())
+        activeOrigins.uncheckedAppend(activeOrigin);
+#else
+    UNUSED_PARAM(activeOrigins);
+#endif
+}
+
 void WebProcess::updateCPULimit()
 {
 #if PLATFORM(MAC)
@@ -494,8 +559,10 @@ RefPtr<ObjCObjectGraph> WebProcess::transformHandlesToObjects(ObjCObjectGraph& o
             if (dynamic_objc_cast<WKBrowsingContextHandle>(object))
                 return true;
 
+            ALLOW_DEPRECATED_DECLARATIONS_BEGIN
             if (dynamic_objc_cast<WKTypeRefWrapper>(object))
                 return true;
+            ALLOW_DEPRECATED_DECLARATIONS_END
 #endif
             return false;
         }
@@ -510,8 +577,10 @@ RefPtr<ObjCObjectGraph> WebProcess::transformHandlesToObjects(ObjCObjectGraph& o
                 return [NSNull null];
             }
 
+            ALLOW_DEPRECATED_DECLARATIONS_BEGIN
             if (auto* wrapper = dynamic_objc_cast<WKTypeRefWrapper>(object))
                 return adoptNS([[WKTypeRefWrapper alloc] initWithObject:toAPI(m_webProcess.transformHandlesToObjects(toImpl(wrapper.object)).get())]);
+            ALLOW_DEPRECATED_DECLARATIONS_END
 #endif
             return object;
         }
@@ -531,8 +600,10 @@ RefPtr<ObjCObjectGraph> WebProcess::transformObjectsToHandles(ObjCObjectGraph& o
             if (dynamic_objc_cast<WKWebProcessPlugInBrowserContextController>(object))
                 return true;
 
+            ALLOW_DEPRECATED_DECLARATIONS_BEGIN
             if (dynamic_objc_cast<WKTypeRefWrapper>(object))
                 return true;
+            ALLOW_DEPRECATED_DECLARATIONS_END
 #endif
 
             return false;
@@ -544,8 +615,10 @@ RefPtr<ObjCObjectGraph> WebProcess::transformObjectsToHandles(ObjCObjectGraph& o
             if (auto* controller = dynamic_objc_cast<WKWebProcessPlugInBrowserContextController>(object))
                 return controller.handle;
 
+            ALLOW_DEPRECATED_DECLARATIONS_BEGIN
             if (auto* wrapper = dynamic_objc_cast<WKTypeRefWrapper>(object))
                 return adoptNS([[WKTypeRefWrapper alloc] initWithObject:toAPI(transformObjectsToHandles(toImpl(wrapper.object)).get())]);
+            ALLOW_DEPRECATED_DECLARATIONS_END
 #endif
             return object;
         }
@@ -572,7 +645,7 @@ void _WKSetCrashReportApplicationSpecificInformation(NSString *infoString)
     return setCrashReportApplicationSpecificInformation((__bridge CFStringRef)infoString);
 }
 
-#if PLATFORM(IOS)
+#if PLATFORM(IOS_FAMILY)
 void WebProcess::accessibilityProcessSuspendedNotification(bool suspended)
 {
     UIAccessibilityPostNotification(kAXPidStatusChangedNotification, @{ @"pid" : @(getpid()), @"suspended" : @(suspended) });
@@ -589,8 +662,21 @@ void WebProcess::scrollerStylePreferenceChanged(bool useOverlayScrollbars)
         return;
 
     static_cast<ScrollbarThemeMac&>(theme).preferencesChanged();
+    
+    NSScrollerStyle style = useOverlayScrollbars ? NSScrollerStyleOverlay : NSScrollerStyleLegacy;
+    [NSScrollerImpPair _updateAllScrollerImpPairsForNewRecommendedScrollerStyle:style];
 }
-#endif    
+
+void WebProcess::displayConfigurationChanged(CGDirectDisplayID displayID, CGDisplayChangeSummaryFlags flags)
+{
+    GraphicsContext3DManager::displayWasReconfigured(displayID, flags, nullptr);
+}
+    
+void WebProcess::displayWasRefreshed(CGDirectDisplayID displayID)
+{
+    DisplayRefreshMonitorManager::sharedManager().displayWasUpdated(displayID);
+}
+#endif
 
 void WebProcess::setMediaMIMETypes(const Vector<String> types)
 {