1use core::fmt::Debug;
2
3use serde::{Deserialize, Serialize};
4
5use crate::input;
6
7pub mod automation;
9pub mod callback;
11pub mod caps_word;
13pub mod chorded;
15pub mod consumer;
17pub mod custom;
19pub mod keyboard;
21pub mod layered;
23pub mod mouse;
25pub mod sticky;
27pub mod tap_dance;
29pub mod tap_hold;
31
32pub mod composite;
34
35pub const MAX_KEY_EVENTS: usize = 4;
37
38#[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 pub fn no_events() -> Self {
45 KeyEvents(None.into_iter().collect())
46 }
47
48 pub fn event(event: Event<E>) -> Self {
50 KeyEvents(Some(ScheduledEvent::immediate(event)).into_iter().collect())
51 }
52
53 pub fn scheduled_event(sch_event: ScheduledEvent<E>) -> Self {
55 KeyEvents(Some(sch_event).into_iter().collect())
56 }
57
58 pub fn schedule_event(&mut self, delay: u16, event: Event<E>) {
60 self.0.push(ScheduledEvent::after(delay, event)).unwrap();
61 }
62
63 pub fn extend(&mut self, other: KeyEvents<E>) {
65 other.0.into_iter().for_each(|ev| self.0.push(ev).unwrap());
66 }
67
68 pub fn add_event(&mut self, ev: ScheduledEvent<E>) {
70 self.0.push(ev).unwrap();
71 }
72
73 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 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#[derive(Debug, PartialEq)]
110pub enum NewPressedKey<R> {
111 Key(R),
113 NoOp,
115}
116
117impl<R> NewPressedKey<R> {
118 pub fn key(key_ref: R) -> Self {
120 NewPressedKey::Key(key_ref)
121 }
122
123 pub fn no_op() -> Self {
125 NewPressedKey::NoOp
126 }
127
128 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#[derive(Debug, PartialEq)]
139pub enum PressedKeyResult<R, PKS, KS> {
140 Pending(PKS),
142 NewPressedKey(NewPressedKey<R>),
144 Resolved(KS),
146}
147
148impl<R, PKS, KS> PressedKeyResult<R, PKS, KS> {
149 #[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 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 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
181pub trait System<R>: Debug {
190 type Ref: Copy;
192
193 type Context: Copy;
198
199 type Event: Copy + Debug + PartialEq;
202
203 type PendingKeyState;
205
206 type KeyState;
208
209 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 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 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 fn key_output(&self, _ref: &Self::Ref, _key_state: &Self::KeyState) -> Option<KeyOutput> {
247 None
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 Consumer(u8),
442 Custom(u8),
444 Mouse(MouseOutput),
446}
447
448impl KeyUsage {
449 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#[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 pub const NO_OUTPUT: KeyOutput = KeyOutput {
494 key_code: KeyUsage::Keyboard(0x00),
495 key_modifiers: KeyboardModifiers::new(),
496 };
497
498 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 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 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 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 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 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 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 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 pub const fn key_code(&self) -> KeyUsage {
598 self.key_code
599 }
600
601 pub const fn key_modifiers(&self) -> KeyboardModifiers {
603 self.key_modifiers
604 }
605}
606
607#[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq)]
609pub struct MouseOutput {
610 pub pressed_buttons: u8,
612 pub x: i8,
614 pub y: i8,
616 pub vertical_scroll: i8,
618 pub horizontal_scroll: i8,
620}
621
622impl MouseOutput {
623 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 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
646pub trait KeyState: Debug {
648 type Context;
650 type Event: Copy + Debug;
652
653 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 fn key_output(&self) -> Option<KeyOutput> {
665 None
666 }
667}
668
669#[derive(Debug, Clone, Copy, PartialEq, Eq)]
671pub struct NoOpKeyState;
672
673#[allow(unused)]
675pub enum EventError {
676 UnmappableEvent,
680}
681
682type EventResult<T> = Result<T, EventError>;
684
685#[derive(Debug, Clone, Copy, PartialEq, Eq)]
690pub enum Event<T> {
691 Input(input::Event),
693 Key {
695 keymap_index: u16,
697 key_event: T,
699 },
700 Keymap(crate::keymap::KeymapEvent),
702}
703
704impl<T: Copy> Event<T> {
705 pub fn key_event(keymap_index: u16, key_event: T) -> Self {
707 Event::Key {
708 keymap_index,
709 key_event,
710 }
711 }
712
713 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 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 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#[allow(unused)]
766#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord)]
767pub enum Schedule {
768 Immediate,
770 After(u16),
772}
773
774#[derive(Debug, Clone, Copy, PartialEq, Eq)]
776pub struct ScheduledEvent<T> {
777 pub schedule: Schedule,
779 pub event: Event<T>,
781}
782
783impl<T: Copy> ScheduledEvent<T> {
784 #[allow(unused)]
786 pub fn immediate(event: Event<T>) -> Self {
787 ScheduledEvent {
788 schedule: Schedule::Immediate,
789 event,
790 }
791 }
792
793 pub fn after(delay: u16, event: Event<T>) -> Self {
795 ScheduledEvent {
796 schedule: Schedule::After(delay),
797 event,
798 }
799 }
800
801 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 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}