keyberon_smart_keyboard/input/
smart_keymap.rs

1/// Callbacks for the keymap.
2pub struct KeymapCallbacks {
3    /// Callback for resetting keyboard state.
4    pub reset: Option<fn() -> ()>,
5    /// Callback for entering the bootloader.
6    pub reset_to_bootloader: Option<fn() -> ()>,
7}
8
9/// The keyboard "backend", manages the keyboard from the events received
10/// (presses/releases of coordinates on a keyboard layout).
11/// through to listing HID scancodes to report using HIDs.
12#[derive(Debug)]
13pub struct KeyboardBackend {
14    keymap: smart_keymap::init::Keymap,
15    keymap_output: smart_keymap::keymap::KeymapOutput,
16}
17
18impl KeyboardBackend {
19    /// Constructs a new keyboard backend.
20    pub fn new(keymap: smart_keymap::init::Keymap) -> Self {
21        Self {
22            keymap,
23            keymap_output: smart_keymap::keymap::KeymapOutput::default(),
24        }
25    }
26
27    /// Set the keymap callbacks.
28    pub fn set_callbacks(&mut self, callbacks: KeymapCallbacks) {
29        use smart_keymap::keymap::KeymapCallback;
30        if let Some(callback_fn) = callbacks.reset {
31            self.keymap.set_callback(KeymapCallback::Reset, callback_fn);
32        }
33        if let Some(callback_fn) = callbacks.reset_to_bootloader {
34            self.keymap
35                .set_callback(KeymapCallback::ResetToBootloader, callback_fn);
36        }
37    }
38
39    /// Register a key event.
40    pub fn event(&mut self, event: smart_keymap::input::Event) {
41        self.keymap.handle_input(event);
42    }
43
44    /// A time event.
45    ///
46    /// This method must be called regularly, typically every millisecond.
47    ///
48    /// Returns true if the pressed_key_codes have changed.
49    pub fn tick(&mut self) -> bool {
50        self.keymap.tick();
51
52        let keymap_output = self.keymap.report_output();
53
54        let old_keymap_output = core::mem::replace(&mut self.keymap_output, keymap_output);
55
56        old_keymap_output != self.keymap_output
57    }
58
59    pub fn keymap_output(&self) -> &smart_keymap::keymap::KeymapOutput {
60        &self.keymap_output
61    }
62}
63
64/// Constructs a [smart_keymap::input::Event] from a [keyberon::layout::Event],
65///  using a map from row, column to (maybe) keymap index.
66pub fn keymap_index_of<const COLS: usize, const ROWS: usize>(
67    indices: &[[Option<u16>; COLS]; ROWS],
68    ev: keyberon::layout::Event,
69) -> Option<smart_keymap::input::Event> {
70    match ev {
71        keyberon::layout::Event::Press(r, c) => indices[r as usize][c as usize]
72            .map(|keymap_index| smart_keymap::input::Event::Press { keymap_index }),
73        keyberon::layout::Event::Release(r, c) => indices[r as usize][c as usize]
74            .map(|keymap_index| smart_keymap::input::Event::Release { keymap_index }),
75    }
76}