1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
use super::events::*;
use std::convert::TryFrom;
use std::io::prelude::*;
pub struct InputDevice {
device: evdev::Device,
}
impl From<evdev::Device> for InputDevice {
fn from(evd: evdev::Device) -> Self {
Self { device: evd }
}
}
impl InputDevice {
pub fn from_name(name: &str) -> Option<Self> {
evdev::enumerate()
.find(|d| d.name() == Some(name))
.map(Self::from)
}
pub fn from_cli() -> Self {
let devices = evdev::enumerate().collect::<Vec<_>>();
for (i, d) in devices.iter().enumerate() {
println!("{}: {}", i, d.name().unwrap_or("Unnamed device"));
}
print!("Select the device [0-{}]: ", devices.len() - 1);
let _ = std::io::stdout().flush();
let mut chosen = String::new();
std::io::stdin().read_line(&mut chosen).unwrap();
let n = chosen.trim().parse::<usize>().unwrap();
let device = devices.into_iter().nth(n).unwrap();
Self { device }
}
pub fn poll<F>(&mut self, mut callback: F) -> Result<(), std::io::Error>
where
F: FnMut(&InputEvent),
{
let events = self.device.fetch_events()?;
for event in events {
if let Ok(input) = InputEvent::try_from(event) {
callback(&input);
}
}
Ok(())
}
}