1use core::fmt::Debug;
2use core::marker::PhantomData;
3
4use serde::{Deserialize, Serialize};
5
6use crate::input;
7
8pub mod callback;
10pub mod caps_word;
12pub mod chorded;
14pub mod custom;
16pub mod keyboard;
18pub mod layered;
20pub mod sticky;
22pub mod tap_dance;
24pub mod tap_hold;
26
27pub mod composite;
29
30pub const MAX_KEY_EVENTS: usize = 4;
32
33pub const MAX_KEY_PATH_LEN: usize = 4;
35
36#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct KeyPath(heapless::Vec<u16, MAX_KEY_PATH_LEN>);
39
40impl KeyPath {
41 pub fn keymap_index(&self) -> u16 {
43 self.0[0]
44 }
45
46 pub fn append_path_item(&self, item: u16) -> KeyPath {
48 let mut kp = self.clone();
49 kp.0.push(item).unwrap();
50 kp
51 }
52}
53
54impl core::ops::Deref for KeyPath {
55 type Target = [u16];
56
57 fn deref(&self) -> &Self::Target {
58 &self.0
59 }
60}
61
62#[derive(Debug, PartialEq, Eq)]
64pub struct KeyEvents<E, const M: usize = { MAX_KEY_EVENTS }>(heapless::Vec<ScheduledEvent<E>, M>);
65
66impl<E: Copy + Debug> KeyEvents<E> {
67 pub fn no_events() -> Self {
69 KeyEvents(None.into_iter().collect())
70 }
71
72 pub fn event(event: Event<E>) -> Self {
74 KeyEvents(Some(ScheduledEvent::immediate(event)).into_iter().collect())
75 }
76
77 pub fn scheduled_event(sch_event: ScheduledEvent<E>) -> Self {
79 KeyEvents(Some(sch_event).into_iter().collect())
80 }
81
82 pub fn schedule_event(&mut self, delay: u16, event: Event<E>) {
84 self.0.push(ScheduledEvent::after(delay, event)).unwrap();
85 }
86
87 pub fn extend(&mut self, other: KeyEvents<E>) {
89 other.0.into_iter().for_each(|ev| self.0.push(ev).unwrap());
90 }
91
92 pub fn add_event(&mut self, ev: ScheduledEvent<E>) {
94 self.0.push(ev).unwrap();
95 }
96
97 pub fn map_events<F>(&self, f: fn(E) -> F) -> KeyEvents<F> {
99 KeyEvents(
100 self.0
101 .as_slice()
102 .iter()
103 .map(|sch_ev| sch_ev.map_scheduled_event(f))
104 .collect(),
105 )
106 }
107
108 pub fn into_events<F>(&self) -> KeyEvents<F>
110 where
111 E: Into<F>,
112 {
113 KeyEvents(
114 self.0
115 .as_slice()
116 .iter()
117 .map(|sch_ev| sch_ev.map_scheduled_event(|ev| ev.into()))
118 .collect(),
119 )
120 }
121}
122
123impl<E: Debug, const M: usize> IntoIterator for KeyEvents<E, M> {
124 type Item = ScheduledEvent<E>;
125 type IntoIter = <heapless::Vec<ScheduledEvent<E>, M> as IntoIterator>::IntoIter;
126
127 fn into_iter(self) -> Self::IntoIter {
128 self.0.into_iter()
129 }
130}
131
132#[derive(Debug)]
134pub enum NewPressedKey {
135 Key(KeyPath),
137 NoOp,
139}
140
141impl NewPressedKey {
142 pub fn key_path(key_path: KeyPath) -> Self {
144 NewPressedKey::Key(key_path)
145 }
146
147 pub fn no_op() -> Self {
149 NewPressedKey::NoOp
150 }
151}
152
153#[derive(Debug)]
155pub enum PressedKeyResult<PKS, KS> {
156 Pending(KeyPath, PKS),
158 NewPressedKey(NewPressedKey),
160 Resolved(KS),
162}
163
164pub fn key_path(keymap_index: u16) -> KeyPath {
166 let mut vec = heapless::Vec::new();
167 vec.push(keymap_index).unwrap();
168 KeyPath(vec)
169}
170
171impl<PKS, KS> PressedKeyResult<PKS, KS> {
172 #[cfg(feature = "std")]
174 pub fn unwrap_resolved(self) -> KS {
175 match self {
176 PressedKeyResult::Resolved(r) => r,
177 _ => panic!("PressedKeyResult::unwrap_resolved: not Resolved"),
178 }
179 }
180
181 pub fn append_path_item(self, item: u16) -> Self {
183 match self {
184 PressedKeyResult::Pending(key_path, pks) => {
185 PressedKeyResult::Pending(key_path.append_path_item(item), pks)
186 }
187 pkr => pkr,
188 }
189 }
190}
191
192pub trait Key: Debug {
201 type Context: Copy;
206
207 type Event: Copy + Debug + PartialEq;
210
211 type PendingKeyState;
213
214 type KeyState;
216
217 fn new_pressed_key(
222 &self,
223 context: &Self::Context,
224 key_path: KeyPath,
225 ) -> (
226 PressedKeyResult<Self::PendingKeyState, Self::KeyState>,
227 KeyEvents<Self::Event>,
228 );
229
230 fn handle_event(
232 &self,
233 pending_state: &mut Self::PendingKeyState,
234 context: &Self::Context,
235 key_path: KeyPath,
236 event: Event<Self::Event>,
237 ) -> (Option<NewPressedKey>, KeyEvents<Self::Event>);
238
239 fn lookup(
241 &self,
242 path: &[u16],
243 ) -> &dyn Key<
244 Context = Self::Context,
245 Event = Self::Event,
246 PendingKeyState = Self::PendingKeyState,
247 KeyState = Self::KeyState,
248 >;
249}
250
251pub trait Context: Clone + Copy {
256 type Event;
258
259 fn handle_event(&mut self, event: Event<Self::Event>) -> KeyEvents<Self::Event>;
261}
262
263#[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 pub const LEFT_CTRL_U8: u8 = 0x01;
309 pub const LEFT_SHIFT_U8: u8 = 0x02;
311 pub const LEFT_ALT_U8: u8 = 0x04;
313 pub const LEFT_GUI_U8: u8 = 0x08;
315 pub const RIGHT_CTRL_U8: u8 = 0x10;
317 pub const RIGHT_SHIFT_U8: u8 = 0x20;
319 pub const RIGHT_ALT_U8: u8 = 0x40;
321 pub const RIGHT_GUI_U8: u8 = 0x80;
323
324 pub const fn new() -> Self {
326 KeyboardModifiers(0x00)
327 }
328
329 pub const fn from_byte(b: u8) -> Self {
331 KeyboardModifiers(b)
332 }
333
334 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 pub const NONE: KeyboardModifiers = KeyboardModifiers {
353 ..KeyboardModifiers::new()
354 };
355
356 pub const LEFT_CTRL: KeyboardModifiers = KeyboardModifiers(Self::LEFT_CTRL_U8);
358
359 pub const LEFT_SHIFT: KeyboardModifiers = KeyboardModifiers(Self::LEFT_SHIFT_U8);
361
362 pub const LEFT_ALT: KeyboardModifiers = KeyboardModifiers(Self::LEFT_ALT_U8);
364
365 pub const LEFT_GUI: KeyboardModifiers = KeyboardModifiers(Self::LEFT_GUI_U8);
367
368 pub const RIGHT_CTRL: KeyboardModifiers = KeyboardModifiers(Self::RIGHT_CTRL_U8);
370
371 pub const RIGHT_SHIFT: KeyboardModifiers = KeyboardModifiers(Self::RIGHT_SHIFT_U8);
373
374 pub const RIGHT_ALT: KeyboardModifiers = KeyboardModifiers(Self::RIGHT_ALT_U8);
376
377 pub const RIGHT_GUI: KeyboardModifiers = KeyboardModifiers(Self::RIGHT_GUI_U8);
379
380 pub const fn is_modifier_key_code(key_code: u8) -> bool {
382 matches!(key_code, 0xE0..=0xE7)
383 }
384
385 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 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 pub const fn union(&self, other: &KeyboardModifiers) -> KeyboardModifiers {
426 KeyboardModifiers(self.0 | other.0)
427 }
428
429 pub const fn has_modifiers(&self, other: &KeyboardModifiers) -> bool {
431 self.0 & other.0 != 0
432 }
433}
434
435#[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq)]
437pub enum KeyUsage {
438 Keyboard(u8),
440 Custom(u8),
442}
443
444#[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq)]
446pub struct KeyOutput {
447 key_code: KeyUsage,
448 key_modifiers: KeyboardModifiers,
449}
450
451impl KeyOutput {
452 pub fn from_key_code(key_code: u8) -> Self {
454 if let Some(key_modifiers) = KeyboardModifiers::from_key_code(key_code) {
455 KeyOutput {
456 key_code: KeyUsage::Keyboard(0x00),
457 key_modifiers,
458 }
459 } else {
460 KeyOutput {
461 key_code: KeyUsage::Keyboard(key_code),
462 key_modifiers: KeyboardModifiers::new(),
463 }
464 }
465 }
466
467 pub fn from_key_code_with_modifiers(key_code: u8, key_modifiers: KeyboardModifiers) -> Self {
469 let KeyOutput {
470 key_code,
471 key_modifiers: km,
472 } = Self::from_key_code(key_code);
473 KeyOutput {
474 key_code,
475 key_modifiers: km.union(&key_modifiers),
476 }
477 }
478
479 pub fn from_key_modifiers(key_modifiers: KeyboardModifiers) -> Self {
481 KeyOutput {
482 key_code: KeyUsage::Keyboard(0x00),
483 key_modifiers,
484 }
485 }
486
487 pub fn from_custom_code(custom_code: u8) -> Self {
489 KeyOutput {
490 key_code: KeyUsage::Custom(custom_code),
491 key_modifiers: KeyboardModifiers::new(),
492 }
493 }
494
495 pub fn key_code(&self) -> KeyUsage {
497 self.key_code
498 }
499
500 pub fn key_modifiers(&self) -> KeyboardModifiers {
502 self.key_modifiers
503 }
504}
505
506pub trait KeyState: Debug {
508 type Context;
510 type Event: Copy + Debug;
512
513 fn handle_event(
515 &mut self,
516 _context: &Self::Context,
517 _keymap_index: u16,
518 _event: Event<Self::Event>,
519 ) -> KeyEvents<Self::Event> {
520 KeyEvents::no_events()
521 }
522
523 fn key_output(&self) -> Option<KeyOutput> {
525 None
526 }
527}
528
529#[derive(Debug, Clone, Copy, PartialEq, Eq)]
531pub struct NoOpKeyState<Ctx, Ev>(PhantomData<(Ctx, Ev)>);
532
533impl<Ctx, Ev> NoOpKeyState<Ctx, Ev> {
534 pub const fn new() -> Self {
536 NoOpKeyState(PhantomData)
537 }
538}
539
540impl<Ctx: Debug, Ev: Copy + Debug> KeyState for NoOpKeyState<Ctx, Ev> {
541 type Context = Ctx;
542 type Event = Ev;
543}
544
545impl<Ctx, Ev> Default for NoOpKeyState<Ctx, Ev> {
546 fn default() -> Self {
547 Self::new()
548 }
549}
550
551#[allow(unused)]
553pub enum EventError {
554 UnmappableEvent,
558}
559
560type EventResult<T> = Result<T, EventError>;
562
563#[derive(Debug, Clone, Copy, PartialEq, Eq)]
568pub enum Event<T> {
569 Input(input::Event),
571 Key {
573 keymap_index: u16,
575 key_event: T,
577 },
578 Keymap(crate::keymap::KeymapEvent),
580}
581
582impl<T: Copy> Event<T> {
583 pub fn key_event(keymap_index: u16, key_event: T) -> Self {
585 Event::Key {
586 keymap_index,
587 key_event,
588 }
589 }
590
591 pub fn map_key_event<U>(self, f: fn(T) -> U) -> Event<U> {
593 match self {
594 Event::Input(event) => Event::Input(event),
595 Event::Key {
596 key_event,
597 keymap_index,
598 } => Event::Key {
599 key_event: f(key_event),
600 keymap_index,
601 },
602 Event::Keymap(cb) => Event::Keymap(cb),
603 }
604 }
605
606 pub fn into_key_event<U>(self) -> Event<U>
608 where
609 T: Into<U>,
610 {
611 self.map_key_event(|ke| ke.into())
612 }
613
614 pub fn try_into_key_event<U, E>(self, f: fn(T) -> Result<U, E>) -> EventResult<Event<U>> {
616 match self {
617 Event::Input(event) => Ok(Event::Input(event)),
618 Event::Key {
619 key_event,
620 keymap_index,
621 } => f(key_event)
622 .map(|key_event| Event::Key {
623 key_event,
624 keymap_index,
625 })
626 .map_err(|_| EventError::UnmappableEvent),
627 Event::Keymap(cb) => Ok(Event::Keymap(cb)),
628 }
629 }
630}
631
632impl<T> From<input::Event> for Event<T> {
633 fn from(event: input::Event) -> Self {
634 Event::Input(event)
635 }
636}
637
638#[allow(unused)]
640#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord)]
641pub enum Schedule {
642 Immediate,
644 After(u16),
646}
647
648#[derive(Debug, Clone, Copy, PartialEq, Eq)]
650pub struct ScheduledEvent<T> {
651 pub schedule: Schedule,
653 pub event: Event<T>,
655}
656
657impl<T: Copy> ScheduledEvent<T> {
658 #[allow(unused)]
660 pub fn immediate(event: Event<T>) -> Self {
661 ScheduledEvent {
662 schedule: Schedule::Immediate,
663 event,
664 }
665 }
666
667 pub fn after(delay: u16, event: Event<T>) -> Self {
669 ScheduledEvent {
670 schedule: Schedule::After(delay),
671 event,
672 }
673 }
674
675 pub fn map_scheduled_event<U>(self, f: fn(T) -> U) -> ScheduledEvent<U> {
677 ScheduledEvent {
678 event: self.event.map_key_event(f),
679 schedule: self.schedule,
680 }
681 }
682
683 pub fn into_scheduled_event<U>(self) -> ScheduledEvent<U>
685 where
686 T: Into<U>,
687 {
688 self.map_scheduled_event(|e| e.into())
689 }
690}