forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB2e2ed69Tahinli3 months ago69 commits

keymap.rs744 lines, 28.0 KiBHistoryRawDownload
1//! The keymap: which stroke means which action, and the file it survives in.
2//!
3//! ```text
4//! edith-keys 1
5//! play space
6//! delete x
7//! delete delete
8//! save ctrl+s
9//! ```
10//!
11//! One line per binding, so an action bound to two strokes is two lines and the
12//! format needs no list syntax. A chord is `key` or `ctrl+key`, where `key` is
13//! exactly what gpui reports for the stroke (`escape`, not `esc`) -- the lookup
14//! compares against that string and nothing translates in between. What a
15//! *person* reads is [`Keymap::display`]'s business, and only there.
16//!
17//! The parser is strict and every refusal names its 1-based line, like the
18//! project file: this file is generated by the keybindings editor, so a line it
19//! did not generate is a corrupt file rather than a dialect. A missing file is
20//! not corrupt -- it means nobody has changed a key yet, and the defaults stand.
21//!
22//! Writing mirrors `engine::edith::save`: `.part`, fsync, rename, directory
23//! fsync, so an interrupted save cannot cost the bindings that were already
24//! there.
25
26// The UI consumes this module in a later step; until then nothing calls it and
27// every item here reads as dead.
28#![allow(dead_code)]
29
30use std::ffi::OsString;
31use std::io::Write;
32use std::path::{Path, PathBuf};
33
34/// First line, exactly. The version is part of it, as in the project file.
35const MAGIC: &str = "edith-keys 1";
36
37/// Everything a stroke can ask for. Not the mouse's actions: only what a key
38/// can reach is bindable.
39#[derive(Clone, Copy, PartialEq, Eq, Debug)]
40pub enum ActionId {
41 Play,
42 Export,
43 Save,
44 Copy,
45 Paste,
46 Cut,
47 Regroup,
48 Delete,
49 Lift,
50 Undo,
51 ToggleMute,
52 VolumeUp,
53 VolumeDown,
54 CancelExport,
55}
56
57impl ActionId {
58 /// Display order everywhere -- the editor lists them in it and
59 /// [`Keymap::defaults`] binds them in it.
60 pub const ALL: [ActionId; 14] = [
61 ActionId::Play,
62 ActionId::Export,
63 ActionId::Save,
64 ActionId::Copy,
65 ActionId::Paste,
66 ActionId::Cut,
67 ActionId::Regroup,
68 ActionId::Delete,
69 ActionId::Lift,
70 ActionId::Undo,
71 ActionId::ToggleMute,
72 ActionId::VolumeUp,
73 ActionId::VolumeDown,
74 ActionId::CancelExport,
75 ];
76
77 /// What a person calls it.
78 pub fn label(self) -> &'static str {
79 match self {
80 ActionId::Play => "Play / Pause",
81 ActionId::Export => "Export",
82 ActionId::Save => "Save",
83 ActionId::Copy => "Copy",
84 ActionId::Paste => "Paste",
85 ActionId::Cut => "Cut",
86 ActionId::Regroup => "Regroup",
87 ActionId::Delete => "Delete",
88 ActionId::Lift => "Lift (leave a gap)",
89 ActionId::Undo => "Undo",
90 ActionId::ToggleMute => "Mute / Unmute",
91 ActionId::VolumeUp => "Volume up",
92 ActionId::VolumeDown => "Volume down",
93 ActionId::CancelExport => "Cancel export",
94 }
95 }
96
97 /// What the file calls it: ASCII, no spaces, one spelling per variant and
98 /// never the label, which is free to be reworded.
99 fn name(self) -> &'static str {
100 match self {
101 ActionId::Play => "play",
102 ActionId::Export => "export",
103 ActionId::Save => "save",
104 ActionId::Copy => "copy",
105 ActionId::Paste => "paste",
106 ActionId::Cut => "cut",
107 ActionId::Regroup => "regroup",
108 ActionId::Delete => "delete",
109 ActionId::Lift => "lift",
110 ActionId::Undo => "undo",
111 ActionId::ToggleMute => "toggle-mute",
112 ActionId::VolumeUp => "volume-up",
113 ActionId::VolumeDown => "volume-down",
114 ActionId::CancelExport => "cancel-export",
115 }
116 }
117
118 fn from_name(name: &str) -> Option<Self> {
119 Self::ALL.into_iter().find(|a| a.name() == name)
120 }
121
122 /// Which heading the keys menu files it under. Every action has one, so a
123 /// new action is listed the moment it exists -- there is no second list to
124 /// forget.
125 pub fn category(self) -> Category {
126 match self {
127 ActionId::Play => Category::Playback,
128 ActionId::Copy | ActionId::Paste | ActionId::Delete | ActionId::Lift => Category::Clips,
129 ActionId::Cut | ActionId::Regroup | ActionId::Undo => Category::Editing,
130 ActionId::ToggleMute | ActionId::VolumeUp | ActionId::VolumeDown => Category::Audio,
131 ActionId::Save | ActionId::Export | ActionId::CancelExport => Category::File,
132 }
133 }
134}
135
136/// A heading in the keys menu, and the order the headings come in.
137#[derive(Clone, Copy, PartialEq, Eq, Debug)]
138pub enum Category {
139 Playback,
140 Editing,
141 Clips,
142 Audio,
143 File,
144 View,
145}
146
147impl Category {
148 pub const ALL: [Category; 6] = [
149 Category::Playback,
150 Category::Editing,
151 Category::Clips,
152 Category::Audio,
153 Category::File,
154 Category::View,
155 ];
156
157 pub fn label(self) -> &'static str {
158 match self {
159 Category::Playback => "Playback",
160 Category::Editing => "Editing",
161 Category::Clips => "Clips",
162 Category::Audio => "Audio",
163 Category::File => "File",
164 Category::View => "View",
165 }
166 }
167}
168
169/// A stroke that works but nobody may rebind: the modal cards read the keyboard
170/// themselves, and what closes a card must not be a thing a user can take away.
171/// Listed here anyway, because the keys menu shows every stroke that works --
172/// `no_stroke_is_missing_from_the_keys_menu` reads the key handler's own source
173/// and fails on any key that reaches neither this table nor a binding.
174pub struct Fixed {
175 /// As a person reads it, which for a single key is [`Chord::pretty`]'s
176 /// spelling and for a family of keys is the family (`0–9`).
177 pub chord: &'static str,
178 pub label: &'static str,
179 pub category: Category,
180}
181
182pub const FIXED: [Fixed; 3] = [
183 Fixed {
184 chord: "esc",
185 label: "Close this card or clip menu, or cancel a capture",
186 category: Category::View,
187 },
188 Fixed {
189 chord: "0–9",
190 label: "Type a custom export bitrate",
191 category: Category::File,
192 },
193 Fixed {
194 chord: "backspace",
195 label: "Erase a bitrate digit",
196 category: Category::File,
197 },
198];
199
200/// A stroke as the key handler sees it: gpui's key name plus the one modifier
201/// this editor binds. Nothing else is a chord here -- shift and alt are part of
202/// the key name gpui reports, and a second modifier would need the file format
203/// to grow before it could be spelled.
204#[derive(Clone, PartialEq, Eq, Debug)]
205pub struct Chord {
206 pub key: String,
207 pub ctrl: bool,
208}
209
210impl Chord {
211 /// The file's spelling, and the only one [`parse`] accepts back.
212 fn text(&self) -> String {
213 if self.ctrl {
214 format!("ctrl+{}", self.key)
215 } else {
216 self.key.clone()
217 }
218 }
219
220 /// The spelling a person reads. Identical to [`Chord::text`] but for the one
221 /// key whose usual name is shorter than gpui's. Public because a
222 /// keybindings row shows one chord, where [`Keymap::display`] shows every
223 /// chord an action answers to.
224 pub fn pretty(&self) -> String {
225 let key = if self.key == "escape" {
226 "esc"
227 } else {
228 &self.key
229 };
230 if self.ctrl {
231 format!("ctrl+{key}")
232 } else {
233 key.to_string()
234 }
235 }
236
237 /// Strict: exactly one optional `ctrl+` and then a key gpui could have
238 /// reported. A spelling this cannot emit back unchanged is refused rather
239 /// than normalised, because the round-trip is what makes the file editable
240 /// by hand at all.
241 fn parse(text: &str, n: usize) -> Result<Self, String> {
242 let (ctrl, key) = match text.strip_prefix("ctrl+") {
243 Some(key) => (true, key),
244 None => (false, text),
245 };
246 if key.is_empty()
247 || key.contains(' ')
248 || key.contains('+')
249 || key.chars().any(|c| c.is_ascii_uppercase())
250 {
251 return Err(format!("line {n}: {text:?} is not a chord"));
252 }
253 Ok(Chord {
254 key: key.to_string(),
255 ctrl,
256 })
257 }
258}
259
260/// One stroke, one action. Two strokes for the same action are two bindings.
261#[derive(Clone, PartialEq, Eq, Debug)]
262pub struct Binding {
263 pub action: ActionId,
264 pub chord: Chord,
265}
266
267/// Every binding in force, in display order. No chord appears twice -- that is
268/// the invariant [`Keymap::rebind_action`] and [`parse`] both defend, and it is what
269/// lets [`Keymap::lookup`] answer with the first match.
270#[derive(Clone, PartialEq, Eq, Debug)]
271pub struct Keymap {
272 bindings: Vec<Binding>,
273}
274
275impl Keymap {
276 /// The bindings the editor has always had, in the order the editor lists
277 /// them. Delete and undo get two strokes each because both have always
278 /// answered to two.
279 pub fn defaults() -> Self {
280 let b = |action, key: &str, ctrl| Binding {
281 action,
282 chord: Chord {
283 key: key.to_string(),
284 ctrl,
285 },
286 };
287 Keymap {
288 bindings: vec![
289 b(ActionId::Play, "space", false),
290 b(ActionId::Export, "e", false),
291 b(ActionId::Save, "s", true),
292 b(ActionId::Copy, "c", true),
293 b(ActionId::Paste, "v", true),
294 b(ActionId::Cut, "c", false),
295 // The two lane keys, on the letters they are named after: both
296 // were free, and neither is next to a key that edits.
297 b(ActionId::Regroup, "g", false),
298 b(ActionId::Delete, "x", false),
299 b(ActionId::Delete, "delete", false),
300 b(ActionId::Lift, "l", false),
301 b(ActionId::Undo, "z", false),
302 b(ActionId::Undo, "z", true),
303 b(ActionId::ToggleMute, "m", false),
304 // The unshifted pair, which is what gpui reports for those two
305 // keys ("=" and "-", platform.rs:862): the volume keys every
306 // player has, without asking for shift to make the "+".
307 b(ActionId::VolumeUp, "=", false),
308 b(ActionId::VolumeDown, "-", false),
309 b(ActionId::CancelExport, "escape", false),
310 ],
311 }
312 }
313
314 /// What a stroke means, if anything. `key` is gpui's key name and `ctrl` its
315 /// control modifier -- the pair the key handler already matches on.
316 pub fn lookup(&self, key: &str, ctrl: bool) -> Option<ActionId> {
317 self.bindings
318 .iter()
319 .find(|b| b.chord.ctrl == ctrl && b.chord.key == key)
320 .map(|b| b.action)
321 }
322
323 /// Every stroke that reaches an action, as one readable phrase: `x or
324 /// delete`. An action nobody can reach says so rather than reading blank.
325 pub fn display(&self, action: ActionId) -> String {
326 let strokes: Vec<String> = self
327 .bindings
328 .iter()
329 .filter(|b| b.action == action)
330 .map(|b| b.chord.pretty())
331 .collect();
332 if strokes.is_empty() {
333 "unbound".to_string()
334 } else {
335 strokes.join(" or ")
336 }
337 }
338
339 /// Every binding, in display order.
340 pub fn entries(&self) -> &[Binding] {
341 &self.bindings
342 }
343
344 /// Makes `chord` the whole of what reaches `action`: its other chords go, so
345 /// what the editor shows for an action is what a rebind replaced. Two
346 /// strokes for one action stay expressible, but only in the file -- the
347 /// parser takes as many lines per action as it is given.
348 ///
349 /// `Err` names the action that already holds the chord and nothing changes:
350 /// two actions on one stroke would make the second unreachable, and silently
351 /// stealing it is worse than refusing. A chord the action already holds is
352 /// not a conflict with itself -- it collapses the action onto that one.
353 pub fn rebind_action(&mut self, action: ActionId, chord: Chord) -> Result<(), ActionId> {
354 if let Some(held) = self
355 .bindings
356 .iter()
357 .find(|b| b.action != action && b.chord == chord)
358 {
359 return Err(held.action);
360 }
361 self.bindings.retain(|b| b.action != action);
362 // Back into its own place in the display order rather than onto the end,
363 // so the file and the editor keep reading in the order of `ALL`.
364 let at = self
365 .bindings
366 .iter()
367 .position(|b| rank(b.action) > rank(action))
368 .unwrap_or(self.bindings.len());
369 self.bindings.insert(at, Binding { action, chord });
370 Ok(())
371 }
372
373 /// The keymap in force, and what to tell the user if the file could not be
374 /// used. A file that is merely absent is the normal case and says nothing;
375 /// anything else -- unreadable, or a line this parser refuses -- falls back
376 /// to the defaults *and* is reported, because a keymap silently not applied
377 /// is a keyboard that has quietly changed under the user.
378 pub fn load() -> (Self, Option<String>) {
379 Self::load_from(&Self::config_path())
380 }
381
382 /// All of [`Keymap::load`] but the path, which the config directory decides
383 /// and a test must not be allowed to.
384 fn load_from(path: &Path) -> (Self, Option<String>) {
385 let text = match std::fs::read_to_string(path) {
386 Ok(text) => text,
387 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return (Self::defaults(), None),
388 Err(e) => {
389 return (
390 Self::defaults(),
391 Some(format!(
392 "KEYBINDINGS IGNORED — {}: {e} — the defaults are in force",
393 path.display()
394 )),
395 );
396 }
397 };
398 match parse(&text) {
399 Ok(keymap) => (keymap, None),
400 Err(e) => (
401 Self::defaults(),
402 Some(format!(
403 "KEYBINDINGS IGNORED — {}, {e} — the defaults are in force",
404 path.display()
405 )),
406 ),
407 }
408 }
409
410 /// Writes the keymap, atomically, creating the config directory if this is
411 /// the first save. Until the rename the previous bindings are still the
412 /// whole truth on disk.
413 pub fn save(&self) -> std::io::Result<()> {
414 self.save_to(&Self::config_path())
415 }
416
417 /// All of [`Keymap::save`] but the path, for the same reason as
418 /// [`Keymap::load_from`].
419 fn save_to(&self, path: &Path) -> std::io::Result<()> {
420 let dir = path.parent().unwrap_or(Path::new(".")).to_path_buf();
421 std::fs::create_dir_all(&dir)?;
422 let mut part = path.to_path_buf().into_os_string();
423 part.push(".part");
424 let part = PathBuf::from(part);
425 let result = std::fs::File::create(&part)
426 .and_then(|mut f| {
427 f.write_all(emit(self).as_bytes())?;
428 f.sync_all()
429 })
430 .and_then(|()| std::fs::rename(&part, path))
431 .and_then(|()| std::fs::File::open(&dir)?.sync_all());
432 if result.is_err() {
433 let _ = std::fs::remove_file(&part);
434 }
435 result
436 }
437
438 /// Where the bindings live: the XDG config directory, or `~/.config` when
439 /// the desktop has not named one.
440 pub fn config_path() -> PathBuf {
441 config_path_in(
442 std::env::var_os("XDG_CONFIG_HOME"),
443 std::env::var_os("HOME"),
444 )
445 }
446}
447
448/// Where an action sits in the display order, which is the order of
449/// [`ActionId::ALL`] and the order the file is written in.
450fn rank(action: ActionId) -> usize {
451 ActionId::ALL
452 .iter()
453 .position(|a| *a == action)
454 .unwrap_or(ActionId::ALL.len())
455}
456
457/// The path rule, with the environment handed in so it can be checked. An
458/// `XDG_CONFIG_HOME` that is empty is one the spec says to ignore; with no
459/// `HOME` either there is nowhere but here, and a relative path is still better
460/// than dropping the file in `/`.
461fn config_path_in(xdg: Option<OsString>, home: Option<OsString>) -> PathBuf {
462 let dir = xdg
463 .filter(|v| !v.is_empty())
464 .map(PathBuf::from)
465 .or_else(|| {
466 home.filter(|v| !v.is_empty())
467 .map(|h| PathBuf::from(h).join(".config"))
468 })
469 .unwrap_or_else(|| PathBuf::from(".config"));
470 dir.join("edith").join("keybindings")
471}
472
473fn emit(keymap: &Keymap) -> String {
474 let mut out = String::from(MAGIC);
475 out.push('\n');
476 for b in &keymap.bindings {
477 out.push_str(b.action.name());
478 out.push(' ');
479 out.push_str(&b.chord.text());
480 out.push('\n');
481 }
482 out
483}
484
485fn parse(text: &str) -> Result<Keymap, String> {
486 // One trailing newline terminates the last line rather than starting an
487 // empty one; a second is an empty line and is refused below.
488 let body = text.strip_suffix('\n').unwrap_or(text);
489 let mut lines = body.split('\n').enumerate();
490 let (_, first) = lines.next().unwrap_or((0, ""));
491 if first != MAGIC {
492 return Err(match first.strip_prefix("edith-keys ") {
493 Some(v) => format!("line 1: unsupported version {v}"),
494 None => "line 1: not a keybindings file".to_string(),
495 });
496 }
497
498 let mut bindings: Vec<Binding> = Vec::new();
499 for (i, line) in lines {
500 let n = i + 1;
501 let Some((name, chord)) = line.split_once(' ') else {
502 return Err(format!("line {n}: {line:?} is not `<action> <chord>`"));
503 };
504 let action = ActionId::from_name(name)
505 .ok_or_else(|| format!("line {n}: unknown action {name:?}"))?;
506 let chord = Chord::parse(chord, n)?;
507 // One stroke, one meaning: the second line to claim it would be the
508 // dead one, and which of them died would depend on line order.
509 if let Some(held) = bindings.iter().find(|b| b.chord == chord) {
510 return Err(format!(
511 "line {n}: {} is already {}'s",
512 chord.text(),
513 held.action.name()
514 ));
515 }
516 bindings.push(Binding { action, chord });
517 }
518 Ok(Keymap { bindings })
519}
520
521#[cfg(test)]
522mod tests {
523 use super::{ActionId, Chord, Keymap, config_path_in, emit, parse};
524
525 fn chord(key: &str, ctrl: bool) -> Chord {
526 Chord {
527 key: key.to_string(),
528 ctrl,
529 }
530 }
531
532 #[test]
533 fn every_default_stroke_reaches_its_action() {
534 let k = Keymap::defaults();
535 assert_eq!(k.entries().len(), 16);
536 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
537 assert_eq!(k.lookup("e", false), Some(ActionId::Export));
538 assert_eq!(k.lookup("s", true), Some(ActionId::Save));
539 assert_eq!(k.lookup("c", true), Some(ActionId::Copy));
540 assert_eq!(k.lookup("v", true), Some(ActionId::Paste));
541 assert_eq!(k.lookup("c", false), Some(ActionId::Cut));
542 assert_eq!(k.lookup("g", false), Some(ActionId::Regroup));
543 assert_eq!(k.lookup("x", false), Some(ActionId::Delete));
544 assert_eq!(k.lookup("delete", false), Some(ActionId::Delete));
545 assert_eq!(k.lookup("l", false), Some(ActionId::Lift));
546 assert_eq!(k.lookup("z", false), Some(ActionId::Undo));
547 assert_eq!(k.lookup("z", true), Some(ActionId::Undo));
548 assert_eq!(k.lookup("m", false), Some(ActionId::ToggleMute));
549 // The volume pair is the unshifted one, so neither needs a modifier
550 // and neither is the "+" gpui reports for shift+=.
551 assert_eq!(k.lookup("=", false), Some(ActionId::VolumeUp));
552 assert_eq!(k.lookup("-", false), Some(ActionId::VolumeDown));
553 assert_eq!(k.lookup("+", false), None);
554 assert_eq!(k.lookup("escape", false), Some(ActionId::CancelExport));
555 // The modifier is half the chord: ctrl+e is not e.
556 assert_eq!(k.lookup("e", true), None);
557 assert_eq!(k.lookup("space", true), None);
558 assert_eq!(k.lookup("q", false), None);
559 // Nothing is bound twice, or lookup's first match would be a coin toss.
560 for (i, a) in k.entries().iter().enumerate() {
561 assert!(
562 !k.entries()[i + 1..].iter().any(|b| b.chord == a.chord),
563 "{:?} bound twice",
564 a.chord
565 );
566 }
567 }
568
569 #[test]
570 fn a_file_survives_the_round_trip_exactly() {
571 let text = emit(&Keymap::defaults());
572 assert!(text.starts_with("edith-keys 1\nplay space\n"));
573 assert!(text.contains("save ctrl+s\n"));
574 assert!(text.contains("cancel-export escape\n"));
575 // Both directions: the file this writes is the file it reads back, and
576 // a file read in comes out byte for byte as it went.
577 assert_eq!(parse(&text), Ok(Keymap::defaults()));
578 assert_eq!(emit(&parse(&text).unwrap()), text);
579 let handwritten = "edith-keys 1\nundo ctrl+z\nplay space\n";
580 assert_eq!(emit(&parse(handwritten).unwrap()), handwritten);
581 // A keymap that binds nothing is legal -- and unusable, which is the
582 // user's business, not the parser's.
583 assert_eq!(parse("edith-keys 1\n").unwrap().entries(), &[]);
584 }
585
586 #[test]
587 fn every_refusal_names_its_line() {
588 let err = |text: &str| parse(text).unwrap_err();
589 assert_eq!(err(""), "line 1: not a keybindings file");
590 assert_eq!(err("nonsense\n"), "line 1: not a keybindings file");
591 assert_eq!(err("edith-keys 2\n"), "line 1: unsupported version 2");
592 assert_eq!(
593 err("edith-keys 1\nfly space\n"),
594 "line 2: unknown action \"fly\""
595 );
596 assert_eq!(
597 err("edith-keys 1\nplay space\nplayspace\n"),
598 "line 3: \"playspace\" is not `<action> <chord>`"
599 );
600 // An empty line is not optional whitespace, it is a line.
601 assert_eq!(
602 err("edith-keys 1\n\n"),
603 "line 2: \"\" is not `<action> <chord>`"
604 );
605 assert_eq!(
606 err("edith-keys 1\nplay ctrl+alt+x\n"),
607 "line 2: \"ctrl+alt+x\" is not a chord"
608 );
609 assert_eq!(
610 err("edith-keys 1\nplay ctrl+\n"),
611 "line 2: \"ctrl+\" is not a chord"
612 );
613 // gpui reports lowercase key names, so an uppercase one would simply
614 // never match -- refused rather than quietly dead.
615 assert_eq!(
616 err("edith-keys 1\nplay X\n"),
617 "line 2: \"X\" is not a chord"
618 );
619 // The same stroke twice: whichever line lost would depend on order.
620 assert_eq!(
621 err("edith-keys 1\nplay space\ncut space\n"),
622 "line 3: space is already play's"
623 );
624 }
625
626 #[test]
627 fn rebinding_refuses_to_steal_another_actions_stroke() {
628 let mut k = Keymap::defaults();
629 assert_eq!(
630 k.rebind_action(ActionId::Export, chord("space", false)),
631 Err(ActionId::Play)
632 );
633 // Refused means unchanged, on both sides of the conflict.
634 assert_eq!(k.lookup("e", false), Some(ActionId::Export));
635 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
636 // A free stroke takes, and the old one stops meaning anything.
637 assert_eq!(k.rebind_action(ActionId::Export, chord("w", true)), Ok(()));
638 assert_eq!(k.lookup("w", true), Some(ActionId::Export));
639 assert_eq!(k.lookup("e", false), None);
640 assert_eq!(k.display(ActionId::Export), "ctrl+w");
641 }
642
643 #[test]
644 fn a_rebound_action_keeps_only_the_new_stroke() {
645 let mut k = Keymap::defaults();
646 assert_eq!(k.display(ActionId::Delete), "x or delete");
647 // One stroke replaces the whole set: what the row showed is what went.
648 assert_eq!(k.rebind_action(ActionId::Delete, chord("d", true)), Ok(()));
649 assert_eq!(k.display(ActionId::Delete), "ctrl+d");
650 assert_eq!(k.lookup("x", false), None);
651 assert_eq!(k.lookup("delete", false), None);
652 assert_eq!(k.lookup("d", true), Some(ActionId::Delete));
653 // One of its own chords is not a conflict with itself -- it collapses
654 // the action onto that one.
655 assert_eq!(k.rebind_action(ActionId::Undo, chord("z", true)), Ok(()));
656 assert_eq!(k.display(ActionId::Undo), "ctrl+z");
657 assert_eq!(k.lookup("z", false), None);
658 // The action keeps its place in the display order, and the file keeps
659 // reading in that order too.
660 let order: Vec<_> = k.entries().iter().map(|b| b.action).collect();
661 assert_eq!(order, ActionId::ALL.to_vec());
662 assert_eq!(emit(&k), emit(&parse(&emit(&k)).unwrap()));
663 // Every action is now single-bound, so the file is one line each.
664 assert_eq!(k.entries().len(), ActionId::ALL.len());
665 }
666
667 #[test]
668 fn display_reads_as_a_person_would_say_it() {
669 let k = Keymap::defaults();
670 assert_eq!(k.display(ActionId::Play), "space");
671 assert_eq!(k.display(ActionId::Save), "ctrl+s");
672 assert_eq!(k.display(ActionId::Delete), "x or delete");
673 assert_eq!(k.display(ActionId::Undo), "z or ctrl+z");
674 // The one key whose common name is not gpui's.
675 assert_eq!(k.display(ActionId::CancelExport), "esc");
676 assert_eq!(
677 parse("edith-keys 1\n").unwrap().display(ActionId::Cut),
678 "unbound"
679 );
680 // The label is the editor's column, and never the file's word for it.
681 assert_eq!(ActionId::CancelExport.label(), "Cancel export");
682 assert_eq!(ActionId::ALL.len(), 14);
683 }
684
685 #[test]
686 fn a_saved_keymap_comes_back_off_the_disk() {
687 // Its own directory, never the real config one: this test writes.
688 let dir = std::env::temp_dir().join(format!("edith-keymap-{}", std::process::id()));
689 let path = dir.join("edith").join("keybindings");
690 let mut written = Keymap::defaults();
691 written
692 .rebind_action(ActionId::Export, chord("w", true))
693 .unwrap();
694 // The config directory does not exist yet -- the first save makes it.
695 written.save_to(&path).unwrap();
696 let (read, notice) = Keymap::load_from(&path);
697 assert_eq!(notice, None);
698 assert_eq!(read, written);
699 assert_eq!(read.lookup("w", true), Some(ActionId::Export));
700 assert_eq!(read.lookup("e", false), None);
701 // The rename left nothing half-written behind.
702 assert!(!dir.join("edith").join("keybindings.part").exists());
703 // A file that is merely absent is not an error and says nothing.
704 let (fresh, notice) = Keymap::load_from(&dir.join("nothing-here"));
705 assert_eq!(fresh, Keymap::defaults());
706 assert_eq!(notice, None);
707 // A corrupt one names its line and still leaves a usable keymap.
708 std::fs::write(&path, "edith-keys 1\nplay ctrl+alt+x\n").unwrap();
709 let (fallback, notice) = Keymap::load_from(&path);
710 assert_eq!(fallback, Keymap::defaults());
711 let notice = notice.expect("a refused file must say so");
712 assert!(notice.contains("line 2:"), "{notice}");
713 assert!(notice.contains("keybindings"), "{notice}");
714 // Saving over it is a whole replacement, not an edit.
715 Keymap::defaults().save_to(&path).unwrap();
716 assert_eq!(Keymap::load_from(&path), (Keymap::defaults(), None));
717 std::fs::remove_dir_all(&dir).ok();
718 }
719
720 #[test]
721 fn the_config_path_follows_xdg_then_home() {
722 let p = |xdg: Option<&str>, home: Option<&str>| {
723 config_path_in(xdg.map(Into::into), home.map(Into::into))
724 };
725 assert_eq!(
726 p(Some("/x/config"), Some("/home/u")),
727 std::path::Path::new("/x/config/edith/keybindings")
728 );
729 assert_eq!(
730 p(None, Some("/home/u")),
731 std::path::Path::new("/home/u/.config/edith/keybindings")
732 );
733 // An empty XDG_CONFIG_HOME is one the spec says to ignore.
734 assert_eq!(
735 p(Some(""), Some("/home/u")),
736 std::path::Path::new("/home/u/.config/edith/keybindings")
737 );
738 // Nowhere to put it but here -- still never `/edith/keybindings`.
739 assert_eq!(
740 p(None, None),
741 std::path::Path::new(".config/edith/keybindings")
742 );
743 }
744}