Truly independent web browser
LibWeb: Implement the Gamepad API in Rust
Shannon Boothe9cc42c83bb9
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rsindex 6fc82ffe2aa..a4c9afc028f 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs@@ -90,6 +90,7 @@ pub(crate) enum TaskSource {Clipboard = 17,Permissions = 18,FontLoading = 19,+ Gamepad = 25,Crypto = 27,Storage = 29,}diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/realm_data.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/realm_data.rsindex ff83b6148be..94065ffc208 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/realm_data.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/realm_data.rs@@ -18,6 +18,7 @@ use crate::bindings::interface::Ref;use crate::bindings::services::web_bindings_wrapper_world;use crate::event_timing::event_timing::WindowEventTimingStateRef;+use crate::gamepad::navigator_gamepad::NavigatorGamepadRef;use crate::performance_timeline::performance_timeline::PerformanceTimelineRef;use crate::web_assembly::tag::Tag;@@ -55,6 +56,8 @@ pub(crate) struct RealmData {pub(crate) performance_observer_supported_entry_types: Cell<Option<Gc<Object>>>,/// https://w3c.github.io/event-timing/#sec-modifications-HTMLpub(crate) event_timing_state: Cell<Option<WindowEventTimingStateRef>>,+ /// https://w3c.github.io/gamepad/#internal-slots+ pub(crate) navigator_gamepad: Cell<Option<NavigatorGamepadRef>>,}static REALM_DATA_CLASS: EmbedderClass<RealmData> = EmbedderClass::new("RealmData");diff --git a/Libraries/LibWeb/Bindings/Rust/src/dom/document.rs b/Libraries/LibWeb/Bindings/Rust/src/dom/document.rsindex 4c420f7dcba..ffb3809e3ee 100644--- a/Libraries/LibWeb/Bindings/Rust/src/dom/document.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/dom/document.rs@@ -44,6 +44,14 @@ unsafe extern "C" {on_origin: unsafe extern "C" fn(*mut c_void, *const FfiOrigin),);fn web_bindings_document_has_focus(document: *mut c_void) -> bool;+ fn web_bindings_document_is_fully_active_descendant_of_a_top_level_traversable_with_user_attention(+ document: *mut c_void,+ ) -> bool;+ fn web_bindings_document_observe_visibility_state(+ document: *mut c_void,+ cell: *mut c_void,+ steps: unsafe extern "C" fn(*mut c_void, *mut c_void, bool),+ ) -> *mut c_void;fn web_bindings_document_has_been_destroyed(document: *mut c_void) -> bool;fn web_bindings_document_url(document: *mut c_void) -> liburl_rust::RustUrl;fn web_bindings_document_load_timing_info(document: *mut c_void, load_timing_info: *mut DocumentLoadTimingInfo);@@ -144,6 +152,33 @@ impl CppDocument {}}+ /// https://html.spec.whatwg.org/multipage/interaction.html#fully-active-descendant-of-a-top-level-traversable-with-user-attention+ pub(crate) fn is_fully_active_descendant_of_a_top_level_traversable_with_user_attention(&self) -> bool {+ // SAFETY: The Document is live.+ unsafe {+ web_bindings_document_is_fully_active_descendant_of_a_top_level_traversable_with_user_attention(+ self.0.as_ptr(),+ )+ }+ }++ /// Calls the steps with the VM, the cell and whether the Document is visible whenever its visibility state+ /// changes, for as long as the returned DocumentObserver lives.+ pub(crate) fn observe_visibility_state(+ &self,+ cell: *mut c_void,+ steps: unsafe extern "C" fn(*mut c_void, *mut c_void, bool),+ ) -> CppCell {+ // SAFETY: The Document and the cell are live, and LibWeb returns a live DocumentObserver.+ unsafe {+ CppCell::from_raw(web_bindings_document_observe_visibility_state(+ self.0.as_ptr(),+ cell,+ steps,+ ))+ }+ }+/// https://html.spec.whatwg.org/multipage/interaction.html#has-focus-stepspub(crate) fn has_focus(&self) -> bool {// SAFETY: The Document is live.diff --git a/Libraries/LibWeb/Bindings/Rust/src/gamepad/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/gamepad/exports.rsnew file mode 100644index 00000000000..22a0ecc716d--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/gamepad/exports.rs@@ -0,0 +1,99 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The entry points through which LibWeb's C++ code runs the Navigator steps of the Gamepad API, declared in+//! Libraries/LibWeb/Gamepad/NavigatorGamepad.cpp.++use core::ffi::c_void;++use libjs_rust::api::Vm;++use crate::bindings::global_object::CppWindow;+use crate::gamepad::gamepad::{GamepadDescription, GamepadDescriptionAbi, GamepadState, GamepadStateAbi};+use crate::gamepad::navigator_gamepad::{+ get_gamepads, handle_gamepad_connected, handle_gamepad_disconnected, handle_gamepad_updated,+};++/// https://w3c.github.io/gamepad/#dom-navigator-getgamepads+///+/// # Safety+///+/// The pointers must be the live VM and live Windows.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_gamepad_get_gamepads(+ vm: *mut c_void,+ navigator_window: *mut c_void,+ current_window: *mut c_void,+ ctx: *mut c_void,+ on_gamepad: unsafe extern "C" fn(*mut c_void, *mut c_void),+) -> bool {+ // SAFETY: The caller passes the live VM and live Windows.+ let (vm, navigator_window, current_window) = unsafe {+ (+ &*vm.cast::<Vm>(),+ CppWindow::from_raw(navigator_window),+ CppWindow::from_raw(current_window),+ )+ };+ let Ok(gamepads) = get_gamepads(vm, &navigator_window, ¤t_window) else {+ return false;+ };+ for index in 0..gamepads.len() {+ let gamepad = gamepads.get(index).flatten();+ let cell = gamepad.map_or(core::ptr::null_mut(), |gamepad| gamepad.as_ptr().cast());+ // SAFETY: The cell is live, and the caller roots it.+ unsafe { on_gamepad(ctx, cell) };+ }+ true+}++/// https://w3c.github.io/gamepad/#event-gamepadconnected+///+/// # Safety+///+/// The pointers must be the live VM, a live Window and a description that the caller lends for the call.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_gamepad_handle_gamepad_connected(+ vm: *mut c_void,+ window: *mut c_void,+ description: *const GamepadDescriptionAbi<'_>,+) {+ // SAFETY: The caller passes the live VM, a live Window and a lent description.+ let (vm, window, description) = unsafe { (&*vm.cast::<Vm>(), CppWindow::from_raw(window), &*description) };+ handle_gamepad_connected(vm, &window, GamepadDescription::from_abi(description));+}++/// https://w3c.github.io/gamepad/#dfn-receives-new-button-or-axis-input-values+///+/// # Safety+///+/// The pointers must be the live VM, a live Window and a state that the caller lends for the call.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_gamepad_handle_gamepad_updated(+ vm: *mut c_void,+ window: *mut c_void,+ state: *const GamepadStateAbi<'_>,+) {+ // SAFETY: The caller passes the live VM, a live Window and a lent state.+ let (vm, window, state) = unsafe { (&*vm.cast::<Vm>(), CppWindow::from_raw(window), &*state) };+ handle_gamepad_updated(vm, &window, GamepadState::from_abi(state));+}++/// https://w3c.github.io/gamepad/#event-gamepaddisconnected+///+/// # Safety+///+/// The pointers must be the live VM and a live Window.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_rust_gamepad_handle_gamepad_disconnected(+ vm: *mut c_void,+ window: *mut c_void,+ handle: u32,+) {+ // SAFETY: The caller passes the live VM and a live Window.+ let (vm, window) = unsafe { (&*vm.cast::<Vm>(), CppWindow::from_raw(window)) };+ handle_gamepad_disconnected(vm, &window, handle);+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/gamepad/gamepad.rs b/Libraries/LibWeb/Bindings/Rust/src/gamepad/gamepad.rsnew file mode 100644index 00000000000..a973c53eefc--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/gamepad/gamepad.rs@@ -0,0 +1,717 @@+/*+ * Copyright (c) 2025, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2025, Luke Wilde <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Gamepad, https://w3c.github.io/gamepad/#dom-gamepad++use core::cell::{Cell, RefCell};+use core::ffi::c_void;++use ak::Utf16String;+use libjs_rust::api::{Gc, MarkedVec, Realm, Trace, Vm};++use crate::bindings::global_object::CppWindow;+use crate::bindings::interface::{Ref, Wrappable, allocate};+use crate::bindings::{CallContext, WebIdlResult};+use crate::gamepad::gamepad_button::GamepadButton;+use crate::gamepad::gamepad_haptic_actuator::GamepadHapticActuator;+use crate::gamepad::navigator_gamepad::{fire_a_gamepad_event, navigator_gamepad, select_an_unused_gamepad_index};++#[repr(C)]+#[derive(Clone, Copy)]+pub(crate) struct GamepadInputDescriptor {+ pub(crate) has_canonical_index: bool,+ pub(crate) canonical_index: u32,+ pub(crate) logical_minimum: i16,+ pub(crate) logical_maximum: i16,+}++#[derive(Clone)]+pub(crate) struct GamepadDescription {+ pub(crate) handle: u32,+ pub(crate) id: String,+ pub(crate) has_standard_mapping: bool,+ pub(crate) supports_dual_rumble: bool,+ pub(crate) supports_trigger_rumble: bool,+ pub(crate) axes: Vec<GamepadInputDescriptor>,+ pub(crate) buttons: Vec<GamepadInputDescriptor>,+}++#[derive(Clone, Default)]+pub(crate) struct GamepadState {+ pub(crate) handle: u32,+ pub(crate) axis_values: Vec<i16>,+ pub(crate) button_values: Vec<i16>,+}++#[repr(C)]+pub struct GamepadDescriptionAbi<'a> {+ handle: u32,+ id: ak::Span<'a, u8>,+ has_standard_mapping: bool,+ supports_dual_rumble: bool,+ supports_trigger_rumble: bool,+ axes: ak::Span<'a, GamepadInputDescriptor>,+ buttons: ak::Span<'a, GamepadInputDescriptor>,+}++#[repr(C)]+pub struct GamepadStateAbi<'a> {+ handle: u32,+ axis_values: ak::Span<'a, i16>,+ button_values: ak::Span<'a, i16>,+}++impl GamepadDescription {+ pub(crate) fn from_abi(description: &GamepadDescriptionAbi<'_>) -> Self {+ Self {+ handle: description.handle,+ id: String::from_utf8_lossy(description.id.as_slice()).into_owned(),+ has_standard_mapping: description.has_standard_mapping,+ supports_dual_rumble: description.supports_dual_rumble,+ supports_trigger_rumble: description.supports_trigger_rumble,+ axes: description.axes.as_slice().to_vec(),+ buttons: description.buttons.as_slice().to_vec(),+ }+ }++ fn to_abi(&self) -> GamepadDescriptionAbi<'_> {+ GamepadDescriptionAbi {+ handle: self.handle,+ id: ak::Span::new(self.id.as_bytes()),+ has_standard_mapping: self.has_standard_mapping,+ supports_dual_rumble: self.supports_dual_rumble,+ supports_trigger_rumble: self.supports_trigger_rumble,+ axes: ak::Span::new(&self.axes),+ buttons: ak::Span::new(&self.buttons),+ }+ }+}++impl GamepadState {+ pub(crate) fn from_abi(state: &GamepadStateAbi<'_>) -> Self {+ Self {+ handle: state.handle,+ axis_values: state.axis_values.as_slice().to_vec(),+ button_values: state.button_values.as_slice().to_vec(),+ }+ }++ fn to_abi(&self) -> GamepadStateAbi<'_> {+ GamepadStateAbi {+ handle: self.handle,+ axis_values: ak::Span::new(&self.axis_values),+ button_values: ak::Span::new(&self.button_values),+ }+ }+}++unsafe extern "C" {+ fn web_high_resolution_time_current_high_resolution_time(global_object: *mut c_void) -> f64;+ fn web_gamepad_normalize_axis_value(logical_value: i16, logical_minimum: i16, logical_maximum: i16) -> f64;+ fn web_gamepad_normalize_button_value(logical_value: i16, logical_minimum: i16, logical_maximum: i16) -> f64;+ fn web_gamepad_is_button_pressed(logical_value: i16, logical_minimum: i16, logical_maximum: i16) -> bool;+ fn web_gamepad_contains_gamepad_user_gesture(+ description: *const GamepadDescriptionAbi,+ state: *const GamepadStateAbi,+ ) -> bool;+}++/// The enumeration GamepadMappingType of Gamepad/Gamepad.idl.+#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum GamepadMappingType {+ Empty,+ Standard,+ #[allow(dead_code, reason = "no gamepad uses the xr-standard mapping")]+ XrStandard,+}++pub(crate) fn current_high_resolution_time(window: &CppWindow) -> f64 {+ // SAFETY: The Window's global object is live.+ unsafe { web_high_resolution_time_current_high_resolution_time(window.realm().global_object().as_ptr().cast()) }+}++struct InitializedInputs {+ mapping: Vec<usize>,+ minimums: Vec<i16>,+ maximums: Vec<i16>,+ size: usize,+}++// https://w3c.github.io/gamepad/#dom-gamepad+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct Gamepad {+ window: CppWindow,+ #[gc(untraced)]+ description: GamepadDescription,++ // https://w3c.github.io/gamepad/#dom-gamepad-id+ // An identification string for the gamepad. This string identifies the brand or style of connected gamepad device.+ // The exact format of the id string is left unspecified. It is RECOMMENDED that the user agent select a string+ // that identifies the product without uniquely identifying the device. For example, a USB gamepad may be+ // identified by its idVendor and idProduct values. Unique identifiers like serial numbers or Bluetooth device+ // addresses MUST NOT be included in the id string.+ id: Utf16String,++ // https://w3c.github.io/gamepad/#dom-gamepad-index+ // The index of the gamepad in the Navigator. When multiple gamepads are connected to a user agent, indices MUST be+ // assigned on a first-come, first-serve basis, starting at zero. If a gamepad is disconnected, previously assigned+ // indices MUST NOT be reassigned to gamepads that continue to be connected. However, if a gamepad is disconnected,+ // and subsequently the same or a different gamepad is then connected, the lowest previously used index MUST be+ // reused.+ index: usize,++ // https://w3c.github.io/gamepad/#dfn-connected+ // A flag indicating that the device is connected to the system+ connected: Cell<bool>,++ // https://w3c.github.io/gamepad/#dfn-timestamp+ // The last time data for this Gamepad was updated+ timestamp: Cell<f64>,++ // https://w3c.github.io/gamepad/#dfn-axes+ // A sequence of double values representing the current state of axes exposed by this device.+ // https://w3c.github.io/gamepad/#dom-gamepad-axes+ // Array of values for all axes of the gamepad. All axis values MUST be linearly normalized to the range [-1 .. 1].+ // If the controller is perpendicular to the ground with the directional stick pointing up, -1 SHOULD correspond to+ // "forward" or "left", and 1 SHOULD correspond to "backward" or "right". Axes that are drawn from a 2D input+ // device SHOULD appear next to each other in the axes array, X then Y. It is RECOMMENDED that axes appear in+ // decreasing order of importance, such that element 0 and 1 typically represent the X and Y axis of a directional+ // stick. The same object MUST be returned until the user agent needs to return different values (or values in a+ // different order).+ // FIXME: Our current FrozenArray implementation only supports returning new objects everytime.+ #[gc(untraced)]+ axes: RefCell<Vec<f64>>,++ // https://w3c.github.io/gamepad/#dfn-axismapping+ // Mapping from unmapped axis index to an index in the axes array+ axis_mapping: Vec<usize>,++ // https://w3c.github.io/gamepad/#dfn-axisminimums+ // A list containing the minimum logical value for each axis+ // NOTE: While the Gamepad API internally uses u32 to represent raw axis values, SDL uses i16 for axes.+ axis_minimums: Vec<i16>,++ // https://w3c.github.io/gamepad/#dfn-axismaximums+ // A list containing the maximum logical value for each axis+ // NOTE: While the Gamepad API internally uses u32 to represent raw axis values, SDL uses i16 for axes.+ axis_maximums: Vec<i16>,++ // https://w3c.github.io/gamepad/#dfn-buttons+ // A sequence of GamepadButton objects representing the current state of buttons exposed by this device+ // Array of button states for all buttons of the gamepad. It is RECOMMENDED that buttons appear in decreasing+ // importance such that the primary button, secondary button, tertiary button, and so on appear as elements 0, 1,+ // 2, ... in the buttons array. The same object MUST be returned until the user agent needs to return different+ // values (or values in a different order).+ // FIXME: Our current FrozenArray implementation only supports returning new objects everytime.+ buttons: Vec<Ref<GamepadButton>>,++ // https://w3c.github.io/gamepad/#dfn-buttonmapping+ // Mapping from unmapped button index to an index in the buttons array+ button_mapping: Vec<usize>,++ // https://w3c.github.io/gamepad/#dfn-buttonminimums+ // A list containing the minimum logical value for each button.+ // NOTE: While the Gamepad API internally uses u32 to represent raw button values, SDL uses bool for buttons and+ // i16 for axes. The left and right triggers are buttons in the Gamepad API.+ button_minimums: Vec<i16>,++ // https://w3c.github.io/gamepad/#dfn-buttonmaximums+ // A list containing the maximum logical value for each button+ button_maximums: Vec<i16>,++ // https://w3c.github.io/gamepad/#dfn-exposed+ // A flag indicating that the Gamepad object has been exposed to script+ exposed: Cell<bool>,++ // https://w3c.github.io/gamepad/#dfn-vibrationactuator+ vibration_actuator: Cell<Option<Ref<GamepadHapticActuator>>>,++ // https://w3c.github.io/gamepad/#dom-gamepad-mapping+ // The mapping in use for this device. If the user agent has knowledge of the layout of the device, then it SHOULD+ // indicate that a mapping is in use by setting mapping to the corresponding GamepadMappingType value.+ #[gc(untraced)]+ mapping: GamepadMappingType,++ #[gc(untraced)]+ latest_state: RefCell<GamepadState>,+}++impl Wrappable for Gamepad {+ fn relevant_realm(&self) -> Option<Gc<Realm>> {+ Some(self.window.realm())+ }+}++// https://w3c.github.io/gamepad/#dfn-initializing-axes+fn initialize_axes(description: &GamepadDescription) -> InitializedInputs {+ // 1. Let inputCount be the number of axis inputs exposed by the device represented by gamepad.+ let inputs = &description.axes;++ // 2. Set gamepad.[[axisMinimums]] to a list of unsigned long values with size equal to inputCount containing minimum logical values for each of the axis inputs.+ // 3. Set gamepad.[[axisMaximums]] to a list of unsigned long values with size equal to inputCount containing maximum logical values for each of the axis inputs.+ let minimums = inputs.iter().map(|input| input.logical_minimum).collect();+ let maximums = inputs.iter().map(|input| input.logical_maximum).collect();+ let mut mapping = vec![0; inputs.len()];++ // 4. Let unmappedInputList be an empty list.+ let mut unmapped_input_list = Vec::new();++ // 5. Let mappedIndexList be an empty list.+ let mut mapped_index_list = Vec::new();++ // 6. Let axesSize be 0.+ let mut axes_size = 0;++ // 7. For each rawInputIndex of the range from 0 to inputCount − 1:+ for (raw_input_index, input) in inputs.iter().enumerate() {+ // 1. If the gamepad axis at index rawInputIndex represents a Standard Gamepad axis:+ if input.has_canonical_index {+ // 1. Let canonicalIndex be the canonical index for the axis.+ let canonical_index = input.canonical_index as usize;++ // 2. If mappedIndexList contains canonicalIndex, then append rawInputIndex to unmappedInputList.+ if mapped_index_list.contains(&canonical_index) {+ unmapped_input_list.push(raw_input_index);+ } else {+ // Otherwise:+ // 1. Set gamepad.[[axisMapping]][rawInputIndex] to canonicalIndex.+ mapping[raw_input_index] = canonical_index;++ // 2. Append canonicalIndex to mappedIndexList.+ mapped_index_list.push(canonical_index);++ // 3. If canonicalIndex + 1 is greater than axesSize, then set axesSize to canonicalIndex + 1.+ if canonical_index + 1 > axes_size {+ axes_size = canonical_index + 1;+ }+ }+ } else {+ // Otherwise, append rawInputIndex to unmappedInputList.+ unmapped_input_list.push(raw_input_index);+ }+ }++ // 8. Let axisIndex be 0.+ let mut axis_index = 0;++ // 9. For each rawInputIndex of unmappedInputList:+ for raw_input_index in unmapped_input_list {+ // 1. While mappedIndexList contains axisIndex:+ while mapped_index_list.contains(&axis_index) {+ // 1. Increment axisIndex.+ axis_index += 1;+ }++ // 2. Set gamepad.[[axisMapping]][rawInputIndex] to axisIndex.+ mapping[raw_input_index] = axis_index;++ // 3. Append axisIndex to mappedIndexList.+ mapped_index_list.push(axis_index);++ // 4. If axisIndex + 1 is greater than axesSize, then set axesSize to axisIndex + 1.+ if axis_index + 1 > axes_size {+ axes_size = axis_index + 1;+ }+ }++ // NB: Instead of returning a list, the caller creates the axes from the size.+ // 10. Let axes be an empty list.+ // 11. For each axisIndex of the range from 0 to axesSize − 1, append 0 to axes.+ // 12. Return axes.+ InitializedInputs {+ mapping,+ minimums,+ maximums,+ size: axes_size,+ }+}++// https://w3c.github.io/gamepad/#dfn-initializing-buttons+fn initialize_buttons(description: &GamepadDescription) -> InitializedInputs {+ // 1. Let inputCount be the number of button inputs exposed by the device represented by gamepad.+ let inputs = &description.buttons;++ // 2. Set gamepad.[[buttonMinimums]] to be a list of unsigned long values with size equal to inputCount containing minimum logical values for each of the button inputs.+ // 3. Set gamepad.[[buttonMaximums]] to be a list of unsigned long values with size equal to inputCount containing maximum logical values for each of the button inputs.+ let minimums = inputs.iter().map(|input| input.logical_minimum).collect();+ let maximums = inputs.iter().map(|input| input.logical_maximum).collect();+ let mut mapping = vec![0; inputs.len()];++ // 4. Let unmappedInputList be an empty list.+ let mut unmapped_input_list = Vec::new();++ // 5. Let mappedIndexList be an empty list.+ let mut mapped_index_list = Vec::new();++ // 6. Let buttonsSize be 0.+ let mut buttons_size = 0;++ // 7. For each rawInputIndex of the range from 0 to inputCount − 1:+ for (raw_input_index, input) in inputs.iter().enumerate() {+ // 1. If the gamepad button at index rawInputIndex represents a Standard Gamepad button:+ if input.has_canonical_index {+ // 1. Let canonicalIndex be the canonical index for the button.+ let canonical_index = input.canonical_index as usize;++ // 2. If mappedIndexList contains canonicalIndex, then append rawInputIndex to unmappedInputList.+ if mapped_index_list.contains(&canonical_index) {+ unmapped_input_list.push(raw_input_index);+ } else {+ // Otherwise:+ // 1. Set gamepad.[[buttonMapping]][rawInputIndex] to canonicalIndex.+ mapping[raw_input_index] = canonical_index;++ // 2. Append canonicalIndex to mappedIndexList.+ mapped_index_list.push(canonical_index);++ // 3. If canonicalIndex + 1 is greater than buttonsSize, then set buttonsSize to canonicalIndex + 1.+ if canonical_index + 1 > buttons_size {+ buttons_size = canonical_index + 1;+ }+ }+ } else {+ // Otherwise, append rawInputIndex to unmappedInputList.+ unmapped_input_list.push(raw_input_index);+ }++ // 2. Increment rawInputIndex.+ }++ // 8. Let buttonIndex be 0.+ let mut button_index = 0;++ // 9. For each rawInputIndex of unmappedInputList:+ for raw_input_index in unmapped_input_list {+ // 1. While mappedIndexList contains buttonIndex:+ while mapped_index_list.contains(&button_index) {+ // 1. Increment buttonIndex.+ button_index += 1;+ }++ // 2. Set gamepad.[[buttonMapping]][rawInputIndex] to buttonIndex.+ mapping[raw_input_index] = button_index;++ // 3. Append buttonIndex to mappedIndexList.+ mapped_index_list.push(button_index);++ // 4. If buttonIndex + 1 is greater than buttonsSize, then set buttonsSize to buttonIndex + 1.+ if button_index + 1 > buttons_size {+ buttons_size = button_index + 1;+ }+ }++ // NB: Instead of returning a list, the caller creates the buttons from the size.+ // 10. Let buttons be an empty list.+ // 11. For each buttonIndex of the range from 0 to buttonsSize − 1, append a new GamepadButton to buttons.+ // 12. Return buttons.+ InitializedInputs {+ mapping,+ minimums,+ maximums,+ size: buttons_size,+ }+}++// https://w3c.github.io/gamepad/#dfn-selecting-a-mapping+fn select_a_mapping(description: &GamepadDescription) -> GamepadMappingType {+ // 1. If the button and axis layout of the gamepad device corresponds with the Standard Gamepad layout, then+ // return "standard".+ // 2. Return "".+ // NB: The UI process performs this check when it builds the description.+ if description.has_standard_mapping {+ GamepadMappingType::Standard+ } else {+ GamepadMappingType::Empty+ }+}++impl Gamepad {+ // https://w3c.github.io/gamepad/#dfn-a-new-gamepad+ pub(crate) fn create(vm: &Vm, window: &CppWindow, description: GamepadDescription) -> Ref<Self> {+ // 1. Let gamepad be a newly created Gamepad instance:+ // 1. Initialize gamepad's id attribute to an identification string for the gamepad.+ let id = Utf16String::from_utf8(&description.id);++ // 2. Initialize gamepad's index attribute to the result of selecting an unused gamepad index for gamepad.+ // https://w3c.github.io/gamepad/#dfn-selecting-an-unused-gamepad-index+ // 1. Let navigator be gamepad's relevant global object's Navigator object.+ // The rest of the steps are implemented in navigator_gamepad.rs.+ // NOTE: Gamepad is only exposed on Window.+ let index = select_an_unused_gamepad_index(vm, &navigator_gamepad(vm, window));++ // 3. Initialize gamepad's mapping attribute to the result of selecting a mapping for the gamepad device.+ let mapping = select_a_mapping(&description);++ // 4. Set gamepad.[[connected]] to true.+ // 5. Set gamepad.[[timestamp]] to the current high resolution time given gamepad's relevant global object.+ let timestamp = current_high_resolution_time(window);++ // 6. Set gamepad.[[axes]] to the result of initializing axes for gamepad.+ let axes = initialize_axes(&description);++ // 7. Set gamepad.[[buttons]] to the result of initializing buttons for gamepad.+ let buttons = initialize_buttons(&description);+ let button_objects = MarkedVec::with_capacity(vm, buttons.size);+ for _ in 0..buttons.size {+ button_objects.push(GamepadButton::create(vm));+ }++ let gamepad = allocate(vm, |_| Self {+ window: window.clone(),+ description,+ id,+ index,+ connected: Cell::new(true),+ timestamp: Cell::new(timestamp),+ axes: RefCell::new(vec![0.0; axes.size]),+ axis_mapping: axes.mapping,+ axis_minimums: axes.minimums,+ axis_maximums: axes.maximums,+ buttons: button_objects.to_vec(),+ button_mapping: buttons.mapping,+ button_minimums: buttons.minimums,+ button_maximums: buttons.maximums,+ exposed: Cell::new(false),+ vibration_actuator: Cell::new(None),+ mapping,+ latest_state: RefCell::default(),+ });++ // 8. Set gamepad.[[vibrationActuator]] to the result of constructing a GamepadHapticActuator for gamepad.+ gamepad+ .vibration_actuator+ .set(Some(GamepadHapticActuator::create(vm, window, gamepad)));++ // 2. Return gamepad.+ gamepad+ }++ pub(crate) fn handle(&self) -> u32 {+ self.description.handle+ }++ pub(crate) fn description(&self) -> &GamepadDescription {+ &self.description+ }++ pub(crate) fn gamepad_index(&self) -> usize {+ self.index+ }++ pub(crate) fn is_exposed(&self) -> bool {+ self.exposed.get()+ }++ pub(crate) fn set_exposed(&self, exposed: bool) {+ self.exposed.set(exposed);+ }++ pub(crate) fn set_connected(&self, connected: bool) {+ self.connected.set(connected);+ }++ pub(crate) fn set_timestamp(&self, timestamp: f64) {+ self.timestamp.set(timestamp);+ }++ pub(crate) fn set_latest_state(&self, state: GamepadState) {+ *self.latest_state.borrow_mut() = state;+ }++ pub(crate) fn id(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {+ Ok(self.id.clone())+ }++ pub(crate) fn index(&self, _: &mut CallContext) -> WebIdlResult<i32> {+ Ok(i32::try_from(self.index).expect("a gamepad index fits in a long"))+ }++ pub(crate) fn connected(&self, _: &mut CallContext) -> WebIdlResult<bool> {+ Ok(self.connected.get())+ }++ pub(crate) fn timestamp(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.timestamp.get())+ }++ pub(crate) fn mapping(&self, _: &mut CallContext) -> WebIdlResult<GamepadMappingType> {+ Ok(self.mapping)+ }++ pub(crate) fn axes(&self, _: &mut CallContext) -> WebIdlResult<Vec<f64>> {+ Ok(self.axes.borrow().clone())+ }++ pub(crate) fn buttons<'vm>(&self, cx: &mut CallContext<'vm>) -> WebIdlResult<MarkedVec<'vm, Ref<GamepadButton>>> {+ let buttons = MarkedVec::with_capacity(cx.vm(), self.buttons.len());+ buttons.extend_from_slice(&self.buttons);+ Ok(buttons)+ }++ pub(crate) fn vibration_actuator(&self, _: &mut CallContext) -> WebIdlResult<Ref<GamepadHapticActuator>> {+ Ok(self+ .vibration_actuator+ .get()+ .expect("a gamepad has a vibration actuator once it is created"))+ }++ // https://w3c.github.io/gamepad/#dfn-map-and-normalize-axes+ fn map_and_normalize_axes(&self) {+ // 1. Let axisValues be a list of unsigned long values representing the most recent logical axis input values for+ // each axis input of the device represented by gamepad.+ // NOTE: While the Gamepad API internally uses u32 to represent raw axis values, SDL uses i16 for axes.+ let latest_state = self.latest_state.borrow();+ let axis_values = &latest_state.axis_values;+ let mut axes = self.axes.borrow_mut();++ // 2. Let maxRawAxisIndex be the size of axisValues − 1.+ // 3. For each rawAxisIndex of the range from 0 to maxRawAxisIndex:+ for (raw_axis_index, &logical_value) in axis_values.iter().enumerate().take(self.axis_minimums.len()) {+ // 1. Let mappedIndex be gamepad.[[axisMapping]][rawAxisIndex].+ let mapped_index = self.axis_mapping[raw_axis_index];++ // 2. Let logicalValue be axisValues[rawAxisIndex].++ // 3. Let logicalMinimum be gamepad.[[axisMinimums]][rawAxisIndex].+ let logical_minimum = self.axis_minimums[raw_axis_index];++ // 4. Let logicalMaximum be gamepad.[[axisMaximums]][rawAxisIndex].+ let logical_maximum = self.axis_maximums[raw_axis_index];++ // 5. Let normalizedValue be 2 (logicalValue − logicalMinimum) / (logicalMaximum − logicalMinimum) − 1.+ // SAFETY: The function only computes with its arguments.+ let normalized_value =+ unsafe { web_gamepad_normalize_axis_value(logical_value, logical_minimum, logical_maximum) };++ // 6. Set gamepad.[[axes]][axisIndex] to be normalizedValue.+ // FIXME: axisIndex should be mappedIndex.+ axes[mapped_index] = normalized_value;+ }+ }++ // https://w3c.github.io/gamepad/#dfn-map-and-normalize-buttons+ fn map_and_normalize_buttons(&self) {+ // 1. Let buttonValues be a list of unsigned long values representing the most recent logical button input values+ // for each button input of the device represented by gamepad.+ // NOTE: While the Gamepad API internally uses u32 to represent raw button values, SDL uses bool for buttons and+ // i16 for axes. The left and right triggers are buttons in the Gamepad API.+ let latest_state = self.latest_state.borrow();+ let button_values = &latest_state.button_values;++ // 2. Let maxRawButtonIndex be the size of buttonValues − 1.+ // 3. For each rawButtonIndex of the range from 0 to maxRawButtonIndex:+ for (raw_button_index, &logical_value) in button_values.iter().enumerate().take(self.button_minimums.len()) {+ // 1. Let mappedIndex be gamepad.[[buttonMapping]][rawButtonIndex].+ let mapped_index = self.button_mapping[raw_button_index];++ // 2. Let logicalValue be buttonValues[rawButtonIndex].++ // 3. Let logicalMinimum be gamepad.[[buttonMinimums]][rawButtonIndex].+ let logical_minimum = self.button_minimums[raw_button_index];++ // 4. Let logicalMaximum be gamepad.[[buttonMaximums]][rawButtonIndex].+ let logical_maximum = self.button_maximums[raw_button_index];++ // 5. Let normalizedValue be (logicalValue − logicalMinimum) / (logicalMaximum − logicalMinimum).+ // SAFETY: The function only computes with its arguments.+ let value = unsafe { web_gamepad_normalize_button_value(logical_value, logical_minimum, logical_maximum) };++ // 6. Let button be gamepad.[[buttons]][mappedIndex].+ let button = self.buttons[mapped_index];++ // 7. Set button.[[value]] to normalizedValue.+ button.set_value(value);++ // 8. If the button has a digital switch to indicate a pure pressed or released state, set button.[[pressed]]+ // 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.+ // SAFETY: The function only computes with its arguments.+ button+ .set_pressed(unsafe { web_gamepad_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]].+ // FIXME: Support the PS4/PS5 controller which has a touchpad, which is a button that can be touched and not pressed in at the same time.+ button.set_touched(button.is_pressed());+ }+ }++ // https://w3c.github.io/gamepad/#dfn-update-gamepad-state+ pub(crate) fn update_gamepad_state(this: Ref<Self>, vm: &Vm) {+ // 1. Let now be the current high resolution time given gamepad's relevant global object.+ let now = current_high_resolution_time(&this.window);+ let window = &this.window;++ // 2. Set gamepad.[[timestamp]] to now.+ this.timestamp.set(now);++ // 3. Run the steps to map and normalize axes for gamepad.+ this.map_and_normalize_axes();++ // 4. Run the steps to map and normalize buttons for gamepad.+ this.map_and_normalize_buttons();++ // FIXME: 5. Run the steps to record touches for gamepad.++ // 6. Let navigator be gamepad's relevant global object's Navigator object.+ let navigator = navigator_gamepad(vm, window);++ // 7. Let document be gamepad's relevant global object's associated Document; otherwise null.+ // 8. If document is null, abort these steps.+ // NB: A Window always has an associated Document.+ let 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()+ && this.contains_gamepad_user_gesture()+ {+ // 1. Set navigator.[[hasGamepadGesture]] to true.+ navigator.set_has_gamepad_gesture(true);++ // 2. For each connectedGamepad of navigator.[[gamepads]]:+ let gamepads = navigator.gamepads(vm);+ for connected_gamepad in gamepads.values().iter() {+ // 1. If connectedGamepad is not equal to null:+ let Some(connected_gamepad) = connected_gamepad else {+ continue;+ };++ // 1. Set connectedGamepad.[[exposed]] to true.+ connected_gamepad.exposed.set(true);++ // 2. Set connectedGamepad.[[timestamp]] to now.+ connected_gamepad.timestamp.set(now);++ // 3. If document is not null and is fully active, then queue a global task on the gamepad task source+ // to fire an event named gamepadconnected at gamepad's relevant global object using GamepadEvent+ // with its gamepad attribute initialized to connectedGamepad.+ if document.is_fully_active() {+ fire_a_gamepad_event(vm, window, "gamepadconnected", *connected_gamepad);+ }+ }+ }+ }++ // https://w3c.github.io/gamepad/#dfn-gamepad-user-gesture+ fn contains_gamepad_user_gesture(&self) -> bool {+ // NB: The UI process uses the same algorithm to decide when to tell this process about its gamepads.+ let latest_state = self.latest_state.borrow();+ let description = self.description.to_abi();+ let state = latest_state.to_abi();+ // SAFETY: The description and the state are lent for the call.+ unsafe { web_gamepad_contains_gamepad_user_gesture(&raw const description, &raw const state) }+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/gamepad/gamepad_button.rs b/Libraries/LibWeb/Bindings/Rust/src/gamepad/gamepad_button.rsnew file mode 100644index 00000000000..7594a3343b5--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/gamepad/gamepad_button.rs@@ -0,0 +1,72 @@+/*+ * Copyright (c) 2025, Luke Wilde <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! GamepadButton, https://w3c.github.io/gamepad/#dom-gamepadbutton++use core::cell::Cell;++use libjs_rust::api::{Trace, Vm};++use crate::bindings::interface::{Ref, Wrappable, allocate};+use crate::bindings::{CallContext, WebIdlResult};++// https://w3c.github.io/gamepad/#dom-gamepadbutton+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct GamepadButton {+ // https://w3c.github.io/gamepad/#dfn-pressed+ // A flag indicating that the button is pressed+ pressed: Cell<bool>,++ // https://w3c.github.io/gamepad/#dfn-touched+ // A flag indicating that the button is touched+ touched: Cell<bool>,++ // https://w3c.github.io/gamepad/#dfn-value+ // A double representing the button value scaled to the range [0 .. 1]+ value: Cell<f64>,+}++impl Wrappable for GamepadButton {}++impl GamepadButton {+ pub(crate) fn create(vm: &Vm) -> Ref<Self> {+ allocate(vm, |_| Self {+ pressed: Cell::new(false),+ touched: Cell::new(false),+ value: Cell::new(0.0),+ })+ }++ pub(crate) fn pressed(&self, _: &mut CallContext) -> WebIdlResult<bool> {+ Ok(self.pressed.get())+ }++ pub(crate) fn touched(&self, _: &mut CallContext) -> WebIdlResult<bool> {+ Ok(self.touched.get())+ }++ pub(crate) fn value(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.value.get())+ }++ pub(crate) fn is_pressed(&self) -> bool {+ self.pressed.get()+ }++ pub(crate) fn set_pressed(&self, pressed: bool) {+ self.pressed.set(pressed);+ }++ pub(crate) fn set_touched(&self, touched: bool) {+ self.touched.set(touched);+ }++ pub(crate) fn set_value(&self, value: f64) {+ self.value.set(value);+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/gamepad/gamepad_event.rs b/Libraries/LibWeb/Bindings/Rust/src/gamepad/gamepad_event.rsnew file mode 100644index 00000000000..33bd6de3b42--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/gamepad/gamepad_event.rs@@ -0,0 +1,79 @@+/*+ * Copyright (c) 2025, Luke Wilde <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! GamepadEvent, https://w3c.github.io/gamepad/#dom-gamepadevent++use core::ffi::c_void;+use core::ptr::NonNull;++use ak::Utf16String;+use libjs_rust::api::{Gc, Realm, Trace, Vm};++use crate::bindings::event_target::CppEvent;+use crate::bindings::interface::{Ref, Wrappable, allocate};+use crate::bindings::{CallContext, WebIdlResult};+use crate::dom::event::EventInit;+use crate::gamepad::gamepad::Gamepad;++/// The dictionary GamepadEventInit of Gamepad/GamepadEvent.idl.+pub(crate) struct GamepadEventInit {+ pub(crate) parent: EventInit,+ pub(crate) gamepad: Option<Ref<Gamepad>>,+}++// https://w3c.github.io/gamepad/#dom-gamepadevent+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct GamepadEvent {+ event: CppEvent,+ gamepad: Option<Ref<Gamepad>>,+}++impl Wrappable for GamepadEvent {+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {+ self.event.as_cpp_parent()+ }+}++impl GamepadEvent {+ pub(crate) fn create(+ vm: &Vm,+ realm: Gc<Realm>,+ event_name: &Utf16String,+ event_init: GamepadEventInit,+ ) -> Ref<GamepadEvent> {+ let event = CppEvent::create_for_owner(+ realm,+ event_name,+ event_init.parent.bubbles,+ event_init.parent.cancelable,+ event_init.parent.composed,+ );+ let object = allocate(vm, |_| GamepadEvent {+ event,+ gamepad: event_init.gamepad,+ });+ object.event.set_owner(object);+ object+ }++ pub(crate) fn construct(+ cx: &mut CallContext,+ r#type: Utf16String,+ event_init_dict: GamepadEventInit,+ ) -> WebIdlResult<Ref<GamepadEvent>> {+ Ok(Self::create(cx.vm(), cx.realm(), &r#type, event_init_dict))+ }++ pub(crate) fn event(&self) -> &CppEvent {+ &self.event+ }++ pub(crate) fn gamepad(&self, _: &mut CallContext) -> WebIdlResult<Option<Ref<Gamepad>>> {+ Ok(self.gamepad)+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/gamepad/gamepad_haptic_actuator.rs b/Libraries/LibWeb/Bindings/Rust/src/gamepad/gamepad_haptic_actuator.rsnew file mode 100644index 00000000000..4a06eaf2233--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/gamepad/gamepad_haptic_actuator.rs@@ -0,0 +1,553 @@+/*+ * Copyright (c) 2025, Luke Wilde <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! GamepadHapticActuator, https://w3c.github.io/gamepad/#gamepadhapticactuator-interface++use core::ffi::c_void;++use ak::Utf16String;+use libjs_rust::api::{Gc, GcRefCell, Object, Realm, Trace, Vm};++use crate::bindings::conversions::ToJs;+use crate::bindings::cpp_cell::CppCell;+use crate::bindings::global_object::{CppWindow, window_from_global_object};+use crate::bindings::interface::{+ Ref, Wrappable, allocate, cell_from_abi, with_temporary_execution_context_and_callbacks,+};+use crate::bindings::promise::{+ TaskSource, WebIdlPromise, deferred_invoke, promise_realm, queue_a_global_task, reject_promise_with_exception,+ resolve_promise,+};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::gamepad::gamepad::Gamepad;+use crate::html::visibility_state::VisibilityState;+use crate::platform::timer::CppTimer;++unsafe extern "C" {+ fn web_gamepad_play_effect(+ window: *mut c_void,+ handle: u32,+ effect_type: u8,+ first_magnitude: u16,+ second_magnitude: u16,+ duration: u32,+ );+ fn web_gamepad_stop_effects(window: *mut c_void, handle: u32);+}++/// The enumeration GamepadHapticsResult of Gamepad/GamepadHapticActuator.idl.+#[derive(Clone, Copy, PartialEq, Eq, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) enum GamepadHapticsResult {+ Complete,+ Preempted,+}++impl GamepadHapticsResult {+ fn as_str(self) -> &'static str {+ match self {+ Self::Complete => "complete",+ Self::Preempted => "preempted",+ }+ }+}++/// The enumeration GamepadHapticEffectType of Gamepad/GamepadHapticActuator.idl.+#[derive(Clone, Copy, PartialEq, Eq, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) enum GamepadHapticEffectType {+ DualRumble,+ TriggerRumble,+}++/// The dictionary GamepadEffectParameters of Gamepad/GamepadHapticActuator.idl.+#[derive(Clone, Copy, Default, Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct GamepadEffectParameters {+ pub(crate) duration: u64,+ pub(crate) start_delay: u64,+ pub(crate) strong_magnitude: f64,+ pub(crate) weak_magnitude: f64,+ pub(crate) left_trigger: f64,+ pub(crate) right_trigger: f64,+}++#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+struct HapticsCompletionSteps {+ promise: WebIdlPromise,+ queue_on: Option<Gc<Object>>,+}++fn resolve_haptics_promise(vm: &Vm, promise: WebIdlPromise, result: GamepadHapticsResult) {+ let realm = promise_realm(promise);+ with_temporary_execution_context_and_callbacks(realm, || {+ let result = Utf16String::from_ascii(result.as_str().as_bytes())+ .to_js(&CallContext::new(vm, realm))+ .expect("a string converts to a JS value");+ resolve_promise(vm, promise, result);+ });+}++impl HapticsCompletionSteps {+ fn run(self, vm: &Vm, result: GamepadHapticsResult) {+ match self.queue_on {+ Some(global) => {+ queue_a_global_task(+ vm,+ global,+ TaskSource::Gamepad,+ (self.promise, result),+ |vm, (promise, result)| resolve_haptics_promise(vm, promise, result),+ );+ }+ None => resolve_haptics_promise(vm, self.promise, result),+ }+ }+}++// FIXME: What is a valid duration and startDelay? The spec doesn't define that.+// Safari: clamps any duration above 5000ms to 5000ms and doesn't seem to clamp or reject any startDelay.+// Chrome: rejects if duration + startDelay > 5000ms.+// Firefox doesn't support vibration at the time of writing.+const MAX_VIBRATION_DURATION: u64 = 5000;++// https://w3c.github.io/gamepad/#gamepadhapticactuator-interface+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct GamepadHapticActuator {+ gamepad: Ref<Gamepad>,+ window: CppWindow,+ document_became_hidden_observer: GcRefCell<Option<CppCell>>,++ // https://w3c.github.io/gamepad/#dfn-effects+ // Represents the effects supported by the actuator.+ #[gc(untraced)]+ effects: Vec<GamepadHapticEffectType>,++ // https://w3c.github.io/gamepad/#dfn-playingeffectpromise+ // The completion steps for playing some effect, or null if no effect is playing.+ playing_effect_completion_steps: GcRefCell<Option<HapticsCompletionSteps>>,+ playing_effect_timer: GcRefCell<Option<CppTimer>>,+}++impl Wrappable for GamepadHapticActuator {+ fn relevant_realm(&self) -> Option<Gc<Realm>> {+ Some(self.window.realm())+ }+}++unsafe extern "C" fn document_visibility_changed(vm: *mut c_void, actuator: *mut c_void, visible: bool) {+ // SAFETY: LibWeb passes the live VM.+ let vm = unsafe { &*vm.cast::<Vm>() };+ // SAFETY: The observer holds the actuator, whose cell it was given.+ let actuator: Ref<GamepadHapticActuator> = unsafe { cell_from_abi(actuator) };+ if !visible {+ GamepadHapticActuator::document_became_hidden(actuator, vm);+ }+}++fn gamepad_effect_magnitudes(r#type: GamepadHapticEffectType, params: &GamepadEffectParameters) -> (f64, f64) {+ match r#type {+ GamepadHapticEffectType::DualRumble => (params.strong_magnitude, params.weak_magnitude),+ GamepadHapticEffectType::TriggerRumble => (params.left_trigger, params.right_trigger),+ }+}++fn magnitude_to_u16(magnitude: f64) -> u16 {+ #[allow(+ clippy::cast_possible_truncation,+ clippy::cast_sign_loss,+ reason = "a valid magnitude is in the range [0 .. 1]"+ )]+ let magnitude = (magnitude * f64::from(u16::MAX)) as u16;+ magnitude+}++impl GamepadHapticActuator {+ // https://w3c.github.io/gamepad/#dfn-constructing-a-gamepadhapticactuator+ pub(crate) fn create(vm: &Vm, window: &CppWindow, gamepad: Ref<Gamepad>) -> Ref<Self> {+ // 1. Let gamepadHapticActuator be a newly created GamepadHapticActuator instance.+ // 2. Let supportedEffectsList be an empty list.+ let mut supported_effects_list = Vec::new();++ // 3. For each enum value type of GamepadHapticEffectType, if the user agent can send a command to initiate effects+ // of that type on that actuator, append type to supportedEffectsList.+ if gamepad.description().supports_dual_rumble {+ supported_effects_list.push(GamepadHapticEffectType::DualRumble);+ }++ if gamepad.description().supports_trigger_rumble {+ supported_effects_list.push(GamepadHapticEffectType::TriggerRumble);+ }++ // 4. Set gamepadHapticActuator.[[effects]] to supportedEffectsList.+ let gamepad_haptic_actuator = allocate(vm, |_| Self {+ gamepad,+ window: window.clone(),+ document_became_hidden_observer: GcRefCell::new(None),+ effects: supported_effects_list,+ playing_effect_completion_steps: GcRefCell::new(None),+ playing_effect_timer: GcRefCell::new(None),+ });++ let observer = window+ .associated_document()+ .observe_visibility_state(gamepad_haptic_actuator.as_ptr().cast(), document_visibility_changed);+ *gamepad_haptic_actuator.document_became_hidden_observer.borrow_mut(vm) = Some(observer);++ gamepad_haptic_actuator+ }++ pub(crate) fn effects(&self, _: &mut CallContext) -> WebIdlResult<Vec<GamepadHapticEffectType>> {+ Ok(self.effects.clone())+ }++ // https://w3c.github.io/gamepad/#dfn-valid-effect+ fn is_valid_effect(r#type: GamepadHapticEffectType, params: &GamepadEffectParameters) -> bool {+ let is_in_unit_range = |value: f64| (0.0..=1.0).contains(&value);++ // 1. Given the value of GamepadHapticEffectType type, switch on:+ // "dual-rumble"+ // If params does not describe a valid dual-rumble effect, return false.+ // "trigger-rumble"+ // If params does not describe a valid trigger-rumble effect, return false.+ // 2. Return true+ match r#type {+ GamepadHapticEffectType::DualRumble => {+ // https://w3c.github.io/gamepad/#dfn-valid-dual-rumble-effect+ // Given GamepadEffectParameters params, a valid dual-rumble effect must have a valid duration, a valid+ // startDelay, and both the strongMagnitude and the weakMagnitude must be in the range [0 .. 1].+ let Some(total_duration) = params.duration.checked_add(params.start_delay) else {+ return false;+ };++ if total_duration > MAX_VIBRATION_DURATION {+ return false;+ }++ if !is_in_unit_range(params.strong_magnitude) {+ return false;+ }++ if !is_in_unit_range(params.weak_magnitude) {+ return false;+ }++ true+ }+ GamepadHapticEffectType::TriggerRumble => {+ // https://w3c.github.io/gamepad/#dfn-valid-trigger-rumble-effect+ // Given GamepadEffectParameters params, a valid trigger-rumble effect must have a valid duration, a valid+ // startDelay, and the strongMagnitude, weakMagnitude, leftTrigger, and rightTrigger must be in the range+ // [0 .. 1].+ let Some(total_duration) = params.duration.checked_add(params.start_delay) else {+ return false;+ };++ if total_duration > MAX_VIBRATION_DURATION {+ return false;+ }++ if !is_in_unit_range(params.strong_magnitude) {+ return false;+ }++ if !is_in_unit_range(params.weak_magnitude) {+ return false;+ }++ if !is_in_unit_range(params.left_trigger) {+ return false;+ }++ if !is_in_unit_range(params.right_trigger) {+ return false;+ }++ true+ }+ }+ }++ fn can_play_effect_with_type(&self, r#type: GamepadHapticEffectType) -> bool {+ // https://w3c.github.io/gamepad/#ref-for-dfn-play-effects-with-type-1+ // A GamepadHapticActuator can play effects with type type if type can be found in the [[effects]] list.+ self.effects.contains(&r#type)+ }++ fn current_document_is_hidden_or_inactive(vm: &Vm) -> bool {+ let realm = vm.current_realm().expect("a binding runs in a realm");+ let window =+ window_from_global_object(realm.global_object()).expect("GamepadHapticActuator is only exposed on Window");+ let document = window.associated_document();+ !document.is_fully_active() || document.visibility_state() == VisibilityState::Hidden+ }++ // https://w3c.github.io/gamepad/#dom-gamepadhapticactuator-playeffect+ pub(crate) fn play_effect(+ this: &Ref<Self>,+ cx: &mut CallContext,+ promise: WebIdlPromise,+ r#type: GamepadHapticEffectType,+ params: GamepadEffectParameters,+ ) -> WebIdlResult<()> {+ let vm = cx.vm();++ // 1. If params does not describe a valid effect of type type, return a promise rejected with a TypeError.+ if !Self::is_valid_effect(r#type, ¶ms) {+ reject_promise_with_exception(vm, promise, Exception::type_error("Invalid effect"));+ return Ok(());+ }++ // 2. Let document be the current settings object's relevant global object's associated Document.+ // 3. If document is null or document is not fully active or document's visibility state is "hidden", return a+ // promise rejected with an "InvalidStateError" DOMException.+ if Self::current_document_is_hidden_or_inactive(vm) {+ reject_promise_with_exception(+ vm,+ promise,+ Exception::Dom(+ "InvalidStateError",+ Utf16String::from_utf8("Haptics are not allowed in a hidden document"),+ ),+ );+ return Ok(());+ }++ // 5. If this GamepadHapticActuator cannot play effects with type type, return a promise rejected with reason+ // NotSupportedError.+ if !this.can_play_effect_with_type(r#type) {+ reject_promise_with_exception(+ vm,+ promise,+ Exception::Dom(+ "NotSupportedError",+ Utf16String::from_utf8("Gamepad does not support this effect"),+ ),+ );+ return Ok(());+ }++ let completion_steps = HapticsCompletionSteps {+ promise,+ queue_on: Some(promise_realm(promise).global_object()),+ };+ Self::play_effect_with_completion_steps(*this, vm, r#type, params, completion_steps);+ Ok(())+ }++ // https://w3c.github.io/gamepad/#dom-gamepadhapticactuator-reset+ pub(crate) fn reset(this: &Ref<Self>, cx: &mut CallContext, promise: WebIdlPromise) -> WebIdlResult<()> {+ let vm = cx.vm();++ // 1. Let document be the current settings object's relevant global object's associated Document.+ // 2. If document is null or document is not fully active or document's visibility state is "hidden", return a+ // promise rejected with an "InvalidStateError" DOMException.+ if Self::current_document_is_hidden_or_inactive(vm) {+ reject_promise_with_exception(+ vm,+ promise,+ Exception::Dom(+ "InvalidStateError",+ Utf16String::from_utf8("Haptics are not allowed in a hidden document"),+ ),+ );+ return Ok(());+ }++ Self::reset_with_completion_steps(+ *this,+ vm,+ HapticsCompletionSteps {+ promise,+ queue_on: None,+ },+ );+ Ok(())+ }++ // https://w3c.github.io/gamepad/#dom-gamepadhapticactuator-playeffect+ fn play_effect_with_completion_steps(+ this: Ref<Self>,+ vm: &Vm,+ r#type: GamepadHapticEffectType,+ params: GamepadEffectParameters,+ completion_steps: HapticsCompletionSteps,+ ) {+ // 4. If this.[[playingEffectPromise]] is not null:+ let playing_effect_completion_steps = this.playing_effect_completion_steps.borrow().clone();+ if let Some(effect_completion_steps) = playing_effect_completion_steps {+ // 1. Let effectPromise be this.[[playingEffectPromise]].+ // 2. Set this.[[playingEffectPromise]] to null.+ *this.playing_effect_completion_steps.borrow_mut(vm) = None;+ this.clear_playing_effect_timers(vm);++ // 3. Queue a global task on the gamepad task source with the relevant global object of this to resolve+ // effectPromise with "preempted".+ effect_completion_steps.run(vm, GamepadHapticsResult::Preempted);+ }++ // 6. Let [[playingEffectPromise]] be a new promise.+ *this.playing_effect_completion_steps.borrow_mut(vm) = Some(completion_steps);++ // 7. Let playEffectTimestamp be the current high resolution time given the document's relevant global object.+ // NOTE: Unused.++ // 8. Do the following steps in parallel:+ deferred_invoke(vm, (this, r#type, params), |vm, (this, r#type, params)| {+ // 1. Issue a haptic effect to the actuator with type, params, and the playEffectTimestamp.+ Self::issue_haptic_effect(this, vm, r#type, params);+ });++ // 9. Return [[playingEffectPromise]].+ }++ fn effect_completed(this: Ref<Self>, vm: &Vm) {+ // 2. When the effect completes, if this.[[playingEffectPromise]] is not null, queue a global task on the+ // gamepad task source with the relevant global object of this to run the following steps:+ let playing_effect_completion_steps = this.playing_effect_completion_steps.borrow().clone();+ if let Some(completion_steps) = playing_effect_completion_steps {+ // 2. Resolve this.[[playingEffectPromise]] with "complete".+ completion_steps.run(vm, GamepadHapticsResult::Complete);++ // 3. Set this.[[playingEffectPromise]] to null.+ *this.playing_effect_completion_steps.borrow_mut(vm) = None;+ this.clear_playing_effect_timers(vm);+ }+ }++ fn reset_with_completion_steps(this: Ref<Self>, vm: &Vm, reset_completion_steps: HapticsCompletionSteps) {+ // 4. If this.[[playingEffectPromise]] is not null, do the following steps in parallel:+ if this.playing_effect_completion_steps.borrow().is_none() {+ return;+ }++ deferred_invoke(+ vm,+ (this, reset_completion_steps),+ |vm, (this, reset_completion_steps)| {+ // 1. Let effectPromise be this.[[playingEffectPromise]].+ let effect_completion_steps = this.playing_effect_completion_steps.borrow().clone();++ // 2. Stop haptic effects on this's gamepad's actuator.+ this.stop_haptic_effects();++ // 3. If the effect has been successfully stopped, do:+ // AD-HOC: The stop command is sent to the UI process without waiting for a reply, so it is taken to have+ // succeeded, matching other engines.+ // 1. If effectPromise and this.[[playingEffectPromise]] are still the same,+ // set this.[[playingEffectPromise]] to null.+ let playing_effect_promise = this+ .playing_effect_completion_steps+ .borrow()+ .as_ref()+ .map(|steps| steps.promise);+ if effect_completion_steps.as_ref().map(|steps| steps.promise) == playing_effect_promise {+ *this.playing_effect_completion_steps.borrow_mut(vm) = None;+ }++ // 2. Queue a global task on the gamepad task source with the relevant global object of this to resolve+ // effectPromise with "preempted".+ if let Some(effect_completion_steps) = effect_completion_steps {+ effect_completion_steps.run(vm, GamepadHapticsResult::Preempted);+ }++ // 4. Resolve resetResultPromise with "complete"+ reset_completion_steps.run(vm, GamepadHapticsResult::Complete);+ },+ );+ }++ // https://w3c.github.io/gamepad/#handling-visibility-change+ fn document_became_hidden(this: Ref<Self>, vm: &Vm) {+ // When the document's visibility state becomes "hidden", run these steps for each GamepadHapticActuator actuator:+ // 1. If actuator.[[playingEffectPromise]] is null, abort these steps.+ let playing_effect_completion_steps = this.playing_effect_completion_steps.borrow().clone();+ let Some(completion_steps) = playing_effect_completion_steps else {+ return;+ };++ // 2. Queue a global task on the gamepad task source with the relevant global object of actuator to run the+ // following steps:+ // 2. Resolve actuator.[[playingEffectPromise]] with "preempted".+ completion_steps.run(vm, GamepadHapticsResult::Preempted);++ // 3. Set actuator.[[playingEffectPromise]] to null.+ *this.playing_effect_completion_steps.borrow_mut(vm) = None;+ this.clear_playing_effect_timers(vm);++ // 3. Stop haptic effects on actuator.+ this.stop_haptic_effects();+ }++ // https://w3c.github.io/gamepad/#dfn-issue-a-haptic-effect+ fn issue_haptic_effect(this: Ref<Self>, vm: &Vm, r#type: GamepadHapticEffectType, params: GamepadEffectParameters) {+ // To issue a haptic effect on an actuator, the user agent MUST send a command to the device to render an effect+ // of type and try to make it use the provided params. The user agent SHOULD use the provided playEffectTimestamp+ // for more precise playback timing when params.startDelay is not 0.0. The user agent MAY modify the effect to+ // increase compatibility. For example, an effect intended for a rumble motor may be transformed into a+ // waveform-based effect for a device that supports waveform haptics but lacks rumble motors.+ let timer = CppTimer::create_single_shot(+ vm,+ params.start_delay,+ (this, r#type, params),+ |vm, (this, r#type, params)| {+ let (first_magnitude, second_magnitude) = gamepad_effect_magnitudes(r#type, ¶ms);+ this.play_gamepad_effect(+ r#type,+ magnitude_to_u16(first_magnitude),+ magnitude_to_u16(second_magnitude),+ u32::try_from(params.duration).expect("a valid duration fits in 32 bits"),+ );++ let timer = CppTimer::create_single_shot(vm, params.duration, (this, r#type), |vm, (this, r#type)| {+ // Explicitly stop the rumble before completing, ensuring the stop signal is sent synchronously.+ this.play_gamepad_effect(r#type, 0, 0, 0);+ Self::effect_completed(this, vm);+ });+ *this.playing_effect_timer.borrow_mut(vm) = Some(timer);+ },+ );+ *this.playing_effect_timer.borrow_mut(vm) = Some(timer);+ }++ fn play_gamepad_effect(+ &self,+ r#type: GamepadHapticEffectType,+ first_magnitude: u16,+ second_magnitude: u16,+ duration: u32,+ ) {+ // SAFETY: The Window is live.+ unsafe {+ web_gamepad_play_effect(+ self.window.as_ptr(),+ self.gamepad.handle(),+ r#type as u8,+ first_magnitude,+ second_magnitude,+ duration,+ );+ }+ }++ // https://w3c.github.io/gamepad/#dfn-stop-haptic-effects+ fn stop_haptic_effects(&self) {+ // To stop haptic effects on an actuator, the user agent MUST send a command to the device to abort any effects+ // currently being played. If a haptic effect was interrupted, the actuator SHOULD return to a motionless state+ // as quickly as possible.+ // SAFETY: The Window is live.+ unsafe { web_gamepad_stop_effects(self.window.as_ptr(), self.gamepad.handle()) };+ }++ fn clear_playing_effect_timers(&self, vm: &Vm) {+ if let Some(timer) = self.playing_effect_timer.borrow_mut(vm).take() {+ timer.stop();+ }+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/gamepad/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/gamepad/mod.rsnew file mode 100644index 00000000000..b890b259b12--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/gamepad/mod.rs@@ -0,0 +1,15 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The Gamepad API, https://w3c.github.io/gamepad/++pub(crate) mod exports;+#[allow(clippy::module_inception, reason = "the module mirrors the Gamepad interface file")]+pub(crate) mod gamepad;+pub(crate) mod gamepad_button;+pub(crate) mod gamepad_event;+pub(crate) mod gamepad_haptic_actuator;+pub(crate) mod navigator_gamepad;diff --git a/Libraries/LibWeb/Bindings/Rust/src/gamepad/navigator_gamepad.rs b/Libraries/LibWeb/Bindings/Rust/src/gamepad/navigator_gamepad.rsnew file mode 100644index 00000000000..2a28a576419--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/gamepad/navigator_gamepad.rs@@ -0,0 +1,354 @@+/*+ * Copyright (c) 2025, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2025, Luke Wilde <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The Navigator partial interface of the Gamepad API, https://w3c.github.io/gamepad/#extensions-to-the-navigator-interface++use core::cell::{Cell, RefCell};+use core::ffi::c_void;++use ak::Utf16String;+use libjs_rust::api::{EmbedderCell, EmbedderClass, EmbedderValue, Gc, GcRefCell, MarkedVec, Trace, Vm};++use crate::bindings::global_object::CppWindow;+use crate::bindings::interface::Ref;+use crate::bindings::promise::{TaskSource, queue_a_global_task};+use crate::bindings::realm_data::realm_data;+use crate::dom::document::CppDocument;+use crate::dom::event::EventInit;+use crate::gamepad::gamepad::{Gamepad, GamepadDescription, GamepadState, current_high_resolution_time};+use crate::gamepad::gamepad_event::{GamepadEvent, GamepadEventInit};+use crate::permissions_policy::permissions_policy::PolicyControlledFeature;++unsafe extern "C" {+ fn web_gamepad_did_start_using_gamepads(window: *mut c_void);+}++/// https://w3c.github.io/gamepad/#internal-slots+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct NavigatorGamepad {+ // https://w3c.github.io/gamepad/#dfn-hasgamepadgesture+ // A flag indicating that a gamepad user gesture has been observed+ has_gamepad_gesture: Cell<bool>,++ // https://w3c.github.io/gamepad/#dfn-gamepads+ // Each Gamepad present at the index specified by its index attribute, or null for unassigned indices.+ gamepads: GcRefCell<Vec<Option<Ref<Gamepad>>>>,++ // Non-standard attribute to know which gamepads are available to the system. This is used to prevent duplicate+ // connections for the same gamepad ID (e.g. if the navigator object is initialized and checks for connected gamepads+ // and also receives a gamepad connected event)+ #[gc(untraced)]+ available_gamepads: RefCell<Vec<u32>>,+}++static NAVIGATOR_GAMEPAD_CLASS: EmbedderClass<NavigatorGamepad> = EmbedderClass::new("NavigatorGamepad");++impl EmbedderValue for NavigatorGamepad {+ const CLASS: &'static EmbedderClass<Self> = &NAVIGATOR_GAMEPAD_CLASS;+}++pub(crate) type NavigatorGamepadRef = Gc<EmbedderCell<NavigatorGamepad>>;++pub(crate) fn navigator_gamepad(vm: &Vm, window: &CppWindow) -> NavigatorGamepadRef {+ let data = realm_data(vm, window.realm());+ if let Some(navigator) = data.navigator_gamepad.get() {+ return navigator;+ }+ let navigator = NAVIGATOR_GAMEPAD_CLASS.allocate(vm, |_| NavigatorGamepad {+ has_gamepad_gesture: Cell::new(false),+ gamepads: GcRefCell::default(),+ available_gamepads: RefCell::default(),+ });+ data.navigator_gamepad.set(Some(navigator));+ navigator+}++pub(crate) fn fire_a_gamepad_event(vm: &Vm, window: &CppWindow, event_name: &str, gamepad: Ref<Gamepad>) {+ let event_init = GamepadEventInit {+ parent: EventInit {+ bubbles: false,+ cancelable: false,+ composed: false,+ },+ gamepad: Some(gamepad),+ };+ let event = GamepadEvent::create(vm, window.realm(), &Utf16String::from_utf8(event_name), event_init);+ window.as_event_target().dispatch_event(event.event());+}++pub(crate) struct NotAllowedToUseGamepads;++impl NavigatorGamepad {+ pub(crate) fn has_gamepad_gesture(&self) -> bool {+ self.has_gamepad_gesture.get()+ }++ pub(crate) fn set_has_gamepad_gesture(&self, has_gamepad_gesture: bool) {+ self.has_gamepad_gesture.set(has_gamepad_gesture);+ }++ pub(crate) fn gamepads<'vm>(&self, vm: &'vm Vm) -> MarkedVec<'vm, Option<Ref<Gamepad>>> {+ let gamepads = MarkedVec::new(vm);+ gamepads.extend_from_slice(&self.gamepads.borrow());+ gamepads+ }+}++// https://w3c.github.io/gamepad/#dom-navigator-getgamepads+pub(crate) fn get_gamepads<'vm>(+ vm: &'vm Vm,+ navigator_window: &CppWindow,+ current_window: &CppWindow,+) -> Result<MarkedVec<'vm, Option<Ref<Gamepad>>>, NotAllowedToUseGamepads> {+ let navigator = navigator_gamepad(vm, navigator_window);++ // 1. Let doc be the current global object's associated Document.+ let document = current_window.associated_document();++ // 2. If doc is null or doc is not fully active, then return an empty list.+ let gamepads = MarkedVec::new(vm);+ if !document.is_fully_active() {+ return Ok(gamepads);+ }++ // 3. If doc is not allowed to use the "gamepad" permission, then throw a "SecurityError" DOMException and abort these steps.+ if !document.is_allowed_to_use_feature(PolicyControlledFeature::Gamepad) {+ return Err(NotAllowedToUseGamepads);+ }++ // AD-HOC: Tell the UI process that this process consumes gamepad input.+ // SAFETY: The Window is live.+ unsafe { web_gamepad_did_start_using_gamepads(current_window.as_ptr()) };++ // 4. If this.[[hasGamepadGesture]] is false, then return an empty list.+ if !navigator.has_gamepad_gesture.get() {+ return Ok(gamepads);+ }++ // 5. Let now be the current high resolution time given the current global object.+ let now = current_high_resolution_time(current_window);++ // 6. Let gamepads be an empty list.+ // NOTE: Already done.++ // 7. For each gamepad of this.[[gamepads]]:+ for gamepad in navigator.gamepads.borrow().iter().copied() {+ // 1. If gamepad is not null and gamepad.[[exposed]] is false:+ if let Some(gamepad) = gamepad+ && !gamepad.is_exposed()+ {+ // 1. Set gamepad.[[exposed]] to true.+ gamepad.set_exposed(true);++ // 2. Set gamepad.[[timestamp]] to now.+ gamepad.set_timestamp(now);+ }++ // 2. Append gamepad to gamepads.+ gamepads.push(gamepad);+ }++ // 8. Return gamepads.+ Ok(gamepads)+}++// https://w3c.github.io/gamepad/#dfn-selecting-an-unused-gamepad-index+pub(crate) fn select_an_unused_gamepad_index(vm: &Vm, navigator: &NavigatorGamepadRef) -> usize {+ let mut gamepads = navigator.gamepads.borrow_mut(vm);++ // 2. Let maxGamepadIndex be the size of navigator.[[gamepads]] − 1.+ // 3. For each gamepadIndex of the range from 0 to maxGamepadIndex:+ for (gamepad_index, gamepad) in gamepads.iter().enumerate() {+ // 1. If navigator.[[gamepads]][gamepadIndex] is null, then return gamepadIndex.+ if gamepad.is_none() {+ return gamepad_index;+ }+ }++ // 4. Append null to navigator.[[gamepads]].+ gamepads.push(None);++ // 5. Return the size of navigator.[[gamepads]] − 1.+ gamepads.len() - 1+}++#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+struct GamepadConnection {+ window: CppWindow,+ document: CppDocument,+ #[gc(untraced)]+ description: GamepadDescription,+}++// https://w3c.github.io/gamepad/#event-gamepadconnected+pub(crate) fn handle_gamepad_connected(vm: &Vm, window: &CppWindow, description: GamepadDescription) {+ let navigator = navigator_gamepad(vm, window);++ // When a gamepad becomes available on the system, run the following steps:+ if navigator.available_gamepads.borrow().contains(&description.handle) {+ return;+ }++ // 1. Let document be the current global object's associated Document; otherwise null.+ // FIXME: We can't use the current global object here, since it's not executing in a scripting context.+ // NOTE: NavigatorGamepad is only available on Window.+ // NOTE: document is never null.+ let global = window.realm().global_object();+ let document = window.associated_document();++ // 2. If document is not null and is not allowed to use the "gamepad" permission, then abort these steps.+ if !document.is_allowed_to_use_feature(PolicyControlledFeature::Gamepad) {+ return;+ }++ navigator.available_gamepads.borrow_mut().push(description.handle);++ // 3. Queue a global task on the gamepad task source with the current global object to perform the following steps:+ let connection = GamepadConnection {+ window: window.clone(),+ document,+ description,+ };+ queue_a_global_task(vm, global, TaskSource::Gamepad, connection, |vm, connection| {+ // 1. Let gamepad be a new Gamepad representing the gamepad.+ let gamepad = Gamepad::create(vm, &connection.window, connection.description);++ // 2. Let navigator be gamepad's relevant global object's Navigator object.+ let navigator = navigator_gamepad(vm, &connection.window);++ // 3. Set navigator.[[gamepads]][gamepad.index] to gamepad.+ navigator.gamepads.borrow_mut(vm)[gamepad.gamepad_index()] = Some(gamepad);++ // 4. If navigator.[[hasGamepadGesture]] is true:+ if navigator.has_gamepad_gesture.get() {+ // 1. Set gamepad.[[exposed]] to true.+ gamepad.set_exposed(true);++ // 2. If document is not null and is fully active, then fire an event named gamepadconnected at gamepad's+ // relevant global object using GamepadEvent with its gamepad attribute initialized to gamepad.+ if connection.document.is_fully_active() {+ fire_a_gamepad_event(vm, &connection.window, "gamepadconnected", gamepad);+ }+ }+ });+}++#[derive(Clone, Trace)]+#[gc(crate = libjs_rust)]+struct GamepadUpdate {+ window: CppWindow,+ #[gc(untraced)]+ state: GamepadState,+}++// https://w3c.github.io/gamepad/#dfn-receives-new-button-or-axis-input-values+pub(crate) fn handle_gamepad_updated(vm: &Vm, window: &CppWindow, state: GamepadState) {+ // When the system receives new button or axis input values, run the following steps:+ if !navigator_gamepad(vm, window)+ .available_gamepads+ .borrow()+ .contains(&state.handle)+ {+ return;+ }++ // 2. Queue a global task on the gamepad task source with gamepad's relevant global object to update gamepad state+ // for gamepad.+ // AD-HOC: Step 1 runs in the task. A newly available gamepad is created by an earlier task on the same task+ // source, so input received before that task has run still reaches the gamepad.+ let global = window.realm().global_object();+ let update = GamepadUpdate {+ window: window.clone(),+ state,+ };+ queue_a_global_task(vm, global, TaskSource::Gamepad, update, |vm, update| {+ // 1. Let gamepad be the Gamepad object representing the device that received new button or axis input values.+ let navigator = navigator_gamepad(vm, &update.window);+ let gamepad = navigator+ .gamepads+ .borrow()+ .iter()+ .flatten()+ .copied()+ .find(|gamepad| gamepad.handle() == update.state.handle);+ let Some(gamepad) = gamepad else {+ return;+ };++ gamepad.set_latest_state(update.state);+ Gamepad::update_gamepad_state(gamepad, vm);+ });+}++pub(crate) fn handle_gamepad_disconnected(vm: &Vm, window: &CppWindow, handle: u32) {+ // When a gamepad becomes unavailable on the system, run the following steps:+ let navigator = navigator_gamepad(vm, window);+ let was_available = {+ let mut available_gamepads = navigator.available_gamepads.borrow_mut();+ let position = available_gamepads+ .iter()+ .position(|available_gamepad| *available_gamepad == handle);+ position.map(|position| available_gamepads.remove(position)).is_some()+ };++ if !was_available {+ return;+ }++ // 2. Queue a global task on the gamepad task source with gamepad's relevant global object to perform the+ // following steps:+ // AD-HOC: Step 1 runs in the task. A newly available gamepad is created by an earlier task on the same task+ // source, so a gamepad that becomes unavailable before that task has run is still removed.+ let global = window.realm().global_object();+ queue_a_global_task(+ vm,+ global,+ TaskSource::Gamepad,+ (window.clone(), handle),+ |vm, (window, handle)| {+ // 1. Let gamepad be the Gamepad representing the unavailable device.+ let navigator = navigator_gamepad(vm, &window);+ let gamepad = navigator+ .gamepads+ .borrow()+ .iter()+ .flatten()+ .copied()+ .find(|gamepad| gamepad.handle() == handle);+ let Some(gamepad) = gamepad else {+ return;+ };++ // 1. Set gamepad.[[connected]] to false.+ gamepad.set_connected(false);++ // 2. Let document be gamepad's relevant global object's associated Document; otherwise null.+ let document = window.associated_document();++ // 3. If gamepad.[[exposed]] is true and document is not null and is fully active, then fire an event named+ // gamepaddisconnected at gamepad's relevant global object using GamepadEvent with its gamepad attribute+ // initialized to gamepad.+ if gamepad.is_exposed() && document.is_fully_active() {+ fire_a_gamepad_event(vm, &window, "gamepaddisconnected", gamepad);+ }++ // 4. Let navigator be gamepad's relevant global object's Navigator object.+ // 5. Set navigator.[[gamepads]][gamepad.index] to null.+ let mut gamepads = navigator.gamepads.borrow_mut(vm);+ gamepads[gamepad.gamepad_index()] = None;++ // 6. While navigator.[[gamepads]] is not empty and the last item of navigator.[[gamepads]] is null, remove the+ // last item of navigator.[[gamepads]].+ while gamepads.last().is_some_and(Option::is_none) {+ gamepads.pop();+ }+ },+ );+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rsindex e329dd6a6f1..9d80bc0f17e 100644--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs@@ -163,6 +163,16 @@ pub(crate) mod file_api;clippy::unnecessary_wraps,reason = "the bindings call every attribute and operation as one that can throw")]+pub(crate) mod gamepad;+#[cfg(not(test))]+#[cfg_attr(+ not(web_idl_bindings),+ allow(dead_code, reason = "only the generated bindings use the interfaces")+)]+#[allow(+ clippy::unnecessary_wraps,+ reason = "the bindings call every attribute and operation as one that can throw"+)]pub(crate) mod geolocation;#[cfg_attr(not(web_idl_bindings),diff --git a/Libraries/LibWeb/Bindings/Rust/src/permissions_policy/permissions_policy.rs b/Libraries/LibWeb/Bindings/Rust/src/permissions_policy/permissions_policy.rsindex fa147b52df1..f6f945fce7a 100644--- a/Libraries/LibWeb/Bindings/Rust/src/permissions_policy/permissions_policy.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/permissions_policy/permissions_policy.rs@@ -8,5 +8,6 @@#[derive(Clone, Copy)]#[repr(u8)]pub(crate) enum PolicyControlledFeature {+ Gamepad = 6,Geolocation = 7,}diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cppindex 6c23fdb20bb..c9b90ee36e9 100644--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp@@ -16,6 +16,7 @@#include <LibWeb/Bindings/Wrappable.h>#include <LibWeb/Bindings/WrapperWorld.h>#include <LibWeb/DOM/Document.h>+#include <LibWeb/DOM/DocumentObserver.h>#include <LibWeb/HTML/CrossOrigin/AbstractOperations.h>#include <LibWeb/HTML/CustomElements/CustomElementReactions.h>#include <LibWeb/HTML/EventLoop/EventLoop.h>@@ -121,6 +122,8 @@ bool web_bindings_document_is_allowed_to_use_feature(DOM::Document*, u8 feature)u8 web_bindings_document_visibility_state(DOM::Document*);void web_bindings_document_origin(DOM::Document*, void* origin, void (*on_origin)(void*, URL::FFI::FfiOrigin const*));bool web_bindings_document_has_focus(DOM::Document*);+bool web_bindings_document_is_fully_active_descendant_of_a_top_level_traversable_with_user_attention(DOM::Document*);+DOM::DocumentObserver* web_bindings_document_observe_visibility_state(DOM::Document*, GC::Cell*, void (*steps)(JSVM*, GC::Cell*, bool visible));bool web_bindings_document_has_been_destroyed(DOM::Document*);URL::FFI::RustUrl web_bindings_document_url(DOM::Document*);void web_bindings_document_load_timing_info(DOM::Document const*, DOM::DocumentLoadTimingInfo*);@@ -303,6 +306,20 @@ bool web_bindings_document_has_focus(DOM::Document* document)return document->has_focus();}+bool web_bindings_document_is_fully_active_descendant_of_a_top_level_traversable_with_user_attention(DOM::Document* document)+{+ return document->is_fully_active_descendant_of_a_top_level_traversable_with_user_attention();+}++DOM::DocumentObserver* web_bindings_document_observe_visibility_state(DOM::Document* document, GC::Cell* cell, void (*steps)(JSVM*, GC::Cell*, bool visible))+{+ auto observer = DOM::DocumentObserver::create(*document);+ observer->set_document_visibility_state_observer(GC::create_function(GC::Heap::the(), GC::captures(GC::Ref { *cell }, steps), [](auto& cell, auto& steps, HTML::VisibilityState state) {+ steps(JS::HostABI::vm_to_abi(JS::VM::the()), cell.ptr(), state == HTML::VisibilityState::Visible);+ }));+ return observer.ptr();+}+bool web_bindings_document_has_been_destroyed(DOM::Document* document){return document->has_been_destroyed();diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex dfd374d51a1..89ae7a8f0fa 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -321,10 +321,6 @@ set(SOURCESFileAPI/File.cppFileAPI/FileList.cppGamepad/EventNames.cpp- Gamepad/Gamepad.cpp- Gamepad/GamepadButton.cpp- Gamepad/GamepadEvent.cpp- Gamepad/GamepadHapticActuator.cppGamepad/GamepadRegistry.cppGamepad/NavigatorGamepad.cppGeolocation/Geolocation.cppdiff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.hindex cd456594806..b72f34ee1ed 100644--- a/Libraries/LibWeb/Forward.h+++ b/Libraries/LibWeb/Forward.h@@ -619,9 +619,6 @@ namespace Web::Gamepad {class NavigatorGamepadPartial;class Gamepad;-class GamepadButton;-class GamepadEvent;-class GamepadHapticActuator;}diff --git a/Libraries/LibWeb/Gamepad/Gamepad.cpp b/Libraries/LibWeb/Gamepad/Gamepad.cppdeleted file mode 100644index 387c18faa0b..00000000000--- a/Libraries/LibWeb/Gamepad/Gamepad.cpp+++ /dev/null@@ -1,423 +0,0 @@-/*- * Copyright (c) 2025, Jelle Raaijmakers <[email protected]>- * Copyright (c) 2025, Luke Wilde <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibWeb/DOM/Document.h>-#include <LibWeb/Gamepad/EventNames.h>-#include <LibWeb/Gamepad/Gamepad.h>-#include <LibWeb/Gamepad/GamepadButton.h>-#include <LibWeb/Gamepad/GamepadEvent.h>-#include <LibWeb/Gamepad/GamepadHapticActuator.h>-#include <LibWeb/HTML/Navigator.h>-#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-a-new-gamepad-GC::Ref<Gamepad> Gamepad::create(HTML::Window& window, GamepadDescription const& description)-{- // 1. Let gamepad be a newly created Gamepad instance:- auto gamepad = GC::Heap::the().allocate<Gamepad>(window, description);-- // 1. Initialize gamepad's id attribute to an identification string for the gamepad.- gamepad->m_id = Utf16String::from_utf8(description.id);-- // 2. Initialize gamepad's index attribute to the result of selecting an unused gamepad index for gamepad.- // https://w3c.github.io/gamepad/#dfn-selecting-an-unused-gamepad-index- // 1. Let navigator be gamepad's relevant global object's Navigator object.- // The rest of the steps are implemented in NavigatorGamepad.- // NOTE: Gamepad is only exposed on Window.- gamepad->m_index = window.navigator()->select_an_unused_gamepad_index({});-- // 3. Initialize gamepad's mapping attribute to the result of selecting a mapping for the gamepad device.- gamepad->select_a_mapping();-- // 4. Set gamepad.[[connected]] to true.- gamepad->m_connected = true;-- // 5. Set gamepad.[[timestamp]] to the current high resolution time given gamepad's relevant global object.- gamepad->m_timestamp = HighResolutionTime::current_high_resolution_time(window.principal_realm().global_object());-- // 6. Set gamepad.[[axes]] to the result of initializing axes for gamepad.- gamepad->initialize_axes();-- // 7. Set gamepad.[[buttons]] to the result of initializing buttons for gamepad.- gamepad->initialize_buttons();-- // 8. Set gamepad.[[vibrationActuator]] to the result of constructing a GamepadHapticActuator for gamepad.- gamepad->m_vibration_actuator = GamepadHapticActuator::create(window, gamepad);-- // 2. Return gamepad.- return gamepad;-}--Gamepad::Gamepad(HTML::Window& window, GamepadDescription const& description)- : m_window(window)- , m_description(description)-{-}--void Gamepad::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_buttons);- visitor.visit(m_vibration_actuator);- visitor.visit(m_window);-}--// https://w3c.github.io/gamepad/#dfn-initializing-axes-void Gamepad::initialize_axes()-{- // 1. Let inputCount be the number of axis inputs exposed by the device represented by gamepad.- auto const& inputs = m_description.axes;-- // 2. Set gamepad.[[axisMinimums]] to a list of unsigned long values with size equal to inputCount containing minimum logical values for each of the axis inputs.- // 3. Set gamepad.[[axisMaximums]] to a list of unsigned long values with size equal to inputCount containing maximum logical values for each of the axis inputs.- for (auto const& input : inputs) {- m_axis_minimums.append(input.logical_minimum);- m_axis_maximums.append(input.logical_maximum);- }-- // 4. Let unmappedInputList be an empty list.- Vector<size_t> unmapped_input_list;-- // 5. Let mappedIndexList be an empty list.- Vector<size_t> mapped_index_list;-- // 6. Let axesSize be 0.- size_t axes_size = 0;-- // 7. For each rawInputIndex of the range from 0 to inputCount − 1:- for (size_t raw_input_index = 0; raw_input_index < inputs.size(); ++raw_input_index) {- // 1. If the gamepad axis at index rawInputIndex represents a Standard Gamepad axis:- if (auto maybe_index = inputs[raw_input_index].canonical_index; maybe_index.has_value()) {- // 1. Let canonicalIndex be the canonical index for the axis.- size_t canonical_index = maybe_index.value();-- // 2. If mappedIndexList contains canonicalIndex, then append rawInputIndex to unmappedInputList.- if (mapped_index_list.contains_slow(canonical_index)) {- unmapped_input_list.append(raw_input_index);- } else {- // Otherwise:- // 1. Set gamepad.[[axisMapping]][rawInputIndex] to canonicalIndex.- m_axis_mapping.set(raw_input_index, canonical_index);-- // 2. Append canonicalIndex to mappedIndexList.- mapped_index_list.append(canonical_index);-- // 3. If canonicalIndex + 1 is greater than axesSize, then set axesSize to canonicalIndex + 1.- if (canonical_index + 1 > axes_size)- axes_size = canonical_index + 1;- }- } else {- // Otherwise, append rawInputIndex to unmappedInputList.- unmapped_input_list.append(raw_input_index);- }- }-- // 8. Let axisIndex be 0.- size_t axis_index = 0;-- // 9. For each rawInputIndex of unmappedInputList:- for (size_t raw_input_index : unmapped_input_list) {- // 1. While mappedIndexList contains axisIndex:- while (mapped_index_list.contains_slow(axis_index)) {- // 1. Increment axisIndex.- ++axis_index;- }-- // 2. Set gamepad.[[axisMapping]][rawInputIndex] to axisIndex.- m_axis_mapping.set(raw_input_index, axis_index);-- // 3. Append axisIndex to mappedIndexList.- mapped_index_list.append(axis_index);-- // 4. If axisIndex + 1 is greater than axesSize, then set axesSize to axisIndex + 1.- if (axis_index + 1 > axes_size)- axes_size = axis_index + 1;- }-- // NOTE: Instead of returning a list, we can just directly update m_axes.- // 10. Let axes be an empty list.- // 11. For each axisIndex of the range from 0 to axesSize − 1, append 0 to axes.- // 12. Return axes.- for (size_t final_axis_index = 0; final_axis_index < axes_size; ++final_axis_index)- m_axes.append(0.0);-}--// https://w3c.github.io/gamepad/#dfn-initializing-buttons-void Gamepad::initialize_buttons()-{- // 1. Let inputCount be the number of button inputs exposed by the device represented by gamepad.- auto const& inputs = m_description.buttons;-- // 2. Set gamepad.[[buttonMinimums]] to be a list of unsigned long values with size equal to inputCount containing minimum logical values for each of the button inputs.- // 3. Set gamepad.[[buttonMaximums]] to be a list of unsigned long values with size equal to inputCount containing maximum logical values for each of the button inputs.- for (auto const& input : inputs) {- m_button_minimums.append(input.logical_minimum);- m_button_maximums.append(input.logical_maximum);- }-- // 4. Let unmappedInputList be an empty list.- Vector<size_t> unmapped_input_list;-- // 5. Let mappedIndexList be an empty list.- Vector<size_t> mapped_index_list;-- // 6. Let buttonsSize be 0.- size_t buttons_size = 0;-- // 7. For each rawInputIndex of the range from 0 to inputCount − 1:- for (size_t raw_input_index = 0; raw_input_index < inputs.size(); ++raw_input_index) {- // 1. If the gamepad button at index rawInputIndex represents a Standard Gamepad button:- if (auto maybe_index = inputs[raw_input_index].canonical_index; maybe_index.has_value()) {- // 1. Let canonicalIndex be the canonical index for the button.- size_t canonical_index = maybe_index.value();-- // 2. If mappedIndexList contains canonicalIndex, then append rawInputIndex to unmappedInputList.- if (mapped_index_list.contains_slow(canonical_index)) {- unmapped_input_list.append(raw_input_index);- } else {- // Otherwise:- // 1. Set gamepad.[[buttonMapping]][rawInputIndex] to canonicalIndex.- m_button_mapping.set(raw_input_index, canonical_index);-- // 2. Append canonicalIndex to mappedIndexList.- mapped_index_list.append(canonical_index);-- // 3. If canonicalIndex + 1 is greater than buttonsSize, then set buttonsSize to canonicalIndex + 1.- if (canonical_index + 1 > buttons_size)- buttons_size = canonical_index + 1;- }- } else {- // Otherwise, append rawInputIndex to unmappedInputList.- unmapped_input_list.append(raw_input_index);- }-- // 2. Increment rawInputIndex.- }-- // 8. Let buttonIndex be 0.- size_t button_index = 0;-- // 9. For each rawInputIndex of unmappedInputList:- for (size_t raw_input_index : unmapped_input_list) {- // 1. While mappedIndexList contains buttonIndex:- while (mapped_index_list.contains_slow(button_index)) {- // 1. Increment buttonIndex.- ++button_index;- }-- // 2. Set gamepad.[[buttonMapping]][rawInputIndex] to buttonIndex.- m_button_mapping.set(raw_input_index, button_index);-- // 3. Append buttonIndex to mappedIndexList.- mapped_index_list.append(button_index);-- // 4. If buttonIndex + 1 is greater than buttonsSize, then set buttonsSize to buttonIndex + 1.- if (button_index + 1 > buttons_size)- buttons_size = button_index + 1;- }-- // NOTE: Instead of returning a list (and thus needing to use RootVector), we can just directly update m_buttons.- // 10. Let buttons be an empty list.- // 11. For each buttonIndex of the range from 0 to buttonsSize − 1, append a new GamepadButton to buttons.- // 12. Return buttons.- for (size_t final_button_index = 0; final_button_index < buttons_size; ++final_button_index) {- auto gamepad_button = GamepadButton::create();- m_buttons.append(gamepad_button);- }-}--GC::Ref<GamepadHapticActuator> Gamepad::vibration_actuator() const-{- VERIFY(m_vibration_actuator);- return *m_vibration_actuator;-}--void Gamepad::set_connected(Badge<NavigatorGamepadPartial>, bool value)-{- m_connected = value;-}--void Gamepad::set_exposed(Badge<NavigatorGamepadPartial>, bool value)-{- m_exposed = value;-}--void Gamepad::set_timestamp(Badge<NavigatorGamepadPartial>, HighResolutionTime::DOMHighResTimeStamp value)-{- m_timestamp = value;-}--void Gamepad::set_latest_state(Badge<NavigatorGamepadPartial>, GamepadState state)-{- m_latest_state = move(state);-}--// https://w3c.github.io/gamepad/#dfn-selecting-a-mapping-void Gamepad::select_a_mapping()-{- // 1. If the button and axis layout of the gamepad device corresponds with the Standard Gamepad layout, then- // return "standard".- // 2. Return "".- // NB: The UI process performs this check when it builds the description.- m_mapping = m_description.has_standard_mapping ? GamepadMappingType::Standard : GamepadMappingType::Empty;-}--// https://w3c.github.io/gamepad/#dfn-map-and-normalize-axes-void Gamepad::map_and_normalize_axes()-{- // 1. Let axisValues be a list of unsigned long values representing the most recent logical axis input values for- // each axis input of the device represented by gamepad.- // NOTE: While the Gamepad API internally uses u32 to represent raw axis values, SDL uses i16 for axes.- auto const& axis_values = m_latest_state.axis_values;-- // 2. Let maxRawAxisIndex be the size of axisValues − 1.- // 3. For each rawAxisIndex of the range from 0 to maxRawAxisIndex:- for (size_t raw_axis_index = 0; raw_axis_index < min(axis_values.size(), m_axis_minimums.size()); ++raw_axis_index) {- // 1. Let mappedIndex be gamepad.[[axisMapping]][rawAxisIndex].- auto mapped_index = m_axis_mapping.get(raw_axis_index).value();-- // 2. Let logicalValue be axisValues[rawAxisIndex].- auto logical_value = axis_values[raw_axis_index];-- // 3. Let logicalMinimum be gamepad.[[axisMinimums]][rawAxisIndex].- auto logical_minimum = m_axis_minimums[raw_axis_index];-- // 4. Let logicalMaximum be gamepad.[[axisMaximums]][rawAxisIndex].- auto logical_maximum = m_axis_maximums[raw_axis_index];-- // 5. Let normalizedValue be 2 (logicalValue − logicalMinimum) / (logicalMaximum − logicalMinimum) − 1.- 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.- m_axes[mapped_index] = normalized_value;- }-}--// https://w3c.github.io/gamepad/#dfn-map-and-normalize-buttons-void Gamepad::map_and_normalize_buttons()-{- // 1. Let buttonValues be a list of unsigned long values representing the most recent logical button input values- // for each button input of the device represented by gamepad.- // NOTE: While the Gamepad API internally uses u32 to represent raw button values, SDL uses bool for buttons and- // i16 for axes. The left and right triggers are buttons in the Gamepad API.- auto const& button_values = m_latest_state.button_values;-- // 2. Let maxRawButtonIndex be the size of buttonValues − 1.- // 3. For each rawButtonIndex of the range from 0 to maxRawButtonIndex:- for (size_t raw_button_index = 0; raw_button_index < min(button_values.size(), m_button_minimums.size()); ++raw_button_index) {- // 1. Let mappedIndex be gamepad.[[buttonMapping]][rawButtonIndex].- auto mapped_index = m_button_mapping.get(raw_button_index).value();-- // 2. Let logicalValue be buttonValues[rawButtonIndex].- auto logical_value = button_values[raw_button_index];-- // 3. Let logicalMinimum be gamepad.[[buttonMinimums]][rawButtonIndex].- auto logical_minimum = m_button_minimums[raw_button_index];-- // 4. Let logicalMaximum be gamepad.[[buttonMaximums]][rawButtonIndex].- auto logical_maximum = m_button_maximums[raw_button_index];-- // 5. Let normalizedValue be (logicalValue − logicalMinimum) / (logicalMaximum − logicalMinimum).- double value = normalize_button_value(logical_value, logical_minimum, logical_maximum);-- // 6. Let button be gamepad.[[buttons]][mappedIndex].- auto button = m_buttons[mapped_index];-- // 7. Set button.[[value]] to normalizedValue.- button->set_value({}, value);-- // 8. If the button has a digital switch to indicate a pure pressed or released state, set button.[[pressed]]- // 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.- 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]].- // FIXME: Support the PS4/PS5 controller which has a touchpad, which is a button that can be touched and not pressed in at the same time.- button->set_touched({}, button->pressed());- }-}--// https://w3c.github.io/gamepad/#dfn-update-gamepad-state-void Gamepad::update_gamepad_state(Badge<NavigatorGamepadPartial>)-{- auto& realm = m_window->principal_realm();-- // 1. Let now be the current high resolution time given gamepad's relevant global object.- auto now = HighResolutionTime::current_high_resolution_time(m_window->principal_realm().global_object());- auto& window = *m_window;-- // 2. Set gamepad.[[timestamp]] to now.- m_timestamp = now;-- // 3. Run the steps to map and normalize axes for gamepad.- map_and_normalize_axes();-- // 4. Run the steps to map and normalize buttons for gamepad.- map_and_normalize_buttons();-- // FIXME: 5. Run the steps to record touches for gamepad.-- // 6. Let navigator be gamepad's relevant global object's Navigator object.- auto navigator = window.navigator();-- // 7. Let document be gamepad's relevant global object's associated Document; otherwise null.- // 8. If document is null, abort these steps.- // 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()) {- // 1. Set navigator.[[hasGamepadGesture]] to true.- navigator->set_has_gamepad_gesture({}, true);-- // 2. For each connectedGamepad of navigator.[[gamepads]]:- for (auto connected_gamepad : navigator->gamepads({})) {- // 1. If connectedGamepad is not equal to null:- if (connected_gamepad) {- // 1. Set connectedGamepad.[[exposed]] to true.- connected_gamepad->m_exposed = true;-- // 2. Set connectedGamepad.[[timestamp]] to now.- connected_gamepad->m_timestamp = now;-- // 3. If document is not null and is fully active, then queue a global task on the gamepad task source- // to fire an event named gamepadconnected at gamepad's relevant global object using GamepadEvent- // with its gamepad attribute initialized to connectedGamepad.- if (document.is_fully_active()) {- GamepadEventInit gamepad_connected_event_init { {}, connected_gamepad };- auto gamepad_connected_event = GamepadEvent::create(EventNames::gamepadconnected, gamepad_connected_event_init, HighResolutionTime::current_high_resolution_time(realm.global_object()));- window.dispatch_event(gamepad_connected_event);- }- }- }- }-}--// https://w3c.github.io/gamepad/#dfn-gamepad-user-gesture-bool Gamepad::contains_gamepad_user_gesture()-{- // 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/Gamepad/Gamepad.h b/Libraries/LibWeb/Gamepad/Gamepad.hindex 60a7caef437..9b5f7739e58 100644--- a/Libraries/LibWeb/Gamepad/Gamepad.h+++ b/Libraries/LibWeb/Gamepad/Gamepad.h@@ -1,6 +1,7 @@/** Copyright (c) 2025, Jelle Raaijmakers <[email protected]>* Copyright (c) 2025, Luke Wilde <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/@@ -8,153 +9,12 @@#pragma once#include <LibWeb/Bindings/Gamepad.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWebCommon/Gamepad/GamepadSnapshot.h>-#include <LibWebCommon/HighResolutionTime/DOMHighResTimeStamp.h>+#include <LibWeb/Bindings/RustInterface.h>namespace Web::Gamepad {-using GamepadMappingType = Bindings::GamepadMappingType;--// https://w3c.github.io/gamepad/#dom-gamepad-class Gamepad final : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(Gamepad, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(Gamepad);--public:- static GC::Ref<Gamepad> create(HTML::Window&, GamepadDescription const&);-- GamepadHandle handle() const { return m_description.handle; }- GamepadDescription const& description() const { return m_description; }-- Utf16String const& id() const { return m_id; }-- HTML::Window& window() const { return m_window; }-- size_t index() const { return m_index; }-- bool connected() const { return m_connected; }- void set_connected(Badge<NavigatorGamepadPartial>, bool);-- HighResolutionTime::DOMHighResTimeStamp timestamp() const { return m_timestamp; }- void set_timestamp(Badge<NavigatorGamepadPartial>, HighResolutionTime::DOMHighResTimeStamp);-- bool exposed() const { return m_exposed; }- void set_exposed(Badge<NavigatorGamepadPartial>, bool);-- GamepadMappingType mapping() const { return m_mapping; }-- Vector<double> const& axes() const { return m_axes; }- ReadonlySpan<GC::Ref<GamepadButton>> buttons() const { return m_buttons; }-- GC::Ref<GamepadHapticActuator> vibration_actuator() const;-- void set_latest_state(Badge<NavigatorGamepadPartial>, GamepadState);- void update_gamepad_state(Badge<NavigatorGamepadPartial>);--private:- explicit Gamepad(HTML::Window&, GamepadDescription const&);-- virtual void visit_edges(GC::Cell::Visitor&) override;-- void select_a_mapping();- void initialize_axes();- void initialize_buttons();-- void map_and_normalize_axes();- void map_and_normalize_buttons();-- bool contains_gamepad_user_gesture();-- // https://w3c.github.io/gamepad/#dom-gamepad-id- // An identification string for the gamepad. This string identifies the brand or style of connected gamepad device.- // The exact format of the id string is left unspecified. It is RECOMMENDED that the user agent select a string- // that identifies the product without uniquely identifying the device. For example, a USB gamepad may be- // identified by its idVendor and idProduct values. Unique identifiers like serial numbers or Bluetooth device- // addresses MUST NOT be included in the id string.- Utf16String m_id;-- // https://w3c.github.io/gamepad/#dom-gamepad-index- // The index of the gamepad in the Navigator. When multiple gamepads are connected to a user agent, indices MUST be- // assigned on a first-come, first-serve basis, starting at zero. If a gamepad is disconnected, previously assigned- // indices MUST NOT be reassigned to gamepads that continue to be connected. However, if a gamepad is disconnected,- // and subsequently the same or a different gamepad is then connected, the lowest previously used index MUST be- // reused.- size_t m_index { 0 };-- // https://w3c.github.io/gamepad/#dfn-connected- // A flag indicating that the device is connected to the system- bool m_connected { false };-- // https://w3c.github.io/gamepad/#dfn-timestamp- // The last time data for this Gamepad was updated- HighResolutionTime::DOMHighResTimeStamp m_timestamp { 0.0 };-- // https://w3c.github.io/gamepad/#dfn-axes- // A sequence of double values representing the current state of axes exposed by this device.- // https://w3c.github.io/gamepad/#dom-gamepad-axes- // Array of values for all axes of the gamepad. All axis values MUST be linearly normalized to the range [-1 .. 1].- // If the controller is perpendicular to the ground with the directional stick pointing up, -1 SHOULD correspond to- // "forward" or "left", and 1 SHOULD correspond to "backward" or "right". Axes that are drawn from a 2D input- // device SHOULD appear next to each other in the axes array, X then Y. It is RECOMMENDED that axes appear in- // decreasing order of importance, such that element 0 and 1 typically represent the X and Y axis of a directional- // stick. The same object MUST be returned until the user agent needs to return different values (or values in a- // different order).- // FIXME: Our current FrozenArray implementation only supports returning new objects everytime.- Vector<double> m_axes;-- // https://w3c.github.io/gamepad/#dfn-axismapping- // Mapping from unmapped axis index to an index in the axes array- HashMap<size_t, size_t> m_axis_mapping;-- // https://w3c.github.io/gamepad/#dfn-axisminimums- // A list containing the minimum logical value for each axis- // NOTE: While the Gamepad API internally uses u32 to represent raw axis values, SDL uses i16 for axes.- Vector<i16> m_axis_minimums;-- // https://w3c.github.io/gamepad/#dfn-axismaximums- // A list containing the maximum logical value for each axis- // NOTE: While the Gamepad API internally uses u32 to represent raw axis values, SDL uses i16 for axes.- Vector<i16> m_axis_maximums;-- // https://w3c.github.io/gamepad/#dfn-buttons- // A sequence of GamepadButton objects representing the current state of buttons exposed by this device- // Array of button states for all buttons of the gamepad. It is RECOMMENDED that buttons appear in decreasing- // importance such that the primary button, secondary button, tertiary button, and so on appear as elements 0, 1,- // 2, ... in the buttons array. The same object MUST be returned until the user agent needs to return different- // values (or values in a different order).- // FIXME: Our current FrozenArray implementation only supports returning new objects everytime.- Vector<GC::Ref<GamepadButton>> m_buttons;-- // https://w3c.github.io/gamepad/#dfn-buttonmapping- // Mapping from unmapped button index to an index in the buttons array- HashMap<size_t, size_t> m_button_mapping;-- // https://w3c.github.io/gamepad/#dfn-buttonminimums- // A list containing the minimum logical value for each button.- // NOTE: While the Gamepad API internally uses u32 to represent raw button values, SDL uses bool for buttons and- // i16 for axes. The left and right triggers are buttons in the Gamepad API.- Vector<i16> m_button_minimums;-- // https://w3c.github.io/gamepad/#dfn-buttonmaximums- // A list containing the maximum logical value for each button- Vector<i16> m_button_maximums;-- // https://w3c.github.io/gamepad/#dfn-exposed- // A flag indicating that the Gamepad object has been exposed to script- bool m_exposed { false };-- // https://w3c.github.io/gamepad/#dfn-vibrationactuator- GC::Ptr<GamepadHapticActuator> m_vibration_actuator;-- // https://w3c.github.io/gamepad/#dom-gamepad-mapping- // The mapping in use for this device. If the user agent has knowledge of the layout of the device, then it SHOULD- // indicate that a mapping is in use by setting mapping to the corresponding GamepadMappingType value.- GamepadMappingType m_mapping { GamepadMappingType::Standard };-- GC::Ref<HTML::Window> m_window;- GamepadDescription m_description;- GamepadState m_latest_state;+class Gamepad : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(Gamepad, gamepad)};}diff --git a/Libraries/LibWeb/Gamepad/Gamepad.idl b/Libraries/LibWeb/Gamepad/Gamepad.idlindex 517746ee4a2..f35a42151e9 100644--- a/Libraries/LibWeb/Gamepad/Gamepad.idl+++ b/Libraries/LibWeb/Gamepad/Gamepad.idl@@ -6,7 +6,7 @@ enum GamepadMappingType {};// https://w3c.github.io/gamepad/#dom-gamepad-[Exposed=Window]+[Exposed=Window, ImplementedIn=Rust]interface Gamepad {readonly attribute DOMString id;readonly attribute long index;diff --git a/Libraries/LibWeb/Gamepad/GamepadButton.cpp b/Libraries/LibWeb/Gamepad/GamepadButton.cppdeleted file mode 100644index beeca6d0938..00000000000--- a/Libraries/LibWeb/Gamepad/GamepadButton.cpp+++ /dev/null@@ -1,40 +0,0 @@-/*- * Copyright (c) 2025, Luke Wilde <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibWeb/Gamepad/GamepadButton.h>--namespace Web::Gamepad {--GC_DEFINE_ALLOCATOR(GamepadButton);--GC::Ref<GamepadButton> GamepadButton::create()-{- return GC::Heap::the().allocate<GamepadButton>();-}--GamepadButton::GamepadButton()-{-}--GamepadButton::~GamepadButton() = default;--void GamepadButton::set_pressed(Badge<Gamepad>, bool value)-{- m_pressed = value;-}--void GamepadButton::set_touched(Badge<Gamepad>, bool value)-{- m_touched = value;-}--void GamepadButton::set_value(Badge<Gamepad>, double value)-{- m_value = value;-}--}diff --git a/Libraries/LibWeb/Gamepad/GamepadButton.h b/Libraries/LibWeb/Gamepad/GamepadButton.hdeleted file mode 100644index a9823100795..00000000000--- a/Libraries/LibWeb/Gamepad/GamepadButton.h+++ /dev/null@@ -1,49 +0,0 @@-/*- * Copyright (c) 2025, Luke Wilde <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Badge.h>-#include <LibWeb/Bindings/Wrappable.h>--namespace Web::Gamepad {--class Gamepad;--class GamepadButton final : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(GamepadButton, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(GamepadButton);--public:- static GC::Ref<GamepadButton> create();-- virtual ~GamepadButton() override;-- bool pressed() const { return m_pressed; }- bool touched() const { return m_touched; }- double value() const { return m_value; }-- void set_pressed(Badge<Gamepad>, bool);- void set_touched(Badge<Gamepad>, bool);- void set_value(Badge<Gamepad>, double);--private:- GamepadButton();-- // https://w3c.github.io/gamepad/#dfn-pressed- // A flag indicating that the button is pressed- bool m_pressed { false };-- // https://w3c.github.io/gamepad/#dfn-touched- // A flag indicating that the button is touched- bool m_touched { false };-- // https://w3c.github.io/gamepad/#dfn-value- // A double representing the button value scaled to the range [0 .. 1]- double m_value { 0.0 };-};--}diff --git a/Libraries/LibWeb/Gamepad/GamepadButton.idl b/Libraries/LibWeb/Gamepad/GamepadButton.idlindex c8ac8f2ee7c..f6ec6438b69 100644--- a/Libraries/LibWeb/Gamepad/GamepadButton.idl+++ b/Libraries/LibWeb/Gamepad/GamepadButton.idl@@ -1,5 +1,5 @@// https://w3c.github.io/gamepad/#dom-gamepadbutton-[Exposed=Window]+[Exposed=Window, ImplementedIn=Rust]interface GamepadButton {readonly attribute boolean pressed;readonly attribute boolean touched;diff --git a/Libraries/LibWeb/Gamepad/GamepadEvent.cpp b/Libraries/LibWeb/Gamepad/GamepadEvent.cppdeleted file mode 100644index 3a8f4c3a3e0..00000000000--- a/Libraries/LibWeb/Gamepad/GamepadEvent.cpp+++ /dev/null@@ -1,34 +0,0 @@-/*- * Copyright (c) 2025, Luke Wilde <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibWeb/Gamepad/Gamepad.h>-#include <LibWeb/Gamepad/GamepadEvent.h>--namespace Web::Gamepad {--GC_DEFINE_ALLOCATOR(GamepadEvent);--GC::Ref<GamepadEvent> GamepadEvent::create(Utf16FlyString const& event_name, GamepadEventInit const& gamepad_event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)-{- return GC::Heap::the().allocate<GamepadEvent>(event_name, gamepad_event_init, time_stamp);-}--GamepadEvent::GamepadEvent(Utf16FlyString const& event_name, GamepadEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)- : DOM::Event(event_name, event_init, time_stamp)- , m_gamepad(event_init.gamepad)-{-}--GamepadEvent::~GamepadEvent() = default;--void GamepadEvent::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_gamepad);-}--}diff --git a/Libraries/LibWeb/Gamepad/GamepadEvent.h b/Libraries/LibWeb/Gamepad/GamepadEvent.hdeleted file mode 100644index 319984c8239..00000000000--- a/Libraries/LibWeb/Gamepad/GamepadEvent.h+++ /dev/null@@ -1,45 +0,0 @@-/*- * Copyright (c) 2025, Luke Wilde <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibJS/Forward.h>-#include <LibWeb/Bindings/GamepadEvent.h>-#include <LibWeb/DOM/Event.h>-#include <LibWebCommon/HighResolutionTime/DOMHighResTimeStamp.h>--namespace Web::HTML {--class Window;--}--namespace Web::Gamepad {--class Gamepad;--using GamepadEventInit = Bindings::GamepadEventInit;--class GamepadEvent final : public DOM::Event {- WEB_WRAPPABLE(GamepadEvent, DOM::Event);- GC_DECLARE_ALLOCATOR(GamepadEvent);--public:- [[nodiscard]] static GC::Ref<GamepadEvent> create(Utf16FlyString const& event_name, GamepadEventInit const&, HighResolutionTime::DOMHighResTimeStamp);-- virtual ~GamepadEvent() override;-- GC::Ptr<Gamepad> gamepad() const { return m_gamepad; }- static constexpr size_t gamepad_offset() { return offsetof(GamepadEvent, m_gamepad); }--private:- GamepadEvent(Utf16FlyString const& event_name, GamepadEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp);- virtual void visit_edges(GC::Cell::Visitor&) override;-- GC::Ptr<Gamepad> m_gamepad;-};--}diff --git a/Libraries/LibWeb/Gamepad/GamepadEvent.idl b/Libraries/LibWeb/Gamepad/GamepadEvent.idlindex 7c95aff3144..b2164f23fac 100644--- a/Libraries/LibWeb/Gamepad/GamepadEvent.idl+++ b/Libraries/LibWeb/Gamepad/GamepadEvent.idl@@ -1,10 +1,10 @@// https://w3c.github.io/gamepad/#dom-gamepadevent-[Exposed=Window]+[Exposed=Window, ImplementedIn=Rust]interface GamepadEvent : Event {// eventInitDict is not marked as optional in the specification, but existing implementations treat it as optional.// See: https://github.com/w3c/gamepad/pull/217constructor(DOMString type, optional GamepadEventInit eventInitDict = {});- [DirectGetter, SameObject] readonly attribute Gamepad? gamepad;+ [SameObject] readonly attribute Gamepad? gamepad;};// https://w3c.github.io/gamepad/#dom-gamepadeventinitdiff --git a/Libraries/LibWeb/Gamepad/GamepadHapticActuator.cpp b/Libraries/LibWeb/Gamepad/GamepadHapticActuator.cppdeleted file mode 100644index 421870e87d4..00000000000--- a/Libraries/LibWeb/Gamepad/GamepadHapticActuator.cpp+++ /dev/null@@ -1,386 +0,0 @@-/*- * Copyright (c) 2025, Luke Wilde <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibJS/Runtime/Error.h>-#include <LibJS/Runtime/PrimitiveString.h>-#include <LibWeb/DOM/Document.h>-#include <LibWeb/DOM/DocumentObserver.h>-#include <LibWeb/Gamepad/Gamepad.h>-#include <LibWeb/Gamepad/GamepadHapticActuator.h>-#include <LibWeb/HTML/EventLoop/EventLoop.h>-#include <LibWeb/HTML/EventLoop/Task.h>-#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>-#include <LibWeb/HTML/Window.h>-#include <LibWeb/Page/Page.h>-#include <LibWeb/Platform/EventLoopPlugin.h>-#include <LibWeb/Platform/Timer.h>-#include <LibWeb/WebIDL/DOMException.h>-#include <LibWeb/WebIDL/Promise.h>--namespace Web::Gamepad {--GC_DEFINE_ALLOCATOR(GamepadHapticActuator);--static void resolve_haptics_promise(WebIDL::Promise const& promise, GamepadHapticsResult result)-{- auto& realm = WebIDL::promise_realm(promise);- HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };-- auto result_string = JS::PrimitiveString::create(realm.vm(), Bindings::idl_enum_to_string(result));- WebIDL::resolve_promise(promise, result_string);-}--static GC::Ref<GamepadHapticsCompletionSteps> create_queued_haptics_completion_steps(JS::Object& global, GC::Ref<WebIDL::Promise> promise)-{- return GC::create_function(GC::Heap::the(), GC::captures(global, promise), [](auto& global, auto& promise, GamepadHapticsResult result) {- HTML::queue_global_task(HTML::Task::Source::Gamepad, global, GC::create_function(GC::Heap::the(), GC::captures(promise, result), [](auto& promise, auto& result) {- resolve_haptics_promise(promise, result);- }));- });-}--static GC::Ref<GamepadHapticsCompletionSteps> create_haptics_completion_steps(GC::Ref<WebIDL::Promise> promise)-{- return GC::create_function(GC::Heap::the(), GC::captures(promise), [](auto& promise, GamepadHapticsResult result) {- resolve_haptics_promise(promise, result);- });-}--static GamepadEffect gamepad_effect_for_type(GamepadHapticEffectType type, u16 first_magnitude, u16 second_magnitude, u32 duration)-{- switch (type) {- case GamepadHapticEffectType::DualRumble:- return GamepadDualRumbleEffect { first_magnitude, second_magnitude, duration };- case GamepadHapticEffectType::TriggerRumble:- return GamepadTriggerRumbleEffect { first_magnitude, second_magnitude, duration };- }- VERIFY_NOT_REACHED();-}--// https://w3c.github.io/gamepad/#dfn-constructing-a-gamepadhapticactuator-GC::Ref<GamepadHapticActuator> GamepadHapticActuator::create(HTML::Window& window, GC::Ref<Gamepad> gamepad)-{- auto document_became_hidden_observer = DOM::DocumentObserver::create(window.associated_document());-- // 1. Let gamepadHapticActuator be a newly created GamepadHapticActuator instance.- auto gamepad_haptic_actuator = GC::Heap::the().allocate<GamepadHapticActuator>(window, gamepad, document_became_hidden_observer);-- // 2. Let supportedEffectsList be an empty list.- Vector<GamepadHapticEffectType> supported_effects_list;-- // 3. For each enum value type of GamepadHapticEffectType, if the user agent can send a command to initiate effects- // of that type on that actuator, append type to supportedEffectsList.- if (gamepad->description().supports_dual_rumble)- supported_effects_list.append(GamepadHapticEffectType::DualRumble);-- if (gamepad->description().supports_trigger_rumble)- supported_effects_list.append(GamepadHapticEffectType::TriggerRumble);-- // 4. Set gamepadHapticActuator.[[effects]] to supportedEffectsList.- gamepad_haptic_actuator->m_effects = move(supported_effects_list);-- return gamepad_haptic_actuator;-}--GamepadHapticActuator::GamepadHapticActuator(HTML::Window& window, GC::Ref<Gamepad> gamepad, GC::Ref<DOM::DocumentObserver> document_became_hidden_observer)- : m_gamepad(gamepad)- , m_window(window)- , m_document_became_hidden_observer(document_became_hidden_observer)-{- m_document_became_hidden_observer->set_document_visibility_state_observer(GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self, HTML::VisibilityState visibility_state) {- if (visibility_state == HTML::VisibilityState::Hidden)- self.document_became_hidden();- }));-}--GamepadHapticActuator::~GamepadHapticActuator() = default;--void GamepadHapticActuator::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_gamepad);- visitor.visit(m_window);- visitor.visit(m_document_became_hidden_observer);- visitor.visit(m_playing_effect_completion_steps);- visitor.visit(m_playing_effect_timer);-}--Vector<GamepadHapticEffectType> GamepadHapticActuator::effects() const-{- return m_effects;-}--// FIXME: What is a valid duration and startDelay? The spec doesn't define that.-// Safari: clamps any duration above 5000ms to 5000ms and doesn't seem to clamp or reject any startDelay.-// Chrome: rejects if duration + startDelay > 5000ms.-// Firefox doesn't support vibration at the time of writing.-static constexpr u64 MAX_VIBRATION_DURATION = 5000;--// https://w3c.github.io/gamepad/#dfn-valid-effect-bool GamepadHapticActuator::is_valid_effect(GamepadHapticEffectType type, GamepadEffectParameters const& params) const-{- // 1. Given the value of GamepadHapticEffectType type, switch on:- // "dual-rumble"- // If params does not describe a valid dual-rumble effect, return false.- // "trigger-rumble"- // If params does not describe a valid trigger-rumble effect, return false.- // 2. Return true- switch (type) {- case GamepadHapticEffectType::DualRumble:- // https://w3c.github.io/gamepad/#dfn-valid-dual-rumble-effect- // Given GamepadEffectParameters params, a valid dual-rumble effect must have a valid duration, a valid- // startDelay, and both the strongMagnitude and the weakMagnitude must be in the range [0 .. 1].- if (Checked<u64>::addition_would_overflow(params.duration, params.start_delay))- return false;-- if (params.duration + params.start_delay > MAX_VIBRATION_DURATION)- return false;-- if (params.strong_magnitude < 0.0 || params.strong_magnitude > 1.0)- return false;-- if (params.weak_magnitude < 0.0 || params.weak_magnitude > 1.0)- return false;-- return true;- case GamepadHapticEffectType::TriggerRumble:- // https://w3c.github.io/gamepad/#dfn-valid-trigger-rumble-effect- // Given GamepadEffectParameters params, a valid trigger-rumble effect must have a valid duration, a valid- // startDelay, and the strongMagnitude, weakMagnitude, leftTrigger, and rightTrigger must be in the range- // [0 .. 1].- if (Checked<u64>::addition_would_overflow(params.duration, params.start_delay))- return false;-- if (params.duration + params.start_delay > MAX_VIBRATION_DURATION)- return false;-- if (params.strong_magnitude < 0.0 || params.strong_magnitude > 1.0)- return false;-- if (params.weak_magnitude < 0.0 || params.weak_magnitude > 1.0)- return false;-- if (params.left_trigger < 0.0 || params.left_trigger > 1.0)- return false;-- if (params.right_trigger < 0.0 || params.right_trigger > 1.0)- return false;-- return true;- }-- VERIFY_NOT_REACHED();-}--bool GamepadHapticActuator::can_play_effect_with_type(GamepadHapticEffectType type) const-{- // https://w3c.github.io/gamepad/#ref-for-dfn-play-effects-with-type-1- // A GamepadHapticActuator can play effects with type type if type can be found in the [[effects]] list.- return m_effects.contains_slow(type);-}--// https://w3c.github.io/gamepad/#dom-gamepadhapticactuator-playeffect-void GamepadHapticActuator::play_effect(GamepadHapticEffectType type, GamepadEffectParameters const& params, GC::Ref<WebIDL::Promise> promise)-{- // 1. If params does not describe a valid effect of type type, return a promise rejected with a TypeError.- if (!is_valid_effect(type, params)) {- WebIDL::reject_promise(promise, JS::TypeError::create(WebIDL::promise_realm(promise), "Invalid effect"sv));- return;- }-- // 2. Let document be the current settings object's relevant global object's associated Document.- auto& window = HTML::relevant_window(HTML::current_settings_object().global_object());- auto& document = window.associated_document();-- // 3. If document is null or document is not fully active or document's visibility state is "hidden", return a- // promise rejected with an "InvalidStateError" DOMException.- if (!document.is_fully_active() || document.visibility_state() == HTML::VisibilityState::Hidden) {- WebIDL::reject_promise(promise, WebIDL::InvalidStateError::create("Haptics are not allowed in a hidden document"_utf16));- return;- }-- // 5. If this GamepadHapticActuator cannot play effects with type type, return a promise rejected with reason- // NotSupportedError.- if (!can_play_effect_with_type(type)) {- WebIDL::reject_promise(promise, WebIDL::NotSupportedError::create("Gamepad does not support this effect"_utf16));- return;- }-- play_effect(type, params, create_queued_haptics_completion_steps(WebIDL::promise_realm(promise).global_object(), promise));-}--// https://w3c.github.io/gamepad/#dom-gamepadhapticactuator-reset-void GamepadHapticActuator::reset(GC::Ref<WebIDL::Promise> promise)-{- // 1. Let document be the current settings object's relevant global object's associated Document.- auto& window = HTML::relevant_window(HTML::current_settings_object().global_object());- auto& document = window.associated_document();-- // 2. If document is null or document is not fully active or document's visibility state is "hidden", return a- // promise rejected with an "InvalidStateError" DOMException.- if (!document.is_fully_active() || document.visibility_state() == HTML::VisibilityState::Hidden) {- WebIDL::reject_promise(promise, WebIDL::InvalidStateError::create("Haptics are not allowed in a hidden document"_utf16));- return;- }-- reset(create_haptics_completion_steps(promise));-}--// https://w3c.github.io/gamepad/#dom-gamepadhapticactuator-playeffect-void GamepadHapticActuator::play_effect(GamepadHapticEffectType type, GamepadEffectParameters const& params, GC::Ref<GamepadHapticsCompletionSteps> completion_steps)-{- // 4. If this.[[playingEffectPromise]] is not null:- if (m_playing_effect_completion_steps) {- // 1. Let effectPromise be this.[[playingEffectPromise]].- auto effect_completion_steps = GC::Ref { *m_playing_effect_completion_steps };-- // 2. Set this.[[playingEffectPromise]] to null.- m_playing_effect_completion_steps = nullptr;- clear_playing_effect_timers();-- // 3. Queue a global task on the gamepad task source with the relevant global object of this to resolve- // effectPromise with "preempted".- effect_completion_steps->function()(GamepadHapticsResult::Preempted);- }-- // 6. Let [[playingEffectPromise]] be a new promise.- m_playing_effect_completion_steps = completion_steps;-- // 7. Let playEffectTimestamp be the current high resolution time given the document's relevant global object.- // NOTE: Unused.-- // 8. Do the following steps in parallel:- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(*this, type, params), [](auto& self, auto& type, auto& params) {- // 1. Issue a haptic effect to the actuator with type, params, and the playEffectTimestamp.- self.issue_haptic_effect(type, params, GC::create_function(GC::Heap::the(), GC::captures(self), [](auto& self) {- // 2. When the effect completes, if this.[[playingEffectPromise]] is not null, queue a global task on the- // gamepad task source with the relevant global object of this to run the following steps:- if (self.m_playing_effect_completion_steps) {- auto completion_steps = GC::Ref { *self.m_playing_effect_completion_steps };-- // 2. Resolve this.[[playingEffectPromise]] with "complete".- completion_steps->function()(GamepadHapticsResult::Complete);-- // 3. Set this.[[playingEffectPromise]] to null.- self.m_playing_effect_completion_steps = nullptr;- self.clear_playing_effect_timers();- }- }));- }));-- // 9. Return [[playingEffectPromise]].-}--void GamepadHapticActuator::reset(GC::Ref<GamepadHapticsCompletionSteps> reset_completion_steps)-{- // 4. If this.[[playingEffectPromise]] is not null, do the following steps in parallel:- if (m_playing_effect_completion_steps) {- Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(GC::Heap::the(), GC::captures(*this, reset_completion_steps), [](auto& self, auto& reset_completion_steps) {- // 1. Let effectPromise be this.[[playingEffectPromise]].- auto effect_completion_steps = self.m_playing_effect_completion_steps;-- // 2. Stop haptic effects on this's gamepad's actuator.- self.stop_haptic_effects();-- // 3. If the effect has been successfully stopped, do:- // AD-HOC: The stop command is sent to the UI process without waiting for a reply, so it is taken to have- // succeeded, matching other engines.- // 1. If effectPromise and this.[[playingEffectPromise]] are still the same,- // set this.[[playingEffectPromise]] to null.- if (effect_completion_steps == self.m_playing_effect_completion_steps)- self.m_playing_effect_completion_steps = nullptr;-- // 2. Queue a global task on the gamepad task source with the relevant global object of this to resolve- // effectPromise with "preempted".- if (effect_completion_steps)- effect_completion_steps->function()(GamepadHapticsResult::Preempted);-- // 4. Resolve resetResultPromise with "complete"- reset_completion_steps->function()(GamepadHapticsResult::Complete);- }));- }-}--// https://w3c.github.io/gamepad/#handling-visibility-change-void GamepadHapticActuator::document_became_hidden()-{- // When the document's visibility state becomes "hidden", run these steps for each GamepadHapticActuator actuator:- // 1. If actuator.[[playingEffectPromise]] is null, abort these steps.- if (!m_playing_effect_completion_steps)- return;-- // 2. Queue a global task on the gamepad task source with the relevant global object of actuator to run the- // following steps:- auto completion_steps = GC::Ref { *m_playing_effect_completion_steps };-- // 2. Resolve actuator.[[playingEffectPromise]] with "preempted".- completion_steps->function()(GamepadHapticsResult::Preempted);-- // 3. Set actuator.[[playingEffectPromise]] to null.- m_playing_effect_completion_steps = nullptr;- clear_playing_effect_timers();-- // 3. Stop haptic effects on actuator.- stop_haptic_effects();-}--// https://w3c.github.io/gamepad/#dfn-issue-a-haptic-effect-void GamepadHapticActuator::issue_haptic_effect(GamepadHapticEffectType type, GamepadEffectParameters const& params, GC::Ref<GC::Function<void()>> on_complete)-{- auto& heap = GC::Heap::the();-- // To issue a haptic effect on an actuator, the user agent MUST send a command to the device to render an effect- // of type and try to make it use the provided params. The user agent SHOULD use the provided playEffectTimestamp- // for more precise playback timing when params.startDelay is not 0.0. The user agent MAY modify the effect to- // increase compatibility. For example, an effect intended for a rumble motor may be transformed into a- // waveform-based effect for a device that supports waveform haptics but lacks rumble motors.- m_playing_effect_timer = Platform::Timer::create_single_shot(heap, AK::Duration::from_milliseconds(static_cast<int>(params.start_delay)), GC::create_function(heap, GC::captures(*this, type, params, on_complete), [](auto& self, auto& type, auto& params, auto& on_complete) {- auto& heap = GC::Heap::the();- auto& page = self.m_window->page();-- auto first_magnitude = type == GamepadHapticEffectType::DualRumble ? params.strong_magnitude : params.left_trigger;- auto second_magnitude = type == GamepadHapticEffectType::DualRumble ? params.weak_magnitude : params.right_trigger;- page.client().page_did_play_gamepad_effect(self.m_gamepad->handle(),- gamepad_effect_for_type(type,- static_cast<u16>(first_magnitude * NumericLimits<u16>::max()),- static_cast<u16>(second_magnitude * NumericLimits<u16>::max()),- static_cast<u32>(params.duration)));-- self.m_playing_effect_timer = Platform::Timer::create_single_shot(heap, AK::Duration::from_milliseconds(params.duration), GC::create_function(heap, GC::captures(self, type, on_complete), [](auto& self, auto& type, auto& on_complete) {- // Explicitly stop the rumble before completing, ensuring the stop signal is sent synchronously.- auto& page = self.m_window->page();-- page.client().page_did_play_gamepad_effect(self.m_gamepad->handle(), gamepad_effect_for_type(type, 0, 0, 0));- on_complete->function()();- }));-- self.m_playing_effect_timer->start();- }));-- m_playing_effect_timer->start();-}--// https://w3c.github.io/gamepad/#dfn-stop-haptic-effects-void GamepadHapticActuator::stop_haptic_effects()-{- // To stop haptic effects on an actuator, the user agent MUST send a command to the device to abort any effects- // currently being played. If a haptic effect was interrupted, the actuator SHOULD return to a motionless state- // as quickly as possible.- auto& page = m_window->page();- page.client().page_did_request_stop_gamepad_effects(m_gamepad->handle());-}--void GamepadHapticActuator::clear_playing_effect_timers()-{- if (m_playing_effect_timer) {- m_playing_effect_timer->stop();- m_playing_effect_timer = nullptr;- }-}--}diff --git a/Libraries/LibWeb/Gamepad/GamepadHapticActuator.h b/Libraries/LibWeb/Gamepad/GamepadHapticActuator.hdeleted file mode 100644index 7cf0877d984..00000000000--- a/Libraries/LibWeb/Gamepad/GamepadHapticActuator.h+++ /dev/null@@ -1,64 +0,0 @@-/*- * Copyright (c) 2025, Luke Wilde <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibGC/Function.h>-#include <LibWeb/Bindings/GamepadHapticActuator.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Forward.h>--namespace Web::Gamepad {--using GamepadHapticEffectType = Bindings::GamepadHapticEffectType;-using GamepadHapticsResult = Bindings::GamepadHapticsResult;-using GamepadHapticsCompletionSteps = GC::Function<void(GamepadHapticsResult)>;-using GamepadEffectParameters = Bindings::GamepadEffectParameters;--class GamepadHapticActuator final : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(GamepadHapticActuator, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(GamepadHapticActuator);--public:- static GC::Ref<GamepadHapticActuator> create(HTML::Window&, GC::Ref<Gamepad>);-- virtual ~GamepadHapticActuator() override;-- Vector<GamepadHapticEffectType> effects() const;-- bool is_valid_effect(GamepadHapticEffectType, GamepadEffectParameters const&) const;- bool can_play_effect_with_type(GamepadHapticEffectType) const;-- void play_effect(GamepadHapticEffectType, GamepadEffectParameters const&, GC::Ref<WebIDL::Promise>);- void reset(GC::Ref<WebIDL::Promise>);-- void play_effect(GamepadHapticEffectType, GamepadEffectParameters const&, GC::Ref<GamepadHapticsCompletionSteps>);- void reset(GC::Ref<GamepadHapticsCompletionSteps>);--private:- GamepadHapticActuator(HTML::Window&, GC::Ref<Gamepad>, GC::Ref<DOM::DocumentObserver>);- virtual void visit_edges(GC::Cell::Visitor&) override;-- void document_became_hidden();- void issue_haptic_effect(GamepadHapticEffectType, GamepadEffectParameters const&, GC::Ref<GC::Function<void()>> on_complete);- void stop_haptic_effects();- void clear_playing_effect_timers();-- GC::Ref<Gamepad> m_gamepad;- GC::Ref<HTML::Window> m_window;- GC::Ref<DOM::DocumentObserver> m_document_became_hidden_observer;-- // https://w3c.github.io/gamepad/#dfn-effects- // Represents the effects supported by the actuator.- Vector<GamepadHapticEffectType> m_effects;-- // https://w3c.github.io/gamepad/#dfn-playingeffectpromise- // The completion steps for playing some effect, or null if no effect is playing.- GC::Ptr<GamepadHapticsCompletionSteps> m_playing_effect_completion_steps;- GC::Ptr<Platform::Timer> m_playing_effect_timer;-};--}diff --git a/Libraries/LibWeb/Gamepad/GamepadHapticActuator.idl b/Libraries/LibWeb/Gamepad/GamepadHapticActuator.idlindex cd930effe30..d259fc29560 100644--- a/Libraries/LibWeb/Gamepad/GamepadHapticActuator.idl+++ b/Libraries/LibWeb/Gamepad/GamepadHapticActuator.idl@@ -21,7 +21,7 @@ dictionary GamepadEffectParameters {};// https://w3c.github.io/gamepad/#gamepadhapticactuator-interface-[Exposed=Window]+[Exposed=Window, ImplementedIn=Rust]interface GamepadHapticActuator {[SameObject] readonly attribute FrozenArray<GamepadHapticEffectType> effects;[CreatesPromise] Promise<GamepadHapticsResult> playEffect(GamepadHapticEffectType type, optional GamepadEffectParameters params = {});diff --git a/Libraries/LibWeb/Gamepad/NavigatorGamepad.cpp b/Libraries/LibWeb/Gamepad/NavigatorGamepad.cppindex 3ebd0505420..ba1cfa50506 100644--- a/Libraries/LibWeb/Gamepad/NavigatorGamepad.cpp+++ b/Libraries/LibWeb/Gamepad/NavigatorGamepad.cpp@@ -1,244 +1,189 @@/** Copyright (c) 2025, Jelle Raaijmakers <[email protected]>* Copyright (c) 2025, Luke Wilde <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/#include <AK/TypeCasts.h>-#include <LibGC/Heap.h>-#include <LibWeb/DOM/Document.h>-#include <LibWeb/Gamepad/EventNames.h>+#include <LibJS/HostClassBuilder.h>#include <LibWeb/Gamepad/Gamepad.h>-#include <LibWeb/Gamepad/GamepadEvent.h>#include <LibWeb/Gamepad/GamepadRegistry.h>#include <LibWeb/Gamepad/NavigatorGamepad.h>#include <LibWeb/HTML/Navigator.h>#include <LibWeb/HTML/Scripting/Environments.h>#include <LibWeb/HTML/Window.h>-#include <LibWeb/HighResolutionTime/TimeOrigin.h>#include <LibWeb/Page/Page.h>+#include <LibWeb/WebIDL/DOMException.h>+#include <LibWebCommon/Gamepad/GamepadInput.h>namespace Web::Gamepad {-// https://w3c.github.io/gamepad/#dom-navigator-getgamepads-WebIDL::ExceptionOr<GC::RootVector<GC::Ptr<Gamepad>>> NavigatorGamepadPartial::get_gamepads()-{- // 1. Let doc be the current global object's associated Document.- auto& window = HTML::current_window();- auto& document = window.associated_document();-- // 2. If doc is null or doc is not fully active, then return an empty list.- GC::RootVector<GC::Ptr<Gamepad>> gamepads;- if (!document.is_fully_active())- return gamepads;-- // 3. If doc is not allowed to use the "gamepad" permission, then throw a "SecurityError" DOMException and abort these steps.- if (!document.is_allowed_to_use_feature(DOM::PolicyControlledFeature::Gamepad))- return WebIDL::SecurityError::create("Not allowed to use gamepads"_utf16);-- // AD-HOC: Tell the UI process that this process consumes gamepad input.- window.page().client().page_did_start_using_gamepads();-- // 4. If this.[[hasGamepadGesture]] is false, then return an empty list.- if (!m_has_gamepad_gesture)- return gamepads;-- // 5. Let now be the current high resolution time given the current global object.- auto now = HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(window));-- // 6. Let gamepads be an empty list.- // NOTE: Already done.-- // 7. For each gamepad of this.[[gamepads]]:- for (auto gamepad : m_gamepads) {- // 1. If gamepad is not null and gamepad.[[exposed]] is false:- if (gamepad && !gamepad->exposed()) {- // 1. Set gamepad.[[exposed]] to true.- gamepad->set_exposed({}, true);-- // 2. Set gamepad.[[timestamp]] to now.- gamepad->set_timestamp({}, now);- }+struct GamepadInputDescriptorABI {+ bool has_canonical_index;+ u32 canonical_index;+ i16 logical_minimum;+ i16 logical_maximum;+};++struct GamepadDescriptionABI {+ GamepadHandle handle;+ ReadonlyBytes id;+ bool has_standard_mapping;+ bool supports_dual_rumble;+ bool supports_trigger_rumble;+ ReadonlySpan<GamepadInputDescriptorABI> axes;+ ReadonlySpan<GamepadInputDescriptorABI> buttons;+};++struct GamepadStateABI {+ GamepadHandle handle;+ ReadonlySpan<i16> axis_values;+ ReadonlySpan<i16> button_values;+};++extern "C" {+// Defined in Bindings/Rust/src/gamepad/exports.rs.+bool web_rust_gamepad_get_gamepads(JSVM*, HTML::Window* navigator_window, HTML::Window* current_window, void* ctx, void (*on_gamepad)(void*, Gamepad*));+void web_rust_gamepad_handle_gamepad_connected(JSVM*, HTML::Window*, GamepadDescriptionABI const*);+void web_rust_gamepad_handle_gamepad_updated(JSVM*, HTML::Window*, GamepadStateABI const*);+void web_rust_gamepad_handle_gamepad_disconnected(JSVM*, HTML::Window*, GamepadHandle);++// Called by Bindings/Rust/src/gamepad/.+void web_gamepad_did_start_using_gamepads(HTML::Window*);+void web_gamepad_play_effect(HTML::Window*, GamepadHandle, u8 effect_type, u16 first_magnitude, u16 second_magnitude, u32 duration);+void web_gamepad_stop_effects(HTML::Window*, GamepadHandle);+double web_gamepad_normalize_axis_value(i16 logical_value, i16 logical_minimum, i16 logical_maximum);+double web_gamepad_normalize_button_value(i16 logical_value, i16 logical_minimum, i16 logical_maximum);+bool web_gamepad_is_button_pressed(i16 logical_value, i16 logical_minimum, i16 logical_maximum);+bool web_gamepad_contains_gamepad_user_gesture(GamepadDescriptionABI const*, GamepadStateABI const*);+}- // 2. Append gamepad to gamepads.- gamepads.append(gamepad);- }+static JSVM* the_vm()+{+ return JS::HostABI::vm_to_abi(JS::VM::the());+}- // 8. Return gamepads.- return gamepads;+static HTML::Window& navigator_window(NavigatorGamepadPartial& navigator)+{+ return as<HTML::Navigator>(navigator).window();}-void NavigatorGamepadPartial::visit_edges(GC::Cell::Visitor& visitor)+static Vector<GamepadInputDescriptorABI> input_descriptors_to_abi(Vector<GamepadInputDescriptor> const& inputs){- visitor.visit(m_gamepads);+ Vector<GamepadInputDescriptorABI> descriptors;+ descriptors.ensure_capacity(inputs.size());+ for (auto const& input : inputs)+ descriptors.unchecked_append({ input.canonical_index.has_value(), input.canonical_index.value_or(0), input.logical_minimum, input.logical_maximum });+ return descriptors;}-// https://w3c.github.io/gamepad/#dfn-selecting-an-unused-gamepad-index-size_t NavigatorGamepadPartial::select_an_unused_gamepad_index(Badge<Gamepad>)+static Vector<GamepadInputDescriptor> input_descriptors_from_abi(ReadonlySpan<GamepadInputDescriptorABI> inputs){- // 2. Let maxGamepadIndex be the size of navigator.[[gamepads]] − 1.- // 3. For each gamepadIndex of the range from 0 to maxGamepadIndex:- for (size_t gamepad_index = 0; gamepad_index < m_gamepads.size(); ++gamepad_index) {- // 1. If navigator.[[gamepads]][gamepadIndex] is null, then return gamepadIndex.- if (!m_gamepads[gamepad_index])- return gamepad_index;+ Vector<GamepadInputDescriptor> descriptors;+ descriptors.ensure_capacity(inputs.size());+ for (auto const& input : inputs) {+ Optional<u32> canonical_index;+ if (input.has_canonical_index)+ canonical_index = input.canonical_index;+ descriptors.unchecked_append({ canonical_index, input.logical_minimum, input.logical_maximum });}+ return descriptors;+}- // 4. Append null to navigator.[[gamepads]].- m_gamepads.append(nullptr);-- // 5. Return the size of navigator.[[gamepads]] − 1.- return m_gamepads.size() - 1;+WebIDL::ExceptionOr<GC::RootVector<GC::Ptr<Gamepad>>> NavigatorGamepadPartial::get_gamepads()+{+ GC::RootVector<GC::Ptr<Gamepad>> gamepads;+ auto allowed = web_rust_gamepad_get_gamepads(the_vm(), &navigator_window(*this), &HTML::current_window(), &gamepads, [](void* ctx, Gamepad* gamepad) {+ static_cast<GC::RootVector<GC::Ptr<Gamepad>>*>(ctx)->append(gamepad);+ });+ if (!allowed)+ return WebIDL::SecurityError::create("Not allowed to use gamepads"_utf16);+ return gamepads;}-// https://w3c.github.io/gamepad/#event-gamepadconnectedvoid NavigatorGamepadPartial::handle_gamepad_connected(GamepadDescription const& description){- // When a gamepad becomes available on the system, run the following steps:- if (m_available_gamepads.contains_slow(description.handle))- return;-- // 1. Let document be the current global object's associated Document; otherwise null.- // FIXME: We can't use the current global object here, since it's not executing in a scripting context.- // NOTE: NavigatorGamepad is only available on Window.- // NOTE: document is never null.- auto& navigator = as<HTML::Navigator>(*this);- auto& window = navigator.window();- auto& realm = window.principal_realm();- auto& global = realm.global_object();- auto& document = window.associated_document();-- // 2. If document is not null and is not allowed to use the "gamepad" permission, then abort these steps.- if (!document.is_allowed_to_use_feature(DOM::PolicyControlledFeature::Gamepad))- return;-- m_available_gamepads.append(description.handle);-- // 3. Queue a global task on the gamepad task source with the current global object to perform the following steps:- HTML::queue_global_task(HTML::Task::Source::Gamepad, global, GC::create_function(GC::Heap::the(), GC::captures(window, document, description), [](auto& window, auto& document, auto& description) {- // 1. Let gamepad be a new Gamepad representing the gamepad.- auto gamepad = Gamepad::create(window, description);-- // 2. Let navigator be gamepad's relevant global object's Navigator object.- auto navigator = window.navigator();-- // 3. Set navigator.[[gamepads]][gamepad.index] to gamepad.- navigator->m_gamepads[gamepad->index()] = gamepad;-- // 4. If navigator.[[hasGamepadGesture]] is true:- if (navigator->m_has_gamepad_gesture) {- // 1. Set gamepad.[[exposed]] to true.- gamepad->set_exposed({}, true);-- // 2. If document is not null and is fully active, then fire an event named gamepadconnected at gamepad's- // relevant global object using GamepadEvent with its gamepad attribute initialized to gamepad.- if (document.is_fully_active()) {- GamepadEventInit gamepad_connected_event_init { {}, gamepad };- auto gamepad_connected_event = GamepadEvent::create(EventNames::gamepadconnected, gamepad_connected_event_init, HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(window)));- window.dispatch_event(gamepad_connected_event);- }- }- }));-}--// https://w3c.github.io/gamepad/#dfn-receives-new-button-or-axis-input-values+ auto axes = input_descriptors_to_abi(description.axes);+ auto buttons = input_descriptors_to_abi(description.buttons);+ GamepadDescriptionABI description_abi {+ description.handle,+ description.id.bytes(),+ description.has_standard_mapping,+ description.supports_dual_rumble,+ description.supports_trigger_rumble,+ axes,+ buttons,+ };+ web_rust_gamepad_handle_gamepad_connected(the_vm(), &navigator_window(*this), &description_abi);+}+void NavigatorGamepadPartial::handle_gamepad_updated(Badge<EventHandler>, GamepadState const& state){- // When the system receives new button or axis input values, run the following steps:- if (!m_available_gamepads.contains_slow(state.handle))- return;-- // 2. Queue a global task on the gamepad task source with gamepad's relevant global object to update gamepad state- // for gamepad.- // AD-HOC: Step 1 runs in the task. A newly available gamepad is created by an earlier task on the same task- // source, so input received before that task has run still reaches the gamepad.- auto& window = as<HTML::Navigator>(*this).window();- HTML::queue_global_task(HTML::Task::Source::Gamepad, window.principal_realm().global_object(), GC::create_function(GC::Heap::the(), GC::captures(window, state), [](auto& window, auto& state) {- // 1. Let gamepad be the Gamepad object representing the device that received new button or axis input values.- auto navigator = window.navigator();- auto gamepad = navigator->m_gamepads.find_if([&state](GC::Ptr<Gamepad> gamepad) {- return gamepad && gamepad->handle() == state.handle;- });-- if (gamepad.is_end())- return;-- (*gamepad)->set_latest_state({}, state);- (*gamepad)->update_gamepad_state({});- }));+ GamepadStateABI state_abi { state.handle, state.axis_values, state.button_values };+ web_rust_gamepad_handle_gamepad_updated(the_vm(), &navigator_window(*this), &state_abi);}void NavigatorGamepadPartial::handle_gamepad_disconnected(Badge<EventHandler>, GamepadHandle handle){- // When a gamepad becomes unavailable on the system, run the following steps:- auto was_available = m_available_gamepads.remove_first_matching([&handle](GamepadHandle available_gamepad) {- return handle == available_gamepad;- });-- if (!was_available)- return;-- // 2. Queue a global task on the gamepad task source with gamepad's relevant global object to perform the- // following steps:- // AD-HOC: Step 1 runs in the task. A newly available gamepad is created by an earlier task on the same task- // source, so a gamepad that becomes unavailable before that task has run is still removed.- auto& window = as<HTML::Navigator>(*this).window();- HTML::queue_global_task(HTML::Task::Source::Gamepad, window.principal_realm().global_object(), GC::create_function(GC::Heap::the(), GC::captures(window, handle), [](auto& window, auto& handle) {- // 1. Let gamepad be the Gamepad representing the unavailable device.- auto matching_gamepad = window.navigator()->m_gamepads.first_matching([&handle](GC::Ptr<Gamepad> gamepad) {- return gamepad && gamepad->handle() == handle;- });-- if (!matching_gamepad.has_value())- return;-- auto gamepad = GC::Ref { **matching_gamepad };-- // 1. Set gamepad.[[connected]] to false.- gamepad->set_connected({}, false);+ web_rust_gamepad_handle_gamepad_disconnected(the_vm(), &navigator_window(*this), handle);+}- // 2. Let document be gamepad's relevant global object's associated Document; otherwise null.- auto& document = window.associated_document();+void NavigatorGamepadPartial::check_for_connected_gamepads()+{+ GamepadRegistry::the().for_each_connected_gamepad([this](GamepadDescription const& description) {+ handle_gamepad_connected(description);+ });+}- // 3. If gamepad.[[exposed]] is true and document is not null and is fully active, then fire an event named- // gamepaddisconnected at gamepad's relevant global object using GamepadEvent with its gamepad attribute- // initialized to gamepad.- if (gamepad->exposed() && document.is_fully_active()) {- GamepadEventInit gamepad_disconnected_event_init { {}, gamepad };- auto gamepad_disconnected_event = GamepadEvent::create(EventNames::gamepaddisconnected, gamepad_disconnected_event_init, HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(window)));- window.dispatch_event(gamepad_disconnected_event);- }+void web_gamepad_did_start_using_gamepads(HTML::Window* window)+{+ window->page().client().page_did_start_using_gamepads();+}- // 4. Let navigator be gamepad's relevant global object's Navigator object.- auto navigator = window.navigator();+void web_gamepad_play_effect(HTML::Window* window, GamepadHandle handle, u8 effect_type, u16 first_magnitude, u16 second_magnitude, u32 duration)+{+ // NB: The effect type is the index of the variant of GamepadHapticEffectType.+ GamepadEffect effect = effect_type == 0+ ? GamepadEffect { GamepadDualRumbleEffect { first_magnitude, second_magnitude, duration } }+ : GamepadEffect { GamepadTriggerRumbleEffect { first_magnitude, second_magnitude, duration } };+ window->page().client().page_did_play_gamepad_effect(handle, effect);+}- // 5. Set navigator.[[gamepads]][gamepad.index] to null.- navigator->m_gamepads[gamepad->index()] = nullptr;+void web_gamepad_stop_effects(HTML::Window* window, GamepadHandle handle)+{+ window->page().client().page_did_request_stop_gamepad_effects(handle);+}- // 6. While navigator.[[gamepads]] is not empty and the last item of navigator.[[gamepads]] is null, remove the- // last item of navigator.[[gamepads]].- while (!navigator->m_gamepads.is_empty() && navigator->m_gamepads.last() == nullptr) {- (void)navigator->m_gamepads.take_last();- }- }));+double web_gamepad_normalize_axis_value(i16 logical_value, i16 logical_minimum, i16 logical_maximum)+{+ return normalize_axis_value(logical_value, logical_minimum, logical_maximum);}-void NavigatorGamepadPartial::check_for_connected_gamepads()+double web_gamepad_normalize_button_value(i16 logical_value, i16 logical_minimum, i16 logical_maximum){- GamepadRegistry::the().for_each_connected_gamepad([this](GamepadDescription const& description) {- handle_gamepad_connected(description);- });+ return normalize_button_value(logical_value, logical_minimum, logical_maximum);}-void NavigatorGamepadPartial::set_has_gamepad_gesture(Badge<Gamepad>, bool value)+bool web_gamepad_is_button_pressed(i16 logical_value, i16 logical_minimum, i16 logical_maximum){- m_has_gamepad_gesture = value;+ return is_button_pressed(logical_value, logical_minimum, logical_maximum);}-GC::RootVector<GC::Ptr<Gamepad>> NavigatorGamepadPartial::gamepads(Badge<Gamepad>) const+bool web_gamepad_contains_gamepad_user_gesture(GamepadDescriptionABI const* description_abi, GamepadStateABI const* state_abi){- return GC::RootVector<GC::Ptr<Gamepad>> { as<HTML::Navigator>(*this).m_gamepads };+ GamepadDescription description;+ description.handle = description_abi->handle;+ description.axes = input_descriptors_from_abi(description_abi->axes);+ description.buttons = input_descriptors_from_abi(description_abi->buttons);++ GamepadState state;+ state.handle = state_abi->handle;+ state.axis_values = Vector<i16> { state_abi->axis_values };+ state.button_values = Vector<i16> { state_abi->button_values };++ return contains_gamepad_user_gesture(description, state);}}diff --git a/Libraries/LibWeb/Gamepad/NavigatorGamepad.h b/Libraries/LibWeb/Gamepad/NavigatorGamepad.hindex 2f1005bdbf7..42ae5a06fdf 100644--- a/Libraries/LibWeb/Gamepad/NavigatorGamepad.h+++ b/Libraries/LibWeb/Gamepad/NavigatorGamepad.h@@ -1,5 +1,6 @@/** Copyright (c) 2025, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.** SPDX-License-Identifier: BSD-2-Clause*/@@ -18,39 +19,17 @@ class NavigatorGamepadPartial {public:WebIDL::ExceptionOr<GC::RootVector<GC::Ptr<Gamepad>>> get_gamepads();- size_t select_an_unused_gamepad_index(Badge<Gamepad>);-void handle_gamepad_connected(GamepadDescription const&);void handle_gamepad_updated(Badge<EventHandler>, GamepadState const&);void handle_gamepad_disconnected(Badge<EventHandler>, GamepadHandle);- bool has_gamepad_gesture() const { return m_has_gamepad_gesture; }- void set_has_gamepad_gesture(Badge<Gamepad>, bool);-- GC::RootVector<GC::Ptr<Gamepad>> gamepads(Badge<Gamepad>) const;-protected:- void visit_edges(GC::Cell::Visitor& visitor);-void check_for_connected_gamepads();private:virtual ~NavigatorGamepadPartial() = default;friend class HTML::Navigator;-- // https://w3c.github.io/gamepad/#dfn-hasgamepadgesture- // A flag indicating that a gamepad user gesture has been observed- bool m_has_gamepad_gesture { false };-- // https://w3c.github.io/gamepad/#dfn-gamepads- // Each Gamepad present at the index specified by its index attribute, or null for unassigned indices.- Vector<GC::Ptr<Gamepad>> m_gamepads;-- // Non-standard attribute to know which gamepads are available to the system. This is used to prevent duplicate- // connections for the same gamepad ID (e.g. if the navigator object is initialized and checks for connected gamepads- // and also receives a gamepad connected event)- Vector<GamepadHandle> m_available_gamepads;};}diff --git a/Libraries/LibWeb/HTML/Navigator.cpp b/Libraries/LibWeb/HTML/Navigator.cppindex 2a796f6dadb..f0c520744ce 100644--- a/Libraries/LibWeb/HTML/Navigator.cpp+++ b/Libraries/LibWeb/HTML/Navigator.cpp@@ -74,7 +74,6 @@ bool Navigator::webdriver() constvoid Navigator::visit_edges(GC::Cell::Visitor& visitor){Base::visit_edges(visitor);- NavigatorGamepadPartial::visit_edges(visitor);visitor.visit(m_window);visitor.visit(m_battery_promise);visitor.visit(m_mime_type_array);