Title: [291938] trunk
Revision
291938
Author
[email protected]
Date
2022-03-26 08:55:18 -0700 (Sat, 26 Mar 2022)

Log Message

Implement ServiceWorkerWindowClient.focus
https://bugs.webkit.org/show_bug.cgi?id=238319
<rdar://90616490>

Reviewed by Brady Eidson.

Source/WebCore:

Add support for service worker focus:
- Implement user gesture requirement by introducing a flag in ServiceWorkerGlobalScope that is turned on for some time
  when receiving specific events like notification click event. The max time is currently set to 2 seconds.
  We might want to improve handling of user activation in non-document contexts but this is a fuzzy area right now so a service worker
  solution seems good for now.
- Remove the map of service worker client since we need to create new ones every time.
- focus will go its context manager that will send an IPC message to the network process to actually trigger focus.
We are missing focused check at promise resolution, this will be done in a follow-up.

Covered by API test.

* testing/ServiceWorkerInternals.cpp:
* testing/ServiceWorkerInternals.h:
* testing/js/WebCoreTestSupport.cpp:
* workers/service/ServiceWorkerClient.cpp:
* workers/service/ServiceWorkerClient.h:
* workers/service/ServiceWorkerClientData.h:
* workers/service/ServiceWorkerClients.cpp:
* workers/service/ServiceWorkerClients.h:
* workers/service/ServiceWorkerGlobalScope.cpp:
* workers/service/ServiceWorkerGlobalScope.h:
* workers/service/ServiceWorkerWindowClient.cpp:
* workers/service/ServiceWorkerWindowClient.h:
* workers/service/ServiceWorkerWindowClient.idl:
* workers/service/context/SWContextManager.h:
* workers/service/context/ServiceWorkerThread.cpp:
* workers/service/server/SWServer.h:

Source/WebKit:

Support new IPC message flow to focus from a service worker to network process to service worker client process to UIProcess.
Introduce a new delegate _focusWebViewFromServiceWorker as the scope is specific to service worker and usage is different from existing _focusWebView and other delegates.

The overall flow is like this:
- ServiceWorker process to NetworkProcess to Client WebProcess process to UIProcess (do the actual focus) to NetworkProcess to ServiceWorker process
We might want to directly go from NetworkProcess to UIProcess but we need to handle potential race conditions in that case.

* NetworkProcess/ServiceWorker/WebSWServerConnection.cpp:
* NetworkProcess/ServiceWorker/WebSWServerConnection.h:
* NetworkProcess/ServiceWorker/WebSWServerToContextConnection.cpp:
* NetworkProcess/ServiceWorker/WebSWServerToContextConnection.h:
* NetworkProcess/ServiceWorker/WebSWServerToContextConnection.messages.in:
* UIProcess/API/APIUIClient.h:
* UIProcess/API/Cocoa/WKUIDelegatePrivate.h:
* UIProcess/Cocoa/UIDelegate.h:
* UIProcess/Cocoa/UIDelegate.mm:
* UIProcess/WebPageProxy.cpp:
* UIProcess/WebPageProxy.h:
* UIProcess/WebPageProxy.messages.in:
* WebProcess/Storage/WebSWClientConnection.cpp:
* WebProcess/Storage/WebSWClientConnection.h:
* WebProcess/Storage/WebSWClientConnection.messages.in:
* WebProcess/Storage/WebSWContextManagerConnection.cpp:
* WebProcess/Storage/WebSWContextManagerConnection.h:

Source/WTF:

* Scripts/Preferences/WebPreferencesInternal.yaml:

Tools:

* TestWebKitAPI/Tests/WebKitCocoa/ServiceWorkerBasic.mm:

LayoutTests:

Update tests to cover the fact we no longer reuse Client objects.

* http/tests/workers/service/resources/postmessage-echo-worker.js:
* http/tests/workers/service/resources/serviceworkerclients-get-worker.js:
* http/tests/workers/service/serviceworkerclients-matchAll-worker.js:
* http/tests/workers/service/serviceworkerclients-matchAll.https-expected.txt:
* http/tests/workers/service/serviceworkerclients-matchAll.https.html:

Modified Paths

Diff

Modified: trunk/LayoutTests/ChangeLog (291937 => 291938)


--- trunk/LayoutTests/ChangeLog	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/LayoutTests/ChangeLog	2022-03-26 15:55:18 UTC (rev 291938)
@@ -1,3 +1,19 @@
+2022-03-26  Youenn Fablet  <[email protected]>
+
+        Implement ServiceWorkerWindowClient.focus
+        https://bugs.webkit.org/show_bug.cgi?id=238319
+        <rdar://90616490>
+
+        Reviewed by Brady Eidson.
+
+        Update tests to cover the fact we no longer reuse Client objects.
+
+        * http/tests/workers/service/resources/postmessage-echo-worker.js:
+        * http/tests/workers/service/resources/serviceworkerclients-get-worker.js:
+        * http/tests/workers/service/serviceworkerclients-matchAll-worker.js:
+        * http/tests/workers/service/serviceworkerclients-matchAll.https-expected.txt:
+        * http/tests/workers/service/serviceworkerclients-matchAll.https.html:
+
 2022-03-25  Alexander Mikhaylenko  <[email protected]>
 
         [GTK][WPE] Update widget style to match libadwaita

Modified: trunk/LayoutTests/http/tests/workers/service/resources/postmessage-echo-worker.js (291937 => 291938)


--- trunk/LayoutTests/http/tests/workers/service/resources/postmessage-echo-worker.js	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/LayoutTests/http/tests/workers/service/resources/postmessage-echo-worker.js	2022-03-26 15:55:18 UTC (rev 291938)
@@ -6,9 +6,12 @@
             event.source.postMessage("FAIL: client source is not a WindowClient");
             return;
         }
-    } else if (client !== event.source) {
+    } else if (client.id !== event.source.id) {
         event.source.postMessage("FAIL: client source of the second message is not the same as the first message");
         return;
+    } else if (client === event.source) {
+        event.source.postMessage("FAIL: client source of the second message is the same object as for the first message");
+        return;
     }
     event.source.postMessage("PASS: Service worker received message '" + event.data + "' from origin '" + event.origin + "'");
 });

Modified: trunk/LayoutTests/http/tests/workers/service/resources/serviceworkerclients-get-worker.js (291937 => 291938)


--- trunk/LayoutTests/http/tests/workers/service/resources/serviceworkerclients-get-worker.js	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/LayoutTests/http/tests/workers/service/resources/serviceworkerclients-get-worker.js	2022-03-26 15:55:18 UTC (rev 291938)
@@ -19,8 +19,8 @@
             return;
         }
 
-        if (retrievedClient !== client) {
-            event.source.postMessage("FAIL: client is different from the one retrieved through self.clients.get");
+        if (retrievedClient === client) {
+            event.source.postMessage("FAIL: reusing same client object in different self.clients.get calls");
             return;
         }
 

Modified: trunk/LayoutTests/http/tests/workers/service/serviceworkerclients-matchAll-worker.js (291937 => 291938)


--- trunk/LayoutTests/http/tests/workers/service/serviceworkerclients-matchAll-worker.js	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/LayoutTests/http/tests/workers/service/serviceworkerclients-matchAll-worker.js	2022-03-26 15:55:18 UTC (rev 291938)
@@ -41,6 +41,25 @@
 async function doTestAfterMessage(event)
 {
     try {
+        if (event.data.test === "checkNewClientObject") {
+            const clients1 = await self.clients.matchAll({ includeUncontrolled : true });
+            const clients2 = await self.clients.matchAll({ includeUncontrolled : true });
+            if (!clients1.length || !clients2.length) {
+                event.source.postMessage("no clients");
+                return;
+            }
+            for (let client1 of clients1) {
+                for (let client2 of clients2) {
+                    if (client1 === client2) {
+                        event.source.postMessage("FAIL: reusing client objects");
+                        return;
+                    }
+                }
+            }
+            event.source.postMessage("PASS");
+            return;
+        }
+
         if (event.data.test !== "checkClientIsUncontrolled") {
             event.source.postMessage("FAIL: received unexpected message from client");
             return;

Modified: trunk/LayoutTests/http/tests/workers/service/serviceworkerclients-matchAll.https-expected.txt (291937 => 291938)


--- trunk/LayoutTests/http/tests/workers/service/serviceworkerclients-matchAll.https-expected.txt	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/LayoutTests/http/tests/workers/service/serviceworkerclients-matchAll.https-expected.txt	2022-03-26 15:55:18 UTC (rev 291938)
@@ -1,4 +1,5 @@
 
 PASS Setup worker
+PASS Test self.clients.matchAll create new client object every time
 PASS Test self.clients.matchAll
 

Modified: trunk/LayoutTests/http/tests/workers/service/serviceworkerclients-matchAll.https.html (291937 => 291938)


--- trunk/LayoutTests/http/tests/workers/service/serviceworkerclients-matchAll.https.html	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/LayoutTests/http/tests/workers/service/serviceworkerclients-matchAll.https.html	2022-03-26 15:55:18 UTC (rev 291938)
@@ -27,6 +27,18 @@
 }, "Setup worker");
 
 promise_test(async (test) => {
+    var promise = new Promise((resolve, reject) => {
+        navigator.serviceWorker.addEventListener("message", test.step_func((event) => {
+            assert_equals(event.data, "PASS");
+            resolve();
+        }));
+    });
+
+    activeWorker.postMessage({test: "checkNewClientObject"});
+    await promise;
+}, "Test self.clients.matchAll create new client object every time");
+
+promise_test(async (test) => {
     const serviceWorkerClientIdentifier = internals.serviceWorkerClientInternalIdentifier(document);
     var promise = new Promise((resolve, reject) => {
         navigator.serviceWorker.addEventListener("message", test.step_func((event) => {

Modified: trunk/Source/WTF/ChangeLog (291937 => 291938)


--- trunk/Source/WTF/ChangeLog	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WTF/ChangeLog	2022-03-26 15:55:18 UTC (rev 291938)
@@ -1,3 +1,13 @@
+2022-03-26  Youenn Fablet  <[email protected]>
+
+        Implement ServiceWorkerWindowClient.focus
+        https://bugs.webkit.org/show_bug.cgi?id=238319
+        <rdar://90616490>
+
+        Reviewed by Brady Eidson.
+
+        * Scripts/Preferences/WebPreferencesInternal.yaml:
+
 2022-03-26  Yusuke Suzuki  <[email protected]>
 
         Use unary static_assert

Modified: trunk/Source/WTF/Scripts/Preferences/WebPreferencesInternal.yaml (291937 => 291938)


--- trunk/Source/WTF/Scripts/Preferences/WebPreferencesInternal.yaml	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WTF/Scripts/Preferences/WebPreferencesInternal.yaml	2022-03-26 15:55:18 UTC (rev 291938)
@@ -843,6 +843,19 @@
     WebCore:
       default: false
 
+ServiceWorkersUserGestureEnabled:
+  type: bool
+  humanReadableName: "Validate UserGesture requirements in Service Workers"
+  humanReadableDescription: "Validate UserGesture requirements in Service Workers"
+  condition: ENABLE(SERVICE_WORKER)
+  defaultValue:
+    WebKitLegacy:
+      default: false
+    WebKit:
+      default: true
+    WebCore:
+      default: true
+
 SimpleLineLayoutEnabled:
   type: bool
   webcoreOnChange: setNeedsRecalcStyleInAllFrames

Modified: trunk/Source/WebCore/ChangeLog (291937 => 291938)


--- trunk/Source/WebCore/ChangeLog	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebCore/ChangeLog	2022-03-26 15:55:18 UTC (rev 291938)
@@ -1,3 +1,39 @@
+2022-03-26  Youenn Fablet  <[email protected]>
+
+        Implement ServiceWorkerWindowClient.focus
+        https://bugs.webkit.org/show_bug.cgi?id=238319
+        <rdar://90616490>
+
+        Reviewed by Brady Eidson.
+
+        Add support for service worker focus:
+        - Implement user gesture requirement by introducing a flag in ServiceWorkerGlobalScope that is turned on for some time
+          when receiving specific events like notification click event. The max time is currently set to 2 seconds.
+          We might want to improve handling of user activation in non-document contexts but this is a fuzzy area right now so a service worker
+          solution seems good for now.
+        - Remove the map of service worker client since we need to create new ones every time.
+        - focus will go its context manager that will send an IPC message to the network process to actually trigger focus.
+        We are missing focused check at promise resolution, this will be done in a follow-up.
+
+        Covered by API test.
+
+        * testing/ServiceWorkerInternals.cpp:
+        * testing/ServiceWorkerInternals.h:
+        * testing/js/WebCoreTestSupport.cpp:
+        * workers/service/ServiceWorkerClient.cpp:
+        * workers/service/ServiceWorkerClient.h:
+        * workers/service/ServiceWorkerClientData.h:
+        * workers/service/ServiceWorkerClients.cpp:
+        * workers/service/ServiceWorkerClients.h:
+        * workers/service/ServiceWorkerGlobalScope.cpp:
+        * workers/service/ServiceWorkerGlobalScope.h:
+        * workers/service/ServiceWorkerWindowClient.cpp:
+        * workers/service/ServiceWorkerWindowClient.h:
+        * workers/service/ServiceWorkerWindowClient.idl:
+        * workers/service/context/SWContextManager.h:
+        * workers/service/context/ServiceWorkerThread.cpp:
+        * workers/service/server/SWServer.h:
+
 2022-03-26  Yusuke Suzuki  <[email protected]>
 
         Use unary static_assert

Modified: trunk/Source/WebCore/testing/ServiceWorkerInternals.cpp (291937 => 291938)


--- trunk/Source/WebCore/testing/ServiceWorkerInternals.cpp	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebCore/testing/ServiceWorkerInternals.cpp	2022-03-26 15:55:18 UTC (rev 291938)
@@ -34,14 +34,16 @@
 #include "PushSubscriptionData.h"
 #include "SWContextManager.h"
 #include "ServiceWorkerClient.h"
+#include "ServiceWorkerGlobalScope.h"
 #include "ServiceWorkerRegistration.h"
 #include <wtf/ProcessID.h>
 
 namespace WebCore {
 
-ServiceWorkerInternals::ServiceWorkerInternals(ServiceWorkerIdentifier identifier)
+ServiceWorkerInternals::ServiceWorkerInternals(ServiceWorkerGlobalScope& globalScope, ServiceWorkerIdentifier identifier)
     : m_identifier(identifier)
 {
+    globalScope.setIsProcessingUserGestureForTesting(true);
 }
 
 ServiceWorkerInternals::~ServiceWorkerInternals() = default;

Modified: trunk/Source/WebCore/testing/ServiceWorkerInternals.h (291937 => 291938)


--- trunk/Source/WebCore/testing/ServiceWorkerInternals.h	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebCore/testing/ServiceWorkerInternals.h	2022-03-26 15:55:18 UTC (rev 291938)
@@ -40,6 +40,7 @@
 class FetchResponse;
 class PushSubscription;
 class ScriptExecutionContext;
+class ServiceWorkerGlobalScope;
 class ServiceWorkerClient;
 
 template<typename IDLType> class DOMPromiseDeferred;
@@ -46,7 +47,7 @@
 
 class WEBCORE_TESTSUPPORT_EXPORT ServiceWorkerInternals : public RefCounted<ServiceWorkerInternals>, public CanMakeWeakPtr<ServiceWorkerInternals> {
 public:
-    static Ref<ServiceWorkerInternals> create(ServiceWorkerIdentifier identifier) { return adoptRef(*new ServiceWorkerInternals { identifier }); }
+    static Ref<ServiceWorkerInternals> create(ServiceWorkerGlobalScope& globalScope, ServiceWorkerIdentifier identifier) { return adoptRef(*new ServiceWorkerInternals { globalScope, identifier }); }
     ~ServiceWorkerInternals();
 
     void setOnline(bool isOnline);
@@ -76,7 +77,7 @@
     void setAsInspected(bool);
 
 private:
-    explicit ServiceWorkerInternals(ServiceWorkerIdentifier);
+    ServiceWorkerInternals(ServiceWorkerGlobalScope&, ServiceWorkerIdentifier);
 
     ServiceWorkerIdentifier m_identifier;
     RefPtr<DeferredPromise> m_lastNavigationWasAppInitiatedPromise;

Modified: trunk/Source/WebCore/testing/js/WebCoreTestSupport.cpp (291937 => 291938)


--- trunk/Source/WebCore/testing/js/WebCoreTestSupport.cpp	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebCore/testing/js/WebCoreTestSupport.cpp	2022-03-26 15:55:18 UTC (rev 291938)
@@ -228,7 +228,7 @@
         auto& vm = globalObject.vm();
         JSLockHolder locker(vm);
         auto* contextWrapper = script->globalScopeWrapper();
-        contextWrapper->putDirect(vm, Identifier::fromString(vm, Internals::internalsId), toJS(&globalObject, contextWrapper, ServiceWorkerInternals::create(identifier)));
+        contextWrapper->putDirect(vm, Identifier::fromString(vm, Internals::internalsId), toJS(&globalObject, contextWrapper, ServiceWorkerInternals::create(globalScope, identifier)));
     });
 #else
     UNUSED_PARAM(serviceWorkerIdentifier);

Modified: trunk/Source/WebCore/workers/service/ServiceWorkerClient.cpp (291937 => 291938)


--- trunk/Source/WebCore/workers/service/ServiceWorkerClient.cpp	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebCore/workers/service/ServiceWorkerClient.cpp	2022-03-26 15:55:18 UTC (rev 291938)
@@ -39,14 +39,8 @@
 
 namespace WebCore {
 
-Ref<ServiceWorkerClient> ServiceWorkerClient::getOrCreate(ServiceWorkerGlobalScope& context, ServiceWorkerClientData&& data)
+Ref<ServiceWorkerClient> ServiceWorkerClient::create(ServiceWorkerGlobalScope& context, ServiceWorkerClientData&& data)
 {
-    if (auto* client = context.serviceWorkerClient(data.identifier)) {
-        // Temporary fix until we remove reusing of same ServiceWorkerClient objects.
-        client->m_data = WTFMove(data);
-        return *client;
-    }
-
     if (data.type == ServiceWorkerClientType::Window)
         return ServiceWorkerWindowClient::create(context, WTFMove(data));
 
@@ -57,13 +51,10 @@
     : ContextDestructionObserver(&context)
     , m_data(WTFMove(data))
 {
-    context.addServiceWorkerClient(*this);
 }
 
 ServiceWorkerClient::~ServiceWorkerClient()
 {
-    if (auto* context = scriptExecutionContext())
-        downcast<ServiceWorkerGlobalScope>(*context).removeServiceWorkerClient(*this);
 }
 
 const URL& ServiceWorkerClient::url() const

Modified: trunk/Source/WebCore/workers/service/ServiceWorkerClient.h (291937 => 291938)


--- trunk/Source/WebCore/workers/service/ServiceWorkerClient.h	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebCore/workers/service/ServiceWorkerClient.h	2022-03-26 15:55:18 UTC (rev 291938)
@@ -52,7 +52,7 @@
     using Type = ServiceWorkerClientType;
     using FrameType = ServiceWorkerClientFrameType;
 
-    static Ref<ServiceWorkerClient> getOrCreate(ServiceWorkerGlobalScope&, ServiceWorkerClientData&&);
+    static Ref<ServiceWorkerClient> create(ServiceWorkerGlobalScope&, ServiceWorkerClientData&&);
 
     ~ServiceWorkerClient();
 

Modified: trunk/Source/WebCore/workers/service/ServiceWorkerClientData.h (291937 => 291938)


--- trunk/Source/WebCore/workers/service/ServiceWorkerClientData.h	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebCore/workers/service/ServiceWorkerClientData.h	2022-03-26 15:55:18 UTC (rev 291938)
@@ -53,7 +53,7 @@
     ServiceWorkerClientData isolatedCopy() const &;
     ServiceWorkerClientData isolatedCopy() &&;
 
-    static ServiceWorkerClientData from(ScriptExecutionContext&);
+    WEBCORE_EXPORT static ServiceWorkerClientData from(ScriptExecutionContext&);
 
     template<class Encoder> void encode(Encoder&) const;
     template<class Decoder> static std::optional<ServiceWorkerClientData> decode(Decoder&);

Modified: trunk/Source/WebCore/workers/service/ServiceWorkerClients.cpp (291937 => 291938)


--- trunk/Source/WebCore/workers/service/ServiceWorkerClients.cpp	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebCore/workers/service/ServiceWorkerClients.cpp	2022-03-26 15:55:18 UTC (rev 291938)
@@ -45,7 +45,7 @@
         return;
     }
 
-    promise.resolve<IDLInterface<ServiceWorkerClient>>(ServiceWorkerClient::getOrCreate(scope, WTFMove(*clientData)));
+    promise.resolve<IDLInterface<ServiceWorkerClient>>(ServiceWorkerClient::create(scope, WTFMove(*clientData)));
 }
 
 void ServiceWorkerClients::get(ScriptExecutionContext& context, const String& id, Ref<DeferredPromise>&& promise)
@@ -52,14 +52,11 @@
 {
     auto serviceWorkerIdentifier = downcast<ServiceWorkerGlobalScope>(context).thread().identifier();
 
-    auto promisePointer = promise.ptr();
-    m_pendingPromises.add(promisePointer, WTFMove(promise));
-
-    callOnMainThread([promisePointer, serviceWorkerIdentifier, id = id.isolatedCopy()] () {
+    callOnMainThread([promiseIdentifier = addPendingPromise(WTFMove(promise)), serviceWorkerIdentifier, id = id.isolatedCopy()] () {
         auto connection = SWContextManager::singleton().connection();
-        connection->findClientByVisibleIdentifier(serviceWorkerIdentifier, id, [promisePointer, serviceWorkerIdentifier] (auto&& clientData) {
-            SWContextManager::singleton().postTaskToServiceWorker(serviceWorkerIdentifier, [promisePointer, data = "" (auto& context) mutable {
-                if (auto promise = context.clients().m_pendingPromises.take(promisePointer))
+        connection->findClientByVisibleIdentifier(serviceWorkerIdentifier, id, [promiseIdentifier, serviceWorkerIdentifier] (auto&& clientData) {
+            SWContextManager::singleton().postTaskToServiceWorker(serviceWorkerIdentifier, [promiseIdentifier, data = "" (auto& context) mutable {
+                if (auto promise = context.clients().takePendingPromise(promiseIdentifier))
                     didFinishGetRequest(context, *promise, WTFMove(data));
             });
         });
@@ -70,7 +67,7 @@
 static inline void matchAllCompleted(ServiceWorkerGlobalScope& scope, DeferredPromise& promise, Vector<ServiceWorkerClientData>&& clientsData)
 {
     auto clients = WTF::map(clientsData, [&] (auto&& clientData) {
-        return ServiceWorkerClient::getOrCreate(scope, WTFMove(clientData));
+        return ServiceWorkerClient::create(scope, WTFMove(clientData));
     });
     std::sort(clients.begin(), clients.end(), [&] (auto& a, auto& b) {
         return a->data().focusOrder > b->data().focusOrder;
@@ -80,16 +77,13 @@
 
 void ServiceWorkerClients::matchAll(ScriptExecutionContext& context, const ClientQueryOptions& options, Ref<DeferredPromise>&& promise)
 {
-    auto promisePointer = promise.ptr();
-    m_pendingPromises.add(promisePointer, WTFMove(promise));
-
     auto serviceWorkerIdentifier = downcast<ServiceWorkerGlobalScope>(context).thread().identifier();
 
-    callOnMainThread([promisePointer, serviceWorkerIdentifier, options] () mutable {
+    callOnMainThread([promiseIdentifier = addPendingPromise(WTFMove(promise)), serviceWorkerIdentifier, options] () mutable {
         auto connection = SWContextManager::singleton().connection();
-        connection->matchAll(serviceWorkerIdentifier, options, [promisePointer, serviceWorkerIdentifier] (auto&& clientsData) mutable {
-            SWContextManager::singleton().postTaskToServiceWorker(serviceWorkerIdentifier, [promisePointer, clientsData = crossThreadCopy(WTFMove(clientsData))] (auto& scope) mutable {
-                if (auto promise = scope.clients().m_pendingPromises.take(promisePointer))
+        connection->matchAll(serviceWorkerIdentifier, options, [promiseIdentifier, serviceWorkerIdentifier] (auto&& clientsData) mutable {
+            SWContextManager::singleton().postTaskToServiceWorker(serviceWorkerIdentifier, [promiseIdentifier, clientsData = crossThreadCopy(WTFMove(clientsData))] (auto& scope) mutable {
+                if (auto promise = scope.clients().takePendingPromise(promiseIdentifier))
                     matchAllCompleted(scope, *promise, WTFMove(clientsData));
             });
         });
@@ -104,18 +98,13 @@
 
 void ServiceWorkerClients::claim(ScriptExecutionContext& context, Ref<DeferredPromise>&& promise)
 {
-    auto& serviceWorkerGlobalScope = downcast<ServiceWorkerGlobalScope>(context);
+    auto serviceWorkerIdentifier = downcast<ServiceWorkerGlobalScope>(context).thread().identifier();
 
-    auto serviceWorkerIdentifier = serviceWorkerGlobalScope.thread().identifier();
-
-    auto promisePointer = promise.ptr();
-    m_pendingPromises.add(promisePointer, WTFMove(promise));
-
-    callOnMainThread([promisePointer, serviceWorkerIdentifier] () mutable {
+    callOnMainThread([promiseIdentifier = addPendingPromise(WTFMove(promise)), serviceWorkerIdentifier] () mutable {
         auto connection = SWContextManager::singleton().connection();
-        connection->claim(serviceWorkerIdentifier, [promisePointer, serviceWorkerIdentifier](auto&& result) mutable {
-            SWContextManager::singleton().postTaskToServiceWorker(serviceWorkerIdentifier, [promisePointer, result = crossThreadCopy(WTFMove(result))](auto& scope) mutable {
-                if (auto promise = scope.clients().m_pendingPromises.take(promisePointer)) {
+        connection->claim(serviceWorkerIdentifier, [promiseIdentifier, serviceWorkerIdentifier](auto&& result) mutable {
+            SWContextManager::singleton().postTaskToServiceWorker(serviceWorkerIdentifier, [promiseIdentifier, result = crossThreadCopy(WTFMove(result))](auto& scope) mutable {
+                if (auto promise = scope.clients().takePendingPromise(promiseIdentifier)) {
                     DOMPromiseDeferred<void> pendingPromise { promise.releaseNonNull() };
                     pendingPromise.settle(WTFMove(result));
                 }
@@ -124,6 +113,18 @@
     });
 }
 
+ServiceWorkerClients::PromiseIdentifier ServiceWorkerClients::addPendingPromise(Ref<DeferredPromise>&& promise)
+{
+    auto identifier = PromiseIdentifier::generateThreadSafe();
+    m_pendingPromises.add(identifier, WTFMove(promise));
+    return identifier;
+}
+
+RefPtr<DeferredPromise> ServiceWorkerClients::takePendingPromise(PromiseIdentifier identifier)
+{
+    return m_pendingPromises.take(identifier);
+}
+
 } // namespace WebCore
 
 #endif // ENABLE(SERVICE_WORKER)

Modified: trunk/Source/WebCore/workers/service/ServiceWorkerClients.h (291937 => 291938)


--- trunk/Source/WebCore/workers/service/ServiceWorkerClients.h	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebCore/workers/service/ServiceWorkerClients.h	2022-03-26 15:55:18 UTC (rev 291938)
@@ -54,10 +54,16 @@
     void openWindow(ScriptExecutionContext&, const String& url, Ref<DeferredPromise>&&);
     void claim(ScriptExecutionContext&, Ref<DeferredPromise>&&);
 
+    enum PromiseIdentifierType { };
+    using PromiseIdentifier = ObjectIdentifier<PromiseIdentifierType>;
+
+    PromiseIdentifier addPendingPromise(Ref<DeferredPromise>&&);
+    RefPtr<DeferredPromise> takePendingPromise(PromiseIdentifier);
+
 private:
     ServiceWorkerClients() = default;
 
-    HashMap<DeferredPromise*, Ref<DeferredPromise>> m_pendingPromises;
+    HashMap<PromiseIdentifier, Ref<DeferredPromise>> m_pendingPromises;
 };
 
 } // namespace WebCore

Modified: trunk/Source/WebCore/workers/service/ServiceWorkerGlobalScope.cpp (291937 => 291938)


--- trunk/Source/WebCore/workers/service/ServiceWorkerGlobalScope.cpp	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebCore/workers/service/ServiceWorkerGlobalScope.cpp	2022-03-26 15:55:18 UTC (rev 291938)
@@ -68,6 +68,7 @@
     , m_clients(ServiceWorkerClients::create())
     , m_sessionID(sessionID)
     , m_notificationClient(WTFMove(notificationClient))
+    , m_userGestureTimer(*this, &ServiceWorkerGlobalScope::resetUserGesture)
 {
 }
 
@@ -134,23 +135,6 @@
     return static_cast<ServiceWorkerThread&>(WorkerGlobalScope::thread());
 }
 
-ServiceWorkerClient* ServiceWorkerGlobalScope::serviceWorkerClient(ScriptExecutionContextIdentifier identifier)
-{
-    return m_clientMap.get(identifier);
-}
-
-void ServiceWorkerGlobalScope::addServiceWorkerClient(ServiceWorkerClient& client)
-{
-    auto result = m_clientMap.add(client.identifier(), &client);
-    ASSERT_UNUSED(result, result.isNewEntry);
-}
-
-void ServiceWorkerGlobalScope::removeServiceWorkerClient(ServiceWorkerClient& client)
-{
-    auto isRemoved = m_clientMap.remove(client.identifier());
-    ASSERT_UNUSED(isRemoved, isRemoved);
-}
-
 // https://w3c.github.io/ServiceWorker/#update-service-worker-extended-events-set-algorithm
 void ServiceWorkerGlobalScope::updateExtendedEventsSet(ExtendableEvent* newEvent)
 {
@@ -224,6 +208,7 @@
             switch (eventType) {
             case NotificationEventType::Click:
                 eventName = eventNames().notificationclickEvent;
+                downcast<ServiceWorkerGlobalScope>(scope).recordUserGesture();
                 break;
             case NotificationEventType::Close:
                 eventName = eventNames().notificationcloseEvent;
@@ -237,6 +222,12 @@
 }
 #endif
 
+void ServiceWorkerGlobalScope::recordUserGesture()
+{
+    m_isProcessingUserGesture = true;
+    m_userGestureTimer.startOneShot(userGestureLifetime);
+}
+
 } // namespace WebCore
 
 #endif // ENABLE(SERVICE_WORKER)

Modified: trunk/Source/WebCore/workers/service/ServiceWorkerGlobalScope.h (291937 => 291938)


--- trunk/Source/WebCore/workers/service/ServiceWorkerGlobalScope.h	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebCore/workers/service/ServiceWorkerGlobalScope.h	2022-03-26 15:55:18 UTC (rev 291938)
@@ -67,10 +67,6 @@
 
     ServiceWorkerThread& thread();
 
-    ServiceWorkerClient* serviceWorkerClient(ScriptExecutionContextIdentifier);
-    void addServiceWorkerClient(ServiceWorkerClient&);
-    void removeServiceWorkerClient(ServiceWorkerClient&);
-
     void updateExtendedEventsSet(ExtendableEvent* newEvent = nullptr);
 
     const ServiceWorkerContextData::ImportedScript* scriptResource(const URL&) const;
@@ -92,6 +88,11 @@
     bool hasPendingSilentPushEvent() const { return m_hasPendingSilentPushEvent; }
     void setHasPendingSilentPushEvent(bool value) { m_hasPendingSilentPushEvent = value; }
 
+    constexpr static Seconds userGestureLifetime  { 2_s };
+    bool isProcessingUserGesture() const { return m_isProcessingUserGesture; }
+    void recordUserGesture();
+    void setIsProcessingUserGestureForTesting(bool value) { m_isProcessingUserGesture = value; }
+
 private:
     ServiceWorkerGlobalScope(ServiceWorkerContextData&&, ServiceWorkerData&&, const WorkerParameters&, Ref<SecurityOrigin>&&, ServiceWorkerThread&, Ref<SecurityOrigin>&& topOrigin, IDBClient::IDBConnectionProxy*, SocketProvider*, std::unique_ptr<NotificationClient>&&, PAL::SessionID);
     void notifyServiceWorkerPageOfCreationIfNecessary();
@@ -103,11 +104,12 @@
 
     std::optional<PAL::SessionID> sessionID() const final { return m_sessionID; }
 
+    void resetUserGesture() { m_isProcessingUserGesture = false; }
+
     ServiceWorkerContextData m_contextData;
     Ref<ServiceWorkerRegistration> m_registration;
     Ref<ServiceWorker> m_serviceWorker;
     Ref<ServiceWorkerClients> m_clients;
-    HashMap<ScriptExecutionContextIdentifier, ServiceWorkerClient*> m_clientMap;
     Vector<Ref<ExtendableEvent>> m_extendedEvents;
 
     uint64_t m_lastRequestIdentifier { 0 };
@@ -115,6 +117,8 @@
     PAL::SessionID m_sessionID;
     std::unique_ptr<NotificationClient> m_notificationClient;
     bool m_hasPendingSilentPushEvent { false };
+    bool m_isProcessingUserGesture { false };
+    Timer m_userGestureTimer;
 };
 
 } // namespace WebCore

Modified: trunk/Source/WebCore/workers/service/ServiceWorkerWindowClient.cpp (291937 => 291938)


--- trunk/Source/WebCore/workers/service/ServiceWorkerWindowClient.cpp	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebCore/workers/service/ServiceWorkerWindowClient.cpp	2022-03-26 15:55:18 UTC (rev 291938)
@@ -29,6 +29,10 @@
 #include "ServiceWorkerWindowClient.h"
 
 #include "JSDOMPromiseDeferred.h"
+#include "JSServiceWorkerWindowClient.h"
+#include "SWContextManager.h"
+#include "ServiceWorkerClients.h"
+#include "ServiceWorkerThread.h"
 
 namespace WebCore {
 
@@ -37,12 +41,36 @@
 {
 }
 
-void ServiceWorkerWindowClient::focus(Ref<DeferredPromise>&& promise)
+void ServiceWorkerWindowClient::focus(ScriptExecutionContext& context, Ref<DeferredPromise>&& promise)
 {
-    promise->reject(Exception { NotSupportedError, "windowClient.focus() is not yet supported"_s });
+    auto& serviceWorkerContext = downcast<ServiceWorkerGlobalScope>(context);
+
+    if (context.settingsValues().serviceWorkersUserGestureEnabled && !serviceWorkerContext.isProcessingUserGesture()) {
+        promise->reject(Exception { InvalidAccessError, "WindowClient focus requires a user gesture"_s });
+        return;
+    }
+
+    auto promiseIdentifier = serviceWorkerContext.clients().addPendingPromise(WTFMove(promise));
+    callOnMainThread([clientIdentifier = identifier(), promiseIdentifier, serviceWorkerIdentifier = serviceWorkerContext.thread().identifier()]() mutable {
+        SWContextManager::singleton().connection()->focus(clientIdentifier, [promiseIdentifier, serviceWorkerIdentifier](auto result) mutable {
+            SWContextManager::singleton().postTaskToServiceWorker(serviceWorkerIdentifier, [promiseIdentifier, result = crossThreadCopy(WTFMove(result))](auto& serviceWorkerContext) mutable {
+                auto promise = serviceWorkerContext.clients().takePendingPromise(promiseIdentifier);
+                if (!promise)
+                    return;
+
+                // FIXME: Check isFocused state and reject if not focused.
+                if (!result) {
+                    promise->reject(Exception { TypeError, "WindowClient focus failed"_s });
+                    return;
+                }
+
+                promise->template resolve<IDLInterface<ServiceWorkerWindowClient>>(ServiceWorkerWindowClient::create(serviceWorkerContext, WTFMove(*result)));
+            });
+        });
+    });
 }
 
-void ServiceWorkerWindowClient::navigate(const String& url, Ref<DeferredPromise>&& promise)
+void ServiceWorkerWindowClient::navigate(ScriptExecutionContext&, const String& url, Ref<DeferredPromise>&& promise)
 {
     UNUSED_PARAM(url);
     promise->reject(Exception { NotSupportedError, "windowClient.navigate() is not yet supported"_s });

Modified: trunk/Source/WebCore/workers/service/ServiceWorkerWindowClient.h (291937 => 291938)


--- trunk/Source/WebCore/workers/service/ServiceWorkerWindowClient.h	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebCore/workers/service/ServiceWorkerWindowClient.h	2022-03-26 15:55:18 UTC (rev 291938)
@@ -45,8 +45,8 @@
     VisibilityState visibilityState() const { return data().isVisible ? VisibilityState::Visible : VisibilityState::Hidden; }
     bool isFocused() const { return data().isFocused; }
 
-    void focus(Ref<DeferredPromise>&&);
-    void navigate(const String& url, Ref<DeferredPromise>&&);
+    void focus(ScriptExecutionContext&, Ref<DeferredPromise>&&);
+    void navigate(ScriptExecutionContext&, const String& url, Ref<DeferredPromise>&&);
 
 private:
     ServiceWorkerWindowClient(ServiceWorkerGlobalScope&, ServiceWorkerClientData&&);

Modified: trunk/Source/WebCore/workers/service/ServiceWorkerWindowClient.idl (291937 => 291938)


--- trunk/Source/WebCore/workers/service/ServiceWorkerWindowClient.idl	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebCore/workers/service/ServiceWorkerWindowClient.idl	2022-03-26 15:55:18 UTC (rev 291938)
@@ -32,6 +32,6 @@
     readonly attribute VisibilityState visibilityState;
     [ImplementedAs=isFocused] readonly attribute boolean focused;
 
-    [NewObject] Promise<ServiceWorkerWindowClient> focus();
-    [NewObject] Promise<ServiceWorkerWindowClient> navigate(USVString url);
+    [NewObject, CallWith=CurrentScriptExecutionContext] Promise<ServiceWorkerWindowClient> focus();
+    [NewObject, CallWith=CurrentScriptExecutionContext] Promise<ServiceWorkerWindowClient> navigate(USVString url);
 };

Modified: trunk/Source/WebCore/workers/service/context/SWContextManager.h (291937 => 291938)


--- trunk/Source/WebCore/workers/service/context/SWContextManager.h	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebCore/workers/service/context/SWContextManager.h	2022-03-26 15:55:18 UTC (rev 291938)
@@ -68,6 +68,8 @@
         virtual void matchAll(ServiceWorkerIdentifier, const ServiceWorkerClientQueryOptions&, ServiceWorkerClientsMatchAllCallback&&) = 0;
         virtual void claim(ServiceWorkerIdentifier, CompletionHandler<void(ExceptionOr<void>&&)>&&) = 0;
 
+        virtual void focus(ScriptExecutionContextIdentifier, CompletionHandler<void(std::optional<WebCore::ServiceWorkerClientData>&&)>&&) = 0;
+
         virtual void didFailHeartBeatCheck(ServiceWorkerIdentifier) = 0;
         virtual void setAsInspected(ServiceWorkerIdentifier, bool) = 0;
 

Modified: trunk/Source/WebCore/workers/service/context/ServiceWorkerThread.cpp (291937 => 291938)


--- trunk/Source/WebCore/workers/service/context/ServiceWorkerThread.cpp	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebCore/workers/service/context/ServiceWorkerThread.cpp	2022-03-26 15:55:18 UTC (rev 291938)
@@ -151,7 +151,7 @@
         URL sourceURL;
         ExtendableMessageEventSource source;
         if (std::holds_alternative<ServiceWorkerClientData>(sourceData)) {
-            RefPtr<ServiceWorkerClient> sourceClient = ServiceWorkerClient::getOrCreate(serviceWorkerGlobalScope, WTFMove(std::get<ServiceWorkerClientData>(sourceData)));
+            RefPtr<ServiceWorkerClient> sourceClient = ServiceWorkerClient::create(serviceWorkerGlobalScope, WTFMove(std::get<ServiceWorkerClientData>(sourceData)));
 
             RELEASE_ASSERT(!sourceClient->url().protocolIsInHTTPFamily() || !serviceWorkerGlobalScope->url().protocolIsInHTTPFamily() || protocolHostAndPortAreEqual(serviceWorkerGlobalScope->url(), sourceClient->url()));
 

Modified: trunk/Source/WebCore/workers/service/server/SWServer.h (291937 => 291938)


--- trunk/Source/WebCore/workers/service/server/SWServer.h	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebCore/workers/service/server/SWServer.h	2022-03-26 15:55:18 UTC (rev 291938)
@@ -91,6 +91,7 @@
         virtual void setRegistrationUpdateViaCache(ServiceWorkerRegistrationIdentifier, ServiceWorkerUpdateViaCache) = 0;
         virtual void notifyClientsOfControllerChange(const HashSet<ScriptExecutionContextIdentifier>& contextIdentifiers, const ServiceWorkerData& newController) = 0;
         virtual void postMessageToServiceWorkerClient(ScriptExecutionContextIdentifier, const MessageWithMessagePorts&, ServiceWorkerIdentifier, const String& sourceOrigin) = 0;
+        virtual void focusServiceWorkerClient(ScriptExecutionContextIdentifier, CompletionHandler<void(std::optional<ServiceWorkerClientData>&&)>&&) = 0;
 
         virtual void contextConnectionCreated(SWServerToContextConnection&) = 0;
 

Modified: trunk/Source/WebKit/ChangeLog (291937 => 291938)


--- trunk/Source/WebKit/ChangeLog	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebKit/ChangeLog	2022-03-26 15:55:18 UTC (rev 291938)
@@ -1,3 +1,36 @@
+2022-03-26  Youenn Fablet  <[email protected]>
+
+        Implement ServiceWorkerWindowClient.focus
+        https://bugs.webkit.org/show_bug.cgi?id=238319
+        <rdar://90616490>
+
+        Reviewed by Brady Eidson.
+
+        Support new IPC message flow to focus from a service worker to network process to service worker client process to UIProcess.
+        Introduce a new delegate _focusWebViewFromServiceWorker as the scope is specific to service worker and usage is different from existing _focusWebView and other delegates.
+
+        The overall flow is like this:
+        - ServiceWorker process to NetworkProcess to Client WebProcess process to UIProcess (do the actual focus) to NetworkProcess to ServiceWorker process
+        We might want to directly go from NetworkProcess to UIProcess but we need to handle potential race conditions in that case.
+
+        * NetworkProcess/ServiceWorker/WebSWServerConnection.cpp:
+        * NetworkProcess/ServiceWorker/WebSWServerConnection.h:
+        * NetworkProcess/ServiceWorker/WebSWServerToContextConnection.cpp:
+        * NetworkProcess/ServiceWorker/WebSWServerToContextConnection.h:
+        * NetworkProcess/ServiceWorker/WebSWServerToContextConnection.messages.in:
+        * UIProcess/API/APIUIClient.h:
+        * UIProcess/API/Cocoa/WKUIDelegatePrivate.h:
+        * UIProcess/Cocoa/UIDelegate.h:
+        * UIProcess/Cocoa/UIDelegate.mm:
+        * UIProcess/WebPageProxy.cpp:
+        * UIProcess/WebPageProxy.h:
+        * UIProcess/WebPageProxy.messages.in:
+        * WebProcess/Storage/WebSWClientConnection.cpp:
+        * WebProcess/Storage/WebSWClientConnection.h:
+        * WebProcess/Storage/WebSWClientConnection.messages.in:
+        * WebProcess/Storage/WebSWContextManagerConnection.cpp:
+        * WebProcess/Storage/WebSWContextManagerConnection.h:
+
 2022-03-26  Yusuke Suzuki  <[email protected]>
 
         Use unary static_assert

Modified: trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerConnection.cpp (291937 => 291938)


--- trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerConnection.cpp	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerConnection.cpp	2022-03-26 15:55:18 UTC (rev 291938)
@@ -659,6 +659,11 @@
     callback(registration->navigationPreloadState());
 }
 
+void WebSWServerConnection::focusServiceWorkerClient(WebCore::ScriptExecutionContextIdentifier clientIdentifier, CompletionHandler<void(std::optional<ServiceWorkerClientData>&&)>&& callback)
+{
+    sendWithAsyncReply(Messages::WebSWClientConnection::FocusServiceWorkerClient { clientIdentifier }, WTFMove(callback));
+}
+
 } // namespace WebKit
 
 #undef CONNECTION_MESSAGE_CHECK_COMPLETION

Modified: trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerConnection.h (291937 => 291938)


--- trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerConnection.h	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerConnection.h	2022-03-26 15:55:18 UTC (rev 291938)
@@ -83,6 +83,8 @@
     std::unique_ptr<ServiceWorkerFetchTask> createFetchTask(NetworkResourceLoader&, const WebCore::ResourceRequest&);
     void fetchTaskTimedOut(WebCore::ServiceWorkerIdentifier);
 
+    void focusServiceWorkerClient(WebCore::ScriptExecutionContextIdentifier, CompletionHandler<void(std::optional<WebCore::ServiceWorkerClientData>&&)>&&);
+
 private:
     // Implement SWServer::Connection (Messages to the client WebProcess)
     void rejectJobInClient(WebCore::ServiceWorkerJobIdentifier, const WebCore::ExceptionData&) final;

Modified: trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerToContextConnection.cpp (291937 => 291938)


--- trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerToContextConnection.cpp	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerToContextConnection.cpp	2022-03-26 15:55:18 UTC (rev 291938)
@@ -217,6 +217,17 @@
     return m_connection.webProcessIdentifier();
 }
 
+void WebSWServerToContextConnection::focus(ScriptExecutionContextIdentifier clientIdentifier, CompletionHandler<void(std::optional<WebCore::ServiceWorkerClientData>&&)>&& callback)
+{
+    auto* server = this->server();
+    auto* connection = server ? server->connection(clientIdentifier.processIdentifier()) : nullptr;
+    if (!connection) {
+        callback({ });
+        return;
+    }
+    connection->focusServiceWorkerClient(clientIdentifier, WTFMove(callback));
+}
+
 } // namespace WebKit
 
 #endif // ENABLE(SERVICE_WORKER)

Modified: trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerToContextConnection.h (291937 => 291938)


--- trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerToContextConnection.h	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerToContextConnection.h	2022-03-26 15:55:18 UTC (rev 291938)
@@ -98,6 +98,7 @@
     void matchAllCompleted(uint64_t requestIdentifier, const Vector<WebCore::ServiceWorkerClientData>&) final;
     void firePushEvent(WebCore::ServiceWorkerIdentifier, const std::optional<Vector<uint8_t>>&, CompletionHandler<void(bool)>&&) final;
     void close() final;
+    void focus(WebCore::ScriptExecutionContextIdentifier, CompletionHandler<void(std::optional<WebCore::ServiceWorkerClientData>&&)>&&);
 
     void connectionIsNoLongerNeeded() final;
     void terminateDueToUnresponsiveness() final;

Modified: trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerToContextConnection.messages.in (291937 => 291938)


--- trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerToContextConnection.messages.in	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebKit/NetworkProcess/ServiceWorker/WebSWServerToContextConnection.messages.in	2022-03-26 15:55:18 UTC (rev 291938)
@@ -35,6 +35,7 @@
     FindClientByVisibleIdentifier(WebCore::ServiceWorkerIdentifier serviceWorkerIdentifier, String clientIdentifier) -> (std::optional<WebCore::ServiceWorkerClientData> data)
     MatchAll(uint64_t matchAllRequestIdentifier, WebCore::ServiceWorkerIdentifier serviceWorkerIdentifier, struct WebCore::ServiceWorkerClientQueryOptions options);
     Claim(WebCore::ServiceWorkerIdentifier serviceWorkerIdentifier) -> (std::optional<WebCore::ExceptionData> result)
+    Focus(WebCore::ScriptExecutionContextIdentifier serviceWorkerClientIdentifier) -> (std::optional<WebCore::ServiceWorkerClientData> result)
     SetScriptResource(WebCore::ServiceWorkerIdentifier identifier, URL scriptURL, WebCore::ServiceWorkerContextData::ImportedScript script)
     PostMessageToServiceWorkerClient(WebCore::ScriptExecutionContextIdentifier destination, struct WebCore::MessageWithMessagePorts message, WebCore::ServiceWorkerIdentifier source, String sourceOrigin)
     DidFailHeartBeatCheck(WebCore::ServiceWorkerIdentifier identifier)

Modified: trunk/Source/WebKit/UIProcess/API/APIUIClient.h (291937 => 291938)


--- trunk/Source/WebKit/UIProcess/API/APIUIClient.h	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebKit/UIProcess/API/APIUIClient.h	2022-03-26 15:55:18 UTC (rev 291938)
@@ -101,6 +101,7 @@
     virtual bool takeFocus(WebKit::WebPageProxy*, WKFocusDirection) { return false; }
     virtual void focus(WebKit::WebPageProxy*) { }
     virtual void unfocus(WebKit::WebPageProxy*) { }
+    virtual bool focusFromServiceWorker(WebKit::WebPageProxy&) { return false; }
 
     virtual void runJavaScriptAlert(WebKit::WebPageProxy&, const WTF::String&, WebKit::WebFrameProxy*, WebKit::FrameInfoData&&, Function<void()>&& completionHandler) { completionHandler(); }
     virtual void runJavaScriptConfirm(WebKit::WebPageProxy&, const WTF::String&, WebKit::WebFrameProxy*, WebKit::FrameInfoData&&, Function<void(bool)>&& completionHandler) { completionHandler(false); }

Modified: trunk/Source/WebKit/UIProcess/API/Cocoa/WKUIDelegatePrivate.h (291937 => 291938)


--- trunk/Source/WebKit/UIProcess/API/Cocoa/WKUIDelegatePrivate.h	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebKit/UIProcess/API/Cocoa/WKUIDelegatePrivate.h	2022-03-26 15:55:18 UTC (rev 291938)
@@ -272,6 +272,7 @@
 - (void)_completeImmediateActionAnimationForWebView:(WKWebView *)webView WK_API_AVAILABLE(macos(10.13.4));
 - (void)_showWebView:(WKWebView *)webView WK_API_AVAILABLE(macos(10.13.4));
 - (void)_focusWebView:(WKWebView *)webView WK_API_AVAILABLE(macos(10.13.4));
+- (bool)_focusWebViewFromServiceWorker:(WKWebView *)webView WK_API_AVAILABLE(macos(WK_MAC_TBA), ios(WK_IOS_TBA));
 - (void)_unfocusWebView:(WKWebView *)webView WK_API_AVAILABLE(macos(10.13.4));
 - (void)_webViewDidScroll:(WKWebView *)webView WK_API_AVAILABLE(macos(10.13.4));
 - (void)_webViewRunModal:(WKWebView *)webView WK_API_AVAILABLE(macos(10.13.4));

Modified: trunk/Source/WebKit/UIProcess/Cocoa/UIDelegate.h (291937 => 291938)


--- trunk/Source/WebKit/UIProcess/Cocoa/UIDelegate.h	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebKit/UIProcess/Cocoa/UIDelegate.h	2022-03-26 15:55:18 UTC (rev 291938)
@@ -116,6 +116,8 @@
         void showPage(WebPageProxy*) final;
         void focus(WebPageProxy*) final;
         void unfocus(WebPageProxy*) final;
+        bool focusFromServiceWorker(WebKit::WebPageProxy&) final;
+
         bool canRunModal() const final;
         void runModal(WebPageProxy&) final;
         void pageDidScroll(WebPageProxy*) final;
@@ -209,6 +211,7 @@
 #if PLATFORM(MAC)
         bool showWebView : 1;
         bool focusWebView : 1;
+        bool focusWebViewFromServiceWorker : 1;
         bool unfocusWebView : 1;
         bool webViewRunModal : 1;
         bool webViewDidScroll : 1;

Modified: trunk/Source/WebKit/UIProcess/Cocoa/UIDelegate.mm (291937 => 291938)


--- trunk/Source/WebKit/UIProcess/Cocoa/UIDelegate.mm	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebKit/UIProcess/Cocoa/UIDelegate.mm	2022-03-26 15:55:18 UTC (rev 291938)
@@ -125,6 +125,7 @@
 #if PLATFORM(MAC)
     m_delegateMethods.showWebView = [delegate respondsToSelector:@selector(_showWebView:)];
     m_delegateMethods.focusWebView = [delegate respondsToSelector:@selector(_focusWebView:)];
+    m_delegateMethods.focusWebViewFromServiceWorker = [delegate respondsToSelector:@selector(_focusWebViewFromServiceWorker:)];
     m_delegateMethods.unfocusWebView = [delegate respondsToSelector:@selector(_unfocusWebView:)];
     m_delegateMethods.webViewRunModal = [delegate respondsToSelector:@selector(_webViewRunModal:)];
     m_delegateMethods.webViewDidScroll = [delegate respondsToSelector:@selector(_webViewDidScroll:)];
@@ -831,6 +832,26 @@
     [(id <WKUIDelegatePrivate>)delegate _webViewDidScroll:m_uiDelegate->m_webView.get().get()];
 }
 
+bool UIDelegate::UIClient::focusFromServiceWorker(WebKit::WebPageProxy& proxy)
+{
+    bool hasImplementation = m_uiDelegate && m_uiDelegate->m_delegateMethods.focusWebViewFromServiceWorker && m_uiDelegate->m_delegate.get();
+    if (!hasImplementation) {
+        auto* webView = m_uiDelegate ? m_uiDelegate->m_webView.get().get() : nullptr;
+        if (!webView || !webView.window)
+            return false;
+
+#if PLATFORM(MAC)
+        [webView.window makeKeyAndOrderFront:nil];
+#else
+        [webView.window makeKeyAndVisible];
+#endif
+        [[webView window] makeFirstResponder:webView];
+        return true;
+    }
+
+    return [(id <WKUIDelegatePrivate>)m_uiDelegate->m_delegate.get() _focusWebViewFromServiceWorker:m_uiDelegate->m_webView.get().get()];
+}
+
 void UIDelegate::UIClient::focus(WebPageProxy*)
 {
     if (!m_uiDelegate)
@@ -842,7 +863,7 @@
     auto delegate = m_uiDelegate->m_delegate.get();
     if (!delegate)
         return;
-    
+
     [(id <WKUIDelegatePrivate>)delegate _focusWebView:m_uiDelegate->m_webView.get().get()];
 }
 

Modified: trunk/Source/WebKit/UIProcess/WebPageProxy.cpp (291937 => 291938)


--- trunk/Source/WebKit/UIProcess/WebPageProxy.cpp	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebKit/UIProcess/WebPageProxy.cpp	2022-03-26 15:55:18 UTC (rev 291938)
@@ -7415,6 +7415,25 @@
 {
     send(Messages::WebPage::DidCancelCheckingText(requestID));
 }
+
+void WebPageProxy::focusFromServiceWorker(CompletionHandler<void()>&& callback)
+{
+    if (!m_uiClient->focusFromServiceWorker(*this)) {
+        callback();
+        return;
+    }
+
+#if PLATFORM(COCOA)
+    makeFirstResponder();
+#endif
+
+    if (m_activityState.contains(ActivityState::IsVisible)) {
+        callback();
+        return;
+    }
+    installActivityStateChangeCompletionHandler(WTFMove(callback));
+}
+
 // Other
 
 void WebPageProxy::setFocus(bool focused)

Modified: trunk/Source/WebKit/UIProcess/WebPageProxy.h (291937 => 291938)


--- trunk/Source/WebKit/UIProcess/WebPageProxy.h	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebKit/UIProcess/WebPageProxy.h	2022-03-26 15:55:18 UTC (rev 291938)
@@ -1692,6 +1692,7 @@
 
     void getLoadDecisionForIcon(const WebCore::LinkIcon&, WebKit::CallbackID);
 
+    void focusFromServiceWorker(CompletionHandler<void()>&&);
     void setFocus(bool focused);
     void setWindowFrame(const WebCore::FloatRect&);
     void getWindowFrame(Messages::WebPageProxy::GetWindowFrameDelayedReply&&);

Modified: trunk/Source/WebKit/UIProcess/WebPageProxy.messages.in (291937 => 291938)


--- trunk/Source/WebKit/UIProcess/WebPageProxy.messages.in	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebKit/UIProcess/WebPageProxy.messages.in	2022-03-26 15:55:18 UTC (rev 291938)
@@ -41,6 +41,7 @@
     SetStatusText(String statusText)
     SetFocus(bool focused)
     TakeFocus(uint8_t direction)
+    FocusFromServiceWorker() -> ()
     FocusedFrameChanged(std::optional<WebCore::FrameIdentifier> frameID)
     SetRenderTreeSize(uint64_t treeSize)
     SetToolbarsAreVisible(bool toolbarsAreVisible)

Modified: trunk/Source/WebKit/WebProcess/Storage/WebSWClientConnection.cpp (291937 => 291938)


--- trunk/Source/WebKit/WebProcess/Storage/WebSWClientConnection.cpp	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebKit/WebProcess/Storage/WebSWClientConnection.cpp	2022-03-26 15:55:18 UTC (rev 291938)
@@ -41,6 +41,8 @@
 #include "WebSWServerConnectionMessages.h"
 #include <WebCore/Document.h>
 #include <WebCore/DocumentLoader.h>
+#include <WebCore/FocusController.h>
+#include <WebCore/Frame.h>
 #include <WebCore/ProcessIdentifier.h>
 #include <WebCore/SecurityOrigin.h>
 #include <WebCore/SerializedScriptValue.h>
@@ -301,6 +303,28 @@
     });
 }
 
+void WebSWClientConnection::focusServiceWorkerClient(ScriptExecutionContextIdentifier clientIdentifier, CompletionHandler<void(std::optional<ServiceWorkerClientData>&&)>&& callback)
+{
+    auto* client = Document::allDocumentsMap().get(clientIdentifier);
+    auto* page = client ? client->page() : nullptr;
+    if (!page) {
+        callback({ });
+        return;
+    }
+
+    WebPage::fromCorePage(*page).sendWithAsyncReply(Messages::WebPageProxy::FocusFromServiceWorker { }, [clientIdentifier, callback = WTFMove(callback)]() mutable {
+        auto* client = Document::allDocumentsMap().get(clientIdentifier);
+        auto* frame = client ? client->frame() : nullptr;
+        auto* page = frame ? frame->page() : nullptr;
+        if (!page) {
+            callback({ });
+            return;
+        }
+        page->focusController().setFocusedFrame(frame);
+        callback(ServiceWorkerClientData::from(*client));
+    });
+}
+
 } // namespace WebKit
 
 #endif // ENABLE(SERVICE_WORKER)

Modified: trunk/Source/WebKit/WebProcess/Storage/WebSWClientConnection.h (291937 => 291938)


--- trunk/Source/WebKit/WebProcess/Storage/WebSWClientConnection.h	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebKit/WebProcess/Storage/WebSWClientConnection.h	2022-03-26 15:55:18 UTC (rev 291938)
@@ -99,6 +99,7 @@
     void disableNavigationPreload(WebCore::ServiceWorkerRegistrationIdentifier, ExceptionOrVoidCallback&&) final;
     void setNavigationPreloadHeaderValue(WebCore::ServiceWorkerRegistrationIdentifier, String&&, ExceptionOrVoidCallback&&) final;
     void getNavigationPreloadState(WebCore::ServiceWorkerRegistrationIdentifier, ExceptionOrNavigationPreloadStateCallback&&) final;
+    void focusServiceWorkerClient(WebCore::ScriptExecutionContextIdentifier, CompletionHandler<void(std::optional<WebCore::ServiceWorkerClientData>&&)>&&);
 
     void scheduleStorageJob(const WebCore::ServiceWorkerJobData&);
 

Modified: trunk/Source/WebKit/WebProcess/Storage/WebSWClientConnection.messages.in (291937 => 291938)


--- trunk/Source/WebKit/WebProcess/Storage/WebSWClientConnection.messages.in	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebKit/WebProcess/Storage/WebSWClientConnection.messages.in	2022-03-26 15:55:18 UTC (rev 291938)
@@ -39,6 +39,8 @@
     PostMessageToServiceWorkerClient(WebCore::ScriptExecutionContextIdentifier destinationContextIdentifier, struct WebCore::MessageWithMessagePorts message, struct WebCore::ServiceWorkerData source, String sourceOrigin)
 
     SetDocumentIsControlled(WebCore::ScriptExecutionContextIdentifier temporaryDocumentIdentifier, struct WebCore::ServiceWorkerRegistrationData data) -> (bool isSuccess)
+
+    FocusServiceWorkerClient(WebCore::ScriptExecutionContextIdentifier clientIdentifier) -> (std::optional<WebCore::ServiceWorkerClientData> result)
 }
 
 #endif // ENABLE(SERVICE_WORKER)

Modified: trunk/Source/WebKit/WebProcess/Storage/WebSWContextManagerConnection.cpp (291937 => 291938)


--- trunk/Source/WebKit/WebProcess/Storage/WebSWContextManagerConnection.cpp	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebKit/WebProcess/Storage/WebSWContextManagerConnection.cpp	2022-03-26 15:55:18 UTC (rev 291938)
@@ -332,7 +332,7 @@
         callback(WTFMove(clientsData));
 }
 
-void WebSWContextManagerConnection::claim(WebCore::ServiceWorkerIdentifier serviceWorkerIdentifier, CompletionHandler<void(ExceptionOr<void>&&)>&& callback)
+void WebSWContextManagerConnection::claim(ServiceWorkerIdentifier serviceWorkerIdentifier, CompletionHandler<void(ExceptionOr<void>&&)>&& callback)
 {
     m_connectionToNetworkProcess->sendWithAsyncReply(Messages::WebSWServerToContextConnection::Claim { serviceWorkerIdentifier }, [callback = WTFMove(callback)](auto&& result) mutable {
         callback(result ? result->toException() : ExceptionOr<void> { });
@@ -339,6 +339,11 @@
     });
 }
 
+void WebSWContextManagerConnection::focus(ScriptExecutionContextIdentifier clientIdentifier, CompletionHandler<void(std::optional<WebCore::ServiceWorkerClientData>&&)>&& callback)
+{
+    m_connectionToNetworkProcess->sendWithAsyncReply(Messages::WebSWServerToContextConnection::Focus { clientIdentifier }, WTFMove(callback));
+}
+
 void WebSWContextManagerConnection::close()
 {
     RELEASE_LOG(ServiceWorker, "Service worker process is requested to stop all service workers");

Modified: trunk/Source/WebKit/WebProcess/Storage/WebSWContextManagerConnection.h (291937 => 291938)


--- trunk/Source/WebKit/WebProcess/Storage/WebSWContextManagerConnection.h	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Source/WebKit/WebProcess/Storage/WebSWContextManagerConnection.h	2022-03-26 15:55:18 UTC (rev 291938)
@@ -81,6 +81,7 @@
     void findClientByVisibleIdentifier(WebCore::ServiceWorkerIdentifier, const String&, FindClientByIdentifierCallback&&) final;
     void matchAll(WebCore::ServiceWorkerIdentifier, const WebCore::ServiceWorkerClientQueryOptions&, WebCore::ServiceWorkerClientsMatchAllCallback&&) final;
     void claim(WebCore::ServiceWorkerIdentifier, CompletionHandler<void(WebCore::ExceptionOr<void>&&)>&&) final;
+    void focus(WebCore::ScriptExecutionContextIdentifier, CompletionHandler<void(std::optional<WebCore::ServiceWorkerClientData>&&)>&&) final;
     void skipWaiting(WebCore::ServiceWorkerIdentifier, CompletionHandler<void()>&&) final;
     void setScriptResource(WebCore::ServiceWorkerIdentifier, const URL&, const WebCore::ServiceWorkerContextData::ImportedScript&) final;
     bool isThrottleable() const final;

Modified: trunk/Tools/ChangeLog (291937 => 291938)


--- trunk/Tools/ChangeLog	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Tools/ChangeLog	2022-03-26 15:55:18 UTC (rev 291938)
@@ -1,3 +1,13 @@
+2022-03-26  Youenn Fablet  <[email protected]>
+
+        Implement ServiceWorkerWindowClient.focus
+        https://bugs.webkit.org/show_bug.cgi?id=238319
+        <rdar://90616490>
+
+        Reviewed by Brady Eidson.
+
+        * TestWebKitAPI/Tests/WebKitCocoa/ServiceWorkerBasic.mm:
+
 2022-03-26  Yusuke Suzuki  <[email protected]>
 
         Use unary static_assert

Modified: trunk/Tools/TestWebKitAPI/Tests/WebKitCocoa/ServiceWorkerBasic.mm (291937 => 291938)


--- trunk/Tools/TestWebKitAPI/Tests/WebKitCocoa/ServiceWorkerBasic.mm	2022-03-26 14:41:15 UTC (rev 291937)
+++ trunk/Tools/TestWebKitAPI/Tests/WebKitCocoa/ServiceWorkerBasic.mm	2022-03-26 15:55:18 UTC (rev 291938)
@@ -46,6 +46,7 @@
 #import <WebKit/WKWebsiteDataStoreRef.h>
 #import <WebKit/WebKit.h>
 #import <WebKit/_WKExperimentalFeature.h>
+#import <WebKit/_WKInternalDebugFeature.h>
 #import <WebKit/_WKProcessPoolConfiguration.h>
 #import <WebKit/_WKRemoteObjectInterface.h>
 #import <WebKit/_WKRemoteObjectRegistry.h>
@@ -2802,3 +2803,166 @@
     }
     TestWebKitAPI::Util::run(&done);
 }
+
+static const char* ServiceWorkerWindowClientFocusMain =
+"<div>test page</div>"
+"<script>"
+"let worker;"
+"async function test() {"
+"    try {"
+"        const registration = await navigator.serviceWorker.register('/sw.js');"
+"        if (registration.active) {"
+"            worker = registration.active;"
+"            alert('already active');"
+"            return;"
+"        }"
+"        worker = registration.installing;"
+"        worker.addEventListener('statechange', () => {"
+"            if (worker.state == 'activated')"
+"                alert('successfully registered');"
+"        });"
+"    } catch(e) {"
+"        alert('Exception: ' + e);"
+"    }"
+"}"
+"window._onload_ = test;"
+""
+"function focusClient() {"
+"    worker.postMessage('start');"
+"    navigator.serviceWorker._onmessage_ = (event) => {"
+"        window.webkit.messageHandlers.sw.postMessage(event.data);"
+"    }"
+"}"
+""
+"function checkFocusValue(value, name) {"
+"    window.webkit.messageHandlers.sw.postMessage(document.hasFocus() === value ? 'PASS' : 'FAIL: expected ' + value + ' for ' + name);"
+"}"
+"</script>";
+static const char* ServiceWorkerWindowClientFocusJS =
+"self.addEventListener('message', (event) => {"
+"   event.source.focus().then((client) => {"
+"       event.source.postMessage('focused');"
+"   }, (error) => {"
+"       event.source.postMessage('not focused');"
+"   });"
+"});";
+
+TEST(ServiceWorker, ServiceWorkerWindowClientFocus)
+{
+    [WKWebsiteDataStore _allowWebsiteDataRecordsForAllOrigins];
+
+    // Start with a clean slate data store
+    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:[WKWebsiteDataStore allWebsiteDataTypes] modifiedSince:[NSDate distantPast] completionHandler:^() {
+        done = true;
+    }];
+    TestWebKitAPI::Util::run(&done);
+    done = false;
+
+    auto configuration = adoptNS([[WKWebViewConfiguration alloc] init]);
+    auto preferences = [configuration preferences];
+
+    for (_WKInternalDebugFeature *feature in [WKPreferences _internalDebugFeatures]) {
+        if ([feature.key isEqualToString:@"ServiceWorkersUserGestureEnabled"])
+            [preferences _setEnabled:NO forInternalDebugFeature:feature];
+    }
+
+    auto messageHandler = adoptNS([[SWMessageHandlerWithExpectedMessage alloc] init]);
+    [[configuration userContentController] addScriptMessageHandler:messageHandler.get() name:@"sw"];
+
+    auto webView1 = adoptNS([[TestWKWebView alloc] initWithFrame:NSMakeRect(0, 0, 300, 300) configuration:configuration.get() addToWindow:YES]);
+    auto webView2 = adoptNS([[TestWKWebView alloc] initWithFrame:NSMakeRect(0, 0, 300, 300) configuration:configuration.get() addToWindow:YES]);
+
+    TestWebKitAPI::HTTPServer server({
+        { "/", { ServiceWorkerWindowClientFocusMain } },
+        { "/sw.js", { {{ "Content-Type", "application/_javascript_" }}, ServiceWorkerWindowClientFocusJS } }
+    });
+
+    [webView1 loadRequest:server.request()];
+    EXPECT_WK_STREQ([webView1 _test_waitForAlert], "successfully registered");
+
+    [webView2 loadRequest:server.request()];
+    EXPECT_WK_STREQ([webView2 _test_waitForAlert], "already active");
+
+#if PLATFORM(MAC)
+    [[webView1 hostWindow] miniaturize:[webView1 hostWindow]];
+    [[webView2 hostWindow] miniaturize:[webView2 hostWindow]];
+    EXPECT_FALSE([webView1 hostWindow].isVisible);
+    EXPECT_FALSE([webView2 hostWindow].isVisible);
+#endif
+
+    done = false;
+    expectedMessage = "focused";
+    [webView1 evaluateJavaScript:@"focusClient()" completionHandler: nil];
+    TestWebKitAPI::Util::run(&done);
+#if PLATFORM(MAC)
+    EXPECT_TRUE([webView1 hostWindow].isVisible);
+    EXPECT_FALSE([webView2 hostWindow].isVisible);
+    EXPECT_FALSE([webView1 hostWindow].isMiniaturized);
+    EXPECT_TRUE([webView2 hostWindow].isMiniaturized);
+
+    // FIXME: We should be able to run these tests in iOS once pages are actually visible.
+    done = false;
+    expectedMessage = "PASS";
+    [webView1 evaluateJavaScript:@"checkFocusValue(true, 'webView1')" completionHandler:nil];
+    TestWebKitAPI::Util::run(&done);
+
+    done = false;
+    expectedMessage = "PASS";
+    [webView2 evaluateJavaScript:@"checkFocusValue(false, 'webView2')" completionHandler:nil];
+    TestWebKitAPI::Util::run(&done);
+#endif
+
+    done = false;
+    expectedMessage = "focused";
+    [webView2 evaluateJavaScript:@"focusClient()" completionHandler: nil];
+    TestWebKitAPI::Util::run(&done);
+#if PLATFORM(MAC)
+    EXPECT_TRUE([webView2 hostWindow].isVisible);
+    EXPECT_FALSE([webView1 hostWindow].isMiniaturized);
+    EXPECT_FALSE([webView2 hostWindow].isMiniaturized);
+
+    // FIXME: We should be able to run these tests in iOS once pages are actually visible.
+    done = false;
+    expectedMessage = "PASS";
+    [webView2 evaluateJavaScript:@"checkFocusValue(true, 'webView2')" completionHandler:nil];
+    TestWebKitAPI::Util::run(&done);
+#endif
+}
+
+TEST(ServiceWorker, ServiceWorkerWindowClientFocusRequiresUserGesture)
+{
+    [WKWebsiteDataStore _allowWebsiteDataRecordsForAllOrigins];
+
+    // Start with a clean slate data store
+    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:[WKWebsiteDataStore allWebsiteDataTypes] modifiedSince:[NSDate distantPast] completionHandler:^() {
+        done = true;
+    }];
+    TestWebKitAPI::Util::run(&done);
+    done = false;
+
+    auto configuration = adoptNS([[WKWebViewConfiguration alloc] init]);
+    auto preferences = [configuration preferences];
+
+    for (_WKInternalDebugFeature *feature in [WKPreferences _internalDebugFeatures]) {
+        if ([feature.key isEqualToString:@"ServiceWorkersUserGestureEnabled"])
+            [preferences _setEnabled:YES forInternalDebugFeature:feature];
+    }
+
+    auto messageHandler = adoptNS([[SWMessageHandlerWithExpectedMessage alloc] init]);
+    [[configuration userContentController] addScriptMessageHandler:messageHandler.get() name:@"sw"];
+
+    auto webView = adoptNS([[TestWKWebView alloc] initWithFrame:NSMakeRect(0, 0, 300, 300) configuration:configuration.get() addToWindow:YES]);
+
+    TestWebKitAPI::HTTPServer server({
+        { "/", { ServiceWorkerWindowClientFocusMain } },
+        { "/sw.js", { {{ "Content-Type", "application/_javascript_" }}, ServiceWorkerWindowClientFocusJS } }
+    });
+
+    [webView loadRequest:server.request()];
+    EXPECT_WK_STREQ([webView _test_waitForAlert], "successfully registered");
+
+    done = false;
+    expectedMessage = "not focused";
+    [webView evaluateJavaScript:@"focusClient()" completionHandler: nil];
+    TestWebKitAPI::Util::run(&done);
+}
_______________________________________________
webkit-changes mailing list
[email protected]
https://lists.webkit.org/mailman/listinfo/webkit-changes

Reply via email to