gui: game controller navigation through /dev/input/js* (untested on hardware)
This commit is contained in:
1 parent
27a559846b
commit
736c12bb1e
2 files changed
+175
No files matched your search
@@ -1,6 +1,7 @@
|
||||
//! Summit launcher window. The UI is in ui/*.slint; this file feeds it data and carries out its actions.
|
||||
mod art;
|
||||
mod data;
|
||||
mod pad;
|
||||
mod shot;
|
||||
|
||||
use slint::{ComponentHandle, Image, Model, ModelRc, SharedString, VecModel};
|
||||
@@ -417,5 +418,15 @@ fn main() {
|
||||
if let Some(k) = queue.pop_front() { with_app(|a| shot::press(a.ui.window(), &k)); }
|
||||
});
|
||||
}
|
||||
// Controllers: polled on the UI thread, pressed as keys.
|
||||
// Without a pad this only looks for one every two seconds, so an idle launcher stays idle.
|
||||
let pad_timer = Rc::new(slint::Timer::default());
|
||||
let mut pads = pad::Pads::new();
|
||||
let timer = pad_timer.clone();
|
||||
pad_timer.start(slint::TimerMode::Repeated, std::time::Duration::from_secs(2), move || {
|
||||
for k in pads.poll(std::time::Instant::now()) { with_app(|a| shot::press(a.ui.window(), k)); }
|
||||
let want = std::time::Duration::from_millis(if pads.connected() { 16 } else { 2000 });
|
||||
if timer.interval() != want { timer.set_interval(want); }
|
||||
});
|
||||
slint::run_event_loop().expect("event loop");
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
//! Game controller input through the kernel's joystick devices (/dev/input/js*), with no extra libraries.
|
||||
//! A pad drives the same navigation as the keyboard: d-pad or left stick = arrows, A = Enter, B = Esc,
|
||||
//! X = pin, LB/RB = previous/next section.
|
||||
//!
|
||||
//! The button and axis numbers are the ones the Linux xpad and hid-playstation drivers report.
|
||||
//! NOT tested on real hardware yet: the event decoding and the mapping are unit tested, the devices are not.
|
||||
use std::io::Read;
|
||||
use std::sync::mpsc::{channel, Receiver, Sender};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const JS_EVENT_BUTTON: u8 = 0x01;
|
||||
const JS_EVENT_AXIS: u8 = 0x02;
|
||||
const JS_EVENT_INIT: u8 = 0x80;
|
||||
/// Stick deflection (of 32767) that counts as a direction.
|
||||
const THRESHOLD: i16 = 18000;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum Event { Button { number: u8, pressed: bool }, Axis { number: u8, value: i16 } }
|
||||
|
||||
/// Decode one 8-byte `struct js_event`. The synthetic events a device sends when it is opened are skipped.
|
||||
pub fn decode(b: &[u8; 8]) -> Option<Event> {
|
||||
let value = i16::from_le_bytes([b[4], b[5]]);
|
||||
let (kind, number) = (b[6], b[7]);
|
||||
if kind & JS_EVENT_INIT != 0 { return None; }
|
||||
match kind {
|
||||
JS_EVENT_BUTTON => Some(Event::Button { number, pressed: value != 0 }),
|
||||
JS_EVENT_AXIS => Some(Event::Axis { number, value }),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Key name (as understood by `shot::press`) for a button press.
|
||||
pub fn button_key(number: u8) -> Option<&'static str> {
|
||||
match number { 0 => Some("Enter"), 1 => Some("Esc"), 2 => Some("p"), 4 => Some("Backtab"), 5 => Some("Tab"), _ => None }
|
||||
}
|
||||
|
||||
/// Which way the pad points: left stick (axes 0, 1) and d-pad hat (axes 6, 7) together.
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq)]
|
||||
pub struct Direction { stick: (i8, i8), hat: (i8, i8) }
|
||||
|
||||
impl Direction {
|
||||
pub fn update(&mut self, axis: u8, value: i16) {
|
||||
let d = if value > THRESHOLD { 1 } else if value < -THRESHOLD { -1 } else { 0 };
|
||||
match axis { 0 => self.stick.0 = d, 1 => self.stick.1 = d, 6 => self.hat.0 = d, 7 => self.hat.1 = d, _ => {} }
|
||||
}
|
||||
/// One arrow key at a time; the d-pad wins over the stick, and up/down over left/right.
|
||||
pub fn key(&self) -> Option<&'static str> {
|
||||
let (x, y) = if self.hat != (0, 0) { self.hat } else { self.stick };
|
||||
match (x, y) { (_, -1) => Some("Up"), (_, 1) => Some("Down"), (-1, _) => Some("Left"), (1, _) => Some("Right"), _ => None }
|
||||
}
|
||||
}
|
||||
|
||||
/// Turns a held direction into key presses: once at first, again after a pause, then at a steady rate.
|
||||
#[derive(Default)]
|
||||
pub struct Repeater { held: Option<&'static str>, next: Option<Instant> }
|
||||
|
||||
impl Repeater {
|
||||
pub fn poll(&mut self, key: Option<&'static str>, now: Instant) -> Option<&'static str> {
|
||||
if key != self.held {
|
||||
self.held = key;
|
||||
self.next = key.map(|_| now + Duration::from_millis(380));
|
||||
return key;
|
||||
}
|
||||
match (key, self.next) {
|
||||
(Some(k), Some(t)) if now >= t => { self.next = Some(now + Duration::from_millis(110)); Some(k) }
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn reader(path: std::path::PathBuf, id: usize, tx: Sender<(usize, Option<Event>)>) {
|
||||
let Ok(mut f) = std::fs::File::open(&path) else { let _ = tx.send((id, None)); return };
|
||||
let mut buf = [0u8; 8];
|
||||
while f.read_exact(&mut buf).is_ok() {
|
||||
if let Some(e) = decode(&buf) { if tx.send((id, Some(e))).is_err() { return; } }
|
||||
}
|
||||
let _ = tx.send((id, None)); // unplugged
|
||||
}
|
||||
|
||||
/// Watches /dev/input/js0..7. Call `poll` from a UI timer; it returns the keys to press.
|
||||
pub struct Pads {
|
||||
tx: Sender<(usize, Option<Event>)>,
|
||||
rx: Receiver<(usize, Option<Event>)>,
|
||||
open: [bool; 8],
|
||||
dirs: [Direction; 8],
|
||||
repeat: Repeater,
|
||||
last_scan: Option<Instant>,
|
||||
}
|
||||
|
||||
impl Pads {
|
||||
pub fn new() -> Self {
|
||||
let (tx, rx) = channel();
|
||||
Pads { tx, rx, open: [false; 8], dirs: Default::default(), repeat: Repeater::default(), last_scan: None }
|
||||
}
|
||||
fn scan(&mut self) {
|
||||
for id in 0..8 {
|
||||
let path = std::path::PathBuf::from(format!("/dev/input/js{id}"));
|
||||
if !self.open[id] && path.exists() {
|
||||
self.open[id] = true;
|
||||
let tx = self.tx.clone();
|
||||
let _ = std::thread::Builder::new().name(format!("summit-pad{id}")).spawn(move || reader(path, id, tx));
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn connected(&self) -> bool { self.open.iter().any(|o| *o) }
|
||||
pub fn poll(&mut self, now: Instant) -> Vec<&'static str> {
|
||||
if self.last_scan.map_or(true, |t| now.duration_since(t) > Duration::from_secs(2)) { self.last_scan = Some(now); self.scan(); }
|
||||
let mut keys = vec![];
|
||||
while let Ok((id, ev)) = self.rx.try_recv() {
|
||||
match ev {
|
||||
None => { self.open[id] = false; self.dirs[id] = Direction::default(); }
|
||||
Some(Event::Button { number, pressed: true }) => keys.extend(button_key(number)),
|
||||
Some(Event::Button { .. }) => {}
|
||||
Some(Event::Axis { number, value }) => self.dirs[id].update(number, value),
|
||||
}
|
||||
}
|
||||
let dir = self.dirs.iter().find_map(|d| d.key());
|
||||
keys.extend(self.repeat.poll(dir, now));
|
||||
keys
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn ev(value: i16, kind: u8, number: u8) -> [u8; 8] {
|
||||
let v = value.to_le_bytes();
|
||||
[0, 0, 0, 0, v[0], v[1], kind, number]
|
||||
}
|
||||
#[test]
|
||||
fn decodes_buttons_and_axes_and_skips_init_events() {
|
||||
assert_eq!(decode(&ev(1, JS_EVENT_BUTTON, 0)), Some(Event::Button { number: 0, pressed: true }));
|
||||
assert_eq!(decode(&ev(0, JS_EVENT_BUTTON, 1)), Some(Event::Button { number: 1, pressed: false }));
|
||||
assert_eq!(decode(&ev(-32767, JS_EVENT_AXIS, 7)), Some(Event::Axis { number: 7, value: -32767 }));
|
||||
assert_eq!(decode(&ev(1, JS_EVENT_BUTTON | JS_EVENT_INIT, 0)), None);
|
||||
assert_eq!(decode(&ev(1, 0x40, 0)), None);
|
||||
}
|
||||
#[test]
|
||||
fn buttons_map_to_navigation_keys() {
|
||||
assert_eq!((button_key(0), button_key(1), button_key(2), button_key(4), button_key(5), button_key(9)), (Some("Enter"), Some("Esc"), Some("p"), Some("Backtab"), Some("Tab"), None));
|
||||
}
|
||||
#[test]
|
||||
fn direction_from_hat_and_stick() {
|
||||
let mut d = Direction::default();
|
||||
assert_eq!(d.key(), None);
|
||||
d.update(0, 30000); assert_eq!(d.key(), Some("Right"));
|
||||
d.update(0, 9000); assert_eq!(d.key(), None); // inside the dead zone
|
||||
d.update(1, -30000); assert_eq!(d.key(), Some("Up"));
|
||||
d.update(6, -32767); assert_eq!(d.key(), Some("Left")); // the d-pad wins over the stick
|
||||
d.update(6, 0); d.update(7, 32767); assert_eq!(d.key(), Some("Down"));
|
||||
}
|
||||
#[test]
|
||||
fn held_direction_repeats_after_a_pause() {
|
||||
let mut r = Repeater::default();
|
||||
let t = Instant::now();
|
||||
assert_eq!(r.poll(Some("Down"), t), Some("Down"));
|
||||
assert_eq!(r.poll(Some("Down"), t + Duration::from_millis(100)), None);
|
||||
assert_eq!(r.poll(Some("Down"), t + Duration::from_millis(400)), Some("Down"));
|
||||
assert_eq!(r.poll(Some("Down"), t + Duration::from_millis(450)), None);
|
||||
assert_eq!(r.poll(Some("Down"), t + Duration::from_millis(520)), Some("Down"));
|
||||
assert_eq!(r.poll(None, t + Duration::from_millis(600)), None);
|
||||
assert_eq!(r.poll(Some("Left"), t + Duration::from_millis(610)), Some("Left"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user