Skip to content

Truly independent web browser

LibWebView+LibWeb+LibWebCommon+WebContent: Hide gamepads until a gesture

Luke Wilde1263fa9aeb49
diff --git a/Libraries/LibWeb/Gamepad/Gamepad.cpp b/Libraries/LibWeb/Gamepad/Gamepad.cpp
index 9f064831159..368e46805ec 100644
--- a/Libraries/LibWeb/Gamepad/Gamepad.cpp
+++ b/Libraries/LibWeb/Gamepad/Gamepad.cpp
@@ -16,20 +16,12 @@
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/Window.h>
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
+#include <LibWebCommon/Gamepad/GamepadInput.h>
namespace Web::Gamepad {
GC_DEFINE_ALLOCATOR(Gamepad);
-// https://w3c.github.io/gamepad/#dfn-button-press-threshold
-// For buttons which do not have a digital switch to indicate a pure pressed or released state, the user
-// agent MUST choose a button press threshold to indicate the button as pressed when its value is above a
-// certain amount. If the platform API gives a recommended value, the user agent SHOULD use that. In other
-// cases, the user agent SHOULD choose some other reasonable value.
-static constexpr double ANALOG_BUTTON_PRESS_THRESHOLD = 0.1;
-
-static constexpr double GAMEPAD_EXPOSURE_AXIS_THRESHOLD = 0.5;
-
// https://w3c.github.io/gamepad/#dfn-a-new-gamepad
GC::Ref<Gamepad> Gamepad::create(HTML::Window& window, GamepadDescription const& description)
{
@@ -306,7 +298,7 @@ void Gamepad::map_and_normalize_axes()
auto logical_maximum = m_axis_maximums[raw_axis_index];
// 5. Let normalizedValue be 2 (logicalValue − logicalMinimum) / (logicalMaximum − logicalMinimum) − 1.
- double normalized_value = 2.0 * static_cast<double>(logical_value - logical_minimum) / static_cast<double>(logical_maximum - logical_minimum) - 1.0;
+ double normalized_value = normalize_axis_value(logical_value, logical_minimum, logical_maximum);
// 6. Set gamepad.[[axes]][axisIndex] to be normalizedValue.
// FIXME: axisIndex should be mappedIndex.
@@ -339,7 +331,7 @@ void Gamepad::map_and_normalize_buttons()
auto logical_maximum = m_button_maximums[raw_button_index];
// 5. Let normalizedValue be (logicalValue − logicalMinimum) / (logicalMaximum − logicalMinimum).
- double value = static_cast<double>(logical_value - logical_minimum) / static_cast<double>(logical_maximum - logical_minimum);
+ double value = normalize_button_value(logical_value, logical_minimum, logical_maximum);
// 6. Let button be gamepad.[[buttons]][mappedIndex].
auto button = m_buttons[mapped_index];
@@ -351,11 +343,7 @@ void Gamepad::map_and_normalize_buttons()
// to true if the button is pressed or false if it is not pressed.
// Otherwise, set button.[[pressed]] to true if the value is above the button press threshold or false if
// it is not above the threshold.
- if (logical_maximum == 1) {
- button->set_pressed({}, logical_value == 1);
- } else {
- button->set_pressed({}, value > ANALOG_BUTTON_PRESS_THRESHOLD);
- }
+ button->set_pressed({}, is_button_pressed(logical_value, logical_minimum, logical_maximum));
// 9. If the button is capable of detecting touch, set button.[[touched]] to true if the button is currently being touched.
// Otherwise, set button.[[touched]] to button.[[pressed]].
@@ -424,33 +412,8 @@ void Gamepad::update_gamepad_state(Badge<NavigatorGamepadPartial>)
// https://w3c.github.io/gamepad/#dfn-gamepad-user-gesture
bool Gamepad::contains_gamepad_user_gesture()
{
- // A gamepad contains a gamepad user gesture if the current input state indicates that the user is currently
- // interacting with the gamepad. The user agent MUST provide an algorithm to check if the input state contains a
- // gamepad user gesture. For buttons that support a neutral default value and have reported a pressed value of
- // false at least once, a pressed value of true SHOULD be considered interaction. If a button does not support a
- // neutral default value (for example, a toggle switch), then a pressed value of true SHOULD NOT be considered
- // interaction. If a button has never reported a pressed value of false then it SHOULD NOT be considered
- // interaction. Axis movements SHOULD be considered interaction if the axis supports a neutral default value, the
- // current displacement from neutral is greater than a threshold chosen by the user agent, and the axis has
- // reported a value below the threshold at least once. If an axis does not support a neutral default value (for
- // example, an axis for a joystick that does not self-center), or an axis has never reported a value below the axis
- // gesture threshold, then the axis SHOULD NOT be considered when checking for interaction. The axis gesture
- // threshold SHOULD be large enough that random jitter is not considered interaction.
-
- // NOTE: This roughly follows Chrome, where it exposes gamepads if a button is pressed (even if it's held across
- // a refresh) or an absolute axis is above 0.5.
- auto pressed_button = m_buttons.find_if([](GC::Ref<GamepadButton> gamepad_button) {
- return gamepad_button->pressed();
- });
-
- if (!pressed_button.is_end())
- return true;
-
- auto axis_above_threshold = m_axes.find_if([](double value) {
- return abs(value) > GAMEPAD_EXPOSURE_AXIS_THRESHOLD;
- });
-
- return !axis_above_threshold.is_end();
+ // NB: The UI process uses the same algorithm to decide when to tell this process about its gamepads.
+ return Web::Gamepad::contains_gamepad_user_gesture(m_description, m_latest_state);
}
}
diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cpp
index bf6cc93d91d..5811b090d9f 100644
--- a/Libraries/LibWeb/Internals/Internals.cpp
+++ b/Libraries/LibWeb/Internals/Internals.cpp
@@ -2108,6 +2108,9 @@ void Internals::perform_per_test_cleanup()
gamepad->disconnect();
m_gamepads.clear();
+ // Reset gamepad access, so that no test relies on the gamepad use and gestures of an earlier one
+ page().client().reset_gamepad_access_for_testing();
+
// Clear any input state
if (auto local_root = local_root_of(window())) {
local_root->event_handler().clear_per_test_input_state({});
diff --git a/Libraries/LibWeb/Page/Page.h b/Libraries/LibWeb/Page/Page.h
index 5737370ea05..ba9ad445711 100644
--- a/Libraries/LibWeb/Page/Page.h
+++ b/Libraries/LibWeb/Page/Page.h
@@ -923,6 +923,7 @@ public:
virtual void disconnect_virtual_gamepad([[maybe_unused]] Gamepad::GamepadHandle handle) { }
virtual Gamepad::ReceivedRumbleEffects virtual_gamepad_received_rumble_effects([[maybe_unused]] Gamepad::GamepadHandle handle) { return {}; }
virtual void pump_gamepad_events() { }
+ virtual void reset_gamepad_access_for_testing() { }
virtual void page_did_block_resource([[maybe_unused]] URL::URL const& url, [[maybe_unused]] StringView kind) { }
virtual void page_did_start_network_request([[maybe_unused]] u64 request_id, [[maybe_unused]] URL::URL const& url, [[maybe_unused]] ByteString const& method, [[maybe_unused]] Vector<HTTP::Header> const& request_headers, [[maybe_unused]] ReadonlyBytes request_body, [[maybe_unused]] Optional<String> initiator_type, [[maybe_unused]] String const& referrer_policy, [[maybe_unused]] bool is_navigation_request, [[maybe_unused]] Fetch::Infrastructure::Request::Priority priority) { }
diff --git a/Libraries/LibWebCommon/CMakeLists.txt b/Libraries/LibWebCommon/CMakeLists.txt
index 4915171e53b..295322eb298 100644
--- a/Libraries/LibWebCommon/CMakeLists.txt
+++ b/Libraries/LibWebCommon/CMakeLists.txt
@@ -10,6 +10,7 @@ set(SOURCES
Fetch/Infrastructure/URL.cpp
FileAPI/BlobURLStore.cpp
FileAPI/SerializedBlobURLEntry.cpp
+ Gamepad/GamepadInput.cpp
Gamepad/GamepadSharedState.cpp
Gamepad/GamepadSnapshot.cpp
Gamepad/GamepadStateBuffer.cpp
diff --git a/Libraries/LibWebCommon/Gamepad/GamepadInput.cpp b/Libraries/LibWebCommon/Gamepad/GamepadInput.cpp
new file mode 100644
index 00000000000..058f18034f2
--- /dev/null
+++ b/Libraries/LibWebCommon/Gamepad/GamepadInput.cpp
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2026, Luke Wilde <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Math.h>
+#include <LibWebCommon/Gamepad/GamepadInput.h>
+
+namespace Web::Gamepad {
+
+// https://w3c.github.io/gamepad/#dfn-button-press-threshold
+// For buttons which do not have a digital switch to indicate a pure pressed or released state, the user
+// agent MUST choose a button press threshold to indicate the button as pressed when its value is above a
+// certain amount. If the platform API gives a recommended value, the user agent SHOULD use that. In other
+// cases, the user agent SHOULD choose some other reasonable value.
+static constexpr double ANALOG_BUTTON_PRESS_THRESHOLD = 0.1;
+
+static constexpr double AXIS_GESTURE_THRESHOLD = 0.5;
+
+// https://w3c.github.io/gamepad/#dfn-map-and-normalize-axes
+double normalize_axis_value(i16 logical_value, i16 logical_minimum, i16 logical_maximum)
+{
+ return 2.0 * static_cast<double>(logical_value - logical_minimum) / static_cast<double>(logical_maximum - logical_minimum) - 1.0;
+}
+
+// https://w3c.github.io/gamepad/#dfn-map-and-normalize-buttons
+double normalize_button_value(i16 logical_value, i16 logical_minimum, i16 logical_maximum)
+{
+ return static_cast<double>(logical_value - logical_minimum) / static_cast<double>(logical_maximum - logical_minimum);
+}
+
+// https://w3c.github.io/gamepad/#dfn-map-and-normalize-buttons
+bool is_button_pressed(i16 logical_value, i16 logical_minimum, i16 logical_maximum)
+{
+ // NB: Buttons with a logical maximum of 1 have a digital switch.
+ if (logical_maximum == 1)
+ return logical_value == 1;
+ return normalize_button_value(logical_value, logical_minimum, logical_maximum) > ANALOG_BUTTON_PRESS_THRESHOLD;
+}
+
+// https://w3c.github.io/gamepad/#dfn-gamepad-user-gesture
+bool contains_gamepad_user_gesture(GamepadDescription const& description, GamepadState const& state)
+{
+ // A gamepad contains a gamepad user gesture if the current input state indicates that the user is currently
+ // interacting with the gamepad. The user agent MUST provide an algorithm to check if the input state contains a
+ // gamepad user gesture. For buttons that support a neutral default value and have reported a pressed value of
+ // false at least once, a pressed value of true SHOULD be considered interaction. If a button does not support a
+ // neutral default value (for example, a toggle switch), then a pressed value of true SHOULD NOT be considered
+ // interaction. If a button has never reported a pressed value of false then it SHOULD NOT be considered
+ // interaction. Axis movements SHOULD be considered interaction if the axis supports a neutral default value, the
+ // current displacement from neutral is greater than a threshold chosen by the user agent, and the axis has
+ // reported a value below the threshold at least once. If an axis does not support a neutral default value (for
+ // example, an axis for a joystick that does not self-center), or an axis has never reported a value below the axis
+ // gesture threshold, then the axis SHOULD NOT be considered when checking for interaction. The axis gesture
+ // threshold SHOULD be large enough that random jitter is not considered interaction.
+
+ // NB: This roughly follows Chrome, where it exposes gamepads if a button is pressed (even if it's held across a
+ // refresh) or an absolute axis is above 0.5.
+ for (size_t button_index = 0; button_index < min(state.button_values.size(), description.buttons.size()); ++button_index) {
+ auto const& button = description.buttons[button_index];
+ if (is_button_pressed(state.button_values[button_index], button.logical_minimum, button.logical_maximum))
+ return true;
+ }
+
+ for (size_t axis_index = 0; axis_index < min(state.axis_values.size(), description.axes.size()); ++axis_index) {
+ auto const& axis = description.axes[axis_index];
+ if (abs(normalize_axis_value(state.axis_values[axis_index], axis.logical_minimum, axis.logical_maximum)) > AXIS_GESTURE_THRESHOLD)
+ return true;
+ }
+
+ return false;
+}
+
+}
diff --git a/Libraries/LibWebCommon/Gamepad/GamepadInput.h b/Libraries/LibWebCommon/Gamepad/GamepadInput.h
new file mode 100644
index 00000000000..7aedaac9349
--- /dev/null
+++ b/Libraries/LibWebCommon/Gamepad/GamepadInput.h
@@ -0,0 +1,20 @@
+/*
+ * Copyright (c) 2026, Luke Wilde <[email protected]>
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <LibWebCommon/Export.h>
+#include <LibWebCommon/Gamepad/GamepadSnapshot.h>
+
+namespace Web::Gamepad {
+
+WEBCOMMON_API double normalize_axis_value(i16 logical_value, i16 logical_minimum, i16 logical_maximum);
+WEBCOMMON_API double normalize_button_value(i16 logical_value, i16 logical_minimum, i16 logical_maximum);
+WEBCOMMON_API bool is_button_pressed(i16 logical_value, i16 logical_minimum, i16 logical_maximum);
+
+WEBCOMMON_API bool contains_gamepad_user_gesture(GamepadDescription const&, GamepadState const&);
+
+}
diff --git a/Libraries/LibWebView/CanonicalDocument.cpp b/Libraries/LibWebView/CanonicalDocument.cpp
index f08caef7128..ccfc6abacfe 100644
--- a/Libraries/LibWebView/CanonicalDocument.cpp
+++ b/Libraries/LibWebView/CanonicalDocument.cpp
@@ -50,6 +50,11 @@ CanonicalDocument::CanonicalDocument(Web::HTML::CrossProcessId id, URL::URL crea
CanonicalDocument::~CanonicalDocument() = default;
+bool CanonicalDocument::is_allowed_to_use(Web::PermissionsPolicy::PolicyControlledFeature feature) const
+{
+ return Web::PermissionsPolicy::check_permissions_policy(m_permissions_policy, feature, m_origin, m_origin) == Web::PermissionsPolicy::FeatureValue::Enabled;
+}
+
Optional<URL::Origin> CanonicalDocument::top_level_origin() const
{
auto& top_level_browsing_context = m_browsing_context->top_level_browsing_context();
diff --git a/Libraries/LibWebView/CanonicalDocument.h b/Libraries/LibWebView/CanonicalDocument.h
index 1b2aac3f0fe..88673396dcd 100644
--- a/Libraries/LibWebView/CanonicalDocument.h
+++ b/Libraries/LibWebView/CanonicalDocument.h
@@ -69,6 +69,7 @@ public:
// https://html.spec.whatwg.org/multipage/dom.html#concept-document-permissions-policy
Web::PermissionsPolicy::PermissionsPolicy const& permissions_policy() const { return m_permissions_policy; }
void set_permissions_policy(Web::PermissionsPolicy::PermissionsPolicy permissions_policy) { m_permissions_policy = move(permissions_policy); }
+ bool is_allowed_to_use(Web::PermissionsPolicy::PolicyControlledFeature) const;
// https://html.spec.whatwg.org/multipage/dom.html#completely-loaded
bool is_completely_loaded() const { return m_completely_loaded; }
diff --git a/Libraries/LibWebView/CanonicalNavigable.cpp b/Libraries/LibWebView/CanonicalNavigable.cpp
index 103c665ff43..d49c3854ed1 100644
--- a/Libraries/LibWebView/CanonicalNavigable.cpp
+++ b/Libraries/LibWebView/CanonicalNavigable.cpp
@@ -569,6 +569,18 @@ bool CanonicalNavigable::is_ancestor_of(CanonicalNavigable const& potential_desc
return false;
}
+// https://html.spec.whatwg.org/multipage/interaction.html#fully-active-descendant-of-a-top-level-traversable-with-user-attention
+bool CanonicalNavigable::active_document_is_fully_active_descendant_of_a_top_level_traversable_with_user_attention() const
+{
+ // A Document d is a fully active descendant of a top-level traversable with user attention when d is fully active
+ // and d's node navigable's top-level traversable has user attention.
+ // NB: The process hosting the active document reports whether it is fully active. A lost document has no host, and
+ // is not fully active whatever its host last reported.
+ if (!active_document().host())
+ return false;
+ return m_hosted_state.has_value() && m_hosted_state->active_document_is_fully_active && top_level_traversable().has_user_attention();
+}
+
// https://html.spec.whatwg.org/multipage/document-sequences.html#familiar-with
// NB: Stated on the navigables whose active browsing contexts are compared, as in the renderer.
bool CanonicalNavigable::is_familiar_with(CanonicalNavigable const& other) const
diff --git a/Libraries/LibWebView/CanonicalNavigable.h b/Libraries/LibWebView/CanonicalNavigable.h
index 0d820d90997..5cb4bedeec4 100644
--- a/Libraries/LibWebView/CanonicalNavigable.h
+++ b/Libraries/LibWebView/CanonicalNavigable.h
@@ -128,6 +128,7 @@ public:
CanonicalNavigable& append_child(NonnullOwnPtr<CanonicalNavigable>);
NonnullOwnPtr<CanonicalNavigable> remove_child(CanonicalNavigable&);
bool is_ancestor_of(CanonicalNavigable const&) const;
+ bool active_document_is_fully_active_descendant_of_a_top_level_traversable_with_user_attention() const;
bool allowed_by_sandboxing_to_navigate(CanonicalNavigable const& target, Web::InitiatorSourceSnapshot const& source_snapshot_params) const;
bool is_familiar_with(CanonicalNavigable const&) const;
// https://html.spec.whatwg.org/multipage/document-sequences.html#the-rules-for-choosing-a-navigable
diff --git a/Libraries/LibWebView/CanonicalTraversable.cpp b/Libraries/LibWebView/CanonicalTraversable.cpp
index 884df1061d1..3efc3f0651d 100644
--- a/Libraries/LibWebView/CanonicalTraversable.cpp
+++ b/Libraries/LibWebView/CanonicalTraversable.cpp
@@ -89,6 +89,17 @@ void CanonicalTraversable::set_has_system_focus(bool has_system_focus, RefPtr<We
});
}
+// https://html.spec.whatwg.org/multipage/interaction.html#user-attention
+bool CanonicalTraversable::has_user_attention() const
+{
+ // A top-level traversable has user attention when its system visibility state is "visible", and it either has
+ // system focus or user agent widgets directly related to it can receive keyboard input channeled from the
+ // operating system.
+ // FIXME: Also give the traversable user attention while a user agent widget related to it, such as the location bar,
+ // can receive keyboard input.
+ return m_system_visibility_state == Web::HTML::VisibilityState::Visible && m_has_system_focus;
+}
+
void CanonicalTraversable::set_focused_navigable(CanonicalNavigable& navigable, WebContentPage& requesting_page)
{
if (m_focused_navigable_id == navigable.id())
diff --git a/Libraries/LibWebView/CanonicalTraversable.h b/Libraries/LibWebView/CanonicalTraversable.h
index 8f6cb69c2a9..7bf58e74c85 100644
--- a/Libraries/LibWebView/CanonicalTraversable.h
+++ b/Libraries/LibWebView/CanonicalTraversable.h
@@ -153,6 +153,8 @@ public:
bool has_system_focus() const { return m_has_system_focus; }
void set_has_system_focus(bool, RefPtr<WebContentPage> requesting_page);
+ bool has_user_attention() const;
+
Optional<Web::HTML::CrossProcessId> const& focused_navigable_id() const { return m_focused_navigable_id; }
void set_focused_navigable(CanonicalNavigable&, WebContentPage& requesting_page);
RefPtr<WebContentPage> focused_navigable_host() const;
diff --git a/Libraries/LibWebView/GamepadManager.cpp b/Libraries/LibWebView/GamepadManager.cpp
index 232ea23d987..44fb419e7ab 100644
--- a/Libraries/LibWebView/GamepadManager.cpp
+++ b/Libraries/LibWebView/GamepadManager.cpp
@@ -7,10 +7,14 @@
#include <AK/AnyOf.h>
#include <AK/NeverDestroyed.h>
#include <LibCore/Timer.h>
+#include <LibWebCommon/Gamepad/GamepadInput.h>
#include <LibWebCommon/Gamepad/GamepadStateBuffer.h>
#include <LibWebView/Application.h>
+#include <LibWebView/CanonicalDocument.h>
+#include <LibWebView/CanonicalTraversable.h>
#include <LibWebView/GamepadManager.h>
#include <LibWebView/WebContentClient.h>
+#include <LibWebView/WebContentPage.h>
#include <SDL3/SDL_events.h>
#include <SDL3/SDL_gamepad.h>
@@ -147,7 +151,8 @@ bool GamepadManager::ensure_sdl_initialized()
void GamepadManager::update_polling_state()
{
- bool should_poll = m_sdl_initialized && !m_in_test_mode && any_of(m_consumers, [](auto const& entry) { return entry.value->receives_real_devices; });
+ // A process waiting for a gesture needs the polling that finds it.
+ bool should_poll = m_sdl_initialized && !m_in_test_mode && any_of(m_consumers, [](auto const& entry) { return !entry.value->pages_using_gamepads.is_empty(); });
if (!should_poll) {
if (m_poll_timer)
@@ -191,21 +196,36 @@ GamepadManager::Consumer* GamepadManager::ensure_consumer(WebContentClient& clie
return consumer;
}
-void GamepadManager::client_did_start_using_gamepads(WebContentClient& client)
+void GamepadManager::page_did_start_using_gamepads(WebContentPage& page)
{
if (!ensure_sdl_initialized())
return;
+ auto& client = page.client();
auto* consumer = ensure_consumer(client);
- if (!consumer || consumer->receives_real_devices)
+ if (!consumer)
return;
drain_sdl_events();
publish_changed_input_states();
- consumer->receives_real_devices = true;
- fill_vacant_slots(*consumer);
+ // A gamepad the user is still interacting with shows a gesture for the page too.
+ consumer->pages_using_gamepads.set(page.id());
+ for (auto& entry : m_devices) {
+ if (entry.value->announced)
+ announce_devices_after_gamepad_user_gesture(*consumer, *entry.value);
+ }
+ notify_consumers_of_state_changes();
+
+ update_polling_state();
+}
+void GamepadManager::page_closed(WebContentPage& page)
+{
+ auto consumer = m_consumers.get(&page.client());
+ if (!consumer.has_value())
+ return;
+ (*consumer)->pages_using_gamepads.remove(page.id());
update_polling_state();
}
@@ -392,6 +412,17 @@ Vector<Web::Gamepad::GamepadChangeEvent> GamepadManager::pump_gamepad_events(Web
return move((*consumer)->buffered_virtual_gamepad_events);
}
+// The renderer forgets only this page's use of gamepads, so the other pages of the process stay registered.
+void GamepadManager::reset_access_for_testing(WebContentPage& page)
+{
+ auto consumer = m_consumers.get(&page.client());
+ if (!consumer.has_value())
+ return;
+ (*consumer)->pages_using_gamepads.remove(page.id());
+ (*consumer)->has_seen_gamepad_user_gesture = false;
+ update_polling_state();
+}
+
Vector<Web::Gamepad::ReceivedDualRumbleEffect> GamepadManager::virtual_gamepad_received_rumble_effects(WebContentClient& client, Web::Gamepad::GamepadHandle handle)
{
auto* device = virtual_device_owned_by_client(client, handle);
@@ -441,9 +472,16 @@ void GamepadManager::publish_changed_input_states()
if (m_scratch_state == device.last_published_state)
continue;
device.last_published_state = m_scratch_state;
+ for (auto& consumer_entry : m_consumers)
+ announce_devices_after_gamepad_user_gesture(*consumer_entry.value, device);
publish_device_state(device);
}
+ notify_consumers_of_state_changes();
+}
+
+void GamepadManager::notify_consumers_of_state_changes()
+{
for (auto& entry : m_consumers) {
if (exchange(entry.value->has_pending_state_changes, false))
entry.key->async_gamepad_states_changed();
@@ -506,14 +544,56 @@ void GamepadManager::announce_device(Device& device)
for (auto& entry : m_consumers) {
if (entry.value->may_receive_device(device))
announce_device_to_consumer(device, *entry.value);
+ else
+ announce_devices_after_gamepad_user_gesture(*entry.value, device);
}
}
+// A process learns of the gamepads once the user interacts with one while a page of the process that uses them has the
+// user's attention, so that it cannot fingerprint gamepads the user never used with it.
+void GamepadManager::announce_devices_after_gamepad_user_gesture(Consumer& consumer, Device const& device)
+{
+ if (consumer.has_seen_gamepad_user_gesture)
+ return;
+ if (!device.may_be_announced_to(consumer.client) || !device.contains_gamepad_user_gesture())
+ return;
+ if (!consumer.has_page_that_may_receive_gamepads())
+ return;
+
+ consumer.has_seen_gamepad_user_gesture = true;
+ fill_vacant_slots(consumer);
+}
+
+bool GamepadManager::Device::contains_gamepad_user_gesture() const
+{
+ return Web::Gamepad::contains_gamepad_user_gesture(description, last_published_state);
+}
+
+bool GamepadManager::Device::may_be_announced_to(WebContentClient const& client) const
+{
+ return !virtual_device_owner || virtual_device_owner == &client;
+}
+
+bool GamepadManager::Consumer::has_page_that_may_receive_gamepads() const
+{
+ return any_of(pages_using_gamepads, [&](Web::PageId page_id) {
+ auto* page = client.page(page_id);
+ if (!page)
+ return false;
+
+ auto may_receive_gamepads = false;
+ page->for_each_navigable_with_a_hosted_active_document([&](CanonicalNavigable const& navigable) {
+ may_receive_gamepads = 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);
+ return may_receive_gamepads ? IterationDecision::Break : IterationDecision::Continue;
+ });
+ return may_receive_gamepads;
+ });
+}
+
bool GamepadManager::Consumer::may_receive_device(Device const& device) const
{
- if (device.virtual_device_owner)
- return device.virtual_device_owner == &client;
- return receives_real_devices;
+ return has_seen_gamepad_user_gesture && device.may_be_announced_to(client);
}
void GamepadManager::fill_vacant_slots(Consumer& consumer)
@@ -537,6 +617,7 @@ void GamepadManager::announce_device_to_consumer(Device const& device, Consumer&
return;
}
Web::Gamepad::publish_gamepad_state_to_slot(consumer.shared_state_slot(*slot_index), device.last_published_state);
+ consumer.has_pending_state_changes = true;
if (device.virtual_device_owner)
consumer.buffered_virtual_gamepad_events.append(Web::Gamepad::GamepadConnectedEvent { device.description });
diff --git a/Libraries/LibWebView/GamepadManager.h b/Libraries/LibWebView/GamepadManager.h
index e21d60ba8de..d5d45aa2667 100644
--- a/Libraries/LibWebView/GamepadManager.h
+++ b/Libraries/LibWebView/GamepadManager.h
@@ -8,6 +8,7 @@
#include <AK/Array.h>
#include <AK/HashMap.h>
+#include <AK/HashTable.h>
#include <AK/NonnullOwnPtr.h>
#include <AK/Optional.h>
#include <AK/Vector.h>
@@ -15,6 +16,7 @@
#include <LibCore/Forward.h>
#include <LibWebCommon/Gamepad/GamepadSharedState.h>
#include <LibWebCommon/Gamepad/GamepadSnapshot.h>
+#include <LibWebCommon/Page/PageId.h>
#include <LibWebView/Forward.h>
struct SDL_Gamepad;
@@ -30,7 +32,8 @@ class WEBVIEW_API GamepadManager {
public:
static GamepadManager& the();
- void client_did_start_using_gamepads(WebContentClient&);
+ void page_did_start_using_gamepads(WebContentPage&);
+ void page_closed(WebContentPage&);
void client_disconnected(WebContentClient&);
void play_effect(WebContentClient&, Web::Gamepad::GamepadHandle, Web::Gamepad::GamepadEffect const&);
@@ -41,12 +44,16 @@ public:
void set_virtual_gamepad_axis(WebContentClient&, Web::Gamepad::GamepadHandle, i32 axis, i16 value);
void disconnect_virtual_gamepad(WebContentClient&, Web::Gamepad::GamepadHandle);
Vector<Web::Gamepad::GamepadChangeEvent> pump_gamepad_events(WebContentClient&);
+ void reset_access_for_testing(WebContentPage&);
Vector<Web::Gamepad::ReceivedDualRumbleEffect> virtual_gamepad_received_rumble_effects(WebContentClient&, Web::Gamepad::GamepadHandle);
Vector<Web::Gamepad::ReceivedTriggerRumbleEffect> virtual_gamepad_received_trigger_rumble_effects(WebContentClient&, Web::Gamepad::GamepadHandle);
struct Device {
AK_ALLOC_WITH_KMALLOC;
+ bool contains_gamepad_user_gesture() const;
+ bool may_be_announced_to(WebContentClient const&) const;
+
u32 sdl_joystick_id { 0 };
SDL_Gamepad* sdl_gamepad { nullptr };
Web::Gamepad::GamepadDescription description;
@@ -73,11 +80,13 @@ public:
Optional<size_t> slot_index_for_device(Web::Gamepad::GamepadHandle) const;
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;
WebContentClient& client;
Core::AnonymousBuffer state_buffer;
Array<Web::Gamepad::GamepadHandle, Web::Gamepad::MAX_SHARED_GAMEPADS> slot_handles {};
- bool receives_real_devices { false };
+ HashTable<Web::PageId> pages_using_gamepads;
+ bool has_seen_gamepad_user_gesture { false };
bool has_pending_state_changes { false };
Vector<Web::Gamepad::GamepadChangeEvent> buffered_virtual_gamepad_events;
};
@@ -89,6 +98,7 @@ private:
void handle_sdl_event(SDL_Event const&);
void publish_changed_input_states();
void publish_device_state(Device const&);
+ void notify_consumers_of_state_changes();
Consumer* ensure_consumer(WebContentClient&);
@@ -106,6 +116,7 @@ private:
void announce_device(Device&);
void announce_device_to_consumer(Device const&, Consumer&);
void fill_vacant_slots(Consumer&);
+ void announce_devices_after_gamepad_user_gesture(Consumer&, Device const&);
void remove_device(Web::Gamepad::GamepadHandle);
bool m_sdl_initialized { false };
diff --git a/Libraries/LibWebView/WebContentClient.cpp b/Libraries/LibWebView/WebContentClient.cpp
index 5919a3e7345..e4911ac6c0f 100644
--- a/Libraries/LibWebView/WebContentClient.cpp
+++ b/Libraries/LibWebView/WebContentClient.cpp
@@ -163,11 +163,6 @@ Optional<WebContentClient&> WebContentClient::client_for_compositor_context_id(W
return client;
}
-void WebContentClient::did_start_using_gamepads()
-{
- GamepadManager::the().client_did_start_using_gamepads(*this);
-}
-
void WebContentClient::gamepad_play_effect(Web::Gamepad::GamepadHandle handle, Web::Gamepad::GamepadEffect effect)
{
GamepadManager::the().play_effect(*this, handle, effect);
diff --git a/Libraries/LibWebView/WebContentClient.h b/Libraries/LibWebView/WebContentClient.h
index 6d4516b806b..e7eead909a2 100644
--- a/Libraries/LibWebView/WebContentClient.h
+++ b/Libraries/LibWebView/WebContentClient.h
@@ -227,7 +227,6 @@ private:
virtual Messages::WebContentClient::RequestMediaServerConnectionResponse request_media_server_connection() override;
virtual Messages::WebContentClient::RequestAudioServerConnectionResponse request_audio_server_connection() override;
virtual void request_video_presentation_channel() override;
- virtual void did_start_using_gamepads() override;
virtual void gamepad_play_effect(Web::Gamepad::GamepadHandle handle, Web::Gamepad::GamepadEffect effect) override;
virtual void gamepad_stop_effects(Web::Gamepad::GamepadHandle handle) override;
diff --git a/Libraries/LibWebView/WebContentPage.cpp b/Libraries/LibWebView/WebContentPage.cpp
index 699a4db2f0e..7cd664d5855 100644
--- a/Libraries/LibWebView/WebContentPage.cpp
+++ b/Libraries/LibWebView/WebContentPage.cpp
@@ -27,6 +27,7 @@
#include <LibWebView/CanonicalTraversable.h>
#include <LibWebView/CanonicalWindow.h>
#include <LibWebView/CookieJar.h>
+#include <LibWebView/GamepadManager.h>
#include <LibWebView/HistoryStore.h>
#include <LibWebView/NavigationLoader.h>
#include <LibWebView/PermissionManager.h>
@@ -656,6 +657,7 @@ void WebContentPage::close()
if (auto* bidi = WebDriverBiDi::the())
bidi->push_session_state_for_client(*m_client);
m_client->forget_audio_playback(m_id);
+ GamepadManager::the().page_closed(*this);
}
if (m_traversable) {
if (auto view = m_traversable->view(); view.has_value())
@@ -1628,15 +1630,21 @@ static Web::PermissionsPolicy::PolicyControlledFeature policy_controlled_feature
bool WebContentPage::hosts_a_document_allowed_to_use(Web::PermissionsPolicy::PolicyControlledFeature feature) const
{
auto is_allowed = false;
+ for_each_navigable_with_a_hosted_active_document([&](CanonicalNavigable const& navigable) {
+ is_allowed = navigable.active_document().is_allowed_to_use(feature);
+ return is_allowed ? IterationDecision::Break : IterationDecision::Continue;
+ });
+ return is_allowed;
+}
+
+// Unlike for_each_hosted_document(), this skips the documents populated for navigations, which are not active yet.
+void WebContentPage::for_each_navigable_with_a_hosted_active_document(Function<IterationDecision(CanonicalNavigable const&)> const& callback) const
+{
traversable().for_each_in_inclusive_subtree([&](CanonicalNavigable const& navigable) {
if (!hosts_active_document_of(navigable))
return IterationDecision::Continue;
- auto const& document = navigable.active_document();
- auto value = Web::PermissionsPolicy::check_permissions_policy(document.permissions_policy(), feature, document.origin(), document.origin());
- is_allowed = value == Web::PermissionsPolicy::FeatureValue::Enabled;
- return is_allowed ? IterationDecision::Break : IterationDecision::Continue;
+ return callback(navigable);
});
- return is_allowed;
}
bool WebContentPage::document_may_use(Web::HTML::CrossProcessId document_id, Web::Permissions::PermissionName name) const
@@ -1668,9 +1676,7 @@ void WebContentPage::did_request_geolocation_position(u64 request_id, Web::HTML:
bool WebContentPage::hosts_a_document_with_top_level_origin(URL::Origin const& origin) const
{
auto hosts = false;
- traversable().for_each_in_inclusive_subtree([&](CanonicalNavigable const& navigable) {
- if (!hosts_active_document_of(navigable))
- return IterationDecision::Continue;
+ for_each_navigable_with_a_hosted_active_document([&](CanonicalNavigable const& navigable) {
auto top_level_origin = navigable.active_document().top_level_origin();
hosts = top_level_origin.has_value() && top_level_origin->is_same_origin(origin);
return hosts ? IterationDecision::Break : IterationDecision::Continue;
@@ -1935,6 +1941,11 @@ void WebContentPage::did_change_screen_wake_lock_state(Web::ScreenWakeLockState
view().did_change_screen_wake_lock_state({}, wake_lock_state);
}
+void WebContentPage::did_start_using_gamepads()
+{
+ GamepadManager::the().page_did_start_using_gamepads(*this);
+}
+
void WebContentPage::did_update_session_history_entry_navigation_api_state(Web::HTML::CrossProcessId navigable_id, Web::HTML::SessionHistoryEntryIdentity entry_identity, Web::HTML::StorageSerializationRecord navigation_api_state)
{
auto navigable = hosted_navigable(navigable_id);
@@ -3232,6 +3243,11 @@ void WebContentPage::did_reset_state_for_testing(Web::HTML::SessionHistoryEntryD
view().did_reset_state_for_testing({}, move(active_entry));
}
+void WebContentPage::reset_gamepad_access_for_testing()
+{
+ GamepadManager::the().reset_access_for_testing(*this);
+}
+
Messages::WebContentTestClient::DidRequestCaptureSessionHistorySnapshotForTestingResponse WebContentPage::did_request_capture_session_history_snapshot_for_testing()
{
if (displays_tab())
diff --git a/Libraries/LibWebView/WebContentPage.h b/Libraries/LibWebView/WebContentPage.h
index 11b85a08064..9d5039a7019 100644
--- a/Libraries/LibWebView/WebContentPage.h
+++ b/Libraries/LibWebView/WebContentPage.h
@@ -119,6 +119,7 @@ public:
// Whether a document this page hosts may use the feature. The process hosting the page can act for any of them.
bool hosts_a_document_allowed_to_use(Web::PermissionsPolicy::PolicyControlledFeature) const;
+ void for_each_navigable_with_a_hosted_active_document(Function<IterationDecision(CanonicalNavigable const&)> const&) const;
RefPtr<CanonicalDocument> hosted_document_with_id(Web::HTML::CrossProcessId) const;
bool hosts_a_document_with_top_level_origin(URL::Origin const&) const;
bool document_may_use(Web::HTML::CrossProcessId, Web::Permissions::PermissionName) const;
@@ -286,6 +287,7 @@ private:
virtual void did_change_background_color(Gfx::Color color) override;
virtual void did_insert_clipboard_item(Web::Clipboard::SystemClipboardItem item, String) override;
virtual void did_change_screen_wake_lock_state(Web::ScreenWakeLockState wake_lock_state) override;
+ virtual void did_start_using_gamepads() override;
virtual void did_update_session_history_entry_navigation_api_state(Web::HTML::CrossProcessId navigable_id, Web::HTML::SessionHistoryEntryIdentity entry_identity, Web::HTML::StorageSerializationRecord navigation_api_state) override;
virtual void did_update_session_history_entry_document_state_navigable_target_name(Web::HTML::CrossProcessId navigable_id, Web::HTML::SessionHistoryEntryIdentity entry_identity, Utf16String navigable_target_name) override;
virtual void did_set_session_history_entry_document_state_reload_pending(Web::HTML::CrossProcessId navigable_id, Utf16String navigation_api_key, bool reload_pending) override;
@@ -391,6 +393,7 @@ private:
virtual void did_request_reload_for_testing(bool bypass_cache) override;
virtual void did_request_traverse_history_by_delta_for_testing(i32 delta) override;
virtual void did_reset_state_for_testing(Web::HTML::SessionHistoryEntryDescriptor) override;
+ virtual void reset_gamepad_access_for_testing() override;
Messages::WebContentTestClient::DidRequestHasPopulatedDocumentForTestingResponse did_request_has_populated_document_for_testing(Web::HTML::CrossProcessId navigable_id) const;
Messages::WebContentTestClient::DidRequestCaptureSessionHistorySnapshotForTestingResponse did_request_capture_session_history_snapshot_for_testing();
Messages::WebContentTestClient::DidRequestRestoreSessionHistorySnapshotForTestingResponse did_request_restore_session_history_snapshot_for_testing();
diff --git a/Services/WebContent/ConnectionFromClient.cpp b/Services/WebContent/ConnectionFromClient.cpp
index 1eeb465fa43..a0cfc5148e5 100644
--- a/Services/WebContent/ConnectionFromClient.cpp
+++ b/Services/WebContent/ConnectionFromClient.cpp
@@ -3615,14 +3615,6 @@ void ConnectionFromClient::dispatch_changed_gamepad_states()
}
}
-void ConnectionFromClient::notify_started_using_gamepads()
-{
- if (m_did_notify_started_using_gamepads)
- return;
- m_did_notify_started_using_gamepads = true;
- async_did_start_using_gamepads();
-}
-
void ConnectionFromClient::pump_and_dispatch_gamepad_events()
{
auto* test_connection = this->test_connection();
diff --git a/Services/WebContent/ConnectionFromClient.h b/Services/WebContent/ConnectionFromClient.h
index 99724a9c9c4..cefc261c26a 100644
--- a/Services/WebContent/ConnectionFromClient.h
+++ b/Services/WebContent/ConnectionFromClient.h
@@ -84,7 +84,6 @@ public:
Queue<Web::QueuedInputEvent>& input_event_queue() { return m_input_event_queue; }
void update_input_method_state(Web::PageId page_id);
- void notify_started_using_gamepads();
void pump_and_dispatch_gamepad_events();
private:
@@ -367,8 +366,6 @@ private:
NonnullOwnPtr<PageHost> m_page_host;
OwnPtr<DevToolsDebugger> m_devtools_debugger;
- bool m_did_notify_started_using_gamepads { false };
-
HashMap<int, Web::FileRequest> m_requested_files {};
int last_id { 0 };
diff --git a/Services/WebContent/PageClient.cpp b/Services/WebContent/PageClient.cpp
index 3f6d07ce13b..5d011965a0a 100644
--- a/Services/WebContent/PageClient.cpp
+++ b/Services/WebContent/PageClient.cpp
@@ -2072,7 +2072,10 @@ void PageClient::page_did_change_screen_wake_lock_state(Web::ScreenWakeLockState
void PageClient::page_did_start_using_gamepads()
{
- client().notify_started_using_gamepads();
+ if (m_did_start_using_gamepads)
+ return;
+ m_did_start_using_gamepads = true;
+ client().async_did_start_using_gamepads(m_id);
}
void PageClient::page_did_play_gamepad_effect(Web::Gamepad::GamepadHandle handle, Web::Gamepad::GamepadEffect const& effect)
@@ -2134,6 +2137,13 @@ void PageClient::pump_gamepad_events()
client().pump_and_dispatch_gamepad_events();
}
+void PageClient::reset_gamepad_access_for_testing()
+{
+ m_did_start_using_gamepads = false;
+ if (auto* test_connection = client().test_connection(); test_connection && test_connection->is_open())
+ test_connection->async_reset_gamepad_access_for_testing(m_id);
+}
+
Web::HTML::WorkerAgentId PageClient::start_worker_agent(Web::HTML::WorkerAgentStartRequest&& request)
{
auto response = client().send_sync_but_allow_failure<Messages::WebContentClient::StartWorkerAgent>(m_id, move(request));
diff --git a/Services/WebContent/PageClient.h b/Services/WebContent/PageClient.h
index 9f193de97f7..4728095b554 100644
--- a/Services/WebContent/PageClient.h
+++ b/Services/WebContent/PageClient.h
@@ -386,6 +386,7 @@ private:
virtual void disconnect_virtual_gamepad(Web::Gamepad::GamepadHandle) override;
virtual Web::Gamepad::ReceivedRumbleEffects virtual_gamepad_received_rumble_effects(Web::Gamepad::GamepadHandle) override;
virtual void pump_gamepad_events() override;
+ virtual void reset_gamepad_access_for_testing() override;
virtual Web::HTML::WorkerAgentId start_worker_agent(Web::HTML::WorkerAgentStartRequest&&) override;
virtual void close_worker_agent(Web::HTML::WorkerAgentId, Web::HTML::WorkerAgentOwnerToken) override;
virtual void page_did_mutate_dom(Utf16FlyString const& type, Web::DOM::Node const& target, Web::DOM::NodeList& added_nodes, Web::DOM::NodeList& removed_nodes, GC::Ptr<Web::DOM::Node> previous_sibling, GC::Ptr<Web::DOM::Node> next_sibling, Optional<Utf16FlyString> const& attribute_name) override;
@@ -431,6 +432,7 @@ private:
HashTable<u64> m_canceled_downloads;
bool m_has_focus { true };
bool m_is_closed { false };
+ bool m_did_start_using_gamepads { false };
Web::CSS::PreferredColorScheme m_preferred_color_scheme { Web::CSS::PreferredColorScheme::Auto };
Web::CSS::PreferredContrast m_preferred_contrast { Web::CSS::PreferredContrast::NoPreference };
diff --git a/Services/WebContent/WebContentClient.ipc b/Services/WebContent/WebContentClient.ipc
index 8b4c631fb1d..753f4e809d5 100644
--- a/Services/WebContent/WebContentClient.ipc
+++ b/Services/WebContent/WebContentClient.ipc
@@ -284,7 +284,7 @@ endpoint WebContentClient routed by Web::PageId page_id
did_change_screen_wake_lock_state(Web::PageId page_id, Web::ScreenWakeLockState wake_lock_state) =|
- did_start_using_gamepads() =|
+ did_start_using_gamepads(Web::PageId page_id) =|
gamepad_play_effect(Web::Gamepad::GamepadHandle handle, Web::Gamepad::GamepadEffect effect) =|
gamepad_stop_effects(Web::Gamepad::GamepadHandle handle) =|
diff --git a/Services/WebContent/WebContentTestClient.ipc b/Services/WebContent/WebContentTestClient.ipc
index cf3058e8942..3a3b750c2c9 100644
--- a/Services/WebContent/WebContentTestClient.ipc
+++ b/Services/WebContent/WebContentTestClient.ipc
@@ -46,5 +46,6 @@ endpoint WebContentTestClient routed by Web::PageId page_id
set_virtual_gamepad_axis(Web::Gamepad::GamepadHandle handle, i32 axis, i16 value) =|
disconnect_virtual_gamepad(Web::Gamepad::GamepadHandle handle) =|
pump_gamepad_events() => (Vector<Web::Gamepad::GamepadChangeEvent> events)
+ reset_gamepad_access_for_testing(Web::PageId page_id) =|
get_virtual_gamepad_received_rumble_effects(Web::Gamepad::GamepadHandle handle) => (Vector<Web::Gamepad::ReceivedDualRumbleEffect> dual_rumble_effects, Vector<Web::Gamepad::ReceivedTriggerRumbleEffect> trigger_rumble_effects)
}
diff --git a/Tests/LibWeb/Text/expected/GamepadAPI/gamepad-press-released-before-delivery.txt b/Tests/LibWeb/Text/expected/GamepadAPI/gamepad-press-released-before-delivery.txt
new file mode 100644
index 00000000000..60b4cddcc5c
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/GamepadAPI/gamepad-press-released-before-delivery.txt
@@ -0,0 +1,3 @@
+Gamepads after a press released before the page read it: 0
+Received gamepadconnected event for 'Ladybird Virtual Gamepad' at index 0
+Gamepads after a held press: 1
diff --git a/Tests/LibWeb/Text/expected/GamepadAPI/gamepad-state-updates-while-hidden.txt b/Tests/LibWeb/Text/expected/GamepadAPI/gamepad-state-updates-while-hidden.txt
new file mode 100644
index 00000000000..928bd99676f
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/GamepadAPI/gamepad-state-updates-while-hidden.txt
@@ -0,0 +1 @@
+Button 1 is pressed after pressing it while hidden: true
diff --git a/Tests/LibWeb/Text/input/GamepadAPI/gamepad-haptic-promise-receiver-realm.html b/Tests/LibWeb/Text/input/GamepadAPI/gamepad-haptic-promise-receiver-realm.html
index dbea0467d56..fc9fc0a9a70 100644
--- a/Tests/LibWeb/Text/input/GamepadAPI/gamepad-haptic-promise-receiver-realm.html
+++ b/Tests/LibWeb/Text/input/GamepadAPI/gamepad-haptic-promise-receiver-realm.html
@@ -3,6 +3,7 @@
<script src="gamepad-helper.js"></script>
<script>
promiseTest(async () => {
+ startUsingGamepads();
const gamepad = internals.connectVirtualGamepad();
await pumpGamepadEvents();
diff --git a/Tests/LibWeb/Text/input/GamepadAPI/gamepad-helper.js b/Tests/LibWeb/Text/input/GamepadAPI/gamepad-helper.js
index 103c09eec94..5c59b31d5b5 100644
--- a/Tests/LibWeb/Text/input/GamepadAPI/gamepad-helper.js
+++ b/Tests/LibWeb/Text/input/GamepadAPI/gamepad-helper.js
@@ -1,4 +1,9 @@
(() => {
+ // A page learns of gamepads only once it uses them and the user then interacts with one.
+ globalThis.startUsingGamepads = () => {
+ navigator.getGamepads();
+ };
+
globalThis.pumpGamepadEvents = () => {
internals.pumpGamepadEvents();
return new Promise(resolve => {
diff --git a/Tests/LibWeb/Text/input/GamepadAPI/gamepad-ninth-connects-after-disconnect.html b/Tests/LibWeb/Text/input/GamepadAPI/gamepad-ninth-connects-after-disconnect.html
index 3b3d50da8e9..9fb6dcc60be 100644
--- a/Tests/LibWeb/Text/input/GamepadAPI/gamepad-ninth-connects-after-disconnect.html
+++ b/Tests/LibWeb/Text/input/GamepadAPI/gamepad-ninth-connects-after-disconnect.html
@@ -3,6 +3,7 @@
<script src="gamepad-helper.js"></script>
<script>
promiseTest(async () => {
+ startUsingGamepads();
const virtualGamepads = [];
for (let index = 0; index < 9; ++index)
virtualGamepads.push(internals.connectVirtualGamepad());
diff --git a/Tests/LibWeb/Text/input/GamepadAPI/gamepad-press-released-before-delivery.html b/Tests/LibWeb/Text/input/GamepadAPI/gamepad-press-released-before-delivery.html
new file mode 100644
index 00000000000..bfe8c2fb66b
--- /dev/null
+++ b/Tests/LibWeb/Text/input/GamepadAPI/gamepad-press-released-before-delivery.html
@@ -0,0 +1,23 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script src="gamepad-helper.js"></script>
+<script>
+ promiseTest(async () => {
+ startUsingGamepads();
+ const gamepad = internals.connectVirtualGamepad();
+ await pumpGamepadEvents();
+ listenForGamepadConnected();
+
+ gamepad.setButton(gamepad.buttons[0], true);
+ gamepad.setButton(gamepad.buttons[0], false);
+ await pumpGamepadEvents();
+ println(`Gamepads after a press released before the page read it: ${navigator.getGamepads().length}`);
+
+ gamepad.setButton(gamepad.buttons[0], true);
+ await pumpGamepadEvents();
+ println(`Gamepads after a held press: ${navigator.getGamepads().length}`);
+
+ gamepad.disconnect();
+ await pumpGamepadEvents();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/GamepadAPI/gamepad-rumble.html b/Tests/LibWeb/Text/input/GamepadAPI/gamepad-rumble.html
index b1e2ebaf790..b1e97f58802 100644
--- a/Tests/LibWeb/Text/input/GamepadAPI/gamepad-rumble.html
+++ b/Tests/LibWeb/Text/input/GamepadAPI/gamepad-rumble.html
@@ -3,6 +3,7 @@
<script src="gamepad-helper.js"></script>
<script>
promiseTest(async () => {
+ startUsingGamepads();
const gamepad = internals.connectVirtualGamepad();
await pumpGamepadEvents();
diff --git a/Tests/LibWeb/Text/input/GamepadAPI/gamepad-state-updates-while-hidden.html b/Tests/LibWeb/Text/input/GamepadAPI/gamepad-state-updates-while-hidden.html
new file mode 100644
index 00000000000..001604fdf9b
--- /dev/null
+++ b/Tests/LibWeb/Text/input/GamepadAPI/gamepad-state-updates-while-hidden.html
@@ -0,0 +1,24 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script src="gamepad-helper.js"></script>
+<script>
+ promiseTest(async () => {
+ startUsingGamepads();
+ const gamepad = internals.connectVirtualGamepad();
+ await pumpGamepadEvents();
+
+ gamepad.setButton(gamepad.buttons[0], true);
+ await pumpGamepadEvents();
+ gamepad.setButton(gamepad.buttons[0], false);
+ await pumpGamepadEvents();
+
+ await setSystemVisibilityState("hidden");
+ gamepad.setButton(gamepad.buttons[1], true);
+ await pumpGamepadEvents();
+ println(`Button 1 is pressed after pressing it while hidden: ${navigator.getGamepads()[0].buttons[1].pressed}`);
+ await setSystemVisibilityState("visible");
+
+ gamepad.disconnect();
+ await pumpGamepadEvents();
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/GamepadAPI/gamepad-state-updates-without-rendering.html b/Tests/LibWeb/Text/input/GamepadAPI/gamepad-state-updates-without-rendering.html
index 4ddd3da2105..07462a87b8b 100644
--- a/Tests/LibWeb/Text/input/GamepadAPI/gamepad-state-updates-without-rendering.html
+++ b/Tests/LibWeb/Text/input/GamepadAPI/gamepad-state-updates-without-rendering.html
@@ -3,9 +3,15 @@
<script src="gamepad-helper.js"></script>
<script>
promiseTest(async () => {
+ startUsingGamepads();
const gamepad = internals.connectVirtualGamepad();
await pumpGamepadEvents();
+ gamepad.setButton(gamepad.buttons[1], true);
+ await pumpGamepadEvents();
+ gamepad.setButton(gamepad.buttons[1], false);
+ await pumpGamepadEvents();
+
gamepad.setButton(gamepad.buttons[0], true);
await new Promise(resolve => {
const poll = () => {
diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txt
index f9b12c8e797..143ae874f8c 100644
--- a/Tests/LibWebView/CMakeLists.txt
+++ b/Tests/LibWebView/CMakeLists.txt
@@ -235,6 +235,7 @@ if (NOT WIN32)
TestCrashReportSubmission.cpp
TestFavicon.cpp
TestFileDownloader.cpp
+ TestGamepadExposure.cpp
TestImageDecoderIsolation.cpp
TestInputMethodState.cpp
TestLinkHoverStatus.cpp
diff --git a/Tests/LibWebView/TestGamepadExposure.cpp b/Tests/LibWebView/TestGamepadExposure.cpp
new file mode 100644
index 00000000000..a92cac3c5a5
--- /dev/null
+++ b/Tests/LibWebView/TestGamepadExposure.cpp
@@ -0,0 +1,200 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include "HeadlessTest.h"
+#include <AK/AnyOf.h>
+#include <AK/LexicalPath.h>
+#include <LibCore/EventLoop.h>
+#include <LibGfx/SystemTheme.h>
+#include <LibTest/TestCase.h>
+#include <LibWebCommon/PermissionsPolicy/PermissionsPolicy.h>
+#include <LibWebView/Application.h>
+#include <LibWebView/CanonicalDocument.h>
+#include <LibWebView/CanonicalNavigable.h>
+#include <LibWebView/CanonicalTraversable.h>
+#include <LibWebView/GamepadManager.h>
+#include <LibWebView/HeadlessWebView.h>
+#include <LibWebView/Utilities.h>
+#include <LibWebView/WebContentClient.h>
+#include <LibWebView/WebContentPage.h>
+
+namespace {
+
+// Test mode keeps the gamepads of the machine running the test away from its pages.
+class TestApplication : public Test::HeadlessApplication {
+ WEB_VIEW_APPLICATION(TestApplication)
+
+public:
+ explicit TestApplication(Optional<ByteString> ladybird_binary_path)
+ : Test::HeadlessApplication(move(ladybird_binary_path))
+ {
+ }
+
+ virtual void create_platform_options(WebView::BrowserOptions& browser_options, WebView::RequestServerOptions&, WebView::WebContentOptions& web_content_options) override
+ {
+ browser_options.headless_mode = WebView::HeadlessMode::Test;
+ browser_options.allow_popups = WebView::AllowPopups::Yes;
+ browser_options.disable_sql_database = WebView::DisableSQLDatabase::Yes;
+ web_content_options.is_test_mode = WebView::IsTestMode::Yes;
+ }
+};
+
+void give_user_attention(WebView::ViewImplementation& view, bool has_user_attention)
+{
+ view.set_system_visibility_state(has_user_attention ? Web::HTML::VisibilityState::Visible : Web::HTML::VisibilityState::Hidden);
+ view.set_has_system_focus(has_user_attention);
+}
+
+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_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);
+}
+
+bool gamepad_is_announced_to(WebView::WebContentClient& client)
+{
+ auto events = WebView::GamepadManager::the().pump_gamepad_events(client);
+ return any_of(events, [](auto const& event) { return event.template has<Web::Gamepad::GamepadConnectedEvent>(); });
+}
+
+}
+
+// A process learns of gamepads only once the user interacts with one while a page of the process uses gamepads, has
+// the user's attention, and holds a document allowed to use gamepads.
+
+TEST_CASE(gamepad_exposure)
+{
+ Test::HeadlessTestEnvironment environment { "TestGamepadExposure"sv };
+
+ auto app = TRY_OR_FAIL(environment.create_application<TestApplication>());
+
+ auto theme_path = LexicalPath::join(WebView::s_ladybird_resource_root, "themes"sv, "Default.ini"sv);
+ auto theme = TRY_OR_FAIL(Gfx::load_system_theme(theme_path.string()));
+ auto& gamepad_manager = WebView::GamepadManager::the();
+
+ {
+ auto view = WebView::HeadlessWebView::create(theme, { 800, 600 });
+ auto& client = view->page().client();
+ give_user_attention(*view, true);
+ auto gamepad = gamepad_manager.create_virtual_gamepad(client).release_value();
+
+ press_button(client, gamepad);
+ VERIFY(!gamepad_is_announced_to(client));
+ outln("PASS: a process with no page using gamepads learns of none");
+
+ start_using_gamepads(*view);
+
+ view->set_has_system_focus(false);
+ press_button(client, gamepad);
+ VERIFY(!gamepad_is_announced_to(client));
+ view->set_has_system_focus(true);
+ outln("PASS: a gesture while the page has no system focus is not one");
+
+ view->set_system_visibility_state(Web::HTML::VisibilityState::Hidden);
+ press_button(client, gamepad);
+ VERIFY(!gamepad_is_announced_to(client));
+ view->set_system_visibility_state(Web::HTML::VisibilityState::Visible);
+ outln("PASS: a gesture while the page is hidden is not one");
+
+ auto& document = view->traversable().active_document();
+ auto permissions_policy = 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;
+ document.set_permissions_policy(move(permissions_policy_without_gamepads));
+ press_button(client, gamepad);
+ VERIFY(!gamepad_is_announced_to(client));
+ document.set_permissions_policy(move(permissions_policy));
+ outln("PASS: a gesture for a page not allowed to use gamepads is not one");
+
+ press_button(client, gamepad);
+ VERIFY(gamepad_is_announced_to(client));
+ outln("PASS: a gesture while the page has the user's attention announces the gamepad");
+ }
+
+ {
+ auto view = WebView::HeadlessWebView::create(theme, { 800, 600 });
+ auto& client = view->page().client();
+ give_user_attention(*view, true);
+
+ OwnPtr<WebView::HeadlessWebView> popup;
+ bool popup_loaded = false;
+ view->on_new_web_view = [&](auto, auto, WebView::CanonicalTraversable& traversable) {
+ popup = WebView::HeadlessWebView::create_child(*view, traversable);
+ popup->on_load_finish = [&](auto const&) { popup_loaded = true; };
+ return popup->handle();
+ };
+ view->run_javascript("window.open('about:blank')"_string);
+ Core::EventLoop::current().spin_until([&] { return popup_loaded; });
+ VERIFY(&popup->page().client() == &client);
+
+ start_using_gamepads(*view);
+ start_using_gamepads(*popup);
+ give_user_attention(*view, false);
+ give_user_attention(*popup, true);
+
+ auto gamepad = gamepad_manager.create_virtual_gamepad(client).release_value();
+ press_button(client, gamepad);
+ VERIFY(gamepad_is_announced_to(client));
+ outln("PASS: a gesture for any page of the process using gamepads announces the gamepad");
+ }
+
+ {
+ auto view = WebView::HeadlessWebView::create(theme, { 800, 600 });
+ auto& page = view->page();
+ auto& client = page.client();
+ auto& traversable = view->traversable();
+ give_user_attention(*view, true);
+
+ size_t loads_finished = 0;
+ view->on_load_finish = [&](auto const&) { ++loads_finished; };
+ Core::EventLoop::current().spin_until([&] { return loads_finished >= 1; });
+ view->load_html("<!DOCTYPE html><iframe srcdoc=\"<!DOCTYPE html>\"></iframe>"sv);
+ WebView::CanonicalNavigable* iframe = nullptr;
+ Core::EventLoop::current().spin_until([&] {
+ traversable.for_each_in_subtree([&](WebView::CanonicalNavigable& navigable) {
+ iframe = &navigable;
+ return IterationDecision::Break;
+ });
+ return loads_finished >= 2 && iframe && page.hosts_active_document_of(*iframe);
+ });
+ start_using_gamepads(*view);
+ VERIFY(iframe->active_document_is_fully_active_descendant_of_a_top_level_traversable_with_user_attention());
+ VERIFY(iframe->active_document().is_allowed_to_use(Web::PermissionsPolicy::PolicyControlledFeature::Gamepad));
+
+ // A crashed process leaves this, with the page of the iframe's container standing in for the lost document.
+ iframe->did_lose_active_document();
+ VERIFY(!iframe->active_document().host());
+ VERIFY(traversable.hosts(*iframe, page));
+ VERIFY(!iframe->active_document_is_fully_active_descendant_of_a_top_level_traversable_with_user_attention());
+
+ auto& top_document = traversable.active_document();
+ auto permissions_policy = top_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;
+ top_document.set_permissions_policy(move(permissions_policy_without_gamepads));
+ VERIFY(!page.hosts_a_document_allowed_to_use(Web::PermissionsPolicy::PolicyControlledFeature::Gamepad));
+
+ auto gamepad = gamepad_manager.create_virtual_gamepad(client).release_value();
+ press_button(client, gamepad);
+ VERIFY(!gamepad_is_announced_to(client));
+ outln("PASS: a page standing in for a lost document gets no gamepads through it");
+
+ top_document.set_permissions_policy(move(permissions_policy));
+ press_button(client, gamepad);
+ VERIFY(gamepad_is_announced_to(client));
+ outln("PASS: the page gets gamepads through a document it hosts");
+ }
+}