diff options
| author | Nathan Reiner <nathan@nathanreiner.xyz> | 2024-08-03 00:08:47 +0200 |
|---|---|---|
| committer | Nathan Reiner <nathan@nathanreiner.xyz> | 2024-08-03 00:08:47 +0200 |
| commit | eafde55afcdf9dc4c17c6c97c1db472fc9ff9957 (patch) | |
| tree | 838cab985495ead6dc005bd934f9e87c896e4ddd /src/config/keymap/keymap_store.rs | |
| parent | bb9944d086332ed0b8d6064316225e901c456bd7 (diff) | |
add keymap for view and global
Diffstat (limited to 'src/config/keymap/keymap_store.rs')
| -rw-r--r-- | src/config/keymap/keymap_store.rs | 81 |
1 files changed, 81 insertions, 0 deletions
diff --git a/src/config/keymap/keymap_store.rs b/src/config/keymap/keymap_store.rs new file mode 100644 index 0000000..c782219 --- /dev/null +++ b/src/config/keymap/keymap_store.rs @@ -0,0 +1,81 @@ +use core::fmt; +use std::{ + collections::HashMap, + sync::{Arc, Mutex}, +}; + +use mlua::{Function, RegistryKey, Result}; +use ratatui::crossterm::event::KeyEvent; + +use crate::lua; + +#[derive(Default, Clone)] +pub struct KeyMapStore { + store: Option<HashMap<KeyEvent, Arc<Mutex<dyn Runnable>>>>, +} + +impl KeyMapStore { + pub const fn new() -> Self { + Self { store: None } + } + + pub fn get(&mut self, event: KeyEvent) -> Option<Arc<Mutex<dyn Runnable>>> { + match &self.store { + Some(store) => match store.get(&event) { + Some(func) => Some(Arc::clone(func)), + None => None, + }, + None => { + self.store = Some(HashMap::new()); + None + } + } + } + + pub fn map(&mut self, event: KeyEvent, func: impl Runnable + 'static) { + match &self.store { + Some(_) => {} + None => self.store = Some(HashMap::new()), + } + + if let Some(store) = &mut self.store { + store.insert(event, Arc::new(Mutex::new(func))); + } + } +} + +pub trait Runnable +where + Self: Send, +{ + fn run(&self) -> Result<()>; +} + +impl<T> Runnable for T +where + T: Fn(), + Self: Send, +{ + fn run(&self) -> Result<()> { + self(); + Ok(()) + } +} + +impl Runnable for RegistryKey +where + Self: Send, +{ + fn run(&self) -> Result<()> { + let lua = lua::get(); + let func: Function = lua.registry_value(self)?; + func.call::<(), ()>(())?; + Ok(()) + } +} + +impl fmt::Debug for KeyMapStore { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "KeyMapStore") + } +} |