Truly independent web browser
LibWebView+LibWeb: Let gamepad user gestures give user activation
Luke Wilde1aa64c71795c
diff --git a/Libraries/LibWeb/Gamepad/Gamepad.cpp b/Libraries/LibWeb/Gamepad/Gamepad.cppindex 368e46805ec..387c18faa0b 100644--- a/Libraries/LibWeb/Gamepad/Gamepad.cpp+++ b/Libraries/LibWeb/Gamepad/Gamepad.cpp@@ -380,6 +380,10 @@ void Gamepad::update_gamepad_state(Badge<NavigatorGamepadPartial>)// NB: A Window always has an associated Document.auto& document = window.associated_document();+ // AD-HOC: https://github.com/w3c/gamepad/pull/230 proposes a step here: "If document is a fully active descendant of+ // a top-level traversable with user attention and gamepad contains a gamepad user gesture, then run the+ // activation notification steps given document." The UI process runs it.+// 9. If navigator.[[hasGamepadGesture]] is false and document is a fully active descendant of a top-level// traversable with user attention and gamepad contains a gamepad user gesture:if (!navigator->has_gamepad_gesture() && document.is_fully_active_descendant_of_a_top_level_traversable_with_user_attention() && contains_gamepad_user_gesture()) {diff --git a/Libraries/LibWebView/GamepadManager.cpp b/Libraries/LibWebView/GamepadManager.cppindex 44fb419e7ab..e2d3e539304 100644--- a/Libraries/LibWebView/GamepadManager.cpp+++ b/Libraries/LibWebView/GamepadManager.cpp@@ -490,15 +490,40 @@ void GamepadManager::notify_consumers_of_state_changes()void GamepadManager::publish_device_state(Device const& device){+ auto contains_gamepad_user_gesture = device.contains_gamepad_user_gesture();+for (auto& entry : m_consumers) {auto& consumer = *entry.value;if (auto slot_index = consumer.slot_index_for_device(device.description.handle); slot_index.has_value()) {Web::Gamepad::publish_gamepad_state_to_slot(consumer.shared_state_slot(*slot_index), device.last_published_state);consumer.has_pending_state_changes = true;++ // The activation is in place before the process learns of the state that gave it.+ if (contains_gamepad_user_gesture)+ consumer.notify_about_user_activation_for_gamepad_user_gesture();}}}+// https://github.com/w3c/gamepad/pull/230+// The activation notification steps that updating a gamepad's state runs for each document it belongs to. The UI+// process runs them, as the gesture is input it received.+void GamepadManager::Consumer::notify_about_user_activation_for_gamepad_user_gesture() const+{+ HashTable<Web::HTML::CrossProcessId> notified_document_ids;+ client.for_each_page([&](WebContentPage& page) {+ page.for_each_navigable_with_a_hosted_active_document([&](CanonicalNavigable const& navigable) {+ // Only the documents allowed to use gamepads have them, so only those start the steps. The steps then reach+ // their ancestors and same-origin descendants whatever those may use.+ if (navigable.active_document_is_fully_active_descendant_of_a_top_level_traversable_with_user_attention()+ && navigable.active_document().is_allowed_to_use(Web::PermissionsPolicy::PolicyControlledFeature::Gamepad))+ navigable.run_activation_notification_steps_for_active_document(notified_document_ids);+ return IterationDecision::Continue;+ });+ return IterationDecision::Continue;+ });+}+void GamepadManager::device_connected(u32 sdl_joystick_id){auto* device = device_for_sdl_joystick_id(sdl_joystick_id);diff --git a/Libraries/LibWebView/GamepadManager.h b/Libraries/LibWebView/GamepadManager.hindex d5d45aa2667..4b589805ed0 100644--- a/Libraries/LibWebView/GamepadManager.h+++ b/Libraries/LibWebView/GamepadManager.h@@ -81,6 +81,7 @@ public:Web::Gamepad::SharedGamepadStateSlot& shared_state_slot(size_t slot_index);bool may_receive_device(Device const&) const;bool has_page_that_may_receive_gamepads() const;+ void notify_about_user_activation_for_gamepad_user_gesture() const;WebContentClient& client;Core::AnonymousBuffer state_buffer;diff --git a/Tests/LibWeb/Text/expected/GamepadAPI/gamepad-user-gesture-activates-same-origin-descendants.txt b/Tests/LibWeb/Text/expected/GamepadAPI/gamepad-user-gesture-activates-same-origin-descendants.txtnew file mode 100644index 00000000000..3997e4ff384--- /dev/null+++ b/Tests/LibWeb/Text/expected/GamepadAPI/gamepad-user-gesture-activates-same-origin-descendants.txt@@ -0,0 +1,2 @@+The iframe may not use gamepads: SecurityError+Same-origin iframe has transient activation after pressing a button: truediff --git a/Tests/LibWeb/Text/expected/GamepadAPI/gamepad-user-gesture-gives-user-activation.txt b/Tests/LibWeb/Text/expected/GamepadAPI/gamepad-user-gesture-gives-user-activation.txtnew file mode 100644index 00000000000..faf4982f43c--- /dev/null+++ b/Tests/LibWeb/Text/expected/GamepadAPI/gamepad-user-gesture-gives-user-activation.txt@@ -0,0 +1,4 @@+Transient activation before pressing a button: false+Transient activation after pressing a button: true+Transient activation after entering fullscreen consumed it: false+Transient activation after pressing a button without system focus: falsediff --git a/Tests/LibWeb/Text/expected/SiteIsolation/iframe/gamepad-user-gesture-in-isolated-iframe-activates-its-ancestors.txt b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/gamepad-user-gesture-in-isolated-iframe-activates-its-ancestors.txtnew file mode 100644index 00000000000..f37022c84e1--- /dev/null+++ b/Tests/LibWeb/Text/expected/SiteIsolation/iframe/gamepad-user-gesture-in-isolated-iframe-activates-its-ancestors.txt@@ -0,0 +1,9 @@+Top-level document has been active before any press: false+Pressing iframe has transient activation after its press: true+Top-level document has been active after the iframe's press: true+Cross-site sibling iframe has been active after the iframe's press: false+Top-level document has transient activation after its own press: true+Cross-site iframe has been active after the top-level press: false+WebContent#0+ iframe#0: remote WebContent#1+ iframe#1: remote WebContent#2diff --git a/Tests/LibWeb/Text/input/GamepadAPI/gamepad-helper.js b/Tests/LibWeb/Text/input/GamepadAPI/gamepad-helper.jsindex 5c59b31d5b5..523dfea91ed 100644--- a/Tests/LibWeb/Text/input/GamepadAPI/gamepad-helper.js+++ b/Tests/LibWeb/Text/input/GamepadAPI/gamepad-helper.js@@ -11,6 +11,11 @@});};+ // The activation of a gamepad user gesture comes over another connection than the pumped gamepad state, so it can+ // arrive after it.+ globalThis.waitForUserActivation = (targetWindow = window) =>+ waitForCondition(() => targetWindow.navigator.userActivation.isActive);+globalThis.getStringifiedGamepads = () => {const gamepads = navigator.getGamepads().map(gamepad => ({id: gamepad.id,diff --git a/Tests/LibWeb/Text/input/GamepadAPI/gamepad-user-gesture-activates-same-origin-descendants.html b/Tests/LibWeb/Text/input/GamepadAPI/gamepad-user-gesture-activates-same-origin-descendants.htmlnew file mode 100644index 00000000000..66ff1f93968--- /dev/null+++ b/Tests/LibWeb/Text/input/GamepadAPI/gamepad-user-gesture-activates-same-origin-descendants.html@@ -0,0 +1,28 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script src="gamepad-helper.js"></script>+<iframe allow="gamepad 'none'" srcdoc="<!DOCTYPE html>"></iframe>+<script>+ promiseTest(async () => {+ await new Promise(resolve => window.addEventListener("load", resolve, { once: true }));+ const iframeWindow = document.querySelector("iframe").contentWindow;+ try {+ iframeWindow.navigator.getGamepads();+ println("FAIL: the iframe is allowed to use gamepads");+ } catch (error) {+ println(`The iframe may not use gamepads: ${error.name}`);+ }++ startUsingGamepads();+ const gamepad = internals.connectVirtualGamepad();+ await pumpGamepadEvents();++ gamepad.setButton(gamepad.buttons[0], true);+ await pumpGamepadEvents();+ await waitForUserActivation(iframeWindow);+ println(`Same-origin iframe has transient activation after pressing a button: ${iframeWindow.navigator.userActivation.isActive}`);++ gamepad.disconnect();+ await pumpGamepadEvents();+ });+</script>diff --git a/Tests/LibWeb/Text/input/GamepadAPI/gamepad-user-gesture-gives-user-activation.html b/Tests/LibWeb/Text/input/GamepadAPI/gamepad-user-gesture-gives-user-activation.htmlnew file mode 100644index 00000000000..e4aff14b16f--- /dev/null+++ b/Tests/LibWeb/Text/input/GamepadAPI/gamepad-user-gesture-gives-user-activation.html@@ -0,0 +1,37 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script src="gamepad-helper.js"></script>+<script>+ promiseTest(async () => {+ startUsingGamepads();+ const gamepad = internals.connectVirtualGamepad();+ await pumpGamepadEvents();+ println(`Transient activation before pressing a button: ${navigator.userActivation.isActive}`);++ gamepad.setButton(gamepad.buttons[0], true);+ await pumpGamepadEvents();+ await waitForUserActivation();+ println(`Transient activation after pressing a button: ${navigator.userActivation.isActive}`);+ gamepad.setButton(gamepad.buttons[0], false);+ await pumpGamepadEvents();++ try {+ await document.documentElement.requestFullscreen();+ await document.exitFullscreen();+ } catch (error) {+ println(`FAIL: entering fullscreen threw ${error.name}`);+ }+ println(`Transient activation after entering fullscreen consumed it: ${navigator.userActivation.isActive}`);++ internals.setPageFocus(false);+ gamepad.setButton(gamepad.buttons[0], true);+ await pumpGamepadEvents();+ println(`Transient activation after pressing a button without system focus: ${navigator.userActivation.isActive}`);+ gamepad.setButton(gamepad.buttons[0], false);+ await pumpGamepadEvents();+ internals.setPageFocus(true);++ gamepad.disconnect();+ await pumpGamepadEvents();+ });+</script>diff --git a/Tests/LibWeb/Text/input/SiteIsolation/iframe/gamepad-user-gesture-in-isolated-iframe-activates-its-ancestors.html b/Tests/LibWeb/Text/input/SiteIsolation/iframe/gamepad-user-gesture-in-isolated-iframe-activates-its-ancestors.htmlnew file mode 100644index 00000000000..85b75312496--- /dev/null+++ b/Tests/LibWeb/Text/input/SiteIsolation/iframe/gamepad-user-gesture-in-isolated-iframe-activates-its-ancestors.html@@ -0,0 +1,91 @@+<!DOCTYPE html>+<script src="../../include.js"></script>+<script src="../../GamepadAPI/gamepad-helper.js"></script>+<script>+ // A gamepad user gesture gives activation to the windows of the ancestors and same-origin descendants of the+ // documents it activates, whichever process hosts them.+ promiseTest(async () => {+ const isolatedIframeUrl = async (name, body) => {+ const url = new URL(+ await httpTestServer().createEcho("GET", `/${name}`, {+ status: 200,+ headers: { "Content-Type": "text/html" },+ body,+ })+ );+ url.hostname = uniqueLocalhostHostname(name);+ return url;+ };++ const nextMessage = () => new Promise(resolve => window.addEventListener("message", event => resolve(event.data), { once: true }));++ const addIframe = async url => {+ const ready = nextMessage();+ const iframe = document.createElement("iframe");+ iframe.src = url;+ document.body.appendChild(iframe);+ await ready;+ return iframe;+ };++ const askIframe = async (iframe, message) => {+ const reply = nextMessage();+ iframe.contentWindow.postMessage(message, "*");+ return await reply;+ };++ const pressingIframe = await addIframe(+ await isolatedIframeUrl(+ "gamepad-pressing-iframe",+ `<!DOCTYPE html><script>+ const pump = () => {+ internals.pumpGamepadEvents();+ return new Promise(resolve => setTimeout(resolve, 0));+ };+ addEventListener("message", async () => {+ navigator.getGamepads();+ const gamepad = internals.connectVirtualGamepad();+ await pump();+ gamepad.setButton(gamepad.buttons[0], true);+ await pump();+ // As in waitForUserActivation(), the activation can arrive after the pumped gamepad state.+ for (let attempts = 0; attempts < 600 && !navigator.userActivation.isActive; ++attempts)+ await new Promise(resolve => setTimeout(resolve, 25));+ const isActive = navigator.userActivation.isActive;+ gamepad.disconnect();+ await pump();+ parent.postMessage(isActive, "*");+ });+ parent.postMessage("ready", "*");+ <\/script>`+ )+ );+ const passiveIframe = await addIframe(+ await isolatedIframeUrl(+ "gamepad-passive-iframe",+ `<!DOCTYPE html><script>+ addEventListener("message", () => parent.postMessage(navigator.userActivation.hasBeenActive, "*"));+ parent.postMessage("ready", "*");+ <\/script>`+ )+ );++ println(`Top-level document has been active before any press: ${navigator.userActivation.hasBeenActive}`);+ println(`Pressing iframe has transient activation after its press: ${await askIframe(pressingIframe, "press")}`);+ println(`Top-level document has been active after the iframe's press: ${navigator.userActivation.hasBeenActive}`);+ println(`Cross-site sibling iframe has been active after the iframe's press: ${await askIframe(passiveIframe, "query")}`);++ startUsingGamepads();+ const gamepad = internals.connectVirtualGamepad();+ await pumpGamepadEvents();+ gamepad.setButton(gamepad.buttons[0], true);+ await pumpGamepadEvents();+ await waitForUserActivation();+ println(`Top-level document has transient activation after its own press: ${navigator.userActivation.isActive}`);+ println(`Cross-site iframe has been active after the top-level press: ${await askIframe(passiveIframe, "query")}`);+ gamepad.disconnect();+ await pumpGamepadEvents();++ println(internals.dumpSiteIsolationProcessTree().trimEnd());+ });+</script>diff --git a/Tests/LibWebView/TestUserActivation.cpp b/Tests/LibWebView/TestUserActivation.cppindex f2656b10a01..edb4cc2d82b 100644--- a/Tests/LibWebView/TestUserActivation.cpp+++ b/Tests/LibWebView/TestUserActivation.cpp@@ -11,7 +11,11 @@#include <LibGfx/SystemTheme.h>#include <LibTest/TestCase.h>#include <LibWebCommon/Page/InputEvent.h>+#include <LibWebCommon/PermissionsPolicy/PermissionsPolicy.h>#include <LibWebView/Application.h>+#include <LibWebView/CanonicalDocument.h>+#include <LibWebView/CanonicalTraversable.h>+#include <LibWebView/GamepadManager.h>#include <LibWebView/HeadlessWebView.h>#include <LibWebView/Utilities.h>@@ -66,6 +70,22 @@ void click(WebView::ViewImplementation& view, Web::DevicePixelPoint position, We});}+void start_using_gamepads(WebView::ViewImplementation& view)+{+ bool title_changed = false;+ view.on_title_change = [&](auto const&) { title_changed = true; };+ view.run_javascript("navigator.getGamepads(); document.title = 'Using gamepads';"_string);+ Core::EventLoop::current().spin_until([&] { return title_changed; });+ view.on_title_change = nullptr;+}++void press_gamepad_button(WebView::WebContentClient& client, Web::Gamepad::VirtualGamepad const& gamepad)+{+ auto& gamepad_manager = WebView::GamepadManager::the();+ gamepad_manager.set_virtual_gamepad_button(client, gamepad.handle, gamepad.buttons[0], true);+ gamepad_manager.set_virtual_gamepad_button(client, gamepad.handle, gamepad.buttons[0], false);+}+}// Each key or mouse press the UI process delivers gives the page one popup, and one link opened in a new tab, even when@@ -117,4 +137,41 @@ TEST_CASE(user_activation)outln("two queued middle-clicks open two popups and two tabs");VERIFY(popups_opened == 4);++ // A gamepad user gesture gives activation too, to a page with the user's attention.+ auto gamepad_view = WebView::HeadlessWebView::create(TRY_OR_FAIL(Gfx::load_system_theme(theme_path.string())), { 800, 600 });+ auto& gamepad_page = gamepad_view->page();+ gamepad_view->set_system_visibility_state(Web::HTML::VisibilityState::Visible);+ gamepad_view->set_has_system_focus(true);+ start_using_gamepads(*gamepad_view);+ auto gamepad = WebView::GamepadManager::the().create_virtual_gamepad(gamepad_page.client()).release_value();+ (void)WebView::GamepadManager::the().pump_gamepad_events(gamepad_page.client());+ VERIFY(!gamepad_page.has_transient_user_activation());++ press_gamepad_button(gamepad_page.client(), gamepad);+ VERIFY(gamepad_page.has_transient_user_activation());+ outln("a gamepad user gesture gives activation");++ VERIFY(gamepad_page.consume_transient_user_activation());+ gamepad_view->set_has_system_focus(false);+ press_gamepad_button(gamepad_page.client(), gamepad);+ VERIFY(!gamepad_page.has_transient_user_activation());+ outln("a gamepad user gesture without the user's attention gives none");++ // Only a document allowed to use gamepads starts the activation of a gesture, in a process that has the gamepad.+ gamepad_view->set_has_system_focus(true);+ auto& gamepad_document = gamepad_view->traversable().active_document();+ auto permissions_policy = gamepad_document.permissions_policy();+ auto permissions_policy_without_gamepads = permissions_policy;+ permissions_policy_without_gamepads.inherited_policy[to_underlying(Web::PermissionsPolicy::PolicyControlledFeature::Gamepad)] = Web::PermissionsPolicy::FeatureValue::Disabled;+ gamepad_document.set_permissions_policy(move(permissions_policy_without_gamepads));+ (void)gamepad_page.consume_transient_user_activation();+ press_gamepad_button(gamepad_page.client(), gamepad);+ VERIFY(!gamepad_page.has_transient_user_activation());+ outln("a gamepad user gesture for a document not allowed to use gamepads gives none");++ gamepad_document.set_permissions_policy(move(permissions_policy));+ press_gamepad_button(gamepad_page.client(), gamepad);+ VERIFY(gamepad_page.has_transient_user_activation());+ outln("a gamepad user gesture for a document allowed to use gamepads again gives activation");}