Skip to main content

kitchen_shell/
keys.rs

1//! Key bindings the user edits: `keybindings.toml` in the app's configuration folder, a key or a
2//! list of keys per command, in sections (`[commands]` for the registry's commands, and one per
3//! part of an app that binds its own keys, as a plot's `[plot]`). Read once at start
4//! ([`load_keybindings`]); each section is resolved against its defaults ([`resolve`]); a
5//! missing file is written with every default ([`write_default_keybindings`]) so the user sees
6//! what can be changed. A key that cannot be read keeps its default and is named in a notice
7//! ([`take_notices`]).
8
9use std::collections::BTreeMap;
10use std::path::Path;
11use std::sync::Mutex;
12
13use gpui_kit::{App, SharedString};
14use toml_edit::DocumentMut;
15
16use crate::command::Registry;
17
18/// A section's commands with their keys.
19pub type Keys = Vec<(String, Vec<String>)>;
20
21#[derive(Default)]
22struct Keymap {
23    /// The file: section → command → keys.
24    file: BTreeMap<String, BTreeMap<String, Vec<String>>>,
25    /// The defaults of every section resolved so far, in order (what the file is written from).
26    defaults: Vec<(String, Keys)>,
27    notices: Vec<String>,
28}
29
30static KEYMAP: Mutex<Option<Keymap>> = Mutex::new(None);
31
32fn with_keymap<R>(f: impl FnOnce(&mut Keymap) -> R) -> R {
33    let mut guard = KEYMAP.lock().unwrap_or_else(|e| e.into_inner());
34    f(guard.get_or_insert_with(Keymap::default))
35}
36
37/// Reads `keybindings.toml` (a missing file: every default). Call once at start, before any
38/// section is resolved.
39pub fn load_keybindings(path: &Path) {
40    let Ok(text) = std::fs::read_to_string(path) else { return };
41    let (file, notices) = parse_keybindings(&text);
42    with_keymap(|k| {
43        k.file = file;
44        k.notices.extend(notices);
45    });
46}
47
48fn parse_keybindings(text: &str) -> (BTreeMap<String, BTreeMap<String, Vec<String>>>, Vec<String>) {
49    let mut notices = Vec::new();
50    let mut file = BTreeMap::new();
51    let doc: DocumentMut = match text.parse() {
52        Ok(d) => d,
53        Err(e) => return (file, vec![format!("keybindings.toml: {e}")]),
54    };
55    for (section, item) in doc.iter() {
56        let mut out = BTreeMap::new();
57        match item.as_table_like() {
58            Some(table) => flatten(section, "", table, &mut out, &mut notices),
59            None => notices.push(format!("keybindings.toml: {section} must be a section ([{section}])")),
60        }
61        file.insert(section.to_string(), out);
62    }
63    (file, notices)
64}
65
66/// `a.b = "key"` is read as the command `a.b` (TOML makes it a table inside a table).
67fn flatten(
68    section: &str,
69    prefix: &str,
70    table: &dyn toml_edit::TableLike,
71    out: &mut BTreeMap<String, Vec<String>>,
72    notices: &mut Vec<String>,
73) {
74    for (key, item) in table.iter() {
75        let name = if prefix.is_empty() { key.to_string() } else { format!("{prefix}.{key}") };
76        if let Some(text) = item.as_str() {
77            out.insert(name, if text.is_empty() { Vec::new() } else { vec![text.to_string()] });
78        } else if let Some(list) = item.as_array() {
79            let keys: Vec<String> =
80                list.iter().filter_map(|v| v.as_str()).filter(|t| !t.is_empty()).map(str::to_string).collect();
81            if keys.len() != list.iter().filter(|v| v.as_str() != Some("")).count() {
82                notices.push(format!("keybindings.toml: [{section}] {name}: every key must be text in quotes"));
83            } else {
84                out.insert(name, keys);
85            }
86        } else if let Some(inner) = item.as_table_like() {
87            flatten(section, &name, inner, out, notices);
88        } else {
89            notices.push(format!("keybindings.toml: [{section}] {name} must be a key in quotes, or a list of keys"));
90        }
91    }
92}
93
94/// The keys of `section`'s commands: the file's where it names the command, else `defaults`.
95/// `valid` says whether a key can be bound (one that cannot keeps the default). Commands the file
96/// names that `defaults` lacks, and one key on two commands, are noticed.
97pub fn resolve(section: &str, defaults: &[(&str, &[&str])], valid: impl Fn(&str) -> bool) -> Keys {
98    with_keymap(|k| {
99        let defaults: Keys = defaults
100            .iter()
101            .map(|(name, keys)| (name.to_string(), keys.iter().map(|s| s.to_string()).collect()))
102            .collect();
103        let empty = BTreeMap::new();
104        let file = k.file.get(section).unwrap_or(&empty);
105        for name in file.keys() {
106            if !defaults.iter().any(|(n, _)| n == name) {
107                k.notices.push(format!("keybindings.toml: [{section}] has no command {name:?}"));
108            }
109        }
110        let mut out = Keys::new();
111        for (name, default) in &defaults {
112            let keys = match file.get(name) {
113                Some(keys) => match keys.iter().find(|key| !valid(key)) {
114                    Some(bad) => {
115                        k.notices.push(format!(
116                            "keybindings.toml: [{section}] {name}: {bad:?} is not a key; the default is kept"
117                        ));
118                        default.clone()
119                    }
120                    None => keys.clone(),
121                },
122                None => default.clone(),
123            };
124            out.push((name.clone(), keys));
125        }
126        let mut seen: BTreeMap<&str, &str> = BTreeMap::new();
127        for (name, keys) in &out {
128            for key in keys {
129                if let Some(other) = seen.insert(key, name)
130                    && other != name
131                {
132                    k.notices
133                        .push(format!("keybindings.toml: [{section}] {key:?} is bound to both {other} and {name}"));
134                }
135            }
136        }
137        k.defaults.retain(|(s, _)| s != section);
138        k.defaults.push((section.to_string(), defaults));
139        out
140    })
141}
142
143/// Writes `keybindings.toml` with every default of the sections resolved so far, when the file
144/// does not exist yet.
145pub fn write_default_keybindings(path: &Path, app: &str) -> std::io::Result<()> {
146    if path.exists() {
147        return Ok(());
148    }
149    let text = with_keymap(|k| default_keybindings(app, &k.defaults));
150    if let Some(dir) = path.parent() {
151        std::fs::create_dir_all(dir)?;
152    }
153    std::fs::write(path, text)
154}
155
156fn default_keybindings(app: &str, sections: &[(String, Keys)]) -> String {
157    let mut text = format!(
158        "# {app} key bindings: command = \"key\", or a list of keys; \"\" removes a binding.\n# Keys are written as ctrl-shift-o, alt-g, space, left, f3, +. Read when the app starts.\n# Delete a line to go back to its default.\n",
159    );
160    for (section, keys) in sections {
161        text.push_str(&format!("\n[{section}]\n"));
162        // A command id that is also the start of another (`a.b` and `a.b.c`) cannot be a dotted key
163        let bare = |name: &str| {
164            name.split('.')
165                .all(|part| !part.is_empty() && part.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'))
166                && !keys.iter().any(|(other, _)| other.starts_with(&format!("{name}.")))
167        };
168        for (name, bound) in keys {
169            let name = if bare(name) { name.clone() } else { format!("{name:?}") };
170            let value = match bound.as_slice() {
171                [one] => format!("{one:?}"),
172                many => format!("[{}]", many.iter().map(|k| format!("{k:?}")).collect::<Vec<_>>().join(", ")),
173            };
174            text.push_str(&format!("{name} = {value}\n"));
175        }
176    }
177    text
178}
179
180/// The notices collected so far (each is given once).
181pub fn take_notices() -> Vec<String> {
182    with_keymap(|k| std::mem::take(&mut k.notices))
183}
184
185/// A key as the files write it, for matching by hand: (control or command, alt, shift, key).
186/// `None`: not a key.
187pub fn parse_key(text: &str) -> Option<(bool, bool, bool, String)> {
188    let (mut cmd, mut alt, mut shift) = (false, false, false);
189    let mut rest = text.trim();
190    loop {
191        let Some((head, tail)) = rest.split_once('-').filter(|(_, tail)| !tail.is_empty()) else { break };
192        match head {
193            "ctrl" | "cmd" | "secondary" | "super" => cmd = true,
194            "alt" => alt = true,
195            "shift" => shift = true,
196            _ => return None,
197        }
198        rest = tail;
199    }
200    (!rest.is_empty() && !rest.contains(' ')).then(|| (cmd, alt, shift, rest.to_lowercase()))
201}
202
203/// Gives the registry's commands their keys from `[commands]` (the first key the file names; the
204/// defaults are the commands' own) and binds them ([`Registry::bind_keys`]). Returns what
205/// could not be bound.
206pub fn bind_commands(registry: &Registry, cx: &mut App) -> Vec<String> {
207    let commands = registry.all();
208    let defaults: Vec<(String, Vec<String>)> =
209        commands.iter().map(|c| (c.id.to_string(), c.key.iter().map(|k| k.to_string()).collect())).collect();
210    let borrowed: Vec<(&str, Vec<&str>)> =
211        defaults.iter().map(|(id, keys)| (id.as_str(), keys.iter().map(String::as_str).collect())).collect();
212    let slices: Vec<(&str, &[&str])> = borrowed.iter().map(|(id, keys)| (*id, keys.as_slice())).collect();
213    let probe =
214        |key: &str| gpui_kit::KeyBinding::load(key, Box::new(gpui_kit::NoAction), None, false, None, cx).is_ok();
215    for ((id, keys), mut command) in resolve("commands", &slices, probe).into_iter().zip(commands) {
216        let key = keys.first().map(|k| SharedString::from(k.clone()));
217        if command.id.as_ref() == id && command.key != key {
218            command.key = key;
219            registry.add(command);
220        }
221    }
222    registry.bind_keys(None, cx)
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228
229    #[test]
230    fn key_bindings_override_defaults_by_command() {
231        let (file, notices) = parse_keybindings(
232            "[plot]\nplay_pause = \"p\"\nzoom_in = [\"+\", \"=\"]\npan_back = \"\"\n[commands]\nfile.open = \"ctrl-shift-o\"\n\"view.dark\" = \"f9\"\nbad = 3\n",
233        );
234        assert_eq!(notices.len(), 1, "{notices:?}");
235        assert_eq!(file["plot"]["play_pause"], vec!["p"]);
236        assert_eq!(file["plot"]["zoom_in"], vec!["+", "="]);
237        assert!(file["plot"]["pan_back"].is_empty(), "an empty key removes the binding");
238        assert_eq!(file["commands"]["file.open"], vec!["ctrl-shift-o"], "a dotted key is the command's id");
239        assert_eq!(file["commands"]["view.dark"], vec!["f9"]);
240    }
241
242    #[test]
243    fn the_default_file_reads_back_as_the_defaults() {
244        let sections = vec![(
245            "commands".to_string(),
246            vec![
247                ("file.open".to_string(), vec!["ctrl-o".to_string()]),
248                ("a.b".to_string(), vec![]),
249                ("a.b.c".to_string(), vec!["f2".to_string(), "f3".to_string()]),
250            ],
251        )];
252        let text = default_keybindings("test-app", &sections);
253        let (file, notices) = parse_keybindings(&text);
254        assert!(notices.is_empty(), "{notices:?}\n{text}");
255        assert_eq!(file["commands"]["file.open"], vec!["ctrl-o"]);
256        assert!(file["commands"]["a.b"].is_empty());
257        assert_eq!(file["commands"]["a.b.c"], vec!["f2", "f3"]);
258    }
259
260    #[test]
261    fn keys_parse_for_matching_by_hand() {
262        assert_eq!(parse_key("alt-g"), Some((false, true, false, "g".into())));
263        assert_eq!(parse_key("ctrl-shift-z"), Some((true, false, true, "z".into())));
264        assert_eq!(parse_key("shift-space"), Some((false, false, true, "space".into())));
265        assert_eq!(parse_key("-"), Some((false, false, false, "-".into())));
266        assert_eq!(parse_key("ctrl--"), Some((true, false, false, "-".into())));
267        assert_eq!(parse_key("hyper-g"), None);
268        assert_eq!(parse_key(""), None);
269    }
270}