Truly independent web browser
LibGamepad+LibWebView+Hub+UI/Qt: Read gamepads in the UI
Andreas Kling325820f69070
diff --git a/Libraries/CMakeLists.txt b/Libraries/CMakeLists.txtindex 4a7b0ed6d8d..99fc4a166ee 100644--- a/Libraries/CMakeLists.txt+++ b/Libraries/CMakeLists.txt@@ -45,6 +45,7 @@ if (ENABLE_GUI_TARGETS)add_subdirectory(LibCompositing)add_subdirectory(LibWeb)add_subdirectory(LibWebView)+ add_subdirectory(LibGamepad)endif()# FIXME: Increase support for building targets on Windowsdiff --git a/Libraries/LibGamepad/CMakeLists.txt b/Libraries/LibGamepad/CMakeLists.txtnew file mode 100644index 00000000000..e93dda20442--- /dev/null+++ b/Libraries/LibGamepad/CMakeLists.txt@@ -0,0 +1,6 @@+set(SOURCES+ SDLGamepadSource.cpp+)++ladybird_lib(LibGamepad gamepad)+target_link_libraries(LibGamepad PRIVATE LibCore LibWebCommon LibWebView SDL3::SDL3)diff --git a/Libraries/LibGamepad/SDLGamepadSource.cpp b/Libraries/LibGamepad/SDLGamepadSource.cppnew file mode 100644index 00000000000..9105089dcfe--- /dev/null+++ b/Libraries/LibGamepad/SDLGamepadSource.cpp@@ -0,0 +1,498 @@+/*+ * Copyright (c) 2026, Tim Ledbetter <[email protected]>+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <LibCore/Timer.h>+#include <LibGamepad/SDLGamepadSource.h>++#include <SDL3/SDL_events.h>+#include <SDL3/SDL_gamepad.h>+#include <SDL3/SDL_hints.h>+#include <SDL3/SDL_init.h>+#include <SDL3/SDL_joystick.h>++#if defined(AK_OS_WINDOWS)+# include <objbase.h>+#endif++namespace Gamepad {++static constexpr int GAMEPAD_POLL_INTERVAL_MS = 8;++// https://w3c.github.io/gamepad/#dfn-standard-gamepad+// Type Index Location+// Button 0 Bottom button in right cluster+// 1 Right button in right cluster+// 2 Left button in right cluster+// 3 Top button in right cluster+// 4 Top left front button+// 5 Top right front button+// 6 Bottom left front button+// 7 Bottom right front button+// 8 Left button in center cluster+// 9 Right button in center cluster+// 10 Left stick pressed button+// 11 Right stick pressed button+// 12 Top button in left cluster+// 13 Bottom button in left cluster+// 14 Left button in left cluster+// 15 Right button in left cluster+// 16 Center button in center cluster+static Array<Variant<SDL_GamepadButton, SDL_GamepadAxis>, 17> const standard_gamepad_button_layout {+ SDL_GAMEPAD_BUTTON_SOUTH,+ SDL_GAMEPAD_BUTTON_EAST,+ SDL_GAMEPAD_BUTTON_WEST,+ SDL_GAMEPAD_BUTTON_NORTH,+ SDL_GAMEPAD_BUTTON_LEFT_SHOULDER,+ SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER,+ SDL_GAMEPAD_AXIS_LEFT_TRIGGER,+ SDL_GAMEPAD_AXIS_RIGHT_TRIGGER,+ SDL_GAMEPAD_BUTTON_BACK,+ SDL_GAMEPAD_BUTTON_START,+ SDL_GAMEPAD_BUTTON_LEFT_STICK,+ SDL_GAMEPAD_BUTTON_RIGHT_STICK,+ SDL_GAMEPAD_BUTTON_DPAD_UP,+ SDL_GAMEPAD_BUTTON_DPAD_DOWN,+ SDL_GAMEPAD_BUTTON_DPAD_LEFT,+ SDL_GAMEPAD_BUTTON_DPAD_RIGHT,+ SDL_GAMEPAD_BUTTON_GUIDE,+};++static Array<SDL_GamepadButton, 11> const non_standard_gamepad_button_layout {+ SDL_GAMEPAD_BUTTON_MISC1,+ SDL_GAMEPAD_BUTTON_RIGHT_PADDLE1,+ SDL_GAMEPAD_BUTTON_LEFT_PADDLE1,+ SDL_GAMEPAD_BUTTON_RIGHT_PADDLE2,+ SDL_GAMEPAD_BUTTON_LEFT_PADDLE2,+ SDL_GAMEPAD_BUTTON_TOUCHPAD,+ SDL_GAMEPAD_BUTTON_MISC2,+ SDL_GAMEPAD_BUTTON_MISC3,+ SDL_GAMEPAD_BUTTON_MISC4,+ SDL_GAMEPAD_BUTTON_MISC5,+ SDL_GAMEPAD_BUTTON_MISC6,+};++// axes 0 Horizontal axis for left stick (negative left/positive right)+// 1 Vertical axis for left stick (negative up/positive down)+// 2 Horizontal axis for right stick (negative left/positive right)+// 3 Vertical axis for right stick (negative up/positive down)+static Array<SDL_GamepadAxis, 4> const standard_gamepad_axes_layout {+ SDL_GAMEPAD_AXIS_LEFTX,+ SDL_GAMEPAD_AXIS_LEFTY,+ SDL_GAMEPAD_AXIS_RIGHTX,+ SDL_GAMEPAD_AXIS_RIGHTY,+};++static constexpr char const* VIRTUAL_GAMEPAD_NAME = "Ladybird Virtual Gamepad";++static SDLCALL bool record_received_dual_rumble_effect(void* user_data, u16 low_frequency_rumble, u16 high_frequency_rumble)+{+ auto* device = static_cast<SDLGamepadSource::Device*>(user_data);+ device->received_dual_rumble_effects.append({ low_frequency_rumble, high_frequency_rumble });+ return true;+}++static SDLCALL bool record_received_trigger_rumble_effect(void* user_data, u16 left_rumble, u16 right_rumble)+{+ auto* device = static_cast<SDLGamepadSource::Device*>(user_data);+ device->received_trigger_rumble_effects.append({ left_rumble, right_rumble });+ return true;+}++SDLGamepadSource::SDLGamepadSource(IgnoreSystemGamepads ignore_system_gamepads)+ : m_ignore_system_gamepads(ignore_system_gamepads)+{+}++SDLGamepadSource::~SDLGamepadSource()+{+ if (m_poll_timer)+ m_poll_timer->stop();++ // NB: A virtual joystick that outlives its device would call back into freed memory.+ for (auto handle : m_devices.keys())+ remove_device(handle);++ if (m_sdl_initialized)+ SDL_QuitSubSystem(SDL_INIT_GAMEPAD);+}++bool SDLGamepadSource::start()+{+ if (m_sdl_initialized)+ return true;++#if defined(AK_OS_WINDOWS)+ // Initialize COM in the multithreaded model before SDL gets a chance to initialize it apartment-threaded, which+ // would add a high overhead to calls across threads. If another component already chose a model, keep it.+ (void)CoInitializeEx(0, COINIT_MULTITHREADED);+#endif++ // Without this, SDL turns SIGINT and SIGTERM into quit events that nothing handles.+ SDL_SetHint(SDL_HINT_NO_SIGNAL_HANDLERS, "1");++ if (!SDL_Init(SDL_INIT_GAMEPAD)) {+ dbgln("Failed to initialize SDL3: {}", SDL_GetError());+ return false;+ }++ m_sdl_initialized = true;+ return true;+}++void SDLGamepadSource::set_polling(bool polling)+{+ // Tests look at their gamepads when they ask.+ if (!polling || !m_sdl_initialized || m_ignore_system_gamepads == IgnoreSystemGamepads::Yes) {+ if (m_poll_timer)+ m_poll_timer->stop();+ return;+ }++ if (!m_poll_timer)+ m_poll_timer = Core::Timer::create_repeating(AK::Duration::from_milliseconds(GAMEPAD_POLL_INTERVAL_MS), [this] { poll(); });+ m_poll_timer->start();+}++void SDLGamepadSource::poll()+{+ if (!m_sdl_initialized)+ return;++ SDL_Event event;+ while (SDL_PollEvent(&event))+ handle_sdl_event(event);++ Vector<Web::Gamepad::GamepadState> changed_states;+ for (auto& entry : m_devices) {+ auto& device = *entry.value;+ if (!device.connected)+ continue;+ // Compare freshly read state, since SDL suppresses some input events, such as a guide button release shortly+ // after its press.+ read_current_state(device, m_scratch_state);+ if (m_scratch_state == device.last_state)+ continue;+ device.last_state = m_scratch_state;+ changed_states.append(device.last_state);+ }++ if (on_gamepad_states_changed)+ on_gamepad_states_changed(move(changed_states));+}++void SDLGamepadSource::handle_sdl_event(SDL_Event const& event)+{+ switch (event.type) {+ case SDL_EVENT_GAMEPAD_ADDED:+ device_connected(event.gdevice.which);+ break;+ case SDL_EVENT_GAMEPAD_REMOVED:+ device_disconnected(event.gdevice.which);+ break;+ default:+ break;+ }+}++void SDLGamepadSource::device_connected(u32 sdl_joystick_id)+{+ auto* device = device_for_sdl_joystick_id(sdl_joystick_id);++ if (!device) {+ if (m_ignore_system_gamepads == IgnoreSystemGamepads::Yes)+ return;++ auto* sdl_gamepad = SDL_OpenGamepad(sdl_joystick_id);+ if (!sdl_gamepad) {+ dbgln("Failed to open gamepad: {}", SDL_GetError());+ return;+ }++ auto handle = m_next_handle++;+ auto new_device = make<Device>();+ new_device->sdl_joystick_id = sdl_joystick_id;+ new_device->sdl_gamepad = sdl_gamepad;+ new_device->description = build_description(handle, sdl_joystick_id, sdl_gamepad);+ device = new_device.ptr();+ m_devices.set(handle, move(new_device));+ }++ if (device->connected)+ return;+ read_current_state(*device, device->last_state);+ device->connected = true;+ if (on_gamepad_connected)+ on_gamepad_connected(device->description, device->last_state);+}++void SDLGamepadSource::device_disconnected(u32 sdl_joystick_id)+{+ auto* device = device_for_sdl_joystick_id(sdl_joystick_id);+ if (!device)+ return;+ auto handle = device->description.handle;+ remove_device(handle);+ if (on_gamepad_disconnected)+ on_gamepad_disconnected(handle);+}++void SDLGamepadSource::remove_device(Web::Gamepad::GamepadHandle handle)+{+ auto removed_device = m_devices.take(handle);+ if (!removed_device.has_value())+ return;+ auto& device = **removed_device;++ SDL_CloseGamepad(device.sdl_gamepad);+ if (device.virtual_sdl_joystick) {+ SDL_CloseJoystick(device.virtual_sdl_joystick);+ SDL_DetachVirtualJoystick(device.sdl_joystick_id);+ }+}++void SDLGamepadSource::rumble(Web::Gamepad::GamepadHandle handle, u16 low_frequency_magnitude, u16 high_frequency_magnitude, u32 duration_ms)+{+ // https://wiki.libsdl.org/SDL3/SDL_RumbleGamepad+ // "Each call to this function cancels any previous rumble effect, and calling it with 0 intensity stops any+ // rumbling."+ if (auto device = m_devices.get(handle); device.has_value())+ SDL_RumbleGamepad((*device)->sdl_gamepad, low_frequency_magnitude, high_frequency_magnitude, duration_ms);+}++void SDLGamepadSource::rumble_triggers(Web::Gamepad::GamepadHandle handle, u16 left_magnitude, u16 right_magnitude, u32 duration_ms)+{+ // https://wiki.libsdl.org/SDL3/SDL_RumbleGamepadTriggers+ // "Each call to this function cancels any previous trigger rumble effect, and calling it with 0 intensity stops+ // any rumbling."+ if (auto device = m_devices.get(handle); device.has_value())+ SDL_RumbleGamepadTriggers((*device)->sdl_gamepad, left_magnitude, right_magnitude, duration_ms);+}++Optional<Web::Gamepad::VirtualGamepad> SDLGamepadSource::create_virtual_gamepad()+{+ if (!start())+ return {};++ auto device = make<Device>();++ Vector<i32> buttons;+ Vector<i32> triggers;+ for (auto const& standard_gamepad_button : standard_gamepad_button_layout) {+ standard_gamepad_button.visit(+ [&](SDL_GamepadButton button) { buttons.append(button); },+ [&](SDL_GamepadAxis axis) { triggers.append(axis); });+ }++ Vector<i32> axes;+ for (auto const standard_gamepad_axis : standard_gamepad_axes_layout)+ axes.append(standard_gamepad_axis);++ SDL_VirtualJoystickDesc virtual_joystick_desc {};+ SDL_INIT_INTERFACE(&virtual_joystick_desc);++ virtual_joystick_desc.type = SDL_JOYSTICK_TYPE_GAMEPAD;+ virtual_joystick_desc.naxes = axes.size() + triggers.size();+ virtual_joystick_desc.nbuttons = buttons.size();++ u32 button_mask = 0;+ for (auto const button : buttons)+ button_mask |= 1 << button;++ virtual_joystick_desc.button_mask = button_mask;++ u32 axis_mask = 0;+ for (auto const axis : axes)+ axis_mask |= 1 << axis;++ for (auto const trigger : triggers)+ axis_mask |= 1 << trigger;++ virtual_joystick_desc.axis_mask = axis_mask;++ virtual_joystick_desc.name = VIRTUAL_GAMEPAD_NAME;+ virtual_joystick_desc.userdata = device.ptr();+ virtual_joystick_desc.Rumble = record_received_dual_rumble_effect;+ virtual_joystick_desc.RumbleTriggers = record_received_trigger_rumble_effect;++ auto sdl_joystick_id = SDL_AttachVirtualJoystick(&virtual_joystick_desc);+ if (sdl_joystick_id == 0) {+ dbgln("Failed to attach virtual joystick: {}", SDL_GetError());+ return {};+ }++ auto* sdl_joystick = SDL_OpenJoystick(sdl_joystick_id);+ auto* sdl_gamepad = SDL_OpenGamepad(sdl_joystick_id);+ if (!sdl_joystick || !sdl_gamepad) {+ dbgln("Failed to open virtual gamepad: {}", SDL_GetError());+ if (sdl_gamepad)+ SDL_CloseGamepad(sdl_gamepad);+ if (sdl_joystick)+ SDL_CloseJoystick(sdl_joystick);+ SDL_DetachVirtualJoystick(sdl_joystick_id);+ return {};+ }++ auto handle = m_next_handle++;+ device->sdl_joystick_id = sdl_joystick_id;+ device->sdl_gamepad = sdl_gamepad;+ device->description = build_description(handle, sdl_joystick_id, sdl_gamepad);+ device->virtual_sdl_joystick = sdl_joystick;+ m_devices.set(handle, move(device));++ return Web::Gamepad::VirtualGamepad { handle, move(buttons), move(axes), move(triggers) };+}++void SDLGamepadSource::set_virtual_gamepad_button(Web::Gamepad::GamepadHandle handle, i32 button, bool down)+{+ auto* device = virtual_device(handle);+ if (!device)+ return;+ SDL_SetJoystickVirtualButton(device->virtual_sdl_joystick, button, down);+ poll();+}++void SDLGamepadSource::set_virtual_gamepad_axis(Web::Gamepad::GamepadHandle handle, i32 axis, i16 value)+{+ auto* device = virtual_device(handle);+ if (!device)+ return;+ SDL_SetJoystickVirtualAxis(device->virtual_sdl_joystick, axis, value);+ poll();+}++void SDLGamepadSource::disconnect_virtual_gamepad(Web::Gamepad::GamepadHandle handle)+{+ if (virtual_device(handle))+ remove_device(handle);+}++Vector<Web::Gamepad::ReceivedDualRumbleEffect> SDLGamepadSource::virtual_gamepad_received_rumble_effects(Web::Gamepad::GamepadHandle handle)+{+ if (auto* device = virtual_device(handle))+ return device->received_dual_rumble_effects;+ return {};+}++Vector<Web::Gamepad::ReceivedTriggerRumbleEffect> SDLGamepadSource::virtual_gamepad_received_trigger_rumble_effects(Web::Gamepad::GamepadHandle handle)+{+ if (auto* device = virtual_device(handle))+ return device->received_trigger_rumble_effects;+ return {};+}++SDLGamepadSource::Device* SDLGamepadSource::device_for_sdl_joystick_id(u32 sdl_joystick_id)+{+ for (auto& entry : m_devices) {+ if (entry.value->sdl_joystick_id == sdl_joystick_id)+ return entry.value.ptr();+ }+ return nullptr;+}++SDLGamepadSource::Device* SDLGamepadSource::virtual_device(Web::Gamepad::GamepadHandle handle)+{+ auto device = m_devices.get(handle);+ if (!device.has_value() || !(*device)->virtual_sdl_joystick)+ return nullptr;+ return *device;+}++Web::Gamepad::GamepadDescription SDLGamepadSource::build_description(Web::Gamepad::GamepadHandle handle, u32 sdl_joystick_id, SDL_Gamepad* sdl_gamepad) const+{+ Web::Gamepad::GamepadDescription description;+ description.handle = handle;++ if (auto const* name = SDL_GetGamepadNameForID(sdl_joystick_id))+ description.id = String::from_utf8_with_replacement_character(StringView { name, strlen(name) });++ SDL_PropertiesID sdl_gamepad_properties = SDL_GetGamepadProperties(sdl_gamepad);+ description.supports_dual_rumble = SDL_GetBooleanProperty(sdl_gamepad_properties, SDL_PROP_GAMEPAD_CAP_RUMBLE_BOOLEAN, /* default_value= */ false);+ description.supports_trigger_rumble = SDL_GetBooleanProperty(sdl_gamepad_properties, SDL_PROP_GAMEPAD_CAP_TRIGGER_RUMBLE_BOOLEAN, /* default_value= */ false);++ bool has_standard_mapping = true;++ for (size_t canonical_index = 0; canonical_index < standard_gamepad_button_layout.size(); ++canonical_index) {+ bool has_input = standard_gamepad_button_layout[canonical_index].visit(+ [&](SDL_GamepadButton button) {+ return SDL_GamepadHasButton(sdl_gamepad, button);+ },+ [&](SDL_GamepadAxis axis) {+ return SDL_GamepadHasAxis(sdl_gamepad, axis);+ });++ if (!has_input) {+ has_standard_mapping = false;+ continue;+ }++ bool is_digital = standard_gamepad_button_layout[canonical_index].has<SDL_GamepadButton>();+ description.buttons.append({+ .canonical_index = static_cast<u32>(canonical_index),+ .logical_minimum = 0,+ // Buttons are binary inputs with SDL.+ // "Trigger axis values range from 0 (released) to SDL_JOYSTICK_AXIS_MAX (fully pressed) when reported by+ // SDL_GetGamepadAxis(). Note that this is not the same range that will be reported by the lower-level+ // SDL_GetJoystickAxis()."+ .logical_maximum = is_digital ? i16(1) : i16(SDL_JOYSTICK_AXIS_MAX),+ });+ }++ for (auto const non_standard_gamepad_button : non_standard_gamepad_button_layout) {+ if (!SDL_GamepadHasButton(sdl_gamepad, non_standard_gamepad_button))+ continue;+ description.buttons.append({+ .canonical_index = {},+ .logical_minimum = 0,+ .logical_maximum = 1,+ });+ }++ for (size_t canonical_index = 0; canonical_index < standard_gamepad_axes_layout.size(); ++canonical_index) {+ if (!SDL_GamepadHasAxis(sdl_gamepad, standard_gamepad_axes_layout[canonical_index])) {+ has_standard_mapping = false;+ continue;+ }+ description.axes.append({+ .canonical_index = static_cast<u32>(canonical_index),+ .logical_minimum = SDL_JOYSTICK_AXIS_MIN,+ .logical_maximum = SDL_JOYSTICK_AXIS_MAX,+ });+ }++ description.has_standard_mapping = has_standard_mapping;+ return description;+}++void SDLGamepadSource::read_current_state(Device const& device, Web::Gamepad::GamepadState& state) const+{+ state.handle = device.description.handle;+ state.axis_values.clear_with_capacity();+ state.button_values.clear_with_capacity();++ for (auto const standard_gamepad_axis : standard_gamepad_axes_layout) {+ if (SDL_GamepadHasAxis(device.sdl_gamepad, standard_gamepad_axis))+ state.axis_values.append(SDL_GetGamepadAxis(device.sdl_gamepad, standard_gamepad_axis));+ }++ for (auto const& standard_gamepad_button : standard_gamepad_button_layout) {+ standard_gamepad_button.visit(+ [&](SDL_GamepadButton button) {+ if (SDL_GamepadHasButton(device.sdl_gamepad, button))+ state.button_values.append(SDL_GetGamepadButton(device.sdl_gamepad, button) ? 1 : 0);+ },+ [&](SDL_GamepadAxis axis) {+ if (SDL_GamepadHasAxis(device.sdl_gamepad, axis))+ state.button_values.append(SDL_GetGamepadAxis(device.sdl_gamepad, axis));+ });+ }++ for (auto const non_standard_gamepad_button : non_standard_gamepad_button_layout) {+ if (SDL_GamepadHasButton(device.sdl_gamepad, non_standard_gamepad_button))+ state.button_values.append(SDL_GetGamepadButton(device.sdl_gamepad, non_standard_gamepad_button) ? 1 : 0);+ }+}++}diff --git a/Libraries/LibGamepad/SDLGamepadSource.h b/Libraries/LibGamepad/SDLGamepadSource.hnew file mode 100644index 00000000000..37df090b99a--- /dev/null+++ b/Libraries/LibGamepad/SDLGamepadSource.h@@ -0,0 +1,78 @@+/*+ * Copyright (c) 2026, Tim Ledbetter <[email protected]>+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/HashMap.h>+#include <AK/NonnullOwnPtr.h>+#include <AK/RefPtr.h>+#include <LibCore/Forward.h>+#include <LibWebView/GamepadSource.h>++struct SDL_Gamepad;+struct SDL_Joystick;+union SDL_Event;++namespace Gamepad {++enum class IgnoreSystemGamepads : u8 {+ No,+ Yes,+};++// Reads the gamepads through SDL, on the main thread.+class SDLGamepadSource final : public WebView::GamepadSource {+public:+ // Tests see only the virtual gamepads they make, and look at them when they ask.+ explicit SDLGamepadSource(IgnoreSystemGamepads);+ virtual ~SDLGamepadSource() override;++ struct Device {+ AK_ALLOC_WITH_KMALLOC;++ u32 sdl_joystick_id { 0 };+ SDL_Gamepad* sdl_gamepad { nullptr };+ Web::Gamepad::GamepadDescription description;+ bool connected { false };+ Web::Gamepad::GamepadState last_state;++ SDL_Joystick* virtual_sdl_joystick { nullptr };+ Vector<Web::Gamepad::ReceivedDualRumbleEffect> received_dual_rumble_effects;+ Vector<Web::Gamepad::ReceivedTriggerRumbleEffect> received_trigger_rumble_effects;+ };++private:+ virtual bool start() override;+ virtual void set_polling(bool) override;+ virtual void poll() override;+ virtual void rumble(Web::Gamepad::GamepadHandle, u16 low_frequency_magnitude, u16 high_frequency_magnitude, u32 duration_ms) override;+ virtual void rumble_triggers(Web::Gamepad::GamepadHandle, u16 left_magnitude, u16 right_magnitude, u32 duration_ms) override;++ virtual Optional<Web::Gamepad::VirtualGamepad> create_virtual_gamepad() override;+ virtual void set_virtual_gamepad_button(Web::Gamepad::GamepadHandle, i32 button, bool down) override;+ virtual void set_virtual_gamepad_axis(Web::Gamepad::GamepadHandle, i32 axis, i16 value) override;+ virtual void disconnect_virtual_gamepad(Web::Gamepad::GamepadHandle) override;+ virtual Vector<Web::Gamepad::ReceivedDualRumbleEffect> virtual_gamepad_received_rumble_effects(Web::Gamepad::GamepadHandle) override;+ virtual Vector<Web::Gamepad::ReceivedTriggerRumbleEffect> virtual_gamepad_received_trigger_rumble_effects(Web::Gamepad::GamepadHandle) override;++ void handle_sdl_event(SDL_Event const&);+ void device_connected(u32 sdl_joystick_id);+ void device_disconnected(u32 sdl_joystick_id);+ void remove_device(Web::Gamepad::GamepadHandle);+ Device* device_for_sdl_joystick_id(u32 sdl_joystick_id);+ Device* virtual_device(Web::Gamepad::GamepadHandle);+ Web::Gamepad::GamepadDescription build_description(Web::Gamepad::GamepadHandle, u32 sdl_joystick_id, SDL_Gamepad*) const;+ void read_current_state(Device const&, Web::Gamepad::GamepadState&) const;++ IgnoreSystemGamepads m_ignore_system_gamepads { IgnoreSystemGamepads::No };+ bool m_sdl_initialized { false };+ Web::Gamepad::GamepadHandle m_next_handle { 1 };+ OrderedHashMap<Web::Gamepad::GamepadHandle, NonnullOwnPtr<Device>> m_devices;+ RefPtr<Core::Timer> m_poll_timer;+ Web::Gamepad::GamepadState m_scratch_state;+};++}diff --git a/Libraries/LibWebView/CMakeLists.txt b/Libraries/LibWebView/CMakeLists.txtindex aadfac8a5e7..26b14898f86 100644--- a/Libraries/LibWebView/CMakeLists.txt+++ b/Libraries/LibWebView/CMakeLists.txt@@ -169,7 +169,7 @@ add_custom_target(generate_build_information DEPENDS ${build_information_stamp})ladybird_lib(LibWebView webview EXPLICIT_SYMBOL_EXPORT)add_dependencies(LibWebView generate_build_information)target_link_libraries(LibWebView PUBLIC LibCompositing LibSandbox LibWebCommon)-target_link_libraries(LibWebView PRIVATE LibCore LibCrypto LibDatabase LibDevTools LibFileSystem LibGfx LibHTTP LibImageDecoderClient LibIPC LibRequests LibMedia LibMediaClient LibUnicode LibURL LibTextCodec LibThreading SDL3::SDL3)+target_link_libraries(LibWebView PRIVATE LibCore LibCrypto LibDatabase LibDevTools LibFileSystem LibGfx LibHTTP LibImageDecoderClient LibIPC LibRequests LibMedia LibMediaClient LibUnicode LibURL LibTextCodec LibThreading)if (LINUX)# The connect broker asks the audio library where the daemon is before connecting a helper to it.diff --git a/Libraries/LibWebView/GamepadManager.cpp b/Libraries/LibWebView/GamepadManager.cppindex e2d3e539304..76095d07949 100644--- a/Libraries/LibWebView/GamepadManager.cpp+++ b/Libraries/LibWebView/GamepadManager.cpp@@ -6,7 +6,6 @@#include <AK/AnyOf.h>#include <AK/NeverDestroyed.h>-#include <LibCore/Timer.h>#include <LibWebCommon/Gamepad/GamepadInput.h>#include <LibWebCommon/Gamepad/GamepadStateBuffer.h>#include <LibWebView/Application.h>@@ -16,20 +15,8 @@#include <LibWebView/WebContentClient.h>#include <LibWebView/WebContentPage.h>-#include <SDL3/SDL_events.h>-#include <SDL3/SDL_gamepad.h>-#include <SDL3/SDL_hints.h>-#include <SDL3/SDL_init.h>-#include <SDL3/SDL_joystick.h>--#if defined(AK_OS_WINDOWS)-# include <objbase.h>-#endif-namespace WebView {-static constexpr int GAMEPAD_POLL_INTERVAL_MS = 8;-// A compromised WebContent process must not be able to request an unbounded rumble.static constexpr u32 GAMEPAD_EFFECT_MAX_DURATION_MS = 5'000;static constexpr u32 GAMEPAD_EFFECT_EXPIRATION_SLACK_MS = 1'000;@@ -39,135 +26,45 @@ static u32 effect_expiration_backstop_ms(u32 duration)return min(duration, GAMEPAD_EFFECT_MAX_DURATION_MS) + GAMEPAD_EFFECT_EXPIRATION_SLACK_MS;}-// https://w3c.github.io/gamepad/#dfn-standard-gamepad-// Type Index Location-// Button 0 Bottom button in right cluster-// 1 Right button in right cluster-// 2 Left button in right cluster-// 3 Top button in right cluster-// 4 Top left front button-// 5 Top right front button-// 6 Bottom left front button-// 7 Bottom right front button-// 8 Left button in center cluster-// 9 Right button in center cluster-// 10 Left stick pressed button-// 11 Right stick pressed button-// 12 Top button in left cluster-// 13 Bottom button in left cluster-// 14 Left button in left cluster-// 15 Right button in left cluster-// 16 Center button in center cluster-static Array<Variant<SDL_GamepadButton, SDL_GamepadAxis>, 17> const standard_gamepad_button_layout {- SDL_GAMEPAD_BUTTON_SOUTH,- SDL_GAMEPAD_BUTTON_EAST,- SDL_GAMEPAD_BUTTON_WEST,- SDL_GAMEPAD_BUTTON_NORTH,- SDL_GAMEPAD_BUTTON_LEFT_SHOULDER,- SDL_GAMEPAD_BUTTON_RIGHT_SHOULDER,- SDL_GAMEPAD_AXIS_LEFT_TRIGGER,- SDL_GAMEPAD_AXIS_RIGHT_TRIGGER,- SDL_GAMEPAD_BUTTON_BACK,- SDL_GAMEPAD_BUTTON_START,- SDL_GAMEPAD_BUTTON_LEFT_STICK,- SDL_GAMEPAD_BUTTON_RIGHT_STICK,- SDL_GAMEPAD_BUTTON_DPAD_UP,- SDL_GAMEPAD_BUTTON_DPAD_DOWN,- SDL_GAMEPAD_BUTTON_DPAD_LEFT,- SDL_GAMEPAD_BUTTON_DPAD_RIGHT,- SDL_GAMEPAD_BUTTON_GUIDE,-};--static Array<SDL_GamepadButton, 11> const non_standard_gamepad_button_layout {- SDL_GAMEPAD_BUTTON_MISC1,- SDL_GAMEPAD_BUTTON_RIGHT_PADDLE1,- SDL_GAMEPAD_BUTTON_LEFT_PADDLE1,- SDL_GAMEPAD_BUTTON_RIGHT_PADDLE2,- SDL_GAMEPAD_BUTTON_LEFT_PADDLE2,- SDL_GAMEPAD_BUTTON_TOUCHPAD,- SDL_GAMEPAD_BUTTON_MISC2,- SDL_GAMEPAD_BUTTON_MISC3,- SDL_GAMEPAD_BUTTON_MISC4,- SDL_GAMEPAD_BUTTON_MISC5,- SDL_GAMEPAD_BUTTON_MISC6,-};--// axes 0 Horizontal axis for left stick (negative left/positive right)-// 1 Vertical axis for left stick (negative up/positive down)-// 2 Horizontal axis for right stick (negative left/positive right)-// 3 Vertical axis for right stick (negative up/positive down)-static Array<SDL_GamepadAxis, 4> const standard_gamepad_axes_layout {- SDL_GAMEPAD_AXIS_LEFTX,- SDL_GAMEPAD_AXIS_LEFTY,- SDL_GAMEPAD_AXIS_RIGHTX,- SDL_GAMEPAD_AXIS_RIGHTY,-};--static constexpr char const* VIRTUAL_GAMEPAD_NAME = "Ladybird Virtual Gamepad";--static SDLCALL bool record_received_dual_rumble_effect(void* user_data, u16 low_frequency_rumble, u16 high_frequency_rumble)-{- auto* device = static_cast<GamepadManager::Device*>(user_data);- device->received_dual_rumble_effects.append({ low_frequency_rumble, high_frequency_rumble });- return true;-}--static SDLCALL bool record_received_trigger_rumble_effect(void* user_data, u16 left_rumble, u16 right_rumble)-{- auto* device = static_cast<GamepadManager::Device*>(user_data);- device->received_trigger_rumble_effects.append({ left_rumble, right_rumble });- return true;-}-GamepadManager& GamepadManager::the(){static NeverDestroyed<GamepadManager> s_the;return *s_the;}-bool GamepadManager::ensure_sdl_initialized()+void GamepadManager::set_source(OwnPtr<GamepadSource> source){- if (m_sdl_initialized)- return true;--#if defined(AK_OS_WINDOWS)- // Initialize COM in the multithreaded model before SDL gets a chance to initialize it apartment-threaded, which- // would add a high overhead to calls across threads. If another component already chose a model, keep it.- (void)CoInitializeEx(0, COINIT_MULTITHREADED);-#endif-- // Without this, SDL turns SIGINT and SIGTERM into quit events that nothing handles.- SDL_SetHint(SDL_HINT_NO_SIGNAL_HANDLERS, "1");+ m_source = move(source);+ m_source_started = false;+ if (!m_source)+ return;+ m_source->on_gamepad_connected = [this](auto description, auto state) {+ device_connected(move(description), move(state));+ notify_consumers_of_state_changes();+ };+ m_source->on_gamepad_disconnected = [this](auto handle) {+ remove_device(handle);+ notify_consumers_of_state_changes();+ };+ m_source->on_gamepad_states_changed = [this](auto states) {+ gamepads_changed(move(states));+ };+}- if (!SDL_Init(SDL_INIT_GAMEPAD)) {- dbgln("Failed to initialize SDL3: {}", SDL_GetError());+bool GamepadManager::ensure_source_started()+{+ if (!m_source)return false;- }-- m_sdl_initialized = true;- m_in_test_mode = Application::web_content_options().is_test_mode == IsTestMode::Yes;- return true;+ if (!m_source_started)+ m_source_started = m_source->start();+ return m_source_started;}void GamepadManager::update_polling_state(){// A process waiting for a gesture needs the polling that finds it.- bool should_poll = m_sdl_initialized && !m_in_test_mode && any_of(m_consumers, [](auto const& entry) { return !entry.value->pages_using_gamepads.is_empty(); });-- if (!should_poll) {- if (m_poll_timer)- m_poll_timer->stop();- return;- }-- if (!m_poll_timer) {- m_poll_timer = Core::Timer::create_repeating(AK::Duration::from_milliseconds(GAMEPAD_POLL_INTERVAL_MS), [this] {- drain_sdl_events();- publish_changed_input_states();- });- }-- m_poll_timer->start();+ if (m_source_started)+ m_source->set_polling(any_of(m_consumers, [](auto const& entry) { return !entry.value->pages_using_gamepads.is_empty(); }));}GamepadManager::Consumer* GamepadManager::ensure_consumer(WebContentClient& client)@@ -198,7 +95,7 @@ GamepadManager::Consumer* GamepadManager::ensure_consumer(WebContentClient& clievoid GamepadManager::page_did_start_using_gamepads(WebContentPage& page){- if (!ensure_sdl_initialized())+ if (!ensure_source_started())return;auto& client = page.client();@@ -206,8 +103,7 @@ void GamepadManager::page_did_start_using_gamepads(WebContentPage& page)if (!consumer)return;- drain_sdl_events();- publish_changed_input_states();+ m_source->poll();// A gamepad the user is still interacting with shows a gesture for the page too.consumer->pages_using_gamepads.set(page.id());@@ -241,8 +137,10 @@ void GamepadManager::client_disconnected(WebContentClient& client)if (entry.value->virtual_device_owner == &client)owned_virtual_devices.append(entry.key);}- for (auto handle : owned_virtual_devices)+ for (auto handle : owned_virtual_devices) {remove_device(handle);+ m_source->disconnect_virtual_gamepad(handle);+ }update_polling_state();}@@ -254,19 +152,19 @@ void GamepadManager::play_effect(WebContentClient& client, Web::Gamepad::Gamepadreturn;// The expiration only silences the device if the client dies or hangs before ending the effect.- auto apply_rumble = [&](WebContentClient*& effect_owner, auto sdl_rumble_function, u16 first_magnitude, u16 second_magnitude, u32 duration) {+ auto apply_rumble = [&](WebContentClient*& effect_owner, auto rumble_function, u16 first_magnitude, u16 second_magnitude, u32 duration) {bool is_stop = first_magnitude == 0 && second_magnitude == 0;if (is_stop && effect_owner != &client)return;effect_owner = is_stop ? nullptr : &client;- sdl_rumble_function(device->sdl_gamepad, first_magnitude, second_magnitude, is_stop ? 0 : effect_expiration_backstop_ms(duration));+ (m_source->*rumble_function)(handle, first_magnitude, second_magnitude, is_stop ? 0 : effect_expiration_backstop_ms(duration));};effect.visit([&](Web::Gamepad::GamepadDualRumbleEffect const& dual_rumble_effect) {- apply_rumble(device->dual_rumble_owner, SDL_RumbleGamepad, dual_rumble_effect.strong_magnitude, dual_rumble_effect.weak_magnitude, dual_rumble_effect.duration);+ apply_rumble(device->dual_rumble_owner, &GamepadSource::rumble, dual_rumble_effect.strong_magnitude, dual_rumble_effect.weak_magnitude, dual_rumble_effect.duration);},[&](Web::Gamepad::GamepadTriggerRumbleEffect const& trigger_rumble_effect) {- apply_rumble(device->trigger_rumble_owner, SDL_RumbleGamepadTriggers, trigger_rumble_effect.left_trigger_magnitude, trigger_rumble_effect.right_trigger_magnitude, trigger_rumble_effect.duration);+ apply_rumble(device->trigger_rumble_owner, &GamepadSource::rumble_triggers, trigger_rumble_effect.left_trigger_magnitude, trigger_rumble_effect.right_trigger_magnitude, trigger_rumble_effect.duration);});}@@ -276,99 +174,36 @@ void GamepadManager::stop_effects(WebContentClient& client, Web::Gamepad::Gamepaif (!device)return;- // https://wiki.libsdl.org/SDL3/SDL_RumbleGamepad- // "Each call to this function cancels any previous rumble effect, and calling it with 0 intensity stops any- // rumbling."if (device->dual_rumble_owner == &client) {device->dual_rumble_owner = nullptr;- SDL_RumbleGamepad(device->sdl_gamepad, 0, 0, 0);+ m_source->rumble(handle, 0, 0, 0);}- // https://wiki.libsdl.org/SDL3/SDL_RumbleGamepadTriggers- // "Each call to this function cancels any previous trigger rumble effect, and calling it with 0 intensity stops- // any rumbling."if (device->trigger_rumble_owner == &client) {device->trigger_rumble_owner = nullptr;- SDL_RumbleGamepadTriggers(device->sdl_gamepad, 0, 0, 0);+ m_source->rumble_triggers(handle, 0, 0, 0);}}Optional<Web::Gamepad::VirtualGamepad> GamepadManager::create_virtual_gamepad(WebContentClient& client){- if (!ensure_sdl_initialized())+ if (!ensure_source_started())return {};if (!ensure_consumer(client))return {};- auto device = make<Device>();-- Vector<i32> buttons;- Vector<i32> triggers;- for (auto const& standard_gamepad_button : standard_gamepad_button_layout) {- standard_gamepad_button.visit(- [&](SDL_GamepadButton button) { buttons.append(button); },- [&](SDL_GamepadAxis axis) { triggers.append(axis); });- }-- Vector<i32> axes;- for (auto const standard_gamepad_axis : standard_gamepad_axes_layout)- axes.append(standard_gamepad_axis);-- SDL_VirtualJoystickDesc virtual_joystick_desc {};- SDL_INIT_INTERFACE(&virtual_joystick_desc);-- virtual_joystick_desc.type = SDL_JOYSTICK_TYPE_GAMEPAD;- virtual_joystick_desc.naxes = axes.size() + triggers.size();- virtual_joystick_desc.nbuttons = buttons.size();-- u32 button_mask = 0;- for (auto const button : buttons)- button_mask |= 1 << button;-- virtual_joystick_desc.button_mask = button_mask;-- u32 axis_mask = 0;- for (auto const axis : axes)- axis_mask |= 1 << axis;-- for (auto const trigger : triggers)- axis_mask |= 1 << trigger;-- virtual_joystick_desc.axis_mask = axis_mask;-- virtual_joystick_desc.name = VIRTUAL_GAMEPAD_NAME;- virtual_joystick_desc.userdata = device.ptr();- virtual_joystick_desc.Rumble = record_received_dual_rumble_effect;- virtual_joystick_desc.RumbleTriggers = record_received_trigger_rumble_effect;-- auto sdl_joystick_id = SDL_AttachVirtualJoystick(&virtual_joystick_desc);- if (sdl_joystick_id == 0) {- dbgln("Failed to attach virtual joystick: {}", SDL_GetError());- return {};- }-- auto* sdl_joystick = SDL_OpenJoystick(sdl_joystick_id);- auto* sdl_gamepad = SDL_OpenGamepad(sdl_joystick_id);- if (!sdl_joystick || !sdl_gamepad) {- dbgln("Failed to open virtual gamepad: {}", SDL_GetError());- if (sdl_gamepad)- SDL_CloseGamepad(sdl_gamepad);- if (sdl_joystick)- SDL_CloseJoystick(sdl_joystick);- SDL_DetachVirtualJoystick(sdl_joystick_id);+ auto virtual_gamepad = m_source->create_virtual_gamepad();+ if (!virtual_gamepad.has_value())return {};- }- auto handle = m_next_handle++;- device->sdl_joystick_id = sdl_joystick_id;- device->sdl_gamepad = sdl_gamepad;- device->description = build_description(handle, sdl_joystick_id, sdl_gamepad);+ // The source tells of the connection, which announces the gamepad to its owner alone.+ auto device = make<Device>();+ device->description.handle = virtual_gamepad->handle;device->virtual_device_owner = &client;- device->virtual_sdl_joystick = sdl_joystick;- m_devices.set(handle, move(device));+ m_devices.set(virtual_gamepad->handle, move(device));- return Web::Gamepad::VirtualGamepad { handle, move(buttons), move(axes), move(triggers) };+ return virtual_gamepad;}void GamepadManager::set_virtual_gamepad_button(WebContentClient& client, Web::Gamepad::GamepadHandle handle, i32 button, bool down)@@ -376,9 +211,7 @@ void GamepadManager::set_virtual_gamepad_button(WebContentClient& client, Web::Gauto* device = virtual_device_owned_by_client(client, handle);if (!device)return;- SDL_SetJoystickVirtualButton(device->virtual_sdl_joystick, button, down);- drain_sdl_events();- publish_changed_input_states();+ m_source->set_virtual_gamepad_button(handle, button, down);}void GamepadManager::set_virtual_gamepad_axis(WebContentClient& client, Web::Gamepad::GamepadHandle handle, i32 axis, i16 value)@@ -386,9 +219,7 @@ void GamepadManager::set_virtual_gamepad_axis(WebContentClient& client, Web::Gamauto* device = virtual_device_owned_by_client(client, handle);if (!device)return;- SDL_SetJoystickVirtualAxis(device->virtual_sdl_joystick, axis, value);- drain_sdl_events();- publish_changed_input_states();+ m_source->set_virtual_gamepad_axis(handle, axis, value);}void GamepadManager::disconnect_virtual_gamepad(WebContentClient& client, Web::Gamepad::GamepadHandle handle)@@ -397,14 +228,13 @@ void GamepadManager::disconnect_virtual_gamepad(WebContentClient& client, Web::Gif (!device)return;remove_device(handle);+ m_source->disconnect_virtual_gamepad(handle);}Vector<Web::Gamepad::GamepadChangeEvent> GamepadManager::pump_gamepad_events(WebContentClient& client){- if (m_sdl_initialized) {- drain_sdl_events();- publish_changed_input_states();- }+ if (m_source_started)+ m_source->poll();auto consumer = m_consumers.get(&client);if (!consumer.has_value())@@ -428,7 +258,7 @@ Vector<Web::Gamepad::ReceivedDualRumbleEffect> GamepadManager::virtual_gamepad_rauto* device = virtual_device_owned_by_client(client, handle);if (!device)return {};- return device->received_dual_rumble_effects;+ return m_source->virtual_gamepad_received_rumble_effects(handle);}Vector<Web::Gamepad::ReceivedTriggerRumbleEffect> GamepadManager::virtual_gamepad_received_trigger_rumble_effects(WebContentClient& client, Web::Gamepad::GamepadHandle handle)@@ -436,45 +266,19 @@ Vector<Web::Gamepad::ReceivedTriggerRumbleEffect> GamepadManager::virtual_gamepaauto* device = virtual_device_owned_by_client(client, handle);if (!device)return {};- return device->received_trigger_rumble_effects;+ return m_source->virtual_gamepad_received_trigger_rumble_effects(handle);}-void GamepadManager::drain_sdl_events()+void GamepadManager::gamepads_changed(Vector<Web::Gamepad::GamepadState> states){- SDL_Event event;- while (SDL_PollEvent(&event))- handle_sdl_event(event);-}--void GamepadManager::handle_sdl_event(SDL_Event const& event)-{- switch (event.type) {- case SDL_EVENT_GAMEPAD_ADDED:- device_connected(event.gdevice.which);- break;- case SDL_EVENT_GAMEPAD_REMOVED:- device_disconnected(event.gdevice.which);- break;- default:- break;- }-}--void GamepadManager::publish_changed_input_states()-{- for (auto& entry : m_devices) {- auto& device = *entry.value;- if (!device.announced)- continue;- // Compare freshly read state, since SDL suppresses some input events, such as a guide button release shortly- // after its press.- read_current_state(device, m_scratch_state);- if (m_scratch_state == device.last_published_state)+ for (auto& state : states) {+ auto* device = device_for_handle(state.handle);+ if (!device || !device->announced)continue;- device.last_published_state = m_scratch_state;+ device->last_published_state = move(state);for (auto& consumer_entry : m_consumers)- announce_devices_after_gamepad_user_gesture(*consumer_entry.value, device);- publish_device_state(device);+ announce_devices_after_gamepad_user_gesture(*consumer_entry.value, *device);+ publish_device_state(*device);}notify_consumers_of_state_changes();@@ -524,46 +328,27 @@ void GamepadManager::Consumer::notify_about_user_activation_for_gamepad_user_ges});}-void GamepadManager::device_connected(u32 sdl_joystick_id)+void GamepadManager::device_connected(Web::Gamepad::GamepadDescription description, Web::Gamepad::GamepadState state){- auto* device = device_for_sdl_joystick_id(sdl_joystick_id);-+ auto* device = device_for_handle(description.handle);if (!device) {- if (m_in_test_mode)- return;-- auto* sdl_gamepad = SDL_OpenGamepad(sdl_joystick_id);- if (!sdl_gamepad) {- dbgln("Failed to open gamepad: {}", SDL_GetError());- return;- }-- auto handle = m_next_handle++;auto new_device = make<Device>();- new_device->sdl_joystick_id = sdl_joystick_id;- new_device->sdl_gamepad = sdl_gamepad;- new_device->description = build_description(handle, sdl_joystick_id, sdl_gamepad);device = new_device.ptr();- m_devices.set(handle, move(new_device));+ m_devices.set(description.handle, move(new_device));}+ if (device->announced)+ return;+ device->description = move(description);+ device->last_published_state = move(state);announce_device(*device);}-void GamepadManager::device_disconnected(u32 sdl_joystick_id)-{- auto* device = device_for_sdl_joystick_id(sdl_joystick_id);- if (!device)- return;- remove_device(device->description.handle);-}-void GamepadManager::announce_device(Device& device){if (device.announced)return;- read_current_state(device, device.last_published_state);device.announced = true;for (auto& entry : m_consumers) {@@ -672,107 +457,6 @@ void GamepadManager::remove_device(Web::Gamepad::GamepadHandle handle)fill_vacant_slots(consumer);}-- SDL_CloseGamepad(device.sdl_gamepad);- if (device.virtual_sdl_joystick) {- SDL_CloseJoystick(device.virtual_sdl_joystick);- SDL_DetachVirtualJoystick(device.sdl_joystick_id);- }-}--Web::Gamepad::GamepadDescription GamepadManager::build_description(Web::Gamepad::GamepadHandle handle, u32 sdl_joystick_id, SDL_Gamepad* sdl_gamepad) const-{- Web::Gamepad::GamepadDescription description;- description.handle = handle;-- if (auto const* name = SDL_GetGamepadNameForID(sdl_joystick_id))- description.id = String::from_utf8_with_replacement_character(StringView { name, strlen(name) });-- SDL_PropertiesID sdl_gamepad_properties = SDL_GetGamepadProperties(sdl_gamepad);- description.supports_dual_rumble = SDL_GetBooleanProperty(sdl_gamepad_properties, SDL_PROP_GAMEPAD_CAP_RUMBLE_BOOLEAN, /* default_value= */ false);- description.supports_trigger_rumble = SDL_GetBooleanProperty(sdl_gamepad_properties, SDL_PROP_GAMEPAD_CAP_TRIGGER_RUMBLE_BOOLEAN, /* default_value= */ false);-- bool has_standard_mapping = true;-- for (size_t canonical_index = 0; canonical_index < standard_gamepad_button_layout.size(); ++canonical_index) {- bool has_input = standard_gamepad_button_layout[canonical_index].visit(- [&](SDL_GamepadButton button) {- return SDL_GamepadHasButton(sdl_gamepad, button);- },- [&](SDL_GamepadAxis axis) {- return SDL_GamepadHasAxis(sdl_gamepad, axis);- });-- if (!has_input) {- has_standard_mapping = false;- continue;- }-- bool is_digital = standard_gamepad_button_layout[canonical_index].has<SDL_GamepadButton>();- description.buttons.append({- .canonical_index = static_cast<u32>(canonical_index),- .logical_minimum = 0,- // Buttons are binary inputs with SDL.- // "Trigger axis values range from 0 (released) to SDL_JOYSTICK_AXIS_MAX (fully pressed) when reported by- // SDL_GetGamepadAxis(). Note that this is not the same range that will be reported by the lower-level- // SDL_GetJoystickAxis()."- .logical_maximum = is_digital ? i16(1) : i16(SDL_JOYSTICK_AXIS_MAX),- });- }-- for (auto const non_standard_gamepad_button : non_standard_gamepad_button_layout) {- if (!SDL_GamepadHasButton(sdl_gamepad, non_standard_gamepad_button))- continue;- description.buttons.append({- .canonical_index = {},- .logical_minimum = 0,- .logical_maximum = 1,- });- }-- for (size_t canonical_index = 0; canonical_index < standard_gamepad_axes_layout.size(); ++canonical_index) {- if (!SDL_GamepadHasAxis(sdl_gamepad, standard_gamepad_axes_layout[canonical_index])) {- has_standard_mapping = false;- continue;- }- description.axes.append({- .canonical_index = static_cast<u32>(canonical_index),- .logical_minimum = SDL_JOYSTICK_AXIS_MIN,- .logical_maximum = SDL_JOYSTICK_AXIS_MAX,- });- }-- description.has_standard_mapping = has_standard_mapping;- return description;-}--void GamepadManager::read_current_state(Device const& device, Web::Gamepad::GamepadState& state) const-{- state.handle = device.description.handle;- state.axis_values.clear_with_capacity();- state.button_values.clear_with_capacity();-- for (auto const standard_gamepad_axis : standard_gamepad_axes_layout) {- if (SDL_GamepadHasAxis(device.sdl_gamepad, standard_gamepad_axis))- state.axis_values.append(SDL_GetGamepadAxis(device.sdl_gamepad, standard_gamepad_axis));- }-- for (auto const& standard_gamepad_button : standard_gamepad_button_layout) {- standard_gamepad_button.visit(- [&](SDL_GamepadButton button) {- if (SDL_GamepadHasButton(device.sdl_gamepad, button))- state.button_values.append(SDL_GetGamepadButton(device.sdl_gamepad, button) ? 1 : 0);- },- [&](SDL_GamepadAxis axis) {- if (SDL_GamepadHasAxis(device.sdl_gamepad, axis))- state.button_values.append(SDL_GetGamepadAxis(device.sdl_gamepad, axis));- });- }-- for (auto const non_standard_gamepad_button : non_standard_gamepad_button_layout) {- if (SDL_GamepadHasButton(device.sdl_gamepad, non_standard_gamepad_button))- state.button_values.append(SDL_GetGamepadButton(device.sdl_gamepad, non_standard_gamepad_button) ? 1 : 0);- }}Optional<size_t> GamepadManager::Consumer::allocate_shared_state_slot(Web::Gamepad::GamepadHandle handle)@@ -816,13 +500,4 @@ GamepadManager::Device* GamepadManager::device_announced_to_client(WebContentClireturn device_for_handle(handle);}-GamepadManager::Device* GamepadManager::device_for_sdl_joystick_id(u32 sdl_joystick_id)-{- for (auto& entry : m_devices) {- if (entry.value->sdl_joystick_id == sdl_joystick_id)- return entry.value.ptr();- }- return nullptr;-}-}diff --git a/Libraries/LibWebView/GamepadManager.h b/Libraries/LibWebView/GamepadManager.hindex 4b589805ed0..0e676bc4e27 100644--- a/Libraries/LibWebView/GamepadManager.h+++ b/Libraries/LibWebView/GamepadManager.h@@ -18,11 +18,7 @@#include <LibWebCommon/Gamepad/GamepadSnapshot.h>#include <LibWebCommon/Page/PageId.h>#include <LibWebView/Forward.h>--struct SDL_Gamepad;-struct SDL_Joystick;--union SDL_Event;+#include <LibWebView/GamepadSource.h>namespace WebView {@@ -32,6 +28,9 @@ class WEBVIEW_API GamepadManager {public:static GamepadManager& the();+ // Without a source, pages find no gamepads.+ void set_source(OwnPtr<GamepadSource>);+void page_did_start_using_gamepads(WebContentPage&);void page_closed(WebContentPage&);void client_disconnected(WebContentClient&);@@ -54,8 +53,6 @@ public:bool contains_gamepad_user_gesture() const;bool may_be_announced_to(WebContentClient const&) const;- u32 sdl_joystick_id { 0 };- SDL_Gamepad* sdl_gamepad { nullptr };Web::Gamepad::GamepadDescription description;bool announced { false };WebContentClient* dual_rumble_owner { nullptr };@@ -63,9 +60,6 @@ public:Web::Gamepad::GamepadState last_published_state;WebContentClient* virtual_device_owner { nullptr };- SDL_Joystick* virtual_sdl_joystick { nullptr };- Vector<Web::Gamepad::ReceivedDualRumbleEffect> received_dual_rumble_effects;- Vector<Web::Gamepad::ReceivedTriggerRumbleEffect> received_trigger_rumble_effects;};struct Consumer {@@ -93,26 +87,19 @@ public:};private:- bool ensure_sdl_initialized();+ bool ensure_source_started();void update_polling_state();- void drain_sdl_events();- void handle_sdl_event(SDL_Event const&);- void publish_changed_input_states();+ void gamepads_changed(Vector<Web::Gamepad::GamepadState>);void publish_device_state(Device const&);void notify_consumers_of_state_changes();Consumer* ensure_consumer(WebContentClient&);- void device_connected(u32 sdl_joystick_id);- void device_disconnected(u32 sdl_joystick_id);-- Web::Gamepad::GamepadDescription build_description(Web::Gamepad::GamepadHandle, u32 sdl_joystick_id, SDL_Gamepad*) const;- void read_current_state(Device const&, Web::Gamepad::GamepadState&) const;+ void device_connected(Web::Gamepad::GamepadDescription, Web::Gamepad::GamepadState);Device* device_for_handle(Web::Gamepad::GamepadHandle);Device* virtual_device_owned_by_client(WebContentClient&, Web::Gamepad::GamepadHandle);Device* device_announced_to_client(WebContentClient&, Web::Gamepad::GamepadHandle);- Device* device_for_sdl_joystick_id(u32 sdl_joystick_id);void announce_device(Device&);void announce_device_to_consumer(Device const&, Consumer&);@@ -120,14 +107,11 @@ private:void announce_devices_after_gamepad_user_gesture(Consumer&, Device const&);void remove_device(Web::Gamepad::GamepadHandle);- bool m_sdl_initialized { false };- bool m_in_test_mode { false };- Web::Gamepad::GamepadHandle m_next_handle { 1 };+ OwnPtr<GamepadSource> m_source;+ bool m_source_started { false };OrderedHashMap<Web::Gamepad::GamepadHandle, NonnullOwnPtr<Device>> m_devices;HashMap<WebContentClient*, NonnullOwnPtr<Consumer>> m_consumers;- RefPtr<Core::Timer> m_poll_timer;- Web::Gamepad::GamepadState m_scratch_state;};}diff --git a/Libraries/LibWebView/GamepadSource.h b/Libraries/LibWebView/GamepadSource.hnew file mode 100644index 00000000000..ae11d10605c--- /dev/null+++ b/Libraries/LibWebView/GamepadSource.h@@ -0,0 +1,52 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Function.h>+#include <AK/Optional.h>+#include <AK/Vector.h>+#include <LibWebCommon/Gamepad/GamepadSnapshot.h>+#include <LibWebView/Export.h>++namespace WebView {++// The gamepads of the system, and the virtual ones that tests make. The GamepadManager decides which pages learn of+// them.+class WEBVIEW_API GamepadSource {+ AK_ALLOC_WITH_KMALLOC;++public:+ virtual ~GamepadSource() = default;++ // Starts looking for gamepads. False if the platform can't.+ virtual bool start() = 0;++ // Whether to look at the gamepads by itself, as often as a game needs. Otherwise it looks only in poll().+ virtual void set_polling(bool) = 0;++ // Reports what changed since it last looked, if it can look right away.+ virtual void poll() = 0;++ // A duration of 0 with magnitudes of 0 stops the effect.+ virtual void rumble(Web::Gamepad::GamepadHandle, u16 low_frequency_magnitude, u16 high_frequency_magnitude, u32 duration_ms) = 0;+ virtual void rumble_triggers(Web::Gamepad::GamepadHandle, u16 left_magnitude, u16 right_magnitude, u32 duration_ms) = 0;++ // Virtual gamepads, for tests. They report a connection like any other gamepad.+ virtual Optional<Web::Gamepad::VirtualGamepad> create_virtual_gamepad() { return {}; }+ virtual void set_virtual_gamepad_button(Web::Gamepad::GamepadHandle, i32, bool) { }+ virtual void set_virtual_gamepad_axis(Web::Gamepad::GamepadHandle, i32, i16) { }+ virtual void disconnect_virtual_gamepad(Web::Gamepad::GamepadHandle) { }+ virtual Vector<Web::Gamepad::ReceivedDualRumbleEffect> virtual_gamepad_received_rumble_effects(Web::Gamepad::GamepadHandle) { return {}; }+ virtual Vector<Web::Gamepad::ReceivedTriggerRumbleEffect> virtual_gamepad_received_trigger_rumble_effects(Web::Gamepad::GamepadHandle) { return {}; }++ Function<void(Web::Gamepad::GamepadDescription, Web::Gamepad::GamepadState)> on_gamepad_connected;+ Function<void(Web::Gamepad::GamepadHandle)> on_gamepad_disconnected;+ // The states that changed since the source last looked.+ Function<void(Vector<Web::Gamepad::GamepadState>)> on_gamepad_states_changed;+};++}diff --git a/Services/Hub/ConnectionFromUI.cpp b/Services/Hub/ConnectionFromUI.cppindex f30126e2b9a..e04994b5860 100644--- a/Services/Hub/ConnectionFromUI.cpp+++ b/Services/Hub/ConnectionFromUI.cpp@@ -13,6 +13,7 @@#include <LibRequests/RequestClient.h>#include <LibWebView/BrowsingSession.h>#include <LibWebView/CrashReportStore.h>+#include <LibWebView/GamepadManager.h>#include <LibWebView/MicrophoneAuthorizer.h>#include <LibWebView/PageTranslation.h>#include <LibWebView/ProcessSnapshot.h>@@ -29,6 +30,8 @@ ConnectionFromUI::ConnectionFromUI(NonnullOwnPtr<IPC::Transport> transport){s_the = this;+ // NB: The UI reads the gamepads.+ WebView::GamepadManager::the().set_source(make<GamepadSourceInUI>());Application::settings().on_persist = [this](JsonValue const& settings) {async_settings_changed(settings.serialized().to_byte_string(), m_last_applied_settings_change_id);};@@ -294,6 +297,24 @@ void ConnectionFromUI::microphone_authorization_changed(WebView::MicrophoneAuthoauthorizer->did_change_authorization(authorization);}+void ConnectionFromUI::gamepad_connected(Web::Gamepad::GamepadDescription description, Web::Gamepad::GamepadState state)+{+ if (auto* source = GamepadSourceInUI::the(); source && source->on_gamepad_connected)+ source->on_gamepad_connected(move(description), move(state));+}++void ConnectionFromUI::gamepad_disconnected(u32 handle)+{+ if (auto* source = GamepadSourceInUI::the(); source && source->on_gamepad_disconnected)+ source->on_gamepad_disconnected(handle);+}++void ConnectionFromUI::gamepad_states_changed(Vector<Web::Gamepad::GamepadState> states)+{+ if (auto* source = GamepadSourceInUI::the(); source && source->on_gamepad_states_changed)+ source->on_gamepad_states_changed(move(states));+}+void ConnectionFromUI::translator_language_detected(u64 request_id, Optional<String> language){if (auto* translator = TranslatorInUI::the())diff --git a/Services/Hub/ConnectionFromUI.h b/Services/Hub/ConnectionFromUI.hindex aff8afeb4c5..bf59fe8a53c 100644--- a/Services/Hub/ConnectionFromUI.h+++ b/Services/Hub/ConnectionFromUI.h@@ -114,6 +114,9 @@ private:virtual void geolocation_error(u64 id, Core::GeolocationError error) override;virtual void geolocation_authorization_changed(Core::GeolocationAuthorization authorization) override;virtual void microphone_authorization_changed(WebView::MicrophoneAuthorization authorization) override;+ virtual void gamepad_connected(Web::Gamepad::GamepadDescription description, Web::Gamepad::GamepadState state) override;+ virtual void gamepad_disconnected(u32 handle) override;+ virtual void gamepad_states_changed(Vector<Web::Gamepad::GamepadState> states) override;virtual void system_time_zone_changed() override;virtual void translator_language_detected(u64 request_id, Optional<String> language) override;virtual void translator_target_languages_ready(u64 request_id, Vector<WebView::Translator::TargetLanguage> target_languages) override;diff --git a/Services/Hub/HubClient.ipc b/Services/Hub/HubClient.ipcindex 2198c0c1e34..ac107afcc60 100644--- a/Services/Hub/HubClient.ipc+++ b/Services/Hub/HubClient.ipc@@ -15,6 +15,7 @@#include <LibURL/URL.h>#include <LibWebCommon/CSS/PreferredColorScheme.h>#include <LibWebCommon/Loader/NavigatorCompatibilityMode.h>+#include <LibWebCommon/Gamepad/GamepadSnapshot.h>#include <LibWebCommon/Page/SpellingError.h>#include <LibWebCommon/Page/Translation.h>#include <LibWebCommon/Page/WritingSuggestion.h>@@ -248,6 +249,10 @@ endpoint HubClienttranslator_translate(u64 request_id, u64 session_id, Web::TranslationUnit unit) =|translator_open_language_download_settings() =|microphone_request_authorization() =|+ gamepad_start(bool ignore_system_gamepads) =|+ gamepad_set_polling(bool polling) =|+ gamepad_rumble(u32 handle, u16 low_frequency_magnitude, u16 high_frequency_magnitude, u32 duration_ms) =|+ gamepad_rumble_triggers(u32 handle, u16 left_magnitude, u16 right_magnitude, u32 duration_ms) =|spell_checker_close_document(i64 document_tag) =|spell_checker_check(u64 request_id, i64 document_tag, Utf16String text) =|spell_checker_guesses(u64 request_id, i64 document_tag, Utf16String word) =|diff --git a/Services/Hub/HubServer.ipc b/Services/Hub/HubServer.ipcindex fcb28a85f53..d5444761cff 100644--- a/Services/Hub/HubServer.ipc+++ b/Services/Hub/HubServer.ipc@@ -18,6 +18,7 @@#include <LibWebCommon/HTML/ActivateTab.h>#include <LibWebCommon/Loader/NavigatorCompatibilityMode.h>#include <LibWebCommon/HTML/VisibilityState.h>+#include <LibWebCommon/Gamepad/GamepadSnapshot.h>#include <LibWebCommon/Page/SpellingError.h>#include <LibWebCommon/Page/WritingSuggestion.h>#include <LibWebCommon/Clipboard/SystemClipboard.h>@@ -185,6 +186,9 @@ endpoint HubServergeolocation_error(u64 id, Core::GeolocationError error) =|geolocation_authorization_changed(Core::GeolocationAuthorization authorization) =|microphone_authorization_changed(WebView::MicrophoneAuthorization authorization) =|+ gamepad_connected(Web::Gamepad::GamepadDescription description, Web::Gamepad::GamepadState state) =|+ gamepad_disconnected(u32 handle) =|+ gamepad_states_changed(Vector<Web::Gamepad::GamepadState> states) =|system_time_zone_changed() =|translator_language_detected(u64 request_id, Optional<String> language) =|translator_target_languages_ready(u64 request_id, Vector<WebView::Translator::TargetLanguage> target_languages) =|diff --git a/Services/Hub/Proxies.cpp b/Services/Hub/Proxies.cppindex 7d01d596cae..154cc33016d 100644--- a/Services/Hub/Proxies.cpp+++ b/Services/Hub/Proxies.cpp@@ -8,6 +8,7 @@#include <Hub/Application.h>#include <Hub/ConnectionFromUI.h>#include <Hub/Proxies.h>+#include <LibWebView/Application.h>namespace Hub {@@ -220,6 +221,48 @@ void MicrophoneAuthorizerInUI::did_change_authorization(WebView::MicrophoneAuthoon_complete(authorization);}+static GamepadSourceInUI* s_gamepad_source = nullptr;++GamepadSourceInUI::GamepadSourceInUI()+{+ s_gamepad_source = this;+}++GamepadSourceInUI::~GamepadSourceInUI()+{+ s_gamepad_source = nullptr;+}++GamepadSourceInUI* GamepadSourceInUI::the()+{+ return s_gamepad_source;+}++bool GamepadSourceInUI::start()+{+ if (auto* ui = ConnectionFromUI::the())+ ui->async_gamepad_start(WebView::Application::web_content_options().is_test_mode == WebView::IsTestMode::Yes);+ return true;+}++void GamepadSourceInUI::set_polling(bool polling)+{+ if (auto* ui = ConnectionFromUI::the())+ ui->async_gamepad_set_polling(polling);+}++void GamepadSourceInUI::rumble(Web::Gamepad::GamepadHandle handle, u16 low_frequency_magnitude, u16 high_frequency_magnitude, u32 duration_ms)+{+ if (auto* ui = ConnectionFromUI::the())+ ui->async_gamepad_rumble(handle, low_frequency_magnitude, high_frequency_magnitude, duration_ms);+}++void GamepadSourceInUI::rumble_triggers(Web::Gamepad::GamepadHandle handle, u16 left_magnitude, u16 right_magnitude, u32 duration_ms)+{+ if (auto* ui = ConnectionFromUI::the())+ ui->async_gamepad_rumble_triggers(handle, left_magnitude, right_magnitude, duration_ms);+}+static TranslatorInUI* s_translator = nullptr;TranslatorInUI::TranslatorInUI()diff --git a/Services/Hub/Proxies.h b/Services/Hub/Proxies.hindex 7e39a392fbb..2257a0a8f1e 100644--- a/Services/Hub/Proxies.h+++ b/Services/Hub/Proxies.h@@ -12,6 +12,7 @@#include <Hub/View.h>#include <LibCore/GeolocationProvider.h>#include <LibWebView/ExternalURLHandler.h>+#include <LibWebView/GamepadSource.h>#include <LibWebView/MicrophoneAuthorizer.h>#include <LibWebView/NotificationBackend.h>#include <LibWebView/PictureInPictureWindow.h>@@ -118,6 +119,22 @@ private:Vector<Function<void(WebView::MicrophoneAuthorization)>> m_pending_requests;};+class GamepadSourceInUI final : public WebView::GamepadSource {+public:+ GamepadSourceInUI();+ virtual ~GamepadSourceInUI() override;++ static GamepadSourceInUI* the();++private:+ virtual bool start() override;+ virtual void set_polling(bool) override;+ // NB: The UI reports what changes as it sees it.+ virtual void poll() override { }+ virtual void rumble(Web::Gamepad::GamepadHandle, u16 low_frequency_magnitude, u16 high_frequency_magnitude, u32 duration_ms) override;+ virtual void rumble_triggers(Web::Gamepad::GamepadHandle, u16 left_magnitude, u16 right_magnitude, u32 duration_ms) override;+};+class TranslatorInUI final : public WebView::Translator {public:TranslatorInUI();diff --git a/Tests/LibWeb/test-web/Application.cpp b/Tests/LibWeb/test-web/Application.cppindex 7b8482d5304..680626a65ae 100644--- a/Tests/LibWeb/test-web/Application.cpp+++ b/Tests/LibWeb/test-web/Application.cpp@@ -13,7 +13,9 @@#include <LibCore/File.h>#include <LibCore/StandardPaths.h>#include <LibCore/System.h>+#include <LibGamepad/SDLGamepadSource.h>#include <LibWebCommon/Loader/DownloadFilename.h>+#include <LibWebView/GamepadManager.h>#include <LibWebView/NotificationManager.h>#include <LibWebView/RecordingNotificationBackend.h>#include <LibWebView/TestSpellChecker.h>@@ -36,6 +38,7 @@ Application::Application(Optional<ByteString> ladybird_binary_path)set_spell_checker(make<WebView::TestSpellChecker>());set_translator(make<WebView::TestTranslator>());+ WebView::GamepadManager::the().set_source(make<Gamepad::SDLGamepadSource>(Gamepad::IgnoreSystemGamepads::Yes));}Application::~Application()diff --git a/Tests/LibWeb/test-web/CMakeLists.txt b/Tests/LibWeb/test-web/CMakeLists.txtindex 5137f3d5a30..a0fbe2e3b6c 100644--- a/Tests/LibWeb/test-web/CMakeLists.txt+++ b/Tests/LibWeb/test-web/CMakeLists.txt@@ -18,7 +18,7 @@ add_executable(test-web ${SOURCES})target_compile_definitions(test-web PRIVATE HAS_PDFJS=$<BOOL:${PDFJS_FOUND}>)target_compile_definitions(test-web PRIVATE LADYBIRD_PYTHON_EXECUTABLE="${LADYBIRD_TEST_PYTHON}")add_dependencies(test-web ladybird_build_resource_files ladybird_python_environment ${ladybird_helper_processes})-target_link_libraries(test-web PRIVATE AK LibCore LibDiff LibFileSystem LibGfx LibImageDecoders LibImageDecoderClient LibIPC LibJS LibMain LibRequests LibURL LibWeb LibWebView)+target_link_libraries(test-web PRIVATE AK LibCore LibDiff LibFileSystem LibGfx LibImageDecoders LibImageDecoderClient LibGamepad LibIPC LibJS LibMain LibRequests LibURL LibWeb LibWebView)if (APPLE)target_compile_definitions(test-web PRIVATE LADYBIRD_BINARY_PATH="$<TARGET_FILE_DIR:ladybird>")diff --git a/Tests/LibWebView/CMakeLists.txt b/Tests/LibWebView/CMakeLists.txtindex 235b9767439..01a867165f0 100644--- a/Tests/LibWebView/CMakeLists.txt+++ b/Tests/LibWebView/CMakeLists.txt@@ -153,7 +153,7 @@ if (NOT WIN32)endif()target_sources(TestLibWebView PRIVATE ${TEST_SOURCES})-target_link_libraries(TestLibWebView PRIVATE LibAudio LibCompositing LibDatabase LibGC LibGfx LibHTTP LibIPC LibRequests LibThreading LibURL LibWeb LibWebCommon LibWebView)+target_link_libraries(TestLibWebView PRIVATE LibAudio LibCompositing LibDatabase LibGamepad LibGC LibGfx LibHTTP LibIPC LibRequests LibThreading LibURL LibWeb LibWebCommon LibWebView)if (APPLE)add_dependencies(TestLibWebView ProcessReaper)diff --git a/Tests/LibWebView/HeadlessTest.cpp b/Tests/LibWebView/HeadlessTest.cppindex d4262745d18..ffa0f6e9b53 100644--- a/Tests/LibWebView/HeadlessTest.cpp+++ b/Tests/LibWebView/HeadlessTest.cpp@@ -12,6 +12,8 @@#include <LibCore/System.h>#include <LibCore/ThreadEventQueue.h>#include <LibFileSystem/FileSystem.h>+#include <LibGamepad/SDLGamepadSource.h>+#include <LibWebView/GamepadManager.h>#include <time.h>#include <unistd.h>@@ -20,6 +22,7 @@ namespace Test {HeadlessApplication::HeadlessApplication(Optional<ByteString> ladybird_binary_path): WebView::Application(move(ladybird_binary_path)){+ WebView::GamepadManager::the().set_source(make<Gamepad::SDLGamepadSource>(Gamepad::IgnoreSystemGamepads::Yes));}void HeadlessApplication::create_platform_options(WebView::BrowserOptions& browser_options, WebView::RequestServerOptions&, WebView::WebContentOptions& web_content_options)diff --git a/UI/CMakeLists.txt b/UI/CMakeLists.txtindex f43d0cb6e4d..d8528197a76 100644--- a/UI/CMakeLists.txt+++ b/UI/CMakeLists.txt@@ -111,7 +111,7 @@ else()set(LADYBIRD_TARGET ladybird PRIVATE)endif()-set(LADYBIRD_LIBS AK LibCore LibGfx LibIPC LibMain LibThreading LibWebView LibURL LibWakeLock hubipc)+set(LADYBIRD_LIBS AK LibCore LibGfx LibIPC LibMain LibThreading LibWebView LibURL LibWakeLock LibGamepad hubipc)# NB: Where the Hub is a process of its own, the UI must not be able to reach into it.if (LINUX OR APPLE)target_compile_definitions(${LADYBIRD_TARGET} LADYBIRD_HUB_IN_OWN_PROCESS)diff --git a/UI/Qt/HubConnection.cpp b/UI/Qt/HubConnection.cppindex 09712b69279..31b39487d57 100644--- a/UI/Qt/HubConnection.cpp+++ b/UI/Qt/HubConnection.cpp@@ -6,6 +6,7 @@#include <AK/JsonValue.h>#include <LibCore/Process.h>+#include <LibGamepad/SDLGamepadSource.h>#include <LibWebView/CrashReportOutbox.h>#include <LibWebView/MicrophoneAuthorizer.h>#include <UI/Qt/Application.h>@@ -542,6 +543,43 @@ void HubConnection::microphone_request_authorization()});}+// NB: The gamepads are read here, as the Hub links no platform input library. The Hub decides which pages learn of them.+void HubConnection::gamepad_start(bool ignore_system_gamepads)+{+ if (m_gamepad_source)+ return;+ m_gamepad_source = make<Gamepad::SDLGamepadSource>(ignore_system_gamepads ? Gamepad::IgnoreSystemGamepads::Yes : Gamepad::IgnoreSystemGamepads::No);+ m_gamepad_source->on_gamepad_connected = [this](auto description, auto state) {+ async_gamepad_connected(description, state);+ };+ m_gamepad_source->on_gamepad_disconnected = [this](auto handle) {+ async_gamepad_disconnected(handle);+ };+ m_gamepad_source->on_gamepad_states_changed = [this](auto states) {+ if (!states.is_empty())+ async_gamepad_states_changed(states);+ };+ m_gamepad_source->start();+}++void HubConnection::gamepad_set_polling(bool polling)+{+ if (m_gamepad_source)+ m_gamepad_source->set_polling(polling);+}++void HubConnection::gamepad_rumble(u32 handle, u16 low_frequency_magnitude, u16 high_frequency_magnitude, u32 duration_ms)+{+ if (m_gamepad_source)+ m_gamepad_source->rumble(handle, low_frequency_magnitude, high_frequency_magnitude, duration_ms);+}++void HubConnection::gamepad_rumble_triggers(u32 handle, u16 left_magnitude, u16 right_magnitude, u32 duration_ms)+{+ if (m_gamepad_source)+ m_gamepad_source->rumble_triggers(handle, left_magnitude, right_magnitude, duration_ms);+}+// The Hub picks its own tag for each document, and the platform gets a tag of its own the first time one is used.WebView::SpellChecker::DocumentTag HubConnection::spell_document_tag(WebView::SpellChecker& spell_checker, i64 document_tag){diff --git a/UI/Qt/HubConnection.h b/UI/Qt/HubConnection.hindex 13547711dfc..0b08419d80f 100644--- a/UI/Qt/HubConnection.h+++ b/UI/Qt/HubConnection.h@@ -11,6 +11,7 @@#include <Hub/HubServerEndpoint.h>#include <LibCore/GeolocationProvider.h>#include <LibIPC/ConnectionToServer.h>+#include <LibWebView/GamepadSource.h>#include <LibWebView/SpellChecker.h>namespace Ladybird {@@ -58,6 +59,8 @@ private:WebView::SpellChecker::DocumentTag spell_document_tag(WebView::SpellChecker&, i64 document_tag);HashMap<i64, WebView::SpellChecker::DocumentTag> m_spell_document_tags;+ OwnPtr<WebView::GamepadSource> m_gamepad_source;+// The Hub owns the settings. The settings here are its last word, plus the changes it has yet to confirm.struct SettingsChange {u64 id { 0 };@@ -96,6 +99,10 @@ private:virtual void translator_translate(u64 request_id, u64 session_id, Web::TranslationUnit unit) override;virtual void translator_open_language_download_settings() override;virtual void microphone_request_authorization() override;+ virtual void gamepad_start(bool ignore_system_gamepads) override;+ virtual void gamepad_set_polling(bool polling) override;+ virtual void gamepad_rumble(u32 handle, u16 low_frequency_magnitude, u16 high_frequency_magnitude, u32 duration_ms) override;+ virtual void gamepad_rumble_triggers(u32 handle, u16 left_magnitude, u16 right_magnitude, u32 duration_ms) override;virtual void spell_checker_close_document(i64 document_tag) override;virtual void spell_checker_check(u64 request_id, i64 document_tag, Utf16String text) override;virtual void spell_checker_guesses(u64 request_id, i64 document_tag, Utf16String word) override;