summaryrefslogtreecommitdiff
path: root/src/config/keymap/keymap_store.rs
blob: e4da9da15a1e49371251e006d0fb4f79dfb78bc0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
use core::fmt;
use std::{
    collections::HashMap,
    sync::{Arc, Mutex},
};

use ratatui::crossterm::event::KeyEvent;

use crate::lua::runnable::Runnable;

type KeyMapHandler = Arc<Mutex<dyn Runnable<(), bool>>>;

#[derive(Default, Clone)]
pub struct KeyMapStore {
    store: Option<HashMap<KeyEvent, KeyMapHandler>>,
}

impl KeyMapStore {
    pub const fn new() -> Self {
        Self { store: None }
    }

    pub fn get(&mut self, event: KeyEvent) -> Option<Arc<Mutex<dyn Runnable<(), bool>>>> {
        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<(), bool> + '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)));
        }
    }
}

impl fmt::Debug for KeyMapStore {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "KeyMapStore")
    }
}