summaryrefslogtreecommitdiff
path: root/src/config/keymap/template.rs
blob: bebcdc3a7d36e550be681518b7967adc5dbac964 (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
53
54
55
56
57
macro_rules! KeyMapSections {
    ($($name:ident => $key:ident),+ $(,)?) => {
        $(
            #[derive(Debug, Default, Clone)]
            pub struct $name {
                store: KeyMapStore,
            }

            impl $name {
                pub const fn new() -> Self {
                    Self {
                        store: KeyMapStore::new(),
                    }
                }

                pub fn handle(event: KeyEvent) -> bool {
                    let func = { GlobalConfig::instance_mut().keymap.$key.store.get(event) };

                    if let Some(func) = func {
                        let func = func.lock().unwrap();
                        if let Err(_error) = func.run() {
                            // TODO: add error buffer
                        }
                        true
                    } else {
                        false
                    }
                }

                pub fn map(event: KeyEvent, func: impl Runnable + 'static) {
                    GlobalConfig::instance_mut()
                        .keymap
                        .$key
                        .store
                        .map(event, func)
                }
            }

            impl UserData for $name {
                fn add_methods<'lua, M: mlua::prelude::LuaUserDataMethods<'lua, Self>>(
                    methods: &mut M,
                ) {
                    methods.add_function("map", |lua, (event, func): (String, Function<'_>)| {
                        let key = lua.create_registry_value(func)?;

                        if let Ok(event) = event_from_string(event) {
                            $name::map(event, key);
                        }
                        Ok(())
                    });
                }
            }
        )*
    };
}

pub(super) use KeyMapSections;