//! Gamepad input. Buttons map to the same `Action`s as the keyboard bindings in app.slint. use std::collections::HashMap; use std::time::{Duration, Instant}; use gilrs::{Axis, Button, EventType, GamepadId, Gilrs}; use crate::Action; use crate::prompts::{self, Family, PRODUCT_STEAM_VIRTUAL_GAMEPAD, VENDOR_VALVE}; /// Steam's virtual controllers. When one is present the physical pad behind it /// also shows up as an evdev device, so only Steam's is listened to. const STEAM_VENDOR: u16 = VENDOR_VALVE; /// How often to look again for the physical controller behind a Steam virtual /// pad that Steam's file did not list yet. SDL checks as often. const RECHECK_VIRTUAL: Duration = Duration::from_secs(3); pub enum PadEvent { /// A press, from a controller of this family. Action(Action, Family), /// The family of a connected controller, or None when the last one went. Present(Option), } const REPEAT_DELAY: Duration = Duration::from_millis(380); const REPEAT_SLOW: Duration = Duration::from_millis(110); const REPEAT_FAST: Duration = Duration::from_millis(45); const FAST_AFTER: Duration = Duration::from_millis(1500); /// How long South is held before it counts as a long press. const LONG_PRESS: Duration = Duration::from_millis(500); const STICK_ON: f32 = 0.55; const STICK_OFF: f32 = 0.35; #[derive(Clone, Copy, PartialEq, Eq, Debug)] enum Source { DPad, LeftStick, RightStick, } /// South acts on release, so a long press can mean something else. struct SouthPress { family: Family, since: Instant, /// Sent as a long press already, so the release sends nothing. long: bool, } struct Held { source: Source, action: Action, family: Family, since: Instant, next: Instant, } pub fn spawn_gamepad(emit: impl Fn(PadEvent) + Send + 'static) { let spawned = std::thread::Builder::new().name("gamepad".into()).spawn(move || { let mut gilrs = match Gilrs::new() { Ok(g) => g, Err(e) => { log::warn!("gamepad support unavailable: {e}"); return; } }; let mut families = Families::default(); for (id, pad) in gilrs.gamepads() { log::info!( "gamepad: {} (vendor {:04x?}, product {:04x?}), {:?} prompts", pad.name(), pad.vendor_id(), pad.product_id(), families.family(&gilrs, id) ); } emit(PadEvent::Present(present(&gilrs, &mut families))); let mut held: Option = None; let mut south: Option = None; loop { while let Some(ev) = gilrs.next_event_blocking(Some(Duration::from_millis(15))) { if matches!(ev.event, EventType::Connected | EventType::Disconnected) { families.forget(ev.id); emit(PadEvent::Present(present(&gilrs, &mut families))); } if !accept_from(&gilrs, ev.id) { continue; } let family = families.family(&gilrs, ev.id); match ev.event { EventType::ButtonPressed(Button::South, _) => { south = Some(SouthPress { family, since: Instant::now(), long: false, }); } EventType::ButtonReleased(Button::South, _) => { if let Some(p) = south.take() && !p.long { emit(PadEvent::Action(Action::Activate, p.family)); } } EventType::ButtonPressed(b, _) => { if let Some(a) = dpad_action(b) { held = Some(start_hold(Source::DPad, a, family)); emit(PadEvent::Action(a, family)); } else if let Some(a) = button_action(b) { emit(PadEvent::Action(a, family)); } } EventType::ButtonReleased(b, _) => { if dpad_action(b).is_some() && held.as_ref().is_some_and(|h| h.source == Source::DPad) { held = None; } } EventType::AxisChanged(axis, value, _) => { let source = match axis { Axis::LeftStickX | Axis::LeftStickY => Source::LeftStick, Axis::RightStickX | Axis::RightStickY => Source::RightStick, _ => continue, }; let pad = gilrs.gamepad(ev.id); let dir = stick_direction(source, &pad, value, held.as_ref()); match (dir, held.as_ref()) { (Some(a), Some(h)) if h.source == source && h.action == a => {} (Some(a), _) => { held = Some(start_hold(source, a, family)); emit(PadEvent::Action(a, family)); } (None, Some(h)) if h.source == source => held = None, _ => {} } } EventType::Disconnected => { held = None; south = None; } _ => {} } } if let Some(p) = south.as_mut() && !p.long && p.since.elapsed() >= LONG_PRESS { p.long = true; emit(PadEvent::Action(Action::HoldActivate, p.family)); } if let Some(h) = held.as_mut() { let now = Instant::now(); if now >= h.next { emit(PadEvent::Action(h.action, h.family)); let step = if now - h.since > FAST_AFTER { REPEAT_FAST } else { REPEAT_SLOW }; h.next = now + step; } } } }); if let Err(e) = spawned { log::warn!("could not start gamepad thread: {e}"); } } fn accept_from(gilrs: &Gilrs, id: GamepadId) -> bool { let steam_present = gilrs.gamepads().any(|(_, p)| p.vendor_id() == Some(STEAM_VENDOR)); !steam_present || gilrs.gamepad(id).vendor_id() == Some(STEAM_VENDOR) } fn start_hold(source: Source, action: Action, family: Family) -> Held { let now = Instant::now(); Held { source, action, family, since: now, next: now + REPEAT_DELAY, } } /// The family of the first controller listened to, if any. fn present(gilrs: &Gilrs, families: &mut Families) -> Option { let id = gilrs.gamepads().map(|(id, _)| id).find(|&id| accept_from(gilrs, id))?; Some(families.family(gilrs, id)) } /// Controller families per pad. A Steam virtual pad whose physical controller /// is not in Steam's file yet is looked up again now and then. #[derive(Default)] struct Families { known: HashMap)>, } impl Families { fn family(&mut self, gilrs: &Gilrs, id: GamepadId) -> Family { if let Some(&(family, unresolved)) = self.known.get(&id) && unresolved.is_none_or(|at| at.elapsed() < RECHECK_VIRTUAL) { return family; } let (family, resolved) = resolve_family(&gilrs.gamepad(id)); self.known.insert(id, (family, (!resolved).then(Instant::now))); family } fn forget(&mut self, id: GamepadId) { self.known.remove(&id); } } /// The family of a pad, and whether it is certain. For Steam's virtual pad the /// physical controller comes from the file Steam names in /// SteamVirtualGamepadInfo, the way SDL finds it. fn resolve_family(pad: &gilrs::Gamepad<'_>) -> (Family, bool) { let (vendor, product) = (pad.vendor_id(), pad.product_id()); if (vendor, product) != (Some(VENDOR_VALVE), Some(PRODUCT_STEAM_VIRTUAL_GAMEPAD)) { return (prompts::family_from_ids(vendor, product), true); } let physical = prompts::virtual_slot(pad.os_name()).and_then(|slot| { let path = std::env::var_os("SteamVirtualGamepadInfo")?; let text = std::fs::read_to_string(path).ok()?; prompts::parse_virtual_pads(&text).remove(&slot) }); match physical { Some(p) => { log::info!( "Steam virtual pad '{}' is a {:04x?}:{:04x?}", pad.os_name(), p.vendor, p.product ); (prompts::family_from_ids(p.vendor, p.product), true) } None => (Family::Xbox, false), } } fn dpad_action(b: Button) -> Option { Some(match b { Button::DPadUp => Action::Up, Button::DPadDown => Action::Down, Button::DPadLeft => Action::Left, Button::DPadRight => Action::Right, _ => return None, }) } fn button_action(b: Button) -> Option { Some(match b { Button::East => Action::Back, Button::West => Action::PlayPause, Button::North => Action::Queue, Button::LeftTrigger => Action::Prev, Button::RightTrigger => Action::Next, Button::LeftTrigger2 => Action::SectionPrev, Button::RightTrigger2 => Action::SectionNext, Button::Start => Action::NowPlaying, Button::Select => Action::Search, Button::RightThumb => Action::ToggleMute, _ => return None, }) } /// Reads the stick's dominant direction, with hysteresis so a stick resting /// near the threshold does not flicker between held and released. fn stick_direction(source: Source, pad: &gilrs::Gamepad<'_>, _changed: f32, held: Option<&Held>) -> Option { let holding = held.is_some_and(|h| h.source == source); let threshold = if holding { STICK_OFF } else { STICK_ON }; match source { Source::LeftStick => { let x = pad.value(Axis::LeftStickX); let y = pad.value(Axis::LeftStickY); if x.abs() < threshold && y.abs() < threshold { None } else if x.abs() > y.abs() { Some(if x > 0.0 { Action::Right } else { Action::Left }) } else { Some(if y > 0.0 { Action::Up } else { Action::Down }) } } // Across seeks, up and down set the volume. The dominant axis wins, so // a diagonal push does only one of them. Source::RightStick => { let x = pad.value(Axis::RightStickX); let y = pad.value(Axis::RightStickY); if x.abs() < threshold && y.abs() < threshold { None } else if x.abs() > y.abs() { Some(if x > 0.0 { Action::SeekForward } else { Action::SeekBack }) } else { Some(if y > 0.0 { Action::VolumeUp } else { Action::VolumeDown }) } } Source::DPad => None, } }