keebrs 0.3.0

Keyboard firmware building blocks
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
//! Utilities for translating physical events to logical events

use alloc::collections::VecDeque;

use log::info;

use crate::{
    key::{
        KeyPos,
        KeyState,
        LogiKey,
        ModuleKey,
        PhysKey,
    },
    keycode::KeyCode,
    vecmap::VecMap,
};

/// Multiple simultaneous keypresses
///
/// All pressed and released simultaneously
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct MultiKey {
    /// The keycodes pressed/released
    pub codes: &'static [KeyCode],
    /// Pressed or released
    pub state: KeyState,
}

/// The result of a translation
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Translated {
    /// A single key event
    Single(LogiKey),
    /// Multiple key events
    Multi(MultiKey),
    /// Broadcast message to send
    Broadcast(crate::serial::Msg),
    /// Direct message to send
    Send(i8, crate::serial::Msg),
}

/// Trait for translating a physical key event to a keycode event
pub trait Translate {
    /// (Maybe) Translate a keystroke to a keycode
    ///
    /// This should be called upon every scan, whether a key event occurred or
    /// not, as well as for every event sent from another module. The "no event"
    /// calls should be used by the translator to judge the passage of time and
    /// as a mechanism to send multiple keys "at the same time."
    fn translate(&mut self, key: Option<ModuleKey>) -> Option<Translated>;
}

/// Keymap action
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum Action {
    /// No action
    Nop,
    /// Transparent: Defers to the layer below
    Trans,
    /// Regular keypress
    Key(KeyCode),
    /// Sequence of keypresses. Sent after release
    Seq(&'static [Action]),
    /// Combination of keys. All pressed and released together
    Combo(&'static [KeyCode]),
    /// Activate a layer
    Layer(usize),
    /// Change backlight effect
    BacklightSwitch,
    /// Function call
    Fn(fn()),
}

/// A single keymap
pub struct Map(pub &'static [&'static [Action]]);

/// A single key matrix
///
/// This represents a single module
pub struct Module {
    /// The type of this module
    pub ty: &'static str,
    /// The layers of this module
    pub layers: &'static [Map],
    /// The orientation of scanning
    pub orientation: Orientation,
}

/// The orientation of the module
pub enum Orientation {
    /// Rows then columns
    RC,
    /// Columns then rows
    CR,
}

/// A full layout
pub struct Layout {
    /// The actual layers comprising the full layout
    pub modules: &'static [Module],
}

/// A key translator backed by a `Layout`
pub struct Translator {
    /// The backing `Layout`
    pub layout: Layout,
    presses: VecMap<(u8, KeyPos), Action>,
    layers: u32,
    queue: VecDeque<Translated>,
    full: usize,
    bucket: usize,
}

impl Translator {
    /// Initialize a new `Tranlator`
    pub fn new(layout: Layout, poll_rate: u32) -> Self {
        let full = (poll_rate / 1000) as usize * 10;
        Self {
            layout,
            presses: Default::default(),
            layers: 0x00_00_00_01,
            queue: VecDeque::new(),
            full,
            bucket: full,
        }
    }

    fn top_layer(&self) -> usize {
        31 - self.layers.leading_zeros() as usize
    }

    fn is_active(&self, layer: usize) -> bool {
        (self.layers & (0x01 << layer)) != 0
    }

    #[inline(never)]
    fn get_action(&self, layer: usize, module: u8, pos: KeyPos) -> Option<Action> {
        info!("layer: {}, module: {}, pos: {:?}", layer, module, pos);
        let action = self
            .layout
            .modules
            .get(module as usize)
            .and_then(|module| {
                let (outer, inner) = match module.orientation {
                    Orientation::RC => (pos.x, pos.y),
                    Orientation::CR => (pos.y, pos.x),
                };
                module
                    .layers
                    .get(layer)
                    .map(|matrix| ((outer as usize, inner as usize), matrix.0))
            })
            .and_then(|((outer, inner), matrix)| matrix.get(outer).and_then(|i| i.get(inner)));
        dbg!(action.cloned())
    }

    #[inline(never)]
    fn get_logical_action(&self, module: u8, pos: KeyPos) -> Option<Action> {
        let mut layer = self.top_layer();
        loop {
            if self.is_active(layer) {
                let action = self.get_action(layer, module, pos);
                if let Some(action) = action {
                    info!("action: {:?}", action);
                    if action != Action::Trans {
                        return Some(action);
                    }
                }
            }
            if layer == 0 {
                return None;
            }
            layer -= 1;
        }
    }

    fn enqueue(&mut self, key: Translated) {
        self.queue.push_back(key)
    }

    fn dequeue(&mut self) -> Option<Translated> {
        if self.bucket < self.full {
            self.bucket += 1;
            return None;
        }
        if !self.queue.is_empty() {
            self.bucket = 0;
        }

        dbg!(self.queue.pop_front())
    }

    fn action_down(&mut self, action: Action) {
        match action {
            Action::Fn(_) => {}
            Action::Nop => {}
            Action::BacklightSwitch => {}
            Action::Trans => unreachable!("should never return a transparent action"),
            Action::Key(code) => self.enqueue(Translated::Single(LogiKey {
                code,
                state: true.into(),
            })),
            Action::Layer(layer) => {
                self.layers ^= 0x1 << layer;
            }
            Action::Seq(_keys) => {}
            Action::Combo(codes) => self.enqueue(Translated::Multi(MultiKey {
                codes,
                state: true.into(),
            })),
        }
    }

    fn action_up(&mut self, down_action: Action, module: u8, pos: KeyPos) {
        match down_action {
            Action::Fn(f) => f(),
            Action::Trans => {}
            Action::Nop => {}
            Action::BacklightSwitch => {}
            Action::Key(code) => self.enqueue(Translated::Single(LogiKey {
                code,
                state: false.into(),
            })),
            Action::Layer(layer) => {
                let layer_action = self.get_action(layer, module, pos);
                if layer_action.is_none() || layer_action == Some(Action::Trans) {
                    self.layers ^= 0x1 << layer;
                }
            }
            Action::Seq(actions) => {
                for action in actions {
                    self.action_down(*action);
                    self.action_up(*action, module, pos);
                }
            }
            Action::Combo(codes) => self.enqueue(Translated::Multi(MultiKey {
                codes,
                state: false.into(),
            })),
        }
    }

    fn get_press(&mut self, module: u8, pos: KeyPos) -> Option<Action> {
        self.presses.take(&(module, pos))
    }

    fn add_press(&mut self, module: u8, pos: KeyPos, action: Action) {
        self.presses.insert((module, pos), action)
    }
}

impl Translate for Translator {
    fn translate(&mut self, key: Option<ModuleKey>) -> Option<Translated> {
        let ModuleKey {
            module,
            key: PhysKey { pos, state },
        } = if let Some(key) = key {
            key
        } else {
            return self.dequeue();
        };

        if *state {
            if let Some(action) = self.get_logical_action(module, pos) {
                self.action_down(action);
                self.add_press(module, pos, action);
            }

            self.dequeue()
        } else {
            if let Some(down_action) = self.get_press(module, pos) {
                self.action_up(down_action, module, pos);
            }

            self.dequeue()
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use Action::*;
    use KeyCode::*;

    #[rustfmt::skip]
    const TEST_LAYOUT: Layout = Layout {
        modules: &[
            Module {
                ty: "",
                orientation: Orientation::RC,
                layers: &[
                    Map(&[
                        &[Key(Kb0), Seq(&[Combo(&[KbLShift, KbP]), Key(KbK), Key(KbB)])],
                        &[Key(KbA), Key(KbS)],
                    ]),
                    Map(&[
                        &[Key(KbQ), Seq(&[Key(KbA), Key(KbB)])],
                        &[Key(KbE), Key(KbS)],
                    ]),
                ],
            },
            Module {
                ty: "",
                orientation: Orientation::RC,
                layers: &[
                    Map(&[
                        &[Key(KbLShift), Key(KbRCtrl)],
                        &[Layer(1), Layer(1)],
                    ]),
                    Map(&[
                        &[Key(KbJ), Key(KbK)],
                        &[Layer(1), Trans],
                    ]),
                ],
            },
        ],
    };

    macro_rules! key_input {
        ($row:expr, $col:expr, $module:expr, nop) => {
            Option::None
        };
        ($row:expr, $col:expr, $module:expr, $press:expr) => {
            Some(ModuleKey {
                module: $module,
                key: PhysKey {
                    pos: KeyPos { x: $row, y: $col },
                    state: $press.into(),
                },
            })
        };
    }
    macro_rules! key_output {
        ($code:expr, $press:expr) => {
            Translated::Single(LogiKey {
                code: $code,
                state: $press.into(),
            })
        };
    }

    macro_rules! multi_output {
        ($($code:expr),* ; $press:expr) => {
            Translated::Multi(MultiKey {
                codes: &[$($code),*],
                state: $press.into(),
            })
        };
    }

    #[test]
    fn test_layout() {
        let mut translator = Translator::new(TEST_LAYOUT, 0);
        let input = &[
            key_input!(0, 0, 0, true),  // 0 down
            key_input!(0, 0, 0, false), // 0 up
            key_input!(1, 0, 1, true),  // layer 1 down
            key_input!(0, 0, 0, true),  // Q down
            key_input!(1, 0, 1, false), // layer 1 up
            key_input!(0, 0, 0, false), // Q up
            key_input!(0, 0, 0, true),  // Q down
            key_input!(0, 0, 0, false), // Q up
            key_input!(1, 0, 1, true),  // layer 1 down
            key_input!(1, 0, 1, false), // layer 1 up
            key_input!(1, 1, 1, true),  // layer 1 down
            key_input!(0, 0, 0, true),  // Q down
            key_input!(1, 1, 1, false), // layer 1 up
            key_input!(0, 0, 0, false), // Q up
            key_input!(0, 0, 0, true),  // 0 down
            key_input!(0, 0, 0, false), // 0 up
            key_input!(1, 0, 1, true),  // layer 1 down
            key_input!(1, 0, 1, false), // layer 1 up
            key_input!(0, 1, 0, true),  // a, b down
            key_input!(0, 1, 0, false), // a, b up
            key_input!(1, 0, 1, true),  // layer 1 down
            key_input!(1, 0, 1, false), // layer 1 up
            key_input!(0, 1, 0, true),
            key_input!(0, 1, 0, false),
            key_input!(1, 1, 1, true),
            key_input!(1, 1, 0, true),
            key_input!(1, 1, 1, false),
            key_input!(1, 1, 0, false),
            key_input!(0, 0, 0, nop),
            key_input!(0, 0, 0, nop),
            key_input!(0, 0, 0, nop),
            key_input!(0, 0, 0, nop),
            key_input!(0, 0, 0, nop),
            key_input!(0, 0, 0, nop),
            key_input!(0, 0, 0, nop),
            key_input!(0, 0, 0, nop),
            key_input!(0, 0, 0, nop),
            key_input!(0, 0, 0, nop),
            key_input!(0, 0, 0, nop),
            key_input!(0, 0, 0, nop),
            key_input!(0, 0, 0, nop),
            key_input!(0, 0, 0, nop),
            key_input!(0, 0, 0, nop),
            key_input!(0, 0, 0, nop),
            key_input!(0, 0, 0, nop),
            key_input!(0, 0, 0, nop),
            key_input!(0, 0, 0, nop),
            key_input!(0, 0, 0, nop),
            key_input!(0, 0, 0, nop),
            key_input!(0, 0, 0, nop),
        ];
        let output: Vec<_> = input
            .iter()
            .filter_map(|e| translator.translate(*e))
            .collect();

        assert_eq!(
            &output,
            &[
                key_output!(Kb0, true),
                key_output!(Kb0, false),
                key_output!(KbQ, true),
                key_output!(KbQ, false),
                key_output!(KbQ, true),
                key_output!(KbQ, false),
                key_output!(KbQ, true),
                key_output!(KbQ, false),
                key_output!(Kb0, true),
                key_output!(Kb0, false),
                key_output!(KbA, true),
                key_output!(KbA, false),
                key_output!(KbB, true),
                key_output!(KbB, false),
                multi_output!(KbLShift, KbP; true),
                multi_output!(KbLShift, KbP; false),
                key_output!(KbK, true),
                key_output!(KbK, false),
                key_output!(KbB, true),
                key_output!(KbB, false),
                key_output!(KbS, true),
                key_output!(KbS, false),
            ]
        );
        assert!(translator.presses.inner().iter().all(|opt| opt.is_none()));
    }
}