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