aboutsummaryrefslogtreecommitdiff
path: root/src/keys/key_commands.rs
blob: fc062866a5fc4b8261a8a6747b5d25b277658485 (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
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

use crate::app_action::AppAction;

#[derive(Default, Clone)]
pub struct KeyCommand {
    pub key_code: String,
    pub description: String,
    pub action: AppAction,
}

impl std::fmt::Display for KeyCommand {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}\t{}", self.key_code, self.description)
    }
}

pub fn serialize_key_event(event: KeyEvent) -> String {
    let mut modifiers = Vec::with_capacity(3);
    if event.modifiers.intersects(KeyModifiers::CONTROL) {
        modifiers.push("ctrl");
    }
    if event.modifiers.intersects(KeyModifiers::SUPER)
        || event.modifiers.intersects(KeyModifiers::HYPER)
        || event.modifiers.intersects(KeyModifiers::META)
    {
        modifiers.push("super");
    }
    if event.modifiers.intersects(KeyModifiers::ALT) {
        modifiers.push("alt");
    }

    let char;
    let key = match event.code {
        KeyCode::Backspace | KeyCode::Delete => "del",
        KeyCode::Enter => "enter",
        KeyCode::Left => "left",
        KeyCode::Right => "right",
        KeyCode::Up => "up",
        KeyCode::Down => "down",
        KeyCode::Tab => "tab",
        KeyCode::Char(' ') => "space",
        KeyCode::Char(c) => {
            char = c.to_string();
            &char
        }
        KeyCode::Esc => "esc",
        _ => "",
    };
    let separator = if modifiers.is_empty() { "" } else { "-" };
    let serialized_event =
        format!("{}{}{}", modifiers.join("-"), separator, key);

    serialized_event
}