[SDL,plugin/hotkeys] Process gamepad events (#15449)

Gives Hotkeys the ability to configure gamepads, at least to a degree. Advanced users might wish to use a shoulder button or a trigger as a modifier like in Tony Hawk or Devil May Cry. But in that case I suggest they might be advanced enough to make a follow-up PR as well. It's out of scope for this one anyway.

Things like deadzones might prefer to be independently configurable in the future, but then again it's a reader app.

Depends on <https://github.com/koreader/koreader-base/pull/2376>.
This commit is contained in:
Frans de Jonge authored and GitHub committed 2026-06-06 20:56:55 +02:00
1 parent fb1dfebd9c
commit fa6b3cde8f
8 files changed
+352 -10

No files matched your search

+1 -1
Submodule base updated: 3a2a55cc47...1f9ad7658b.
+1
View File
@@ -47,6 +47,7 @@ local Device = {
canKeyRepeat = no,
hasDPad = no,
useDPadAsActionKeys = no,
supportsGamepad = no,
hasExitOptions = yes,
hasFewKeys = no,
hasWifiToggle = yes,
+73
View File
@@ -1,6 +1,8 @@
local Event = require("ui/event")
local Geom = require("ui/geometry")
local Gamepad = require("device/sdl/gamepad")
local Generic = require("device/generic/device")
local Key = require("device/key")
local UIManager
local SDL = require("ffi/SDL3")
local ffi = require("ffi")
@@ -72,6 +74,7 @@ local Device = Generic:extend{
hasSymKey = os.getenv("DISABLE_TOUCH") == "1" and yes or no,
hasDPad = yes,
useDPadAsActionKeys = os.getenv("DISABLE_TOUCH") == "1" and yes or no,
supportsGamepad = yes,
hasWifiToggle = no,
hasSeamlessWifiToggle = no,
isTouchDevice = yes,
@@ -201,6 +204,53 @@ function Device:init()
local ok, re = pcall(self.screen.setWindowIcon, self.screen, "resources/koreader.png")
if not ok then logger.warn(re) end
local function makeKeyPressEvent(keycode)
if not keycode then
return nil
end
return Event:new("KeyPress", Key:new(keycode, {}))
end
local function dispatchGamepadAxisMotion(axis, value, event_time)
local axis_ev = {
axis = axis,
value = value,
time = event_time,
}
if not UIManager:broadcastEvent(Event:new("GamepadAxisMotion", axis_ev)) then
local key_ev = makeKeyPressEvent(Gamepad:getAxisKeyName(axis, value))
if key_ev then
UIManager:sendEvent(key_ev)
end
end
end
local function unscheduleAxisRepeat(clear_state)
if self._axis_repeat_action then
UIManager:unschedule(self._axis_repeat_action)
self._axis_repeat_action = nil
end
if clear_state ~= false then
Gamepad:clearRepeatingAxis()
end
end
local function scheduleAxisRepeat(axis, delay_s)
unscheduleAxisRepeat(false)
Gamepad:setRepeatingAxis(axis)
self._axis_repeat_action = function()
local axis_ev = Gamepad:getHeldAxisEvent()
if not axis_ev then
Gamepad:clearRepeatingAxis()
self._axis_repeat_action = nil
return
end
dispatchGamepadAxisMotion(axis_ev.axis, axis_ev.value, time.now())
UIManager:scheduleIn(Gamepad.axis_repeat_interval_s, self._axis_repeat_action)
end
UIManager:scheduleIn(delay_s, self._axis_repeat_action)
end
self.input = require("device/input"):new{
device = self,
event_map = dofile("frontend/device/sdl/event_map_sdl2.lua"),
@@ -275,6 +325,29 @@ function Device:init()
elseif ev.code == SDL.SDL.SDL_EVENT_WINDOW_MOVED then
self.window.left = ev.value.data1
self.window.top = ev.value.data2
elseif ev.code == SDL.SDL.SDL_EVENT_GAMEPAD_AXIS_MOTION then
local should_process = Gamepad:shouldProcessAxisMotion(ev.value.axis, ev.value.value)
local held_direction = Gamepad:getHeldDirection(ev.value.axis)
if not held_direction then
if Gamepad.repeating_axis == ev.value.axis then
unscheduleAxisRepeat()
end
return
end
if should_process then
scheduleAxisRepeat(ev.value.axis, Gamepad.axis_repeat_delay_s)
dispatchGamepadAxisMotion(ev.value.axis, ev.value.value, time.timeval(ev.time))
end
return
elseif ev.code == SDL.SDL.SDL_EVENT_GAMEPAD_BUTTON_DOWN then
-- Broadcast for plugins; if not handled, emit default key events
if not UIManager:broadcastEvent(Event:new("GamepadButtonDown", ev.value)) then
return makeKeyPressEvent(Gamepad:getButtonKeyName(ev.value.button))
end
elseif ev.code == SDL.SDL.SDL_EVENT_GAMEPAD_BUTTON_UP then
UIManager:broadcastEvent(Event:new("GamepadButtonUp", ev.value))
elseif ev.code == SDL.SDL.SDL_EVENT_TEXT_INPUT then
UIManager:sendEvent(Event:new("TextInput", tostring(ev.value)))
end
+147
View File
@@ -0,0 +1,147 @@
local Gamepad = {
axis_press_deadzone = 5000,
axis_release_deadzone = 4500,
axis_repeat_delay_s = 0.5,
axis_repeat_interval_s = 0.2,
held_axis_directions = {},
repeating_axis = nil,
repeating_direction = nil,
button_ids = {
[0] = "a", [1] = "b", [2] = "x", [3] = "y", [4] = "back", [5] = "guide",
[6] = "start", [7] = "left_stick", [8] = "right_stick", [9] = "left_shoulder",
[10] = "right_shoulder", [11] = "dpad_up", [12] = "dpad_down",
[13] = "dpad_left", [14] = "dpad_right", [15] = "misc_1",
},
axis_ids = {
[0] = "left_x", [1] = "left_y", [2] = "right_x", [3] = "right_y",
[4] = "left_trigger", [5] = "right_trigger",
},
button_names = {
[0] = "South (A/B)",
[1] = "East (B/A)",
[2] = "West (X/Y)",
[3] = "North (Y/X)",
[4] = "Back",
[5] = "Guide",
[6] = "Start",
[7] = "Left Stick (L3)",
[8] = "Right Stick (R3)",
[9] = "Left Shoulder (L1)",
[10] = "Right Shoulder (R1)",
[11] = "D-pad Up",
[12] = "D-pad Down",
[13] = "D-pad Left",
[14] = "D-pad Right",
[15] = "Misc 1",
},
axis_names = {
[0] = "Left Stick X",
[1] = "Left Stick Y",
[2] = "Right Stick X",
[3] = "Right Stick Y",
[4] = "Left Trigger",
[5] = "Right Trigger",
},
button_key_names = {
[0] = "Press",
[1] = "Back",
[3] = "ContextMenu",
[4] = "RPgBack",
[5] = "RPgFwd",
[6] = "Menu",
[7] = "Menu",
[9] = "RPgBack",
[10] = "RPgFwd",
[11] = "Up",
[12] = "Down",
[13] = "Left",
[14] = "Right",
},
axis_key_names = {
[0] = { minus = "Left", plus = "Right" },
[1] = { minus = "Up", plus = "Down" },
[3] = { minus = "RPgBack", plus = "RPgFwd" },
},
}
function Gamepad:getAxisDirection(value, held_direction)
local deadzone = held_direction and self.axis_release_deadzone or self.axis_press_deadzone
if value > -deadzone and value < deadzone then
return nil
end
return value < 0 and "minus" or "plus"
end
function Gamepad:shouldProcessAxisMotion(axis, value)
local held_direction = self.held_axis_directions[axis]
local direction = self:getAxisDirection(value, held_direction)
if direction == held_direction then
return false
end
self.held_axis_directions[axis] = direction
if direction == nil and self.repeating_axis == axis then
self.repeating_axis = nil
self.repeating_direction = nil
end
return direction ~= nil
end
function Gamepad:getHeldDirection(axis)
return self.held_axis_directions[axis]
end
function Gamepad:setRepeatingAxis(axis)
self.repeating_axis = axis
self.repeating_direction = self.held_axis_directions[axis]
end
function Gamepad:isRepeatingAxisHeld()
return self.repeating_axis ~= nil
and self.held_axis_directions[self.repeating_axis] == self.repeating_direction
end
function Gamepad:clearRepeatingAxis(axis)
if axis == nil or self.repeating_axis == axis then
self.repeating_axis = nil
self.repeating_direction = nil
end
end
function Gamepad:getHeldAxisEvent()
if not self:isRepeatingAxisHeld() then
return nil
end
local value = self.repeating_direction == "minus"
and -(self.axis_press_deadzone + 1)
or self.axis_press_deadzone + 1
return {
axis = self.repeating_axis,
value = value,
}
end
function Gamepad:getAxisHotkeyName(axis, value)
local id = self.axis_ids[axis]
local direction = self:getAxisDirection(value)
if not id or not direction then
return nil
end
return "gamepad_axis_" .. id .. "_" .. direction
end
function Gamepad:getAxisKeyName(axis, value)
local mapping = self.axis_key_names[axis]
local direction = self:getAxisDirection(value)
if not mapping or not direction then
return nil
end
return mapping[direction]
end
function Gamepad:getButtonKeyName(button)
return self.button_key_names[button]
end
return Gamepad
+5
View File
@@ -33,6 +33,7 @@ local KoptOptions = require("ui/data/koptoptions")
local Device = require("device")
local Event = require("ui/event")
local FileManager = require("apps/filemanager/filemanager")
local Key = require("device/key")
local Notification = require("ui/widget/notification")
local ReaderDictionary = require("apps/reader/modules/readerdictionary")
local ReaderFooter = require("apps/reader/modules/readerfooter")
@@ -1327,6 +1328,10 @@ function Dispatcher:execute(settings, exec_props)
-- the event can accept a gesture object or a number
arg = v ~= 0 and v or gesture or 0
UIManager:sendEvent(Event:new(event, arg))
elseif category == "key" then
local key = Key:new(arg, {})
UIManager:sendEvent(Event:new("KeyPress", key))
UIManager:sendEvent(Event:new("KeyRelease", key))
end
end
end
+5 -1
View File
@@ -965,17 +965,21 @@ function UIManager:broadcastEvent(event)
-- Unlike sendEvent, we send the event to *all* (window-level) widgets (i.e., we don't stop, even if a handler returns true).
-- NOTE: Same defensive approach to _window_stack changing from under our feet as above.
local checked_widgets = {}
local handled = false
local i = #self._window_stack
while i > 0 do
local widget = self._window_stack[i].widget
if not checked_widgets[widget] then
checked_widgets[widget] = true
widget:handleEvent(event)
if widget:handleEvent(event) then
handled = true
end
i = #self._window_stack
else
i = i - 1
end
end
return handled
end
--[[
+33 -1
View File
@@ -1,5 +1,6 @@
-- typed on my Commodore 64 ;)
local Device = require("device")
local util = require("util")
-- The hotkey shortcuts defined here are only the defaults. The user can
-- change them at any time using the hotkey shortcuts configuration menu.
@@ -7,7 +8,8 @@ local Device = require("device")
-- should never be assigned to any action in this plugin, because they are already assigned
-- to events in core. If you assign them to actions in this plugin, those actions will be in
-- conflict with the existing ones and hell will break loose.
return {
local defaults = {
hotkeys_fm = {
modifier_plus_up = nil,
-- modifier_plus_down -- keep nil, brings up FM search widget (equivalent to tapping on 'Page x of y').
@@ -138,3 +140,33 @@ return {
u = nil, v = nil, w = nil, x = nil, y = nil, z = nil,
},
}
if Device:supportsGamepad() then
local gamepad_defaults = {
gamepad_axis_left_x_minus = {key_left = true,}, -- left
gamepad_axis_left_x_plus = {key_right = true,}, -- right
gamepad_axis_left_y_minus = {key_up = true,}, -- up
gamepad_axis_left_y_plus = {key_down = true,}, -- down
gamepad_axis_right_y_minus = {key_right_page_back = true,}, -- Page Up
gamepad_axis_right_y_plus = {key_right_page_forward = true,}, -- Page Down
gamepad_button_a = {key_press = true,}, -- South (A) -> Enter/Press
gamepad_button_b = {key_back = true,}, -- East (B) -> Escape
gamepad_button_y = {key_context_menu = true,}, -- North (Y) -> ContextMenu
gamepad_button_back = {key_right_page_back = true,}, -- Back
gamepad_button_guide = {key_right_page_forward = true,}, -- Guide
gamepad_button_start = {key_menu = true,}, -- Start
gamepad_button_left_stick = {key_menu = true,}, -- Left Stick
gamepad_button_left_shoulder = {key_right_page_back = true,}, -- Left Shoulder
gamepad_button_right_shoulder = {key_right_page_forward = true,}, -- Right Shoulder
gamepad_button_dpad_up = {key_up = true,}, -- D-pad Up
gamepad_button_dpad_down = {key_down = true,}, -- D-pad Down
gamepad_button_dpad_left = {key_left = true,}, -- D-pad Left
gamepad_button_dpad_right = {key_right = true,}, -- D-pad Right
}
for _, mode in ipairs({"hotkeys_fm", "hotkeys_reader"}) do
util.tableMerge(defaults[mode], gamepad_defaults)
end
end
return defaults
+87 -7
View File
@@ -2,6 +2,7 @@ local DataStorage = require("datastorage")
local Device = require("device")
local Dispatcher = require("dispatcher")
local InputContainer = require("ui/widget/container/inputcontainer")
local Gamepad = require("device/sdl/gamepad")
local LuaSettings = require("luasettings")
local UIManager = require("ui/uimanager")
local ffiUtil = require("ffi/util")
@@ -31,32 +32,61 @@ local base_keys = {
right_page_back = "RPgBack", right_page_forward = "RPgFwd",
back = "Back", home = "Home", press = "Press"
}
local key_emitter_actions = {
key_up = { key = "Up", title = T(_("Send key: %1"), _("Up")) },
key_down = { key = "Down", title = T(_("Send key: %1"), _("Down")) },
key_left = { key = "Left", title = T(_("Send key: %1"), _("Left")) },
key_right = { key = "Right", title = T(_("Send key: %1"), _("Right")) },
key_left_page_back = { key = "LPgBack", title = T(_("Send key: %1"), _("Left page back")) },
key_left_page_forward = { key = "LPgFwd", title = T(_("Send key: %1"), _("Left page forward")) },
key_right_page_back = { key = "RPgBack", title = T(_("Send key: %1"), _("Right page back")) },
key_right_page_forward = { key = "RPgFwd", title = T(_("Send key: %1"), _("Right page forward")) },
key_back = { key = "Back", title = T(_("Send key: %1"), _("Back")) },
key_home = { key = "Home", title = T(_("Send key: %1"), _("Home")) },
key_press = { key = "Press", title = T(_("Send key: %1"), _("Press")) },
key_menu = { key = "Menu", title = T(_("Send key: %1"), _("Menu")) },
key_context_menu = { key = "ContextMenu", title = T(_("Send key: %1"), _("Context menu")) },
}
-- modifier *here* refers to either screenkb or shift
local modifier_one = Device:hasScreenKB() and "ScreenKB + " or "Shift + "
local modifier_one = Device:hasScreenKB() and _("ScreenKB + %1") or _("Shift + %1")
-- screenkb/shift + base_keys
for key, label in pairs(base_keys) do
hotkeys_list["modifier_plus_" .. key] = _(modifier_one .. label)
hotkeys_list["modifier_plus_" .. key] = T(modifier_one, label)
-- modifier_plus_menu (screenkb+menu) is already used globally for screenshots (on k4), don't add it here.
end
if LuaSettings:open(hotkeys_path).data["press_key_does_hotkeys"] then
util.tableMerge(hotkeys_list, { press = _("Press") })
end
if Device:supportsGamepad() then
for i = 0, 15 do
local id = Gamepad.button_ids[i] or tostring(i)
local name = Gamepad.button_names[i] or T(_("Button %1"), i)
hotkeys_list["gamepad_button_" .. id] = T(_("Gamepad %1"), name)
end
for i = 0, 5 do
local id = Gamepad.axis_ids[i] or tostring(i)
local name = Gamepad.axis_names[i] or T(_("Axis %1"), i)
hotkeys_list["gamepad_axis_" .. id .. "_minus"] = T(_("Gamepad %1 –"), name)
hotkeys_list["gamepad_axis_" .. id .. "_plus"] = T(_("Gamepad %1 +"), name)
end
end
if Device:hasKeyboard() then
local hotkeys_list_haskeyboard = { modifier_plus_menu = _("Shift + Menu") }
-- now we can add the "menu" button to base_keys, so we can use it on haskeyboard devices
base_keys.menu = "Menu"
-- NOTE: we will use 'alt' for kindles and 'ctrl' for other devices with keyboards
-- but for simplicity we will use in code 'alt+keys' as the array's key for all.
local modifier_two = Device:hasSymKey() and "Alt + " or "Ctrl + "
local modifier_two = Device:hasSymKey() and _("Alt + %1") or _("Ctrl + %1")
-- Alt/Ctrl + base_keys
for key, label in pairs(base_keys) do
hotkeys_list_haskeyboard["alt_plus_" .. key] = _(modifier_two .. label)
hotkeys_list_haskeyboard["alt_plus_" .. key] = T(modifier_two, label)
end
local type_to_search = LuaSettings:open(hotkeys_path).data["type_to_search"]
-- Alt/Ctrl + alphabet keys and (no modifier) + alphabet keys
for dummy, char in ipairs(Device.input.group.Alphabet) do
hotkeys_list_haskeyboard["alt_plus_" .. char:lower()] = _(modifier_two .. char)
hotkeys_list_haskeyboard["alt_plus_" .. char:lower()] = T(modifier_two, char)
if not type_to_search then
hotkeys_list_haskeyboard[char:lower()] = char
end
@@ -72,9 +102,16 @@ function HotKeys:init()
if not self.settings_data then
self.settings_data = LuaSettings:open(hotkeys_path)
if not next(self.settings_data.data) then
logger.warn("No hotkeys file or invalid hotkeys file found, copying defaults")
logger.warn("No hotkeys file or invalid hotkeys file found, building defaults")
self.settings_data:purge()
ffiUtil.copyFile(defaults_path, hotkeys_path)
local defaults_src = LuaSettings:open(defaults_path).data
for mode_name, mode_data in pairs(defaults_src) do
self.settings_data.data[mode_name] = {}
for k, v in pairs(mode_data) do
self.settings_data.data[mode_name][k] = v
end
end
self.settings_data:flush()
self.settings_data = LuaSettings:open(hotkeys_path)
end
end
@@ -83,8 +120,20 @@ function HotKeys:init()
self.ui.menu:registerToMainMenu(self)
Dispatcher:init()
self:registerDispatcherActions()
self:registerKeyEvents()
end
function HotKeys:registerDispatcherActions()
if not Device:supportsGamepad() then return end --- @todo Are we sure this should be gated? It seems generically useful.
for action_name, action in pairs(key_emitter_actions) do
Dispatcher:registerAction(action_name, {
category = "key",
arg = action.key,
title = action.title,
general = true,
})
end
end
--[[
Handles the action triggered by a hotkey press.
@@ -108,6 +157,20 @@ function HotKeys:onHotkeyAction(hotkey)
return true
end
end
if Device:supportsGamepad() then
function HotKeys:onGamepadButtonDown(ev)
local button = ev.button
local id = Gamepad.button_ids[button] or tostring(button)
local hotkey = "gamepad_button_" .. id
return self:onHotkeyAction(hotkey)
end
function HotKeys:onGamepadAxisMotion(ev)
return self:onHotkeyAction(Gamepad:getAxisHotkeyName(ev.axis, ev.value))
end
end
--[[ The following snippet is an example of the hotkeys.lua file that is generated in the settings directory:
["modifier_plus_right_page_forward"] = {
["settings"] = {
@@ -420,9 +483,26 @@ function HotKeys:addToMainMenu(menu_items)
"j", "k", "l", "m", "n", "o", "p", "q", "r",
"s", "t", "u", "v", "w", "x", "y", "z",
}),
separator = true,
})
end
end
if Device:supportsGamepad() then
local gamepad_keys = {}
for i = 0, 15 do
local id = Gamepad.button_ids[i] or tostring(i)
table.insert(gamepad_keys, "gamepad_button_" .. id)
end
for i = 0, 5 do
local id = Gamepad.axis_ids[i] or tostring(i)
table.insert(gamepad_keys, "gamepad_axis_" .. id .. "_minus")
table.insert(gamepad_keys, "gamepad_axis_" .. id .. "_plus")
end
table.insert(menu_items.hotkeys.sub_item_table, {
text = _("Gamepad"),
sub_item_table = self:genSubItemTable(gamepad_keys),
})
end
end
--[[