tek/src/core/keymap.rs
2024-07-04 01:36:32 +03:00

39 lines
1.1 KiB
Rust

use crate::core::*;
pub type KeyHandler<T> = &'static dyn Fn(&mut T)->Usually<bool>;
pub type KeyBinding<T> = (
KeyCode, KeyModifiers, &'static str, &'static str, KeyHandler<T>
);
pub type KeyMap<T> = [KeyBinding<T>];
pub fn handle_keymap <T> (
state: &mut T, event: &AppEvent, keymap: &KeyMap<T>,
) -> Usually<bool> {
match event {
AppEvent::Input(Event::Key(event)) => {
for (code, modifiers, _, _, command) in keymap.iter() {
if *code == event.code && modifiers.bits() == event.modifiers.bits() {
return command(state)
}
}
},
_ => {}
};
Ok(false)
}
#[macro_export] macro_rules! key {
($k:ident $(($char:literal))?, $m:ident, $n: literal, $d: literal, $f: expr) => {
(KeyCode::$k $(($char))?, KeyModifiers::$m, $n, $d, &$f)
};
}
#[macro_export] macro_rules! keymap {
($T:ty { $([$k:ident $(($char:literal))?, $m:ident, $n: literal, $d: literal, $f: expr]),* $(,)? }) => {
&[
$((KeyCode::$k $(($char))?, KeyModifiers::$m, $n, $d, &$f as KeyHandler<$T>)),*
] as &'static [KeyBinding<$T>]
}
}