summaryrefslogtreecommitdiffstats
path: root/src/config/keymap/keymapping.rs
blob: 0f42e94010456be3a84622d25fbd71a9aa71d3e9 (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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
use serde_derive::Deserialize;

use std::collections::{hash_map::Entry, HashMap};
use std::str::FromStr;

#[cfg(feature = "mouse")]
use termion::event::MouseEvent;
use termion::event::{Event, Key};

use crate::config::{parse_to_config_file, ConfigStructure, Flattenable};
use crate::error::JoshutoResult;
use crate::io::IoWorkerOptions;
use crate::key_command::{Command, CommandKeybind};
use crate::util::keyparse::str_to_event;

use super::default_keymap::DEFAULT_KEYMAP;

#[derive(Debug, Deserialize)]
struct CommandKeymap {
    pub command: String,
    pub keys: Vec<String>,
}

#[derive(Debug, Deserialize)]
struct RawAppKeyMapping {
    #[serde(default)]
    mapcommand: Vec<CommandKeymap>,
}

impl Flattenable<AppKeyMapping> for RawAppKeyMapping {
    fn flatten(self) -> AppKeyMapping {
        let mut keymaps = AppKeyMapping::new();
        for m in self.mapcommand {
            match Command::from_str(m.command.as_str()) {
                Ok(command) => {
                    let events: Vec<Event> = m
                        .keys
                        .iter()
                        .filter_map(|s| str_to_event(s.as_str()))
                        .collect();

                    if events.len() != m.keys.len() {
                        eprintln!("Failed to parse events: {:?}", m.keys);
                        continue;
                    }

                    let result = insert_keycommand(&mut keymaps, command, &events);
                    match result {
                        Ok(_) => {}
                        Err(e) => eprintln!("{}", e),
                    }
                }
                Err(e) => eprintln!("{}", e),
            }
        }
        keymaps
    }
}

#[derive(Debug)]
pub struct AppKeyMapping {
    map: HashMap<Event, CommandKeybind>,
}

impl std::convert::AsRef<HashMap<Event, CommandKeybind>> for AppKeyMapping {
    fn as_ref(&self) -> &HashMap<Event, CommandKeybind> {
        &self.map
    }
}

impl std::convert::AsMut<HashMap<Event, CommandKeybind>> for AppKeyMapping {
    fn as_mut(&mut self) -> &mut HashMap<Event, CommandKeybind> {
        &mut self.map
    }
}

impl AppKeyMapping {
    pub fn new() -> Self {
        Self {
            map: HashMap::new(),
        }
    }

    pub fn default_res() -> JoshutoResult<Self> {
        let raw: RawAppKeyMapping = toml::from_str(DEFAULT_KEYMAP)?;
        let keymapping: Self = raw.flatten();
        Ok(keymapping)
    }
}

impl std::default::Default for AppKeyMapping {
    fn default() -> Self {
        AppKeyMapping::default_res().unwrap()
    }
}

impl ConfigStructure for AppKeyMapping {
    fn get_config(file_name: &str) -> Self {
        parse_to_config_file::<RawAppKeyMapping, AppKeyMapping>(file_name)
            .unwrap_or_else(Self::default)
    }
}

fn insert_keycommand(
    keymap: &mut AppKeyMapping,
    keycommand: Command,
    events: &[Event],
) -> Result<(), String> {
    let num_events = events.len();
    if num_events == 0 {
        return Ok(());
    }

    let event = events[0].clone();
    if num_events == 1 {
        match keymap.as_mut().entry(event) {
            Entry::Occupied(_) => {
                return Err(format!("Error: Keybindings ambiguous for {}", keycommand))
            }
            Entry::Vacant(entry) => entry.insert(CommandKeybind::SimpleKeybind(keycommand)),
        };
        return Ok(());
    }

    match keymap.as_mut().entry(event) {
        Entry::Occupied(mut entry) => match entry.get_mut() {
            CommandKeybind::CompositeKeybind(ref mut m) => {
                insert_keycommand(m, keycommand, &events[1..])
            }
            _ => Err(format!("Error: Keybindings ambiguous for {}", keycommand)),
        },
        Entry::Vacant(entry) => {
            let mut new_map = AppKeyMapping::new();
            let result = insert_keycommand(&mut new_map, keycommand, &events[1..]);
            if result.is_ok() {
                let composite_command = CommandKeybind::CompositeKeybind(new_map);
                entry.insert(composite_command);
            }
            result
        }
    }
}