Skip to main content

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