one_fpga/inputs/
keyboard.rs

1use std::collections::HashSet;
2use std::fmt;
3
4/// A scancode maps a virtual key on the keyboard to a physical key on the keyboard.
5/// We reuse the SDL3 type for simplicity, as it is well maintained and complete.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
7#[repr(transparent)]
8pub struct Scancode(sdl3::keyboard::Scancode);
9
10impl Scancode {
11    /// Get the SDL3 scancode.
12    pub fn as_sdl(&self) -> sdl3::keyboard::Scancode {
13        self.0
14    }
15
16    /// Get an integer representation of the key (the key scan code).
17    #[inline]
18    pub fn as_repr(&self) -> i32 {
19        self.0 as i32
20    }
21}
22
23impl std::str::FromStr for Scancode {
24    type Err = String;
25
26    fn from_str(s: &str) -> Result<Self, Self::Err> {
27        sdl3::keyboard::Scancode::from_name(s)
28            .map(Scancode)
29            .ok_or_else(|| format!("Could not parse scancode: {}", s))
30    }
31}
32
33impl fmt::Display for Scancode {
34    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
35        write!(f, "{}", self.0.name())
36    }
37}
38
39impl From<sdl3::keyboard::Scancode> for Scancode {
40    fn from(scancode: sdl3::keyboard::Scancode) -> Self {
41        Self(scancode)
42    }
43}
44
45impl From<Scancode> for sdl3::keyboard::Scancode {
46    fn from(scancode: Scancode) -> Self {
47        scancode.0
48    }
49}
50
51#[derive(Debug, Clone, PartialEq, Eq, Default)]
52pub struct ScancodeSet {
53    set: HashSet<Scancode>,
54}
55
56impl ScancodeSet {
57    pub fn new() -> Self {
58        Self::default()
59    }
60
61    pub fn contains(&self, scancode: Scancode) -> bool {
62        self.set.contains(&scancode)
63    }
64
65    pub fn insert(&mut self, scancode: Scancode) {
66        self.set.insert(scancode);
67    }
68
69    pub fn remove(&mut self, scancode: Scancode) {
70        self.set.remove(&scancode);
71    }
72}