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(
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
94pub 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
143pub 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 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
180pub fn take_notices() -> Vec<String> {
182 with_keymap(|k| std::mem::take(&mut k.notices))
183}
184
185pub 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
203pub 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", §ions);
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}