smart_keymap/
key.rs

1use core::fmt::Debug;
2
3use serde::{Deserialize, Serialize};
4
5use crate::input;
6
7/// Keymap Callback keys
8pub mod callback;
9/// CapsWord key(s).
10pub mod caps_word;
11/// Chorded keys. (Chording functionality).
12pub mod chorded;
13/// Custom keys.
14pub mod custom;
15/// HID Keyboard keys.
16pub mod keyboard;
17/// Layered keys. (Layering functionality).
18pub mod layered;
19/// Sticky Modifier keys.
20pub mod sticky;
21/// Tap-Dance keys.
22pub mod tap_dance;
23/// Tap-Hold keys.
24pub mod tap_hold;
25
26/// "Composite" keys; an aggregate type used for a common context and event.
27pub mod composite;
28
29/// The maximum number of key events that are emitted by [crate::key::System] implementations.
30pub const MAX_KEY_EVENTS: usize = 4;
31
32/// Events emitted when a key is pressed.
33#[derive(Debug, PartialEq, Eq)]
34pub struct KeyEvents<E, const M: usize = { MAX_KEY_EVENTS }>(heapless::Vec<ScheduledEvent<E>, M>);
35
36impl<E: Copy + Debug> KeyEvents<E> {
37    /// Constructs a [KeyEvents] with no events scheduled.
38    pub fn no_events() -> Self {
39        KeyEvents(None.into_iter().collect())
40    }
41
42    /// Constructs a [KeyEvents] with an immediate [Event].
43    pub fn event(event: Event<E>) -> Self {
44        KeyEvents(Some(ScheduledEvent::immediate(event)).into_iter().collect())
45    }
46
47    /// Constructs a [KeyEvents] with an [Event] scheduled after a delay.
48    pub fn scheduled_event(sch_event: ScheduledEvent<E>) -> Self {
49        KeyEvents(Some(sch_event).into_iter().collect())
50    }
51
52    /// Adds an event with the schedule to the [KeyEvents].
53    pub fn schedule_event(&mut self, delay: u16, event: Event<E>) {
54        self.0.push(ScheduledEvent::after(delay, event)).unwrap();
55    }
56
57    /// Adds events from the other [KeyEvents] to the [KeyEvents].
58    pub fn extend(&mut self, other: KeyEvents<E>) {
59        other.0.into_iter().for_each(|ev| self.0.push(ev).unwrap());
60    }
61
62    /// Adds an event from to the [KeyEvents].
63    pub fn add_event(&mut self, ev: ScheduledEvent<E>) {
64        self.0.push(ev).unwrap();
65    }
66
67    /// Maps over the KeyEvents.
68    pub fn map_events<F>(&self, f: fn(E) -> F) -> KeyEvents<F> {
69        KeyEvents(
70            self.0
71                .as_slice()
72                .iter()
73                .map(|sch_ev| sch_ev.map_scheduled_event(f))
74                .collect(),
75        )
76    }
77
78    /// Maps the KeyEvents to a new type.
79    pub fn into_events<F>(&self) -> KeyEvents<F>
80    where
81        E: Into<F>,
82    {
83        KeyEvents(
84            self.0
85                .as_slice()
86                .iter()
87                .map(|sch_ev| sch_ev.map_scheduled_event(|ev| ev.into()))
88                .collect(),
89        )
90    }
91}
92
93impl<E: Debug, const M: usize> IntoIterator for KeyEvents<E, M> {
94    type Item = ScheduledEvent<E>;
95    type IntoIter = <heapless::Vec<ScheduledEvent<E>, M> as IntoIterator>::IntoIter;
96
97    fn into_iter(self) -> Self::IntoIter {
98        self.0.into_iter()
99    }
100}
101
102/// Newtype for invoking new_pressed_key on the key for the given ref.
103#[derive(Debug, PartialEq)]
104pub enum NewPressedKey<R> {
105    /// Invoke new_pressed_key on the key at the given ref.
106    Key(R),
107    /// For keys which do nothing when pressed.
108    NoOp,
109}
110
111impl<R> NewPressedKey<R> {
112    /// Constructs a NewPressedKey value.
113    pub fn key(key_ref: R) -> Self {
114        NewPressedKey::Key(key_ref)
115    }
116
117    /// Constructs a NoOp NewPressedKey value.
118    pub fn no_op() -> Self {
119        NewPressedKey::NoOp
120    }
121
122    /// Maps the NewPressedKey into a new type.
123    pub fn map<TR>(self, f: fn(R) -> TR) -> NewPressedKey<TR> {
124        match self {
125            NewPressedKey::Key(r) => NewPressedKey::Key(f(r)),
126            NewPressedKey::NoOp => NewPressedKey::NoOp,
127        }
128    }
129}
130
131/// Pressed Key which may be pending, or a resolved key state.
132#[derive(Debug, PartialEq)]
133pub enum PressedKeyResult<R, PKS, KS> {
134    /// Unresolved key state. (e.g. tap-hold or chorded keys when first pressed).
135    Pending(PKS),
136    /// Resolved as a new pressed key.
137    NewPressedKey(NewPressedKey<R>),
138    /// Resolved key state.
139    Resolved(KS),
140}
141
142impl<R, PKS, KS> PressedKeyResult<R, PKS, KS> {
143    /// Returns the Resolved variant, or else panics.
144    #[cfg(feature = "std")]
145    pub fn unwrap_resolved(self) -> KS {
146        match self {
147            PressedKeyResult::Resolved(r) => r,
148            _ => panic!("PressedKeyResult::unwrap_resolved: not Resolved"),
149        }
150    }
151
152    /// Maps the PressedKeyResult into a new type.
153    pub fn map<TPKS, TKS>(
154        self,
155        f: fn(PKS) -> TPKS,
156        g: fn(KS) -> TKS,
157    ) -> PressedKeyResult<R, TPKS, TKS> {
158        match self {
159            PressedKeyResult::Pending(pks) => PressedKeyResult::Pending(f(pks)),
160            PressedKeyResult::NewPressedKey(npk) => PressedKeyResult::NewPressedKey(npk),
161            PressedKeyResult::Resolved(ks) => PressedKeyResult::Resolved(g(ks)),
162        }
163    }
164}
165
166/// The interface for key `System` behaviour.
167///
168/// A `System` has an associated `Ref`, [Context], `Event`, and [KeyState].
169///
170/// The generic `PK` is used as the type of the `PressedKey` that the `Key`
171///  produces.
172/// (e.g. [layered::LayeredKey]'s pressed key state passes-through to
173///  the keys of its layers).
174pub trait System<R>: Debug {
175    /// Used to identify the key definition in the keymap.
176    type Ref: Copy;
177
178    /// The associated [Context] is used to provide state that
179    ///  may affect behaviour when pressing the key.
180    /// (e.g. the behaviour of [layered::LayeredKey] depends on which
181    ///  layers are active in [layered::Context]).
182    type Context: Copy;
183
184    /// The associated `Event` is to be handled by the associated [Context],
185    ///  pending key states, and key states.
186    type Event: Copy + Debug + PartialEq;
187
188    /// Associated pending key state.
189    type PendingKeyState;
190
191    /// Associated key state type.
192    type KeyState;
193
194    /// Produces a pressed key value, and may
195    ///  yield some [ScheduledEvent]s.
196    /// (e.g. [tap_hold::Key] schedules a [tap_hold::Event::TapHoldTimeout]
197    ///  so that holding the key resolves as a hold).
198    fn new_pressed_key(
199        &self,
200        keymap_index: u16,
201        context: &Self::Context,
202        key_ref: Self::Ref,
203    ) -> (
204        PressedKeyResult<R, Self::PendingKeyState, Self::KeyState>,
205        KeyEvents<Self::Event>,
206    );
207
208    /// Update the given pending key state with the given impl.
209    fn update_pending_state(
210        &self,
211        pending_state: &mut Self::PendingKeyState,
212        keymap_index: u16,
213        context: &Self::Context,
214        key_ref: Self::Ref,
215        event: Event<Self::Event>,
216    ) -> (Option<NewPressedKey<R>>, KeyEvents<Self::Event>);
217
218    /// Used to update the [KeyState]'s state, and possibly yield event(s).
219    fn update_state(
220        &self,
221        _key_state: &mut Self::KeyState,
222        _ref: &Self::Ref,
223        _context: &Self::Context,
224        _keymap_index: u16,
225        _event: Event<Self::Event>,
226    ) -> KeyEvents<Self::Event> {
227        KeyEvents::no_events()
228    }
229
230    /// Output for the pressed key state.
231    fn key_output(&self, _ref: &Self::Ref, _key_state: &Self::KeyState) -> Option<KeyOutput> {
232        None
233    }
234}
235
236/// Used to provide state that may affect behaviour when pressing the key.
237///
238/// e.g. the behaviour of [layered::LayeredKey] depends on which
239///  layers are active in [layered::Context].
240pub trait Context: Clone + Copy {
241    /// The type of `Event` the context handles.
242    type Event;
243
244    /// Used to update the [Context]'s state.
245    fn handle_event(&mut self, event: Event<Self::Event>) -> KeyEvents<Self::Event>;
246}
247
248/// Bool flags for each of the modifier keys (left ctrl, etc.).
249#[derive(Deserialize, Serialize, Default, Clone, Copy, PartialEq, Eq)]
250pub struct KeyboardModifiers(u8);
251
252impl core::ops::Deref for KeyboardModifiers {
253    type Target = u8;
254
255    fn deref(&self) -> &Self::Target {
256        &self.0
257    }
258}
259
260impl core::fmt::Debug for KeyboardModifiers {
261    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
262        let mut ds = f.debug_struct("KeyboardModifiers");
263        if self.0 & Self::LEFT_CTRL_U8 != 0 {
264            ds.field("left_ctrl", &true);
265        }
266        if self.0 & Self::LEFT_SHIFT_U8 != 0 {
267            ds.field("left_shift", &true);
268        }
269        if self.0 & Self::LEFT_ALT_U8 != 0 {
270            ds.field("left_alt", &true);
271        }
272        if self.0 & Self::LEFT_GUI_U8 != 0 {
273            ds.field("left_gui", &true);
274        }
275        if self.0 & Self::RIGHT_CTRL_U8 != 0 {
276            ds.field("right_ctrl", &true);
277        }
278        if self.0 & Self::RIGHT_SHIFT_U8 != 0 {
279            ds.field("right_shift", &true);
280        }
281        if self.0 & Self::RIGHT_ALT_U8 != 0 {
282            ds.field("right_alt", &true);
283        }
284        if self.0 & Self::RIGHT_GUI_U8 != 0 {
285            ds.field("right_gui", &true);
286        }
287        ds.finish_non_exhaustive()
288    }
289}
290
291impl KeyboardModifiers {
292    /// Byte value for left ctrl.
293    pub const LEFT_CTRL_U8: u8 = 0x01;
294    /// Byte value for left shift.
295    pub const LEFT_SHIFT_U8: u8 = 0x02;
296    /// Byte value for left alt.
297    pub const LEFT_ALT_U8: u8 = 0x04;
298    /// Byte value for left gui.
299    pub const LEFT_GUI_U8: u8 = 0x08;
300    /// Byte value for right ctrl.
301    pub const RIGHT_CTRL_U8: u8 = 0x10;
302    /// Byte value for right shift.
303    pub const RIGHT_SHIFT_U8: u8 = 0x20;
304    /// Byte value for right alt.
305    pub const RIGHT_ALT_U8: u8 = 0x40;
306    /// Byte value for right gui.
307    pub const RIGHT_GUI_U8: u8 = 0x80;
308
309    /// Constructs with modifiers defaulting to false.
310    pub const fn new() -> Self {
311        KeyboardModifiers(0x00)
312    }
313
314    /// Constructs with modifiers with the given byte.
315    pub const fn from_byte(b: u8) -> Self {
316        KeyboardModifiers(b)
317    }
318
319    /// Constructs with the given key_code.
320    ///
321    /// Returns None if the key_code is not a modifier key code.
322    pub const fn from_key_code(key_code: u8) -> Option<Self> {
323        match key_code {
324            0xE0 => Some(Self::LEFT_CTRL),
325            0xE1 => Some(Self::LEFT_SHIFT),
326            0xE2 => Some(Self::LEFT_ALT),
327            0xE3 => Some(Self::LEFT_GUI),
328            0xE4 => Some(Self::RIGHT_CTRL),
329            0xE5 => Some(Self::RIGHT_SHIFT),
330            0xE6 => Some(Self::RIGHT_ALT),
331            0xE7 => Some(Self::RIGHT_GUI),
332            _ => None,
333        }
334    }
335
336    /// Const for no modifiers
337    pub const NONE: KeyboardModifiers = KeyboardModifiers {
338        ..KeyboardModifiers::new()
339    };
340
341    /// Const for left ctrl.
342    pub const LEFT_CTRL: KeyboardModifiers = KeyboardModifiers(Self::LEFT_CTRL_U8);
343
344    /// Const for left shift.
345    pub const LEFT_SHIFT: KeyboardModifiers = KeyboardModifiers(Self::LEFT_SHIFT_U8);
346
347    /// Const for left alt.
348    pub const LEFT_ALT: KeyboardModifiers = KeyboardModifiers(Self::LEFT_ALT_U8);
349
350    /// Const for left gui.
351    pub const LEFT_GUI: KeyboardModifiers = KeyboardModifiers(Self::LEFT_GUI_U8);
352
353    /// Const for right ctrl.
354    pub const RIGHT_CTRL: KeyboardModifiers = KeyboardModifiers(Self::RIGHT_CTRL_U8);
355
356    /// Const for right shift.
357    pub const RIGHT_SHIFT: KeyboardModifiers = KeyboardModifiers(Self::RIGHT_SHIFT_U8);
358
359    /// Const for right alt.
360    pub const RIGHT_ALT: KeyboardModifiers = KeyboardModifiers(Self::RIGHT_ALT_U8);
361
362    /// Const for right gui.
363    pub const RIGHT_GUI: KeyboardModifiers = KeyboardModifiers(Self::RIGHT_GUI_U8);
364
365    /// Predicate for whether the key code is a modifier key code.
366    pub const fn is_modifier_key_code(key_code: u8) -> bool {
367        matches!(key_code, 0xE0..=0xE7)
368    }
369
370    /// Constructs a Vec of key codes from the modifiers.
371    pub fn as_key_codes(&self) -> heapless::Vec<u8, 8> {
372        let mut key_codes = heapless::Vec::new();
373
374        if self.0 & Self::LEFT_CTRL_U8 != 0 {
375            key_codes.push(0xE0).unwrap();
376        }
377        if self.0 & Self::LEFT_SHIFT_U8 != 0 {
378            key_codes.push(0xE1).unwrap();
379        }
380        if self.0 & Self::LEFT_ALT_U8 != 0 {
381            key_codes.push(0xE2).unwrap();
382        }
383        if self.0 & Self::LEFT_GUI_U8 != 0 {
384            key_codes.push(0xE3).unwrap();
385        }
386        if self.0 & Self::RIGHT_CTRL_U8 != 0 {
387            key_codes.push(0xE4).unwrap();
388        }
389        if self.0 & Self::RIGHT_SHIFT_U8 != 0 {
390            key_codes.push(0xE5).unwrap();
391        }
392        if self.0 & Self::RIGHT_ALT_U8 != 0 {
393            key_codes.push(0xE6).unwrap();
394        }
395        if self.0 & Self::RIGHT_GUI_U8 != 0 {
396            key_codes.push(0xE7).unwrap();
397        }
398
399        key_codes
400    }
401
402    /// Constructs the byte for the modifiers of an HID keyboard report.
403    pub fn as_byte(&self) -> u8 {
404        self.as_key_codes()
405            .iter()
406            .fold(0u8, |acc, &kc| acc | (1 << (kc - 0xE0)))
407    }
408
409    /// Union of two KeyboardModifiers, taking "or" of each modifier.
410    pub const fn union(&self, other: &KeyboardModifiers) -> KeyboardModifiers {
411        KeyboardModifiers(self.0 | other.0)
412    }
413
414    /// Whether this keyboard modifiers includes all the other modifiers.
415    pub const fn has_modifiers(&self, other: &KeyboardModifiers) -> bool {
416        self.0 & other.0 != 0
417    }
418}
419
420/// Enum for the different types of key codes.
421#[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq)]
422pub enum KeyUsage {
423    /// Key usage code.
424    Keyboard(u8),
425    /// Custom code. (Behaviour defined by firmware implementation).
426    Custom(u8),
427}
428
429/// Struct for the output from [KeyState].
430#[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq)]
431pub struct KeyOutput {
432    key_code: KeyUsage,
433    key_modifiers: KeyboardModifiers,
434}
435
436impl KeyOutput {
437    /// Constructs a [KeyOutput] from a key code.
438    pub fn from_key_code(key_code: u8) -> Self {
439        if let Some(key_modifiers) = KeyboardModifiers::from_key_code(key_code) {
440            KeyOutput {
441                key_code: KeyUsage::Keyboard(0x00),
442                key_modifiers,
443            }
444        } else {
445            KeyOutput {
446                key_code: KeyUsage::Keyboard(key_code),
447                key_modifiers: KeyboardModifiers::new(),
448            }
449        }
450    }
451
452    /// Constructs a [KeyOutput] from a key code with the given keyboard modifiers.
453    pub fn from_key_code_with_modifiers(key_code: u8, key_modifiers: KeyboardModifiers) -> Self {
454        let KeyOutput {
455            key_code,
456            key_modifiers: km,
457        } = Self::from_key_code(key_code);
458        KeyOutput {
459            key_code,
460            key_modifiers: km.union(&key_modifiers),
461        }
462    }
463
464    /// Constructs a [KeyOutput] for just the given keyboard modifiers.
465    pub fn from_key_modifiers(key_modifiers: KeyboardModifiers) -> Self {
466        KeyOutput {
467            key_code: KeyUsage::Keyboard(0x00),
468            key_modifiers,
469        }
470    }
471
472    /// Constructs a [KeyOutput] from a custom code.
473    pub fn from_custom_code(custom_code: u8) -> Self {
474        KeyOutput {
475            key_code: KeyUsage::Custom(custom_code),
476            key_modifiers: KeyboardModifiers::new(),
477        }
478    }
479
480    /// Returns the key code value.
481    pub fn key_code(&self) -> KeyUsage {
482        self.key_code
483    }
484
485    /// Returns the keyboard modifiers of the key output.
486    pub fn key_modifiers(&self) -> KeyboardModifiers {
487        self.key_modifiers
488    }
489}
490
491/// Implements functionality for the pressed key.
492pub trait KeyState: Debug {
493    /// The type of `Context` the pressed key state handles.
494    type Context;
495    /// The type of `Event` the pressed key state handles.
496    type Event: Copy + Debug;
497
498    /// Used to update the [KeyState]'s state, and possibly yield event(s).
499    fn handle_event(
500        &mut self,
501        _context: &Self::Context,
502        _keymap_index: u16,
503        _event: Event<Self::Event>,
504    ) -> KeyEvents<Self::Event> {
505        KeyEvents::no_events()
506    }
507
508    /// Output for the pressed key state.
509    fn key_output(&self) -> Option<KeyOutput> {
510        None
511    }
512}
513
514/// A NoOp key state, for keys which do nothing when pressed.
515#[derive(Debug, Clone, Copy, PartialEq, Eq)]
516pub struct NoOpKeyState;
517
518/// Errors for [TryFrom] implementations.
519#[allow(unused)]
520pub enum EventError {
521    /// Error when mapping isn't possible.
522    ///
523    /// e.g. trying to map variants of [composite::Event] to [tap_hold::Event].
524    UnmappableEvent,
525}
526
527/// Convenience alias for a [Result] with an [EventError].
528type EventResult<T> = Result<T, EventError>;
529
530/// Events which are either input, or for a particular [System::Event].
531///
532/// It's useful for key implementations to use [Event] with [System::Event],
533///  and map [System::Event] to and partially from [composite::Event].
534#[derive(Debug, Clone, Copy, PartialEq, Eq)]
535pub enum Event<T> {
536    /// Keymap input events, such as physical key presses.
537    Input(input::Event),
538    /// Key implementation specific events.
539    Key {
540        /// The keymap index the event was generated from.
541        keymap_index: u16,
542        /// A [System::Event] event.
543        key_event: T,
544    },
545    /// Invoke a keymap callback
546    Keymap(crate::keymap::KeymapEvent),
547}
548
549impl<T: Copy> Event<T> {
550    /// Constructs an [Event] from an [System::Event].
551    pub fn key_event(keymap_index: u16, key_event: T) -> Self {
552        Event::Key {
553            keymap_index,
554            key_event,
555        }
556    }
557
558    /// Maps the Event into a new type.
559    pub fn map_key_event<U>(self, f: fn(T) -> U) -> Event<U> {
560        match self {
561            Event::Input(event) => Event::Input(event),
562            Event::Key {
563                key_event,
564                keymap_index,
565            } => Event::Key {
566                key_event: f(key_event),
567                keymap_index,
568            },
569            Event::Keymap(cb) => Event::Keymap(cb),
570        }
571    }
572
573    /// Maps the Event into a new type.
574    pub fn into_key_event<U>(self) -> Event<U>
575    where
576        T: Into<U>,
577    {
578        self.map_key_event(|ke| ke.into())
579    }
580
581    /// Maps the Event into a new type.
582    pub fn try_into_key_event<U, E>(self, f: fn(T) -> Result<U, E>) -> EventResult<Event<U>> {
583        match self {
584            Event::Input(event) => Ok(Event::Input(event)),
585            Event::Key {
586                key_event,
587                keymap_index,
588            } => f(key_event)
589                .map(|key_event| Event::Key {
590                    key_event,
591                    keymap_index,
592                })
593                .map_err(|_| EventError::UnmappableEvent),
594            Event::Keymap(cb) => Ok(Event::Keymap(cb)),
595        }
596    }
597}
598
599impl<T> From<input::Event> for Event<T> {
600    fn from(event: input::Event) -> Self {
601        Event::Input(event)
602    }
603}
604
605/// Schedule for a [ScheduledEvent].
606#[allow(unused)]
607#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord)]
608pub enum Schedule {
609    /// Immediately.
610    Immediate,
611    /// After a given number of `tick`s.
612    After(u16),
613}
614
615/// Schedules a given `T` with [Event], for some [Schedule].
616#[derive(Debug, Clone, Copy, PartialEq, Eq)]
617pub struct ScheduledEvent<T> {
618    /// Whether to handle the event immediately, or after some delay.
619    pub schedule: Schedule,
620    /// The event.
621    pub event: Event<T>,
622}
623
624impl<T: Copy> ScheduledEvent<T> {
625    /// Constructs a [ScheduledEvent] with [Schedule::Immediate].
626    #[allow(unused)]
627    pub fn immediate(event: Event<T>) -> Self {
628        ScheduledEvent {
629            schedule: Schedule::Immediate,
630            event,
631        }
632    }
633
634    /// Constructs a [ScheduledEvent] with [Schedule::After].
635    pub fn after(delay: u16, event: Event<T>) -> Self {
636        ScheduledEvent {
637            schedule: Schedule::After(delay),
638            event,
639        }
640    }
641
642    /// Maps the Event of the ScheduledEvent into a new type.
643    pub fn map_scheduled_event<U>(self, f: fn(T) -> U) -> ScheduledEvent<U> {
644        ScheduledEvent {
645            event: self.event.map_key_event(f),
646            schedule: self.schedule,
647        }
648    }
649
650    /// Maps the ScheduledEvent into a new type.
651    pub fn into_scheduled_event<U>(self) -> ScheduledEvent<U>
652    where
653        T: Into<U>,
654    {
655        self.map_scheduled_event(|e| e.into())
656    }
657}