1use 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
18pub type Keys = Vec<(String, Vec<String>)>;
20
21#[derive(Default)]
22struct Keymap {
23 file: BTreeMap<String, BTreeMap<String, Vec<String>>>,
25 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
37pub 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
66fn flatten(section: &str, prefix: &str, table: &dyn toml_edit::TableLike, out: &mut BTreeMap<String, Vec<String>>, notices: &mut Vec<String>) {
68 for (key, item) in table.iter() {
69 let name = if prefix.is_empty() { key.to_string() } else { format!("{prefix}.{key}") };
70 if let Some(text) = item.as_str() {
71 out.insert(name, if text.is_empty() { Vec::new() } else { vec![text.to_string()] });
72 } else if let Some(list) = item.as_array() {
73 let keys: Vec<String> = list.iter().filter_map(|v| v.as_str()).filter(|t| !t.is_empty()).map(str::to_string).collect();
74 if keys.len() != list.iter().filter(|v| v.as_str() != Some("")).count() {
75 notices.push(format!("keybindings.toml: [{section}] {name}: every key must be text in quotes"));
76 } else {
77 out.insert(name, keys);
78 }
79 } else if let Some(inner) = item.as_table_like() {
80 flatten(section, &name, inner, out, notices);
81 } else {
82 notices.push(format!("keybindings.toml: [{section}] {name} must be a key in quotes, or a list of keys"));
83 }
84 }
85}
86
87pub fn resolve(section: &str, defaults: &[(&str, &[&str])], valid: impl Fn(&str) -> bool) -> Keys {
91 with_keymap(|k| {
92 let defaults: Keys = defaults.iter().map(|(name, keys)| (name.to_string(), keys.iter().map(|s| s.to_string()).collect())).collect();
93 let empty = BTreeMap::new();
94 let file = k.file.get(section).unwrap_or(&empty);
95 for name in file.keys() {
96 if !defaults.iter().any(|(n, _)| n == name) {
97 k.notices.push(format!("keybindings.toml: [{section}] has no command {name:?}"));
98 }
99 }
100 let mut out = Keys::new();
101 for (name, default) in &defaults {
102 let keys = match file.get(name) {
103 Some(keys) => match keys.iter().find(|key| !valid(key)) {
104 Some(bad) => {
105 k.notices.push(format!("keybindings.toml: [{section}] {name}: {bad:?} is not a key; the default is kept"));
106 default.clone()
107 }
108 None => keys.clone(),
109 },
110 None => default.clone(),
111 };
112 out.push((name.clone(), keys));
113 }
114 let mut seen: BTreeMap<&str, &str> = BTreeMap::new();
115 for (name, keys) in &out {
116 for key in keys {
117 if let Some(other) = seen.insert(key, name)
118 && other != name
119 {
120 k.notices.push(format!("keybindings.toml: [{section}] {key:?} is bound to both {other} and {name}"));
121 }
122 }
123 }
124 k.defaults.retain(|(s, _)| s != section);
125 k.defaults.push((section.to_string(), defaults));
126 out
127 })
128}
129
130pub fn write_default_keybindings(path: &Path, app: &str) -> std::io::Result<()> {
133 if path.exists() {
134 return Ok(());
135 }
136 let text = with_keymap(|k| default_keybindings(app, &k.defaults));
137 if let Some(dir) = path.parent() {
138 std::fs::create_dir_all(dir)?;
139 }
140 std::fs::write(path, text)
141}
142
143fn default_keybindings(app: &str, sections: &[(String, Keys)]) -> String {
144 let mut text = format!(
145 "# {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",
146 );
147 for (section, keys) in sections {
148 text.push_str(&format!("\n[{section}]\n"));
149 let bare = |name: &str| name.split('.').all(|part| !part.is_empty() && part.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')) && !keys.iter().any(|(other, _)| other.starts_with(&format!("{name}.")));
151 for (name, bound) in keys {
152 let name = if bare(name) { name.clone() } else { format!("{name:?}") };
153 let value = match bound.as_slice() {
154 [one] => format!("{one:?}"),
155 many => format!("[{}]", many.iter().map(|k| format!("{k:?}")).collect::<Vec<_>>().join(", ")),
156 };
157 text.push_str(&format!("{name} = {value}\n"));
158 }
159 }
160 text
161}
162
163pub fn take_notices() -> Vec<String> {
165 with_keymap(|k| std::mem::take(&mut k.notices))
166}
167
168pub fn parse_key(text: &str) -> Option<(bool, bool, bool, String)> {
171 let (mut cmd, mut alt, mut shift) = (false, false, false);
172 let mut rest = text.trim();
173 loop {
174 let Some((head, tail)) = rest.split_once('-').filter(|(_, tail)| !tail.is_empty()) else { break };
175 match head {
176 "ctrl" | "cmd" | "secondary" | "super" => cmd = true,
177 "alt" => alt = true,
178 "shift" => shift = true,
179 _ => return None,
180 }
181 rest = tail;
182 }
183 (!rest.is_empty() && !rest.contains(' ')).then(|| (cmd, alt, shift, rest.to_lowercase()))
184}
185
186pub fn bind_commands(registry: &Registry, cx: &mut App) -> Vec<String> {
190 let commands = registry.all();
191 let defaults: Vec<(String, Vec<String>)> = commands.iter().map(|c| (c.id.to_string(), c.key.iter().map(|k| k.to_string()).collect())).collect();
192 let borrowed: Vec<(&str, Vec<&str>)> = defaults.iter().map(|(id, keys)| (id.as_str(), keys.iter().map(String::as_str).collect())).collect();
193 let slices: Vec<(&str, &[&str])> = borrowed.iter().map(|(id, keys)| (*id, keys.as_slice())).collect();
194 let probe = |key: &str| gpui_kit::KeyBinding::load(key, Box::new(gpui_kit::NoAction), None, false, None, cx).is_ok();
195 for ((id, keys), mut command) in resolve("commands", &slices, probe).into_iter().zip(commands) {
196 let key = keys.first().map(|k| SharedString::from(k.clone()));
197 if command.id.as_ref() == id && command.key != key {
198 command.key = key;
199 registry.add(command);
200 }
201 }
202 registry.bind_keys(None, cx)
203}
204
205#[cfg(test)]
206mod tests {
207 use super::*;
208
209 #[test]
210 fn key_bindings_override_defaults_by_command() {
211 let (file, notices) = parse_keybindings("[plot]\nplay_pause = \"p\"\nzoom_in = [\"+\", \"=\"]\npan_back = \"\"\n[commands]\nfile.open = \"ctrl-shift-o\"\n\"view.dark\" = \"f9\"\nbad = 3\n");
212 assert_eq!(notices.len(), 1, "{notices:?}");
213 assert_eq!(file["plot"]["play_pause"], vec!["p"]);
214 assert_eq!(file["plot"]["zoom_in"], vec!["+", "="]);
215 assert!(file["plot"]["pan_back"].is_empty(), "an empty key removes the binding");
216 assert_eq!(file["commands"]["file.open"], vec!["ctrl-shift-o"], "a dotted key is the command's id");
217 assert_eq!(file["commands"]["view.dark"], vec!["f9"]);
218 }
219
220 #[test]
221 fn the_default_file_reads_back_as_the_defaults() {
222 let sections = vec![("commands".to_string(), vec![("file.open".to_string(), vec!["ctrl-o".to_string()]), ("a.b".to_string(), vec![]), ("a.b.c".to_string(), vec!["f2".to_string(), "f3".to_string()])])];
223 let text = default_keybindings("test-app", §ions);
224 let (file, notices) = parse_keybindings(&text);
225 assert!(notices.is_empty(), "{notices:?}\n{text}");
226 assert_eq!(file["commands"]["file.open"], vec!["ctrl-o"]);
227 assert!(file["commands"]["a.b"].is_empty());
228 assert_eq!(file["commands"]["a.b.c"], vec!["f2", "f3"]);
229 }
230
231 #[test]
232 fn keys_parse_for_matching_by_hand() {
233 assert_eq!(parse_key("alt-g"), Some((false, true, false, "g".into())));
234 assert_eq!(parse_key("ctrl-shift-z"), Some((true, false, true, "z".into())));
235 assert_eq!(parse_key("shift-space"), Some((false, false, true, "space".into())));
236 assert_eq!(parse_key("-"), Some((false, false, false, "-".into())));
237 assert_eq!(parse_key("ctrl--"), Some((true, false, false, "-".into())));
238 assert_eq!(parse_key("hyper-g"), None);
239 assert_eq!(parse_key(""), None);
240 }
241}