Skip to main content

smart_keymap/
key.rs

1use core::fmt::Debug;
2
3use serde::{Deserialize, Serialize};
4
5use crate::input;
6
7/// Automation (macro) keys.
8pub mod automation;
9/// Keymap Callback keys
10pub mod callback;
11/// CapsWord key(s).
12pub mod caps_word;
13/// Chorded keys. (Chording functionality).
14pub mod chorded;
15/// Consumer keys.
16pub mod consumer;
17/// Custom keys.
18pub mod custom;
19/// HID Keyboard keys.
20pub mod keyboard;
21/// Layered keys. (Layering functionality).
22pub mod layered;
23/// Mouse keys.
24pub mod mouse;
25/// Sticky Modifier keys.
26pub mod sticky;
27/// Tap-Dance keys.
28pub mod tap_dance;
29/// Tap-Hold keys.
30pub mod tap_hold;
31
32/// "Composite" keys; an aggregate type used for a common context and event.
33pub mod composite;
34
35/// The maximum number of key events that are emitted by [crate::key::System] implementations.
36pub const MAX_KEY_EVENTS: usize = 4;
37
38/// Events emitted when a key is pressed.
39#[derive(Debug, PartialEq, Eq)]
40pub struct KeyEvents<E, const M: usize = { MAX_KEY_EVENTS }>(heapless::Vec<ScheduledEvent<E>, M>);
41
42impl<E: Copy + Debug> KeyEvents<E> {
43    /// Constructs a [KeyEvents] with no events scheduled.
44    pub fn no_events() -> Self {
45        KeyEvents(None.into_iter().collect())
46    }
47
48    /// Constructs a [KeyEvents] with an immediate [Event].
49    pub fn event(event: Event<E>) -> Self {
50        KeyEvents(Some(ScheduledEvent::immediate(event)).into_iter().collect())
51    }
52
53    /// Constructs a [KeyEvents] with an [Event] scheduled after a delay.
54    pub fn scheduled_event(sch_event: ScheduledEvent<E>) -> Self {
55        KeyEvents(Some(sch_event).into_iter().collect())
56    }
57
58    /// Adds an event with the schedule to the [KeyEvents].
59    pub fn schedule_event(&mut self, delay: u16, event: Event<E>) {
60        let _ = self.0.push(ScheduledEvent::after(delay, event));
61    }
62
63    /// Adds events from the other [KeyEvents] to the [KeyEvents].
64    pub fn extend(&mut self, other: KeyEvents<E>) {
65        other.0.into_iter().for_each(|ev| {
66            let _ = self.0.push(ev);
67        });
68    }
69
70    /// Adds an event from to the [KeyEvents].
71    pub fn add_event(&mut self, ev: ScheduledEvent<E>) {
72        let _ = self.0.push(ev);
73    }
74
75    /// Maps over the KeyEvents.
76    pub fn map_events<F>(&self, f: fn(E) -> F) -> KeyEvents<F> {
77        KeyEvents(
78            self.0
79                .as_slice()
80                .iter()
81                .map(|sch_ev| sch_ev.map_scheduled_event(f))
82                .collect(),
83        )
84    }
85
86    /// Maps the KeyEvents to a new type.
87    pub fn into_events<F>(&self) -> KeyEvents<F>
88    where
89        E: Into<F>,
90    {
91        KeyEvents(
92            self.0
93                .as_slice()
94                .iter()
95                .map(|sch_ev| sch_ev.map_scheduled_event(|ev| ev.into()))
96                .collect(),
97        )
98    }
99}
100
101impl<E: Debug, const M: usize> IntoIterator for KeyEvents<E, M> {
102    type Item = ScheduledEvent<E>;
103    type IntoIter = <heapless::Vec<ScheduledEvent<E>, M> as IntoIterator>::IntoIter;
104
105    fn into_iter(self) -> Self::IntoIter {
106        self.0.into_iter()
107    }
108}
109
110/// Newtype for invoking new_pressed_key on the key for the given ref.
111#[derive(Debug, PartialEq)]
112pub enum NewPressedKey<R> {
113    /// Invoke new_pressed_key on the key at the given ref.
114    Key(R),
115    /// For keys which do nothing when pressed.
116    NoOp,
117}
118
119impl<R> NewPressedKey<R> {
120    /// Constructs a NewPressedKey value.
121    pub fn key(key_ref: R) -> Self {
122        NewPressedKey::Key(key_ref)
123    }
124
125    /// Constructs a NoOp NewPressedKey value.
126    pub fn no_op() -> Self {
127        NewPressedKey::NoOp
128    }
129
130    /// Maps the NewPressedKey into a new type.
131    pub fn map<TR>(self, f: fn(R) -> TR) -> NewPressedKey<TR> {
132        match self {
133            NewPressedKey::Key(r) => NewPressedKey::Key(f(r)),
134            NewPressedKey::NoOp => NewPressedKey::NoOp,
135        }
136    }
137}
138
139/// Pressed Key which may be pending, or a resolved key state.
140#[derive(Debug, PartialEq)]
141pub enum PressedKeyResult<R, PKS, KS> {
142    /// Unresolved key state. (e.g. tap-hold or chorded keys when first pressed).
143    Pending(PKS),
144    /// Resolved as a new pressed key.
145    NewPressedKey(NewPressedKey<R>),
146    /// Resolved key state.
147    Resolved(KS),
148}
149
150impl<R, PKS, KS> PressedKeyResult<R, PKS, KS> {
151    /// Returns the Resolved variant, or else panics.
152    #[cfg(feature = "std")]
153    pub fn unwrap_resolved(self) -> KS {
154        match self {
155            PressedKeyResult::Resolved(r) => r,
156            _ => panic!("PressedKeyResult::unwrap_resolved: not Resolved"),
157        }
158    }
159
160    /// Maps the PressedKeyResult into a new type.
161    pub fn map<TPKS, TKS>(
162        self,
163        f: fn(PKS) -> TPKS,
164        g: fn(KS) -> TKS,
165    ) -> PressedKeyResult<R, TPKS, TKS> {
166        match self {
167            PressedKeyResult::Pending(pks) => PressedKeyResult::Pending(f(pks)),
168            PressedKeyResult::NewPressedKey(npk) => PressedKeyResult::NewPressedKey(npk),
169            PressedKeyResult::Resolved(ks) => PressedKeyResult::Resolved(g(ks)),
170        }
171    }
172
173    /// Maps the PressedKeyResult into a new type.
174    pub fn into_result<TPKS, TKS>(self) -> PressedKeyResult<R, TPKS, TKS>
175    where
176        PKS: Into<TPKS>,
177        KS: Into<TKS>,
178    {
179        self.map(|pks| pks.into(), |ks| ks.into())
180    }
181}
182
183/// Outcome of [System::new_pressed_key].
184pub type NewPressedKeyOutput<R, PKS, KS, E> = (PressedKeyResult<R, PKS, KS>, KeyEvents<E>);
185
186/// The interface for key `System` behaviour.
187///
188/// A `System` has an associated `Ref`, [Context], `Event`, and [KeyState].
189///
190/// The generic `PK` is used as the type of the `PressedKey` that the `Key`
191///  produces.
192/// (e.g. [layered::LayeredKey]'s pressed key state passes-through to
193///  the keys of its layers).
194pub trait System<R>: Debug {
195    /// Used to identify the key definition in the keymap.
196    type Ref: Copy;
197
198    /// The associated [Context] is used to provide state that
199    ///  may affect behaviour when pressing the key.
200    /// (e.g. the behaviour of [layered::LayeredKey] depends on which
201    ///  layers are active in [layered::Context]).
202    type Context: Copy;
203
204    /// The associated `Event` is to be handled by the associated [Context],
205    ///  pending key states, and key states.
206    type Event: Copy + Debug + PartialEq;
207
208    /// Associated pending key state.
209    type PendingKeyState;
210
211    /// Associated key state type.
212    type KeyState;
213
214    /// Produces a pressed key value, and may
215    ///  yield some [ScheduledEvent]s.
216    /// (e.g. [tap_hold::Key] may schedule a [tap_hold::Event::TapHoldTimeout]
217    ///  so that holding the key resolves as a hold,
218    ///  when a timeout is configured).
219    fn new_pressed_key(
220        &self,
221        keymap_index: u16,
222        context: &Self::Context,
223        key_ref: Self::Ref,
224    ) -> NewPressedKeyOutput<R, Self::PendingKeyState, Self::KeyState, Self::Event>;
225
226    /// Update the given pending key state with the given impl.
227    fn update_pending_state(
228        &self,
229        pending_state: &mut Self::PendingKeyState,
230        keymap_index: u16,
231        context: &Self::Context,
232        key_ref: Self::Ref,
233        event: Event<Self::Event>,
234    ) -> (Option<NewPressedKey<R>>, KeyEvents<Self::Event>);
235
236    /// Used to update the [KeyState]'s state, and possibly yield event(s).
237    fn update_state(
238        &self,
239        _key_state: &mut Self::KeyState,
240        _ref: &Self::Ref,
241        _context: &Self::Context,
242        _keymap_index: u16,
243        _event: Event<Self::Event>,
244    ) -> KeyEvents<Self::Event> {
245        KeyEvents::no_events()
246    }
247
248    /// Output for the pressed key state.
249    fn key_output(&self, _ref: &Self::Ref, _key_state: &Self::KeyState) -> Option<KeyOutput> {
250        None
251    }
252}
253
254/// Used to provide state that may affect behaviour when pressing the key.
255///
256/// e.g. the behaviour of [layered::LayeredKey] depends on which
257///  layers are active in [layered::Context].
258pub trait Context: Clone + Copy {
259    /// The type of `Event` the context handles.
260    type Event;
261
262    /// Used to update the [Context]'s state.
263    fn handle_event(&mut self, event: Event<Self::Event>) -> KeyEvents<Self::Event>;
264}
265
266/// Bool flags for each of the modifier keys (left ctrl, etc.).
267#[derive(Deserialize, Serialize, Default, Clone, Copy, PartialEq, Eq)]
268pub struct KeyboardModifiers(u8);
269
270impl core::ops::Deref for KeyboardModifiers {
271    type Target = u8;
272
273    fn deref(&self) -> &Self::Target {
274        &self.0
275    }
276}
277
278impl core::fmt::Debug for KeyboardModifiers {
279    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
280        let mut ds = f.debug_struct("KeyboardModifiers");
281        if self.0 & Self::LEFT_CTRL_U8 != 0 {
282            ds.field("left_ctrl", &true);
283        }
284        if self.0 & Self::LEFT_SHIFT_U8 != 0 {
285            ds.field("left_shift", &true);
286        }
287        if self.0 & Self::LEFT_ALT_U8 != 0 {
288            ds.field("left_alt", &true);
289        }
290        if self.0 & Self::LEFT_GUI_U8 != 0 {
291            ds.field("left_gui", &true);
292        }
293        if self.0 & Self::RIGHT_CTRL_U8 != 0 {
294            ds.field("right_ctrl", &true);
295        }
296        if self.0 & Self::RIGHT_SHIFT_U8 != 0 {
297            ds.field("right_shift", &true);
298        }
299        if self.0 & Self::RIGHT_ALT_U8 != 0 {
300            ds.field("right_alt", &true);
301        }
302        if self.0 & Self::RIGHT_GUI_U8 != 0 {
303            ds.field("right_gui", &true);
304        }
305        ds.finish_non_exhaustive()
306    }
307}
308
309impl KeyboardModifiers {
310    /// Byte value for left ctrl.
311    pub const LEFT_CTRL_U8: u8 = 0x01;
312    /// Byte value for left shift.
313    pub const LEFT_SHIFT_U8: u8 = 0x02;
314    /// Byte value for left alt.
315    pub const LEFT_ALT_U8: u8 = 0x04;
316    /// Byte value for left gui.
317    pub const LEFT_GUI_U8: u8 = 0x08;
318    /// Byte value for right ctrl.
319    pub const RIGHT_CTRL_U8: u8 = 0x10;
320    /// Byte value for right shift.
321    pub const RIGHT_SHIFT_U8: u8 = 0x20;
322    /// Byte value for right alt.
323    pub const RIGHT_ALT_U8: u8 = 0x40;
324    /// Byte value for right gui.
325    pub const RIGHT_GUI_U8: u8 = 0x80;
326
327    /// Constructs with modifiers defaulting to false.
328    pub const fn new() -> Self {
329        KeyboardModifiers(0x00)
330    }
331
332    /// Constructs with modifiers with the given byte.
333    pub const fn from_byte(b: u8) -> Self {
334        KeyboardModifiers(b)
335    }
336
337    /// Constructs with the given key_code.
338    ///
339    /// Returns None if the key_code is not a modifier key code.
340    pub const fn from_key_code(key_code: u8) -> Option<Self> {
341        match key_code {
342            0xE0 => Some(Self::LEFT_CTRL),
343            0xE1 => Some(Self::LEFT_SHIFT),
344            0xE2 => Some(Self::LEFT_ALT),
345            0xE3 => Some(Self::LEFT_GUI),
346            0xE4 => Some(Self::RIGHT_CTRL),
347            0xE5 => Some(Self::RIGHT_SHIFT),
348            0xE6 => Some(Self::RIGHT_ALT),
349            0xE7 => Some(Self::RIGHT_GUI),
350            _ => None,
351        }
352    }
353
354    /// Const for no modifiers
355    pub const NONE: KeyboardModifiers = KeyboardModifiers {
356        ..KeyboardModifiers::new()
357    };
358
359    /// Const for left ctrl.
360    pub const LEFT_CTRL: KeyboardModifiers = KeyboardModifiers(Self::LEFT_CTRL_U8);
361
362    /// Const for left shift.
363    pub const LEFT_SHIFT: KeyboardModifiers = KeyboardModifiers(Self::LEFT_SHIFT_U8);
364
365    /// Const for left alt.
366    pub const LEFT_ALT: KeyboardModifiers = KeyboardModifiers(Self::LEFT_ALT_U8);
367
368    /// Const for left gui.
369    pub const LEFT_GUI: KeyboardModifiers = KeyboardModifiers(Self::LEFT_GUI_U8);
370
371    /// Const for right ctrl.
372    pub const RIGHT_CTRL: KeyboardModifiers = KeyboardModifiers(Self::RIGHT_CTRL_U8);
373
374    /// Const for right shift.
375    pub const RIGHT_SHIFT: KeyboardModifiers = KeyboardModifiers(Self::RIGHT_SHIFT_U8);
376
377    /// Const for right alt.
378    pub const RIGHT_ALT: KeyboardModifiers = KeyboardModifiers(Self::RIGHT_ALT_U8);
379
380    /// Const for right gui.
381    pub const RIGHT_GUI: KeyboardModifiers = KeyboardModifiers(Self::RIGHT_GUI_U8);
382
383    /// Predicate for whether the key code is a modifier key code.
384    pub const fn is_modifier_key_code(key_code: u8) -> bool {
385        matches!(key_code, 0xE0..=0xE7)
386    }
387
388    /// Constructs a Vec of key codes from the modifiers.
389    pub fn as_key_codes(&self) -> heapless::Vec<u8, 8> {
390        let mut key_codes = heapless::Vec::new();
391
392        if self.0 & Self::LEFT_CTRL_U8 != 0 {
393            let _ = key_codes.push(0xE0);
394        }
395        if self.0 & Self::LEFT_SHIFT_U8 != 0 {
396            let _ = key_codes.push(0xE1);
397        }
398        if self.0 & Self::LEFT_ALT_U8 != 0 {
399            let _ = key_codes.push(0xE2);
400        }
401        if self.0 & Self::LEFT_GUI_U8 != 0 {
402            let _ = key_codes.push(0xE3);
403        }
404        if self.0 & Self::RIGHT_CTRL_U8 != 0 {
405            let _ = key_codes.push(0xE4);
406        }
407        if self.0 & Self::RIGHT_SHIFT_U8 != 0 {
408            let _ = key_codes.push(0xE5);
409        }
410        if self.0 & Self::RIGHT_ALT_U8 != 0 {
411            let _ = key_codes.push(0xE6);
412        }
413        if self.0 & Self::RIGHT_GUI_U8 != 0 {
414            let _ = key_codes.push(0xE7);
415        }
416
417        key_codes
418    }
419
420    /// Constructs the byte for the modifiers of an HID keyboard report.
421    pub fn as_byte(&self) -> u8 {
422        self.as_key_codes()
423            .iter()
424            .fold(0u8, |acc, &kc| acc | (1 << (kc - 0xE0)))
425    }
426
427    /// Union of two KeyboardModifiers, taking "or" of each modifier.
428    pub const fn union(&self, other: &KeyboardModifiers) -> KeyboardModifiers {
429        KeyboardModifiers(self.0 | other.0)
430    }
431
432    /// Whether this keyboard modifiers includes all the other modifiers.
433    pub const fn has_modifiers(&self, other: &KeyboardModifiers) -> bool {
434        self.0 & other.0 != 0
435    }
436}
437
438/// Enum for the different types of key codes.
439#[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq)]
440pub enum KeyUsage {
441    /// Key usage code.
442    Keyboard(u8),
443    /// Consumer usage code.
444    Consumer(u8),
445    /// Custom code. (Behaviour defined by firmware implementation).
446    Custom(u8),
447    /// Mouse usage.
448    Mouse(MouseOutput),
449}
450
451impl KeyUsage {
452    /// A key usage with no key code.
453    pub const NO_USAGE: KeyUsage = KeyUsage::Keyboard(0x00);
454}
455
456impl Default for KeyUsage {
457    fn default() -> Self {
458        KeyUsage::NO_USAGE
459    }
460}
461
462/// Struct for the output from [KeyState].
463#[derive(Deserialize, Serialize, Clone, Copy, PartialEq, Eq)]
464pub struct KeyOutput {
465    #[serde(default)]
466    key_code: KeyUsage,
467    #[serde(default)]
468    key_modifiers: KeyboardModifiers,
469}
470
471impl core::fmt::Debug for KeyOutput {
472    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
473        match (
474            self.key_code != KeyUsage::NO_USAGE,
475            self.key_modifiers != KeyboardModifiers::NONE,
476        ) {
477            (true, true) => f
478                .debug_struct("KeyOutput")
479                .field("key_code", &self.key_code)
480                .field("key_modifiers", &self.key_modifiers)
481                .finish(),
482            (false, true) => f
483                .debug_struct("KeyOutput")
484                .field("key_modifiers", &self.key_modifiers)
485                .finish(),
486            _ => f
487                .debug_struct("KeyOutput")
488                .field("key_code", &self.key_code)
489                .finish(),
490        }
491    }
492}
493
494impl KeyOutput {
495    /// A key output with no key code and no modifiers.
496    pub const NO_OUTPUT: KeyOutput = KeyOutput {
497        key_code: KeyUsage::Keyboard(0x00),
498        key_modifiers: KeyboardModifiers::new(),
499    };
500
501    /// Constructs a [KeyOutput] from a key usage.
502    pub const fn from_usage(key_usage: KeyUsage) -> Self {
503        match key_usage {
504            KeyUsage::Keyboard(kc) => Self::from_key_code(kc),
505            KeyUsage::Consumer(cc) => Self::from_consumer_code(cc),
506            KeyUsage::Custom(cu) => Self::from_custom_code(cu),
507            KeyUsage::Mouse(mo) => Self::from_mouse_output(mo),
508        }
509    }
510
511    /// Constructs a [KeyOutput] from a key usage.
512    pub const fn from_usage_with_modifiers(
513        key_usage: KeyUsage,
514        key_modifiers: KeyboardModifiers,
515    ) -> Self {
516        match key_usage {
517            KeyUsage::Keyboard(kc) => {
518                if let Some(usage_key_modifiers) = KeyboardModifiers::from_key_code(kc) {
519                    KeyOutput {
520                        key_code: KeyUsage::Keyboard(0x00),
521                        key_modifiers: usage_key_modifiers.union(&key_modifiers),
522                    }
523                } else {
524                    KeyOutput {
525                        key_code: KeyUsage::Keyboard(kc),
526                        key_modifiers,
527                    }
528                }
529            }
530            _ => KeyOutput {
531                key_code: key_usage,
532                key_modifiers,
533            },
534        }
535    }
536
537    /// Constructs a [KeyOutput] from a key code.
538    pub const fn from_key_code(key_code: u8) -> Self {
539        if let Some(key_modifiers) = KeyboardModifiers::from_key_code(key_code) {
540            KeyOutput {
541                key_code: KeyUsage::Keyboard(0x00),
542                key_modifiers,
543            }
544        } else {
545            KeyOutput {
546                key_code: KeyUsage::Keyboard(key_code),
547                key_modifiers: KeyboardModifiers::new(),
548            }
549        }
550    }
551
552    /// Constructs a [KeyOutput] from a key code with the given keyboard modifiers.
553    pub const fn from_key_code_with_modifiers(
554        key_code: u8,
555        key_modifiers: KeyboardModifiers,
556    ) -> Self {
557        let KeyOutput {
558            key_code,
559            key_modifiers: km,
560        } = Self::from_key_code(key_code);
561        KeyOutput {
562            key_code,
563            key_modifiers: km.union(&key_modifiers),
564        }
565    }
566
567    /// Constructs a [KeyOutput] for just the given keyboard modifiers.
568    pub const fn from_key_modifiers(key_modifiers: KeyboardModifiers) -> Self {
569        KeyOutput {
570            key_code: KeyUsage::Keyboard(0x00),
571            key_modifiers,
572        }
573    }
574
575    /// Constructs a [KeyOutput] from a consumer code.
576    pub const fn from_consumer_code(usage_code: u8) -> Self {
577        KeyOutput {
578            key_code: KeyUsage::Consumer(usage_code),
579            key_modifiers: KeyboardModifiers::new(),
580        }
581    }
582
583    /// Constructs a [KeyOutput] from a custom code.
584    pub const fn from_custom_code(custom_code: u8) -> Self {
585        KeyOutput {
586            key_code: KeyUsage::Custom(custom_code),
587            key_modifiers: KeyboardModifiers::new(),
588        }
589    }
590
591    /// Constructs a [KeyOutput] from a mouse output.
592    pub const fn from_mouse_output(mouse_output: MouseOutput) -> Self {
593        KeyOutput {
594            key_code: KeyUsage::Mouse(mouse_output),
595            key_modifiers: KeyboardModifiers::new(),
596        }
597    }
598
599    /// Returns the key code value.
600    pub const fn key_code(&self) -> KeyUsage {
601        self.key_code
602    }
603
604    /// Returns the keyboard modifiers of the key output.
605    pub const fn key_modifiers(&self) -> KeyboardModifiers {
606        self.key_modifiers
607    }
608}
609
610/// Struct for the mouse output.
611#[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq)]
612pub struct MouseOutput {
613    /// Bitmask of pressed buttons.
614    pub pressed_buttons: u8,
615    /// X direction.
616    pub x: i8,
617    /// Y direction.
618    pub y: i8,
619    /// Vertical scroll.
620    pub vertical_scroll: i8,
621    /// Horizontal scroll.
622    pub horizontal_scroll: i8,
623}
624
625impl MouseOutput {
626    /// A mouse output with no buttons pressed and no movement.
627    pub const NO_OUTPUT: MouseOutput = MouseOutput {
628        pressed_buttons: 0,
629        x: 0,
630        y: 0,
631        vertical_scroll: 0,
632        horizontal_scroll: 0,
633    };
634
635    /// Combines two mouse output values into one.
636    pub fn combine(&self, other: &Self) -> Self {
637        Self {
638            pressed_buttons: self.pressed_buttons | other.pressed_buttons,
639            x: self.x.saturating_add(other.x),
640            y: self.y.saturating_add(other.y),
641            vertical_scroll: self.vertical_scroll.saturating_add(other.vertical_scroll),
642            horizontal_scroll: self
643                .horizontal_scroll
644                .saturating_add(other.horizontal_scroll),
645        }
646    }
647}
648
649/// Implements functionality for the pressed key.
650pub trait KeyState: Debug {
651    /// The type of `Context` the pressed key state handles.
652    type Context;
653    /// The type of `Event` the pressed key state handles.
654    type Event: Copy + Debug;
655
656    /// Used to update the [KeyState]'s state, and possibly yield event(s).
657    fn handle_event(
658        &mut self,
659        _context: &Self::Context,
660        _keymap_index: u16,
661        _event: Event<Self::Event>,
662    ) -> KeyEvents<Self::Event> {
663        KeyEvents::no_events()
664    }
665
666    /// Output for the pressed key state.
667    fn key_output(&self) -> Option<KeyOutput> {
668        None
669    }
670}
671
672/// A NoOp key state, for keys which do nothing when pressed.
673#[derive(Debug, Clone, Copy, PartialEq, Eq)]
674pub struct NoOpKeyState;
675
676/// Errors for [TryFrom] implementations.
677#[allow(unused)]
678pub enum EventError {
679    /// Error when mapping isn't possible.
680    ///
681    /// e.g. trying to map variants of [composite::Event] to [tap_hold::Event].
682    UnmappableEvent,
683}
684
685/// Convenience alias for a [Result] with an [EventError].
686type EventResult<T> = Result<T, EventError>;
687
688/// Events which are either input, or for a particular [System::Event].
689///
690/// It's useful for key implementations to use [Event] with [System::Event],
691///  and map [System::Event] to and partially from [composite::Event].
692#[derive(Debug, Clone, Copy, PartialEq, Eq)]
693pub enum Event<T> {
694    /// Keymap input events, such as physical key presses.
695    Input(input::Event),
696    /// Key implementation specific events.
697    Key {
698        /// The keymap index the event was generated from.
699        keymap_index: u16,
700        /// A [System::Event] event.
701        key_event: T,
702    },
703    /// Invoke a keymap callback
704    Keymap(crate::keymap::KeymapEvent),
705}
706
707impl<T: Copy> Event<T> {
708    /// Constructs an [Event] from an [System::Event].
709    pub fn key_event(keymap_index: u16, key_event: T) -> Self {
710        Event::Key {
711            keymap_index,
712            key_event,
713        }
714    }
715
716    /// Maps the Event into a new type.
717    pub fn map_key_event<U>(self, f: fn(T) -> U) -> Event<U> {
718        match self {
719            Event::Input(event) => Event::Input(event),
720            Event::Key {
721                key_event,
722                keymap_index,
723            } => Event::Key {
724                key_event: f(key_event),
725                keymap_index,
726            },
727            Event::Keymap(cb) => Event::Keymap(cb),
728        }
729    }
730
731    /// Maps the Event into a new type.
732    pub fn into_key_event<U>(self) -> Event<U>
733    where
734        T: Into<U>,
735    {
736        self.map_key_event(|ke| ke.into())
737    }
738
739    /// Maps the Event into a new type.
740    pub fn try_into_key_event<U, E>(self) -> EventResult<Event<U>>
741    where
742        T: TryInto<U, Error = E>,
743    {
744        match self {
745            Event::Input(event) => Ok(Event::Input(event)),
746            Event::Key {
747                key_event,
748                keymap_index,
749            } => key_event
750                .try_into()
751                .map(|key_event| Event::Key {
752                    key_event,
753                    keymap_index,
754                })
755                .map_err(|_| EventError::UnmappableEvent),
756            Event::Keymap(cb) => Ok(Event::Keymap(cb)),
757        }
758    }
759
760    /// Whether this event targets the given `keymap_index`.
761    ///
762    /// Input press/release and key-specific events carry a `keymap_index`;
763    /// keymap callbacks and other variants do not.
764    pub(crate) fn targets_keymap_index(&self, keymap_index: u16) -> bool {
765        match self {
766            Event::Input(input::Event::Press {
767                keymap_index: queued_kmi,
768            })
769            | Event::Input(input::Event::Release {
770                keymap_index: queued_kmi,
771            }) => *queued_kmi == keymap_index,
772            Event::Key {
773                keymap_index: queued_kmi,
774                ..
775            } => *queued_kmi == keymap_index,
776            _ => false,
777        }
778    }
779}
780
781/// Returns the events that should be replayed when a pending key resolves.
782///
783/// Resolution filter:
784/// - All queued events **not** targeting `keymap_index` are included.
785/// - Only the **last** event targeting `keymap_index` is included (if any).
786///
787/// **Example:**
788///  session log `[Press(1), Press(0), Release(0)]` for resolving key 0:
789///   yields `[Press(1), Release(0)]`
790///   — other-key inputs are kept,
791///   - but only the final self-event (`Release(0)`) remains from key 0's own press/release pair.
792pub(crate) fn pending_resolution_events<Ev: Copy, const N: usize>(
793    queued_events: &heapless::Vec<Event<Ev>, N>,
794    keymap_index: u16,
795) -> heapless::Vec<Event<Ev>, N> {
796    let (self_events, other_events): (heapless::Vec<Event<Ev>, N>, heapless::Vec<Event<Ev>, N>) =
797        queued_events
798            .iter()
799            .partition(|ev| ev.targets_keymap_index(keymap_index));
800
801    let mut result = heapless::Vec::new();
802    for ev in other_events.iter().chain(self_events.last()) {
803        let _ = result.push(*ev);
804    }
805    result
806}
807
808impl<T> From<input::Event> for Event<T> {
809    fn from(event: input::Event) -> Self {
810        Event::Input(event)
811    }
812}
813
814/// Schedule for a [ScheduledEvent].
815#[allow(unused)]
816#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord)]
817pub enum Schedule {
818    /// Immediately.
819    Immediate,
820    /// After a given number of `tick`s.
821    After(u16),
822}
823
824/// Schedules a given `T` with [Event], for some [Schedule].
825#[derive(Debug, Clone, Copy, PartialEq, Eq)]
826pub struct ScheduledEvent<T> {
827    /// Whether to handle the event immediately, or after some delay.
828    pub schedule: Schedule,
829    /// The event.
830    pub event: Event<T>,
831}
832
833impl<T: Copy> ScheduledEvent<T> {
834    /// Constructs a [ScheduledEvent] with [Schedule::Immediate].
835    #[allow(unused)]
836    pub fn immediate(event: Event<T>) -> Self {
837        ScheduledEvent {
838            schedule: Schedule::Immediate,
839            event,
840        }
841    }
842
843    /// Constructs a [ScheduledEvent] with [Schedule::After].
844    pub fn after(delay: u16, event: Event<T>) -> Self {
845        ScheduledEvent {
846            schedule: Schedule::After(delay),
847            event,
848        }
849    }
850
851    /// Maps the Event of the ScheduledEvent into a new type.
852    pub fn map_scheduled_event<U>(self, f: fn(T) -> U) -> ScheduledEvent<U> {
853        ScheduledEvent {
854            event: self.event.map_key_event(f),
855            schedule: self.schedule,
856        }
857    }
858
859    /// Maps the ScheduledEvent into a new type.
860    pub fn into_scheduled_event<U>(self) -> ScheduledEvent<U>
861    where
862        T: Into<U>,
863    {
864        self.map_scheduled_event(|e| e.into())
865    }
866}
867
868#[cfg(test)]
869#[allow(clippy::unwrap_used, clippy::expect_used)]
870mod tests {
871    use super::*;
872
873    #[test]
874    fn pending_resolution_events_empty_returns_empty() {
875        let queued: heapless::Vec<Event<()>, 16> = heapless::Vec::new();
876        let result = pending_resolution_events(&queued, 0);
877        assert!(result.is_empty());
878    }
879
880    #[test]
881    fn pending_resolution_events_other_key_events_all_included() {
882        let mut queued: heapless::Vec<Event<()>, 16> = heapless::Vec::new();
883        queued
884            .push(Event::Input(input::Event::Press { keymap_index: 1 }))
885            .unwrap();
886        queued
887            .push(Event::Input(input::Event::Release { keymap_index: 2 }))
888            .unwrap();
889        let result = pending_resolution_events(&queued, 0);
890        assert_eq!(2, result.len());
891    }
892
893    #[test]
894    fn pending_resolution_events_resolving_key_only_last_included() {
895        let mut queued: heapless::Vec<Event<()>, 16> = heapless::Vec::new();
896        queued
897            .push(Event::Input(input::Event::Press { keymap_index: 0 }))
898            .unwrap();
899        queued
900            .push(Event::Input(input::Event::Release { keymap_index: 0 }))
901            .unwrap();
902        let result = pending_resolution_events(&queued, 0);
903        assert_eq!(1, result.len());
904        assert_eq!(
905            Event::Input(input::Event::Release { keymap_index: 0 }),
906            result[0]
907        );
908    }
909
910    #[test]
911    fn pending_resolution_events_mix_other_and_resolving_key() {
912        let mut queued: heapless::Vec<Event<()>, 16> = heapless::Vec::new();
913        queued
914            .push(Event::Input(input::Event::Press { keymap_index: 1 }))
915            .unwrap();
916        queued
917            .push(Event::Input(input::Event::Press { keymap_index: 0 }))
918            .unwrap();
919        queued
920            .push(Event::Input(input::Event::Release { keymap_index: 0 }))
921            .unwrap();
922        let result = pending_resolution_events(&queued, 0);
923        assert_eq!(2, result.len());
924        assert_eq!(
925            Event::Input(input::Event::Press { keymap_index: 1 }),
926            result[0]
927        );
928        assert_eq!(
929            Event::Input(input::Event::Release { keymap_index: 0 }),
930            result[1]
931        );
932    }
933}