1use core::fmt::Debug;
2
3use serde::{Deserialize, Serialize};
4
5use crate::input;
6
7pub mod callback;
9pub mod caps_word;
11pub mod chorded;
13pub mod custom;
15pub mod keyboard;
17pub mod layered;
19pub mod sticky;
21pub mod tap_dance;
23pub mod tap_hold;
25
26pub mod composite;
28
29pub const MAX_KEY_EVENTS: usize = 4;
31
32#[derive(Debug, PartialEq, Eq)]
34pub struct KeyEvents<E, const M: usize = { MAX_KEY_EVENTS }>(heapless::Vec<ScheduledEvent<E>, M>);
35
36impl<E: Copy + Debug> KeyEvents<E> {
37 pub fn no_events() -> Self {
39 KeyEvents(None.into_iter().collect())
40 }
41
42 pub fn event(event: Event<E>) -> Self {
44 KeyEvents(Some(ScheduledEvent::immediate(event)).into_iter().collect())
45 }
46
47 pub fn scheduled_event(sch_event: ScheduledEvent<E>) -> Self {
49 KeyEvents(Some(sch_event).into_iter().collect())
50 }
51
52 pub fn schedule_event(&mut self, delay: u16, event: Event<E>) {
54 self.0.push(ScheduledEvent::after(delay, event)).unwrap();
55 }
56
57 pub fn extend(&mut self, other: KeyEvents<E>) {
59 other.0.into_iter().for_each(|ev| self.0.push(ev).unwrap());
60 }
61
62 pub fn add_event(&mut self, ev: ScheduledEvent<E>) {
64 self.0.push(ev).unwrap();
65 }
66
67 pub fn map_events<F>(&self, f: fn(E) -> F) -> KeyEvents<F> {
69 KeyEvents(
70 self.0
71 .as_slice()
72 .iter()
73 .map(|sch_ev| sch_ev.map_scheduled_event(f))
74 .collect(),
75 )
76 }
77
78 pub fn into_events<F>(&self) -> KeyEvents<F>
80 where
81 E: Into<F>,
82 {
83 KeyEvents(
84 self.0
85 .as_slice()
86 .iter()
87 .map(|sch_ev| sch_ev.map_scheduled_event(|ev| ev.into()))
88 .collect(),
89 )
90 }
91}
92
93impl<E: Debug, const M: usize> IntoIterator for KeyEvents<E, M> {
94 type Item = ScheduledEvent<E>;
95 type IntoIter = <heapless::Vec<ScheduledEvent<E>, M> as IntoIterator>::IntoIter;
96
97 fn into_iter(self) -> Self::IntoIter {
98 self.0.into_iter()
99 }
100}
101
102#[derive(Debug, PartialEq)]
104pub enum NewPressedKey<R> {
105 Key(R),
107 NoOp,
109}
110
111impl<R> NewPressedKey<R> {
112 pub fn key(key_ref: R) -> Self {
114 NewPressedKey::Key(key_ref)
115 }
116
117 pub fn no_op() -> Self {
119 NewPressedKey::NoOp
120 }
121
122 pub fn map<TR>(self, f: fn(R) -> TR) -> NewPressedKey<TR> {
124 match self {
125 NewPressedKey::Key(r) => NewPressedKey::Key(f(r)),
126 NewPressedKey::NoOp => NewPressedKey::NoOp,
127 }
128 }
129}
130
131#[derive(Debug, PartialEq)]
133pub enum PressedKeyResult<R, PKS, KS> {
134 Pending(PKS),
136 NewPressedKey(NewPressedKey<R>),
138 Resolved(KS),
140}
141
142impl<R, PKS, KS> PressedKeyResult<R, PKS, KS> {
143 #[cfg(feature = "std")]
145 pub fn unwrap_resolved(self) -> KS {
146 match self {
147 PressedKeyResult::Resolved(r) => r,
148 _ => panic!("PressedKeyResult::unwrap_resolved: not Resolved"),
149 }
150 }
151
152 pub fn map<TPKS, TKS>(
154 self,
155 f: fn(PKS) -> TPKS,
156 g: fn(KS) -> TKS,
157 ) -> PressedKeyResult<R, TPKS, TKS> {
158 match self {
159 PressedKeyResult::Pending(pks) => PressedKeyResult::Pending(f(pks)),
160 PressedKeyResult::NewPressedKey(npk) => PressedKeyResult::NewPressedKey(npk),
161 PressedKeyResult::Resolved(ks) => PressedKeyResult::Resolved(g(ks)),
162 }
163 }
164}
165
166pub trait System<R>: Debug {
175 type Ref: Copy;
177
178 type Context: Copy;
183
184 type Event: Copy + Debug + PartialEq;
187
188 type PendingKeyState;
190
191 type KeyState;
193
194 fn new_pressed_key(
199 &self,
200 keymap_index: u16,
201 context: &Self::Context,
202 key_ref: Self::Ref,
203 ) -> (
204 PressedKeyResult<R, Self::PendingKeyState, Self::KeyState>,
205 KeyEvents<Self::Event>,
206 );
207
208 fn update_pending_state(
210 &self,
211 pending_state: &mut Self::PendingKeyState,
212 keymap_index: u16,
213 context: &Self::Context,
214 key_ref: Self::Ref,
215 event: Event<Self::Event>,
216 ) -> (Option<NewPressedKey<R>>, KeyEvents<Self::Event>);
217
218 fn update_state(
220 &self,
221 _key_state: &mut Self::KeyState,
222 _ref: &Self::Ref,
223 _context: &Self::Context,
224 _keymap_index: u16,
225 _event: Event<Self::Event>,
226 ) -> KeyEvents<Self::Event> {
227 KeyEvents::no_events()
228 }
229
230 fn key_output(&self, _ref: &Self::Ref, _key_state: &Self::KeyState) -> Option<KeyOutput> {
232 None
233 }
234}
235
236pub trait Context: Clone + Copy {
241 type Event;
243
244 fn handle_event(&mut self, event: Event<Self::Event>) -> KeyEvents<Self::Event>;
246}
247
248#[derive(Deserialize, Serialize, Default, Clone, Copy, PartialEq, Eq)]
250pub struct KeyboardModifiers(u8);
251
252impl core::ops::Deref for KeyboardModifiers {
253 type Target = u8;
254
255 fn deref(&self) -> &Self::Target {
256 &self.0
257 }
258}
259
260impl core::fmt::Debug for KeyboardModifiers {
261 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
262 let mut ds = f.debug_struct("KeyboardModifiers");
263 if self.0 & Self::LEFT_CTRL_U8 != 0 {
264 ds.field("left_ctrl", &true);
265 }
266 if self.0 & Self::LEFT_SHIFT_U8 != 0 {
267 ds.field("left_shift", &true);
268 }
269 if self.0 & Self::LEFT_ALT_U8 != 0 {
270 ds.field("left_alt", &true);
271 }
272 if self.0 & Self::LEFT_GUI_U8 != 0 {
273 ds.field("left_gui", &true);
274 }
275 if self.0 & Self::RIGHT_CTRL_U8 != 0 {
276 ds.field("right_ctrl", &true);
277 }
278 if self.0 & Self::RIGHT_SHIFT_U8 != 0 {
279 ds.field("right_shift", &true);
280 }
281 if self.0 & Self::RIGHT_ALT_U8 != 0 {
282 ds.field("right_alt", &true);
283 }
284 if self.0 & Self::RIGHT_GUI_U8 != 0 {
285 ds.field("right_gui", &true);
286 }
287 ds.finish_non_exhaustive()
288 }
289}
290
291impl KeyboardModifiers {
292 pub const LEFT_CTRL_U8: u8 = 0x01;
294 pub const LEFT_SHIFT_U8: u8 = 0x02;
296 pub const LEFT_ALT_U8: u8 = 0x04;
298 pub const LEFT_GUI_U8: u8 = 0x08;
300 pub const RIGHT_CTRL_U8: u8 = 0x10;
302 pub const RIGHT_SHIFT_U8: u8 = 0x20;
304 pub const RIGHT_ALT_U8: u8 = 0x40;
306 pub const RIGHT_GUI_U8: u8 = 0x80;
308
309 pub const fn new() -> Self {
311 KeyboardModifiers(0x00)
312 }
313
314 pub const fn from_byte(b: u8) -> Self {
316 KeyboardModifiers(b)
317 }
318
319 pub const fn from_key_code(key_code: u8) -> Option<Self> {
323 match key_code {
324 0xE0 => Some(Self::LEFT_CTRL),
325 0xE1 => Some(Self::LEFT_SHIFT),
326 0xE2 => Some(Self::LEFT_ALT),
327 0xE3 => Some(Self::LEFT_GUI),
328 0xE4 => Some(Self::RIGHT_CTRL),
329 0xE5 => Some(Self::RIGHT_SHIFT),
330 0xE6 => Some(Self::RIGHT_ALT),
331 0xE7 => Some(Self::RIGHT_GUI),
332 _ => None,
333 }
334 }
335
336 pub const NONE: KeyboardModifiers = KeyboardModifiers {
338 ..KeyboardModifiers::new()
339 };
340
341 pub const LEFT_CTRL: KeyboardModifiers = KeyboardModifiers(Self::LEFT_CTRL_U8);
343
344 pub const LEFT_SHIFT: KeyboardModifiers = KeyboardModifiers(Self::LEFT_SHIFT_U8);
346
347 pub const LEFT_ALT: KeyboardModifiers = KeyboardModifiers(Self::LEFT_ALT_U8);
349
350 pub const LEFT_GUI: KeyboardModifiers = KeyboardModifiers(Self::LEFT_GUI_U8);
352
353 pub const RIGHT_CTRL: KeyboardModifiers = KeyboardModifiers(Self::RIGHT_CTRL_U8);
355
356 pub const RIGHT_SHIFT: KeyboardModifiers = KeyboardModifiers(Self::RIGHT_SHIFT_U8);
358
359 pub const RIGHT_ALT: KeyboardModifiers = KeyboardModifiers(Self::RIGHT_ALT_U8);
361
362 pub const RIGHT_GUI: KeyboardModifiers = KeyboardModifiers(Self::RIGHT_GUI_U8);
364
365 pub const fn is_modifier_key_code(key_code: u8) -> bool {
367 matches!(key_code, 0xE0..=0xE7)
368 }
369
370 pub fn as_key_codes(&self) -> heapless::Vec<u8, 8> {
372 let mut key_codes = heapless::Vec::new();
373
374 if self.0 & Self::LEFT_CTRL_U8 != 0 {
375 key_codes.push(0xE0).unwrap();
376 }
377 if self.0 & Self::LEFT_SHIFT_U8 != 0 {
378 key_codes.push(0xE1).unwrap();
379 }
380 if self.0 & Self::LEFT_ALT_U8 != 0 {
381 key_codes.push(0xE2).unwrap();
382 }
383 if self.0 & Self::LEFT_GUI_U8 != 0 {
384 key_codes.push(0xE3).unwrap();
385 }
386 if self.0 & Self::RIGHT_CTRL_U8 != 0 {
387 key_codes.push(0xE4).unwrap();
388 }
389 if self.0 & Self::RIGHT_SHIFT_U8 != 0 {
390 key_codes.push(0xE5).unwrap();
391 }
392 if self.0 & Self::RIGHT_ALT_U8 != 0 {
393 key_codes.push(0xE6).unwrap();
394 }
395 if self.0 & Self::RIGHT_GUI_U8 != 0 {
396 key_codes.push(0xE7).unwrap();
397 }
398
399 key_codes
400 }
401
402 pub fn as_byte(&self) -> u8 {
404 self.as_key_codes()
405 .iter()
406 .fold(0u8, |acc, &kc| acc | (1 << (kc - 0xE0)))
407 }
408
409 pub const fn union(&self, other: &KeyboardModifiers) -> KeyboardModifiers {
411 KeyboardModifiers(self.0 | other.0)
412 }
413
414 pub const fn has_modifiers(&self, other: &KeyboardModifiers) -> bool {
416 self.0 & other.0 != 0
417 }
418}
419
420#[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq)]
422pub enum KeyUsage {
423 Keyboard(u8),
425 Custom(u8),
427}
428
429#[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq, Eq)]
431pub struct KeyOutput {
432 key_code: KeyUsage,
433 key_modifiers: KeyboardModifiers,
434}
435
436impl KeyOutput {
437 pub fn from_key_code(key_code: u8) -> Self {
439 if let Some(key_modifiers) = KeyboardModifiers::from_key_code(key_code) {
440 KeyOutput {
441 key_code: KeyUsage::Keyboard(0x00),
442 key_modifiers,
443 }
444 } else {
445 KeyOutput {
446 key_code: KeyUsage::Keyboard(key_code),
447 key_modifiers: KeyboardModifiers::new(),
448 }
449 }
450 }
451
452 pub fn from_key_code_with_modifiers(key_code: u8, key_modifiers: KeyboardModifiers) -> Self {
454 let KeyOutput {
455 key_code,
456 key_modifiers: km,
457 } = Self::from_key_code(key_code);
458 KeyOutput {
459 key_code,
460 key_modifiers: km.union(&key_modifiers),
461 }
462 }
463
464 pub fn from_key_modifiers(key_modifiers: KeyboardModifiers) -> Self {
466 KeyOutput {
467 key_code: KeyUsage::Keyboard(0x00),
468 key_modifiers,
469 }
470 }
471
472 pub fn from_custom_code(custom_code: u8) -> Self {
474 KeyOutput {
475 key_code: KeyUsage::Custom(custom_code),
476 key_modifiers: KeyboardModifiers::new(),
477 }
478 }
479
480 pub fn key_code(&self) -> KeyUsage {
482 self.key_code
483 }
484
485 pub fn key_modifiers(&self) -> KeyboardModifiers {
487 self.key_modifiers
488 }
489}
490
491pub trait KeyState: Debug {
493 type Context;
495 type Event: Copy + Debug;
497
498 fn handle_event(
500 &mut self,
501 _context: &Self::Context,
502 _keymap_index: u16,
503 _event: Event<Self::Event>,
504 ) -> KeyEvents<Self::Event> {
505 KeyEvents::no_events()
506 }
507
508 fn key_output(&self) -> Option<KeyOutput> {
510 None
511 }
512}
513
514#[derive(Debug, Clone, Copy, PartialEq, Eq)]
516pub struct NoOpKeyState;
517
518#[allow(unused)]
520pub enum EventError {
521 UnmappableEvent,
525}
526
527type EventResult<T> = Result<T, EventError>;
529
530#[derive(Debug, Clone, Copy, PartialEq, Eq)]
535pub enum Event<T> {
536 Input(input::Event),
538 Key {
540 keymap_index: u16,
542 key_event: T,
544 },
545 Keymap(crate::keymap::KeymapEvent),
547}
548
549impl<T: Copy> Event<T> {
550 pub fn key_event(keymap_index: u16, key_event: T) -> Self {
552 Event::Key {
553 keymap_index,
554 key_event,
555 }
556 }
557
558 pub fn map_key_event<U>(self, f: fn(T) -> U) -> Event<U> {
560 match self {
561 Event::Input(event) => Event::Input(event),
562 Event::Key {
563 key_event,
564 keymap_index,
565 } => Event::Key {
566 key_event: f(key_event),
567 keymap_index,
568 },
569 Event::Keymap(cb) => Event::Keymap(cb),
570 }
571 }
572
573 pub fn into_key_event<U>(self) -> Event<U>
575 where
576 T: Into<U>,
577 {
578 self.map_key_event(|ke| ke.into())
579 }
580
581 pub fn try_into_key_event<U, E>(self, f: fn(T) -> Result<U, E>) -> EventResult<Event<U>> {
583 match self {
584 Event::Input(event) => Ok(Event::Input(event)),
585 Event::Key {
586 key_event,
587 keymap_index,
588 } => f(key_event)
589 .map(|key_event| Event::Key {
590 key_event,
591 keymap_index,
592 })
593 .map_err(|_| EventError::UnmappableEvent),
594 Event::Keymap(cb) => Ok(Event::Keymap(cb)),
595 }
596 }
597}
598
599impl<T> From<input::Event> for Event<T> {
600 fn from(event: input::Event) -> Self {
601 Event::Input(event)
602 }
603}
604
605#[allow(unused)]
607#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord)]
608pub enum Schedule {
609 Immediate,
611 After(u16),
613}
614
615#[derive(Debug, Clone, Copy, PartialEq, Eq)]
617pub struct ScheduledEvent<T> {
618 pub schedule: Schedule,
620 pub event: Event<T>,
622}
623
624impl<T: Copy> ScheduledEvent<T> {
625 #[allow(unused)]
627 pub fn immediate(event: Event<T>) -> Self {
628 ScheduledEvent {
629 schedule: Schedule::Immediate,
630 event,
631 }
632 }
633
634 pub fn after(delay: u16, event: Event<T>) -> Self {
636 ScheduledEvent {
637 schedule: Schedule::After(delay),
638 event,
639 }
640 }
641
642 pub fn map_scheduled_event<U>(self, f: fn(T) -> U) -> ScheduledEvent<U> {
644 ScheduledEvent {
645 event: self.event.map_key_event(f),
646 schedule: self.schedule,
647 }
648 }
649
650 pub fn into_scheduled_event<U>(self) -> ScheduledEvent<U>
652 where
653 T: Into<U>,
654 {
655 self.map_scheduled_event(|e| e.into())
656 }
657}