forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB8c7bf80Tahinli3 months ago114 commits

keymap.rs1001 lines, 39.8 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 everything it cannot use names its 1-based line,
18//! like the project file. Only the first line refuses the whole file: a binding
19//! line the parser cannot use is *dropped*, named in the notice, and every other
20//! line still stands -- one unusable line is not a reason to throw away the
21//! rebinds around it. A missing file is not corrupt either -- it means nobody
22//! has changed a key yet, and the defaults stand.
23//!
24//! Writing mirrors `engine::edith::save`: `.part`, fsync, rename, directory
25//! fsync, so an interrupted save cannot cost the bindings that were already
26//! there.
27
28// The UI consumes this module in a later step; until then nothing calls it and
29// every item here reads as dead.
30#![allow(dead_code)]
31
32use std::ffi::OsString;
33use std::io::Write;
34use std::path::{Path, PathBuf};
35
36/// First line, exactly. The version is part of it, as in the project file.
37const MAGIC: &str = "edith-keys 1";
38
39/// Everything a stroke can ask for. Not the mouse's actions: only what a key
40/// can reach is bindable.
41#[derive(Clone, Copy, PartialEq, Eq, Debug)]
42pub enum ActionId {
43 Play,
44 Export,
45 Save,
46 Copy,
47 Paste,
48 Cut,
49 Regroup,
50 Select,
51 SelectNext,
52 SelectPrev,
53 Delete,
54 Lift,
55 Color,
56 Fit,
57 Resolution,
58 Undo,
59 AddVideoLane,
60 AddAudioLane,
61 ToggleMute,
62 VolumeUp,
63 VolumeDown,
64 Equalizer,
65 CancelExport,
66}
67
68impl ActionId {
69 /// Display order everywhere -- the editor lists them in it and
70 /// [`Keymap::defaults`] binds them in it.
71 pub const ALL: [ActionId; 23] = [
72 ActionId::Play,
73 ActionId::Export,
74 ActionId::Save,
75 ActionId::Copy,
76 ActionId::Paste,
77 ActionId::Cut,
78 ActionId::Regroup,
79 ActionId::Select,
80 ActionId::SelectNext,
81 ActionId::SelectPrev,
82 ActionId::Delete,
83 ActionId::Lift,
84 ActionId::Color,
85 ActionId::Fit,
86 ActionId::Resolution,
87 ActionId::Undo,
88 ActionId::AddVideoLane,
89 ActionId::AddAudioLane,
90 ActionId::ToggleMute,
91 ActionId::VolumeUp,
92 ActionId::VolumeDown,
93 ActionId::Equalizer,
94 ActionId::CancelExport,
95 ];
96
97 /// What a person calls it.
98 pub fn label(self) -> &'static str {
99 match self {
100 ActionId::Play => "Play / Pause",
101 ActionId::Export => "Export",
102 ActionId::Save => "Save",
103 ActionId::Copy => "Copy",
104 ActionId::Paste => "Paste",
105 ActionId::Cut => "Cut",
106 ActionId::Regroup => "Regroup",
107 ActionId::Select => "Select the clip under the playhead (again for the next lane)",
108 ActionId::SelectNext => "Select the next clip in the lane",
109 ActionId::SelectPrev => "Select the previous clip in the lane",
110 ActionId::Delete => "Delete",
111 ActionId::Lift => "Lift (leave a gap)",
112 ActionId::Color => "Colour…",
113 ActionId::Fit => "Fit policy: fit → fill → stretch → centre",
114 ActionId::Resolution => "Project resolution: source → 2160p → 1080p → 720p → 480p",
115 ActionId::Undo => "Undo",
116 ActionId::AddVideoLane => "Add a video track",
117 ActionId::AddAudioLane => "Add an audio track",
118 ActionId::ToggleMute => "Mute / Unmute",
119 ActionId::VolumeUp => "Volume up",
120 ActionId::VolumeDown => "Volume down",
121 ActionId::Equalizer => "Equalizer",
122 ActionId::CancelExport => "Cancel export",
123 }
124 }
125
126 /// What the file calls it: ASCII, no spaces, one spelling per variant and
127 /// never the label, which is free to be reworded.
128 fn name(self) -> &'static str {
129 match self {
130 ActionId::Play => "play",
131 ActionId::Export => "export",
132 ActionId::Save => "save",
133 ActionId::Copy => "copy",
134 ActionId::Paste => "paste",
135 ActionId::Cut => "cut",
136 ActionId::Regroup => "regroup",
137 ActionId::Select => "select",
138 ActionId::SelectNext => "select-next",
139 ActionId::SelectPrev => "select-prev",
140 ActionId::Delete => "delete",
141 ActionId::Lift => "lift",
142 ActionId::Color => "color",
143 ActionId::Fit => "fit",
144 ActionId::Resolution => "resolution",
145 ActionId::Undo => "undo",
146 ActionId::AddVideoLane => "add-video-lane",
147 ActionId::AddAudioLane => "add-audio-lane",
148 ActionId::ToggleMute => "toggle-mute",
149 ActionId::VolumeUp => "volume-up",
150 ActionId::VolumeDown => "volume-down",
151 ActionId::Equalizer => "equalizer",
152 ActionId::CancelExport => "cancel-export",
153 }
154 }
155
156 fn from_name(name: &str) -> Option<Self> {
157 Self::ALL.into_iter().find(|a| a.name() == name)
158 }
159
160 /// Which heading the keys menu files it under. Every action has one, so a
161 /// new action is listed the moment it exists -- there is no second list to
162 /// forget.
163 pub fn category(self) -> Category {
164 match self {
165 ActionId::Play => Category::Playback,
166 ActionId::Copy
167 | ActionId::Paste
168 | ActionId::Select
169 | ActionId::SelectNext
170 | ActionId::SelectPrev
171 | ActionId::Delete
172 | ActionId::Lift
173 | ActionId::Color
174 | ActionId::Fit => Category::Clips,
175 // The project's own picture size is not a clip's business, and not
176 // a file operation either: it is what the viewer is looking at.
177 ActionId::Resolution => Category::View,
178 ActionId::Cut
179 | ActionId::Regroup
180 | ActionId::Undo
181 | ActionId::AddVideoLane
182 | ActionId::AddAudioLane => Category::Editing,
183 ActionId::ToggleMute
184 | ActionId::VolumeUp
185 | ActionId::VolumeDown
186 | ActionId::Equalizer => Category::Audio,
187 ActionId::Save | ActionId::Export | ActionId::CancelExport => Category::File,
188 }
189 }
190}
191
192/// A heading in the keys menu, and the order the headings come in.
193#[derive(Clone, Copy, PartialEq, Eq, Debug)]
194pub enum Category {
195 Playback,
196 Editing,
197 Clips,
198 Audio,
199 File,
200 View,
201}
202
203impl Category {
204 pub const ALL: [Category; 6] = [
205 Category::Playback,
206 Category::Editing,
207 Category::Clips,
208 Category::Audio,
209 Category::File,
210 Category::View,
211 ];
212
213 pub fn label(self) -> &'static str {
214 match self {
215 Category::Playback => "Playback",
216 Category::Editing => "Editing",
217 Category::Clips => "Clips",
218 Category::Audio => "Audio",
219 Category::File => "File",
220 Category::View => "View",
221 }
222 }
223}
224
225/// A stroke that works but nobody may rebind: the modal cards read the keyboard
226/// themselves, and what closes a card must not be a thing a user can take away.
227/// Listed here anyway, because the keys menu shows every stroke that works --
228/// `no_stroke_is_missing_from_the_keys_menu` reads the key handler's own source
229/// and fails on any key that reaches neither this table nor a binding.
230pub struct Fixed {
231 /// As a person reads it, which for a single key is [`Chord::pretty`]'s
232 /// spelling and for a family of keys is the family (`0–9`).
233 pub chord: &'static str,
234 pub label: &'static str,
235 pub category: Category,
236}
237
238pub const FIXED: [Fixed; 12] = [
239 Fixed {
240 chord: "esc",
241 label: "Close this card or clip menu, or cancel a capture",
242 category: Category::View,
243 },
244 Fixed {
245 chord: "0–9",
246 label: "Type a custom export bitrate",
247 category: Category::File,
248 },
249 Fixed {
250 chord: "m / w / f",
251 label: "Pick the export format: MP4, WAV or FLAC",
252 category: Category::File,
253 },
254 Fixed {
255 chord: "enter",
256 label: "Start the export the card is set to",
257 category: Category::File,
258 },
259 Fixed {
260 chord: "backspace",
261 label: "Erase a bitrate digit",
262 category: Category::File,
263 },
264 // The equalizer card's own input, for the same reason the export card has
265 // its own: a band nothing but a drag can reach is a band half the users of
266 // this editor cannot move at all. Card-local, so none of them is bindable.
267 Fixed {
268 chord: "1–5",
269 label: "Pick an equalizer band",
270 category: Category::Audio,
271 },
272 Fixed {
273 chord: "up",
274 label: "Raise the picked band 1 dB",
275 category: Category::Audio,
276 },
277 Fixed {
278 chord: "down",
279 label: "Lower the picked band 1 dB",
280 category: Category::Audio,
281 },
282 Fixed {
283 chord: "r",
284 label: "Flatten every band",
285 category: Category::Audio,
286 },
287 // The colour card's own three, which mean nothing outside it -- the same
288 // card-local input the export card's digits are.
289 Fixed {
290 chord: "↑ / ↓",
291 label: "Pick a colour slider",
292 category: Category::Clips,
293 },
294 Fixed {
295 chord: "← / →",
296 label: "Move the picked colour slider",
297 category: Category::Clips,
298 },
299 Fixed {
300 chord: "r",
301 label: "Take the colour grade off the clip",
302 category: Category::Clips,
303 },
304];
305
306/// A stroke as the key handler sees it: gpui's key name plus the one modifier
307/// this editor binds. Nothing else is a chord here -- shift and alt are part of
308/// the key name gpui reports, and a second modifier would need the file format
309/// to grow before it could be spelled.
310#[derive(Clone, PartialEq, Eq, Debug)]
311pub struct Chord {
312 pub key: String,
313 pub ctrl: bool,
314}
315
316impl Chord {
317 /// The file's spelling, and the only one [`parse`] accepts back.
318 fn text(&self) -> String {
319 if self.ctrl {
320 format!("ctrl+{}", self.key)
321 } else {
322 self.key.clone()
323 }
324 }
325
326 /// The spelling a person reads. Identical to [`Chord::text`] but for the one
327 /// key whose usual name is shorter than gpui's. Public because a
328 /// keybindings row shows one chord, where [`Keymap::display`] shows every
329 /// chord an action answers to.
330 pub fn pretty(&self) -> String {
331 let key = if self.key == "escape" {
332 "esc"
333 } else {
334 &self.key
335 };
336 if self.ctrl {
337 format!("ctrl+{key}")
338 } else {
339 key.to_string()
340 }
341 }
342
343 /// Whether the file can carry this stroke and read it back as itself. gpui
344 /// reports strokes this format cannot spell -- shift+= arrives as the key
345 /// `"+"`, which is the chord grammar's own separator -- and binding one
346 /// would write a line the next load has to drop. Asked before a capture is
347 /// taken, so a stroke that cannot be saved is refused while the user is
348 /// still looking at the row.
349 pub fn bindable(&self) -> bool {
350 Chord::parse(&self.text(), 0).is_ok_and(|round_trip| round_trip == *self)
351 }
352
353 /// Strict: exactly one optional `ctrl+` and then a key gpui could have
354 /// reported. A spelling this cannot emit back unchanged is refused rather
355 /// than normalised, because the round-trip is what makes the file editable
356 /// by hand at all.
357 fn parse(text: &str, n: usize) -> Result<Self, String> {
358 let (ctrl, key) = match text.strip_prefix("ctrl+") {
359 Some(key) => (true, key),
360 None => (false, text),
361 };
362 if key.is_empty()
363 || key.contains(' ')
364 || key.contains('+')
365 || key.chars().any(|c| c.is_ascii_uppercase())
366 {
367 return Err(format!("line {n}: {text:?} is not a chord"));
368 }
369 Ok(Chord {
370 key: key.to_string(),
371 ctrl,
372 })
373 }
374}
375
376/// One stroke, one action. Two strokes for the same action are two bindings.
377#[derive(Clone, PartialEq, Eq, Debug)]
378pub struct Binding {
379 pub action: ActionId,
380 pub chord: Chord,
381}
382
383/// Every binding in force, in display order. No chord appears twice -- that is
384/// the invariant [`Keymap::rebind_action`] and [`parse`] both defend, and it is what
385/// lets [`Keymap::lookup`] answer with the first match.
386#[derive(Clone, PartialEq, Eq, Debug)]
387pub struct Keymap {
388 bindings: Vec<Binding>,
389}
390
391impl Keymap {
392 /// The bindings the editor has always had, in the order the editor lists
393 /// them. Delete and undo get two strokes each because both have always
394 /// answered to two.
395 pub fn defaults() -> Self {
396 let b = |action, key: &str, ctrl| Binding {
397 action,
398 chord: Chord {
399 key: key.to_string(),
400 ctrl,
401 },
402 };
403 Keymap {
404 bindings: vec![
405 b(ActionId::Play, "space", false),
406 b(ActionId::Export, "e", false),
407 b(ActionId::Save, "s", true),
408 b(ActionId::Copy, "c", true),
409 b(ActionId::Paste, "v", true),
410 b(ActionId::Cut, "c", false),
411 // The two lane keys, on the letters they are named after: both
412 // were free, and neither is next to a key that edits.
413 b(ActionId::Regroup, "g", false),
414 // Selection without a pointer. Tab is what a keyboard already
415 // means by "move on to the next thing", and the two brackets
416 // are the pair either side of it in the lane -- shift+tab is
417 // the obvious partner and is unspellable here, since a chord
418 // carries only ctrl and `parse` refuses an uppercase key.
419 b(ActionId::Select, "tab", false),
420 b(ActionId::SelectNext, "]", false),
421 b(ActionId::SelectPrev, "[", false),
422 b(ActionId::Delete, "x", false),
423 b(ActionId::Delete, "delete", false),
424 b(ActionId::Lift, "l", false),
425 // The c of colour is Cut and ctrl+c is Copy, so the grade takes
426 // k: free, next to nothing that edits, and one press like the
427 // rest of the clip keys.
428 b(ActionId::Color, "k", false),
429 // The fit policy is a clip key like the grade beside it: "p" for
430 // policy, free, and one press like the rest of them. The project
431 // resolution is not a clip key and takes a ctrl chord, next to
432 // nothing that edits and out of the way of a stray press --
433 // it changes what every clip is composed onto.
434 b(ActionId::Fit, "p", false),
435 b(ActionId::Resolution, "r", true),
436 b(ActionId::Undo, "z", false),
437 b(ActionId::Undo, "z", true),
438 // The unshifted initials of what they add. Both were free --
439 // the copy and paste chords are the *ctrl* ones -- and a track
440 // is added often enough to deserve a key that is one press.
441 b(ActionId::AddVideoLane, "v", false),
442 b(ActionId::AddAudioLane, "a", false),
443 b(ActionId::ToggleMute, "m", false),
444 // The unshifted pair, which is what gpui reports for those two
445 // keys ("=" and "-", platform.rs:862): the volume keys every
446 // player has, without asking for shift to make the "+".
447 b(ActionId::VolumeUp, "=", false),
448 b(ActionId::VolumeDown, "-", false),
449 // The one free letter that says the word: "e" is already the
450 // export and an equalizer is the q in nobody else's way.
451 b(ActionId::Equalizer, "q", false),
452 b(ActionId::CancelExport, "escape", false),
453 ],
454 }
455 }
456
457 /// What a stroke means, if anything. `key` is gpui's key name and `ctrl` its
458 /// control modifier -- the pair the key handler already matches on.
459 pub fn lookup(&self, key: &str, ctrl: bool) -> Option<ActionId> {
460 self.bindings
461 .iter()
462 .find(|b| b.chord.ctrl == ctrl && b.chord.key == key)
463 .map(|b| b.action)
464 }
465
466 /// Every stroke that reaches an action, as one readable phrase: `x or
467 /// delete`. An action nobody can reach says so rather than reading blank.
468 pub fn display(&self, action: ActionId) -> String {
469 let strokes: Vec<String> = self
470 .bindings
471 .iter()
472 .filter(|b| b.action == action)
473 .map(|b| b.chord.pretty())
474 .collect();
475 if strokes.is_empty() {
476 "unbound".to_string()
477 } else {
478 strokes.join(" or ")
479 }
480 }
481
482 /// Every binding, in display order.
483 pub fn entries(&self) -> &[Binding] {
484 &self.bindings
485 }
486
487 /// Makes `chord` the whole of what reaches `action`: its other chords go, so
488 /// what the editor shows for an action is what a rebind replaced. Two
489 /// strokes for one action stay expressible, but only in the file -- the
490 /// parser takes as many lines per action as it is given.
491 ///
492 /// `Err` names the action that already holds the chord and nothing changes:
493 /// two actions on one stroke would make the second unreachable, and silently
494 /// stealing it is worse than refusing. A chord the action already holds is
495 /// not a conflict with itself -- it collapses the action onto that one.
496 pub fn rebind_action(&mut self, action: ActionId, chord: Chord) -> Result<(), ActionId> {
497 if let Some(held) = self
498 .bindings
499 .iter()
500 .find(|b| b.action != action && b.chord == chord)
501 {
502 return Err(held.action);
503 }
504 self.bindings.retain(|b| b.action != action);
505 // Back into its own place in the display order rather than onto the end,
506 // so the file and the editor keep reading in the order of `ALL`.
507 let at = self
508 .bindings
509 .iter()
510 .position(|b| rank(b.action) > rank(action))
511 .unwrap_or(self.bindings.len());
512 self.bindings.insert(at, Binding { action, chord });
513 Ok(())
514 }
515
516 /// The keymap in force, and what to tell the user if the file could not be
517 /// used. A file that is merely absent is the normal case and says nothing;
518 /// anything else -- unreadable, or a line this parser refuses -- falls back
519 /// to the defaults *and* is reported, because a keymap silently not applied
520 /// is a keyboard that has quietly changed under the user.
521 pub fn load() -> (Self, Option<String>) {
522 Self::load_from(&Self::config_path())
523 }
524
525 /// All of [`Keymap::load`] but the path, which the config directory decides
526 /// and a test must not be allowed to.
527 fn load_from(path: &Path) -> (Self, Option<String>) {
528 let text = match std::fs::read_to_string(path) {
529 Ok(text) => text,
530 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return (Self::defaults(), None),
531 Err(e) => {
532 return (
533 Self::defaults(),
534 Some(format!(
535 "KEYBINDINGS IGNORED — {}: {e} — the defaults are in force",
536 path.display()
537 )),
538 );
539 }
540 };
541 match parse(&text) {
542 Ok((keymap, dropped)) if dropped.is_empty() => (keymap, None),
543 // The lines it could use are in force; the ones it could not are
544 // named, and only those are lost.
545 Ok((keymap, dropped)) => (
546 keymap,
547 Some(format!(
548 "KEYBINDINGS PART-READ — {}, {} — those strokes are unbound",
549 path.display(),
550 dropped.join("; ")
551 )),
552 ),
553 Err(e) => (
554 Self::defaults(),
555 Some(format!(
556 "KEYBINDINGS IGNORED — {}, {e} — the defaults are in force",
557 path.display()
558 )),
559 ),
560 }
561 }
562
563 /// Writes the keymap, atomically, creating the config directory if this is
564 /// the first save. Until the rename the previous bindings are still the
565 /// whole truth on disk.
566 pub fn save(&self) -> std::io::Result<()> {
567 self.save_to(&Self::config_path())
568 }
569
570 /// All of [`Keymap::save`] but the path, for the same reason as
571 /// [`Keymap::load_from`].
572 fn save_to(&self, path: &Path) -> std::io::Result<()> {
573 let dir = path.parent().unwrap_or(Path::new(".")).to_path_buf();
574 std::fs::create_dir_all(&dir)?;
575 let mut part = path.to_path_buf().into_os_string();
576 part.push(".part");
577 let part = PathBuf::from(part);
578 let result = std::fs::File::create(&part)
579 .and_then(|mut f| {
580 f.write_all(emit(self).as_bytes())?;
581 f.sync_all()
582 })
583 .and_then(|()| std::fs::rename(&part, path))
584 .and_then(|()| std::fs::File::open(&dir)?.sync_all());
585 if result.is_err() {
586 let _ = std::fs::remove_file(&part);
587 }
588 result
589 }
590
591 /// Where the bindings live: the XDG config directory, or `~/.config` when
592 /// the desktop has not named one.
593 pub fn config_path() -> PathBuf {
594 config_path_in(
595 std::env::var_os("XDG_CONFIG_HOME"),
596 std::env::var_os("HOME"),
597 )
598 }
599}
600
601/// Where an action sits in the display order, which is the order of
602/// [`ActionId::ALL`] and the order the file is written in.
603fn rank(action: ActionId) -> usize {
604 ActionId::ALL
605 .iter()
606 .position(|a| *a == action)
607 .unwrap_or(ActionId::ALL.len())
608}
609
610/// The path rule, with the environment handed in so it can be checked. An
611/// `XDG_CONFIG_HOME` that is empty is one the spec says to ignore; with no
612/// `HOME` either there is nowhere but here, and a relative path is still better
613/// than dropping the file in `/`.
614fn config_path_in(xdg: Option<OsString>, home: Option<OsString>) -> PathBuf {
615 let dir = xdg
616 .filter(|v| !v.is_empty())
617 .map(PathBuf::from)
618 .or_else(|| {
619 home.filter(|v| !v.is_empty())
620 .map(|h| PathBuf::from(h).join(".config"))
621 })
622 .unwrap_or_else(|| PathBuf::from(".config"));
623 dir.join("edith").join("keybindings")
624}
625
626fn emit(keymap: &Keymap) -> String {
627 let mut out = String::from(MAGIC);
628 out.push('\n');
629 for b in &keymap.bindings {
630 out.push_str(b.action.name());
631 out.push(' ');
632 out.push_str(&b.chord.text());
633 out.push('\n');
634 }
635 out
636}
637
638/// The magic line is the whole of what makes this a keybindings file, so it is
639/// the only thing refused outright. A *binding* line this parser cannot use is
640/// dropped instead, and named in the returned warnings: one unusable line used
641/// to cost every other rebind in the file, which is the user's data. What
642/// survives is still exactly what emits back, so the by-hand round-trip holds
643/// for every line that is kept.
644fn parse(text: &str) -> Result<(Keymap, Vec<String>), String> {
645 // One trailing newline terminates the last line rather than starting an
646 // empty one; a second is an empty line and is refused below.
647 let body = text.strip_suffix('\n').unwrap_or(text);
648 let mut lines = body.split('\n').enumerate();
649 let (_, first) = lines.next().unwrap_or((0, ""));
650 if first != MAGIC {
651 return Err(match first.strip_prefix("edith-keys ") {
652 Some(v) => format!("line 1: unsupported version {v}"),
653 None => "line 1: not a keybindings file".to_string(),
654 });
655 }
656
657 let mut bindings: Vec<Binding> = Vec::new();
658 let mut dropped: Vec<String> = Vec::new();
659 for (i, line) in lines {
660 let n = i + 1;
661 let Some((name, chord)) = line.split_once(' ') else {
662 dropped.push(format!("line {n}: {line:?} is not `<action> <chord>`"));
663 continue;
664 };
665 let Some(action) = ActionId::from_name(name) else {
666 dropped.push(format!("line {n}: unknown action {name:?}"));
667 continue;
668 };
669 let chord = match Chord::parse(chord, n) {
670 Ok(chord) => chord,
671 Err(e) => {
672 dropped.push(e);
673 continue;
674 }
675 };
676 // One stroke, one meaning: the second line to claim it would be the
677 // dead one, and which of them died would depend on line order. The
678 // first line keeps the stroke, which is the order the file reads in.
679 if let Some(held) = bindings.iter().find(|b| b.chord == chord) {
680 dropped.push(format!(
681 "line {n}: {} is already {}'s",
682 chord.text(),
683 held.action.name()
684 ));
685 continue;
686 }
687 bindings.push(Binding { action, chord });
688 }
689 Ok((Keymap { bindings }, dropped))
690}
691
692#[cfg(test)]
693mod tests {
694 use super::{ActionId, Chord, Keymap, config_path_in, emit, parse};
695
696 fn chord(key: &str, ctrl: bool) -> Chord {
697 Chord {
698 key: key.to_string(),
699 ctrl,
700 }
701 }
702
703 /// A file every line of which the parser could use -- what most assertions
704 /// are about. A dropped line here is a failure, not a warning.
705 fn whole(text: &str) -> Keymap {
706 let (keymap, dropped) = parse(text).expect("a keybindings file");
707 assert!(dropped.is_empty(), "unexpected dropped lines: {dropped:?}");
708 keymap
709 }
710
711 #[test]
712 fn every_default_stroke_reaches_its_action() {
713 let k = Keymap::defaults();
714 assert_eq!(k.entries().len(), 25);
715 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
716 assert_eq!(k.lookup("e", false), Some(ActionId::Export));
717 assert_eq!(k.lookup("s", true), Some(ActionId::Save));
718 assert_eq!(k.lookup("c", true), Some(ActionId::Copy));
719 assert_eq!(k.lookup("v", true), Some(ActionId::Paste));
720 assert_eq!(k.lookup("c", false), Some(ActionId::Cut));
721 assert_eq!(k.lookup("g", false), Some(ActionId::Regroup));
722 // The keyboard's way onto a clip, and the pair that walks the lane.
723 assert_eq!(k.lookup("tab", false), Some(ActionId::Select));
724 assert_eq!(k.lookup("]", false), Some(ActionId::SelectNext));
725 assert_eq!(k.lookup("[", false), Some(ActionId::SelectPrev));
726 assert_eq!(k.lookup("x", false), Some(ActionId::Delete));
727 assert_eq!(k.lookup("delete", false), Some(ActionId::Delete));
728 assert_eq!(k.lookup("l", false), Some(ActionId::Lift));
729 assert_eq!(k.lookup("k", false), Some(ActionId::Color));
730 assert_eq!(k.lookup("p", false), Some(ActionId::Fit));
731 assert_eq!(k.lookup("r", true), Some(ActionId::Resolution));
732 assert_eq!(k.lookup("z", false), Some(ActionId::Undo));
733 assert_eq!(k.lookup("z", true), Some(ActionId::Undo));
734 // The track keys are the bare letters; the ctrl ones stay copy/paste.
735 assert_eq!(k.lookup("v", false), Some(ActionId::AddVideoLane));
736 assert_eq!(k.lookup("a", false), Some(ActionId::AddAudioLane));
737 assert_eq!(k.lookup("m", false), Some(ActionId::ToggleMute));
738 assert_eq!(k.lookup("q", false), Some(ActionId::Equalizer));
739 // The volume pair is the unshifted one, so neither needs a modifier
740 // and neither is the "+" gpui reports for shift+=.
741 assert_eq!(k.lookup("=", false), Some(ActionId::VolumeUp));
742 assert_eq!(k.lookup("-", false), Some(ActionId::VolumeDown));
743 assert_eq!(k.lookup("+", false), None);
744 assert_eq!(k.lookup("escape", false), Some(ActionId::CancelExport));
745 // The modifier is half the chord: ctrl+e is not e.
746 assert_eq!(k.lookup("e", true), None);
747 assert_eq!(k.lookup("space", true), None);
748 assert_eq!(k.lookup("j", false), None);
749 // Nothing is bound twice, or lookup's first match would be a coin toss.
750 for (i, a) in k.entries().iter().enumerate() {
751 assert!(
752 !k.entries()[i + 1..].iter().any(|b| b.chord == a.chord),
753 "{:?} bound twice",
754 a.chord
755 );
756 }
757 }
758
759 #[test]
760 fn a_file_survives_the_round_trip_exactly() {
761 let text = emit(&Keymap::defaults());
762 assert!(text.starts_with("edith-keys 1\nplay space\n"));
763 assert!(text.contains("save ctrl+s\n"));
764 assert!(text.contains("cancel-export escape\n"));
765 // Both directions: the file this writes is the file it reads back, and
766 // a file read in comes out byte for byte as it went.
767 assert_eq!(whole(&text), Keymap::defaults());
768 assert_eq!(emit(&whole(&text)), text);
769 let handwritten = "edith-keys 1\nundo ctrl+z\nplay space\n";
770 assert_eq!(emit(&whole(handwritten)), handwritten);
771 // A keymap that binds nothing is legal -- and unusable, which is the
772 // user's business, not the parser's.
773 assert_eq!(whole("edith-keys 1\n").entries(), &[]);
774 }
775
776 #[test]
777 fn every_refusal_names_its_line() {
778 // Only the first line refuses the whole file.
779 let err = |text: &str| parse(text).unwrap_err();
780 assert_eq!(err(""), "line 1: not a keybindings file");
781 assert_eq!(err("nonsense\n"), "line 1: not a keybindings file");
782 assert_eq!(err("edith-keys 2\n"), "line 1: unsupported version 2");
783
784 // Every other kind of bad line costs that line and nothing else.
785 let dropped = |text: &str| parse(text).unwrap().1;
786 assert_eq!(
787 dropped("edith-keys 1\nfly space\n"),
788 ["line 2: unknown action \"fly\""]
789 );
790 assert_eq!(
791 dropped("edith-keys 1\nplay space\nplayspace\n"),
792 ["line 3: \"playspace\" is not `<action> <chord>`"]
793 );
794 // An empty line is not optional whitespace, it is a line.
795 assert_eq!(
796 dropped("edith-keys 1\n\n"),
797 ["line 2: \"\" is not `<action> <chord>`"]
798 );
799 assert_eq!(
800 dropped("edith-keys 1\nplay ctrl+alt+x\n"),
801 ["line 2: \"ctrl+alt+x\" is not a chord"]
802 );
803 assert_eq!(
804 dropped("edith-keys 1\nplay ctrl+\n"),
805 ["line 2: \"ctrl+\" is not a chord"]
806 );
807 // gpui reports lowercase key names, so an uppercase one would simply
808 // never match -- dropped rather than quietly dead.
809 assert_eq!(
810 dropped("edith-keys 1\nplay X\n"),
811 ["line 2: \"X\" is not a chord"]
812 );
813 // The same stroke twice: whichever line lost would depend on order, so
814 // the second one is the one that goes.
815 assert_eq!(
816 dropped("edith-keys 1\nplay space\ncut space\n"),
817 ["line 3: space is already play's"]
818 );
819 }
820
821 /// The rebind data-loss path: one line the parser cannot use must not cost
822 /// the rebinds around it (a `capture` of shift+= wrote `play +`, and the
823 /// next load threw the whole file away and went back to the defaults).
824 #[test]
825 fn one_bad_line_costs_only_that_line() {
826 let text = "edith-keys 1\nplay +\nexport ctrl+w\ncut j\n";
827 let (keymap, dropped) = parse(text).expect("the magic line is still good");
828 assert_eq!(dropped, ["line 2: \"+\" is not a chord"]);
829 // The lines around it are in force, which is the whole point.
830 assert_eq!(keymap.lookup("w", true), Some(ActionId::Export));
831 assert_eq!(keymap.lookup("j", false), Some(ActionId::Cut));
832 // ...and the one that went is unbound, not silently something else.
833 assert_eq!(keymap.display(ActionId::Play), "unbound");
834 // What survives still round-trips: the kept lines emit back as read.
835 assert_eq!(emit(&keymap), "edith-keys 1\nexport ctrl+w\ncut j\n");
836
837 // The notice names the line and the file, and the defaults do *not*
838 // take over -- that was the data loss.
839 let dir = std::env::temp_dir().join(format!("edith-keymap-drop-{}", std::process::id()));
840 let path = dir.join("edith").join("keybindings");
841 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
842 std::fs::write(&path, text).unwrap();
843 let (read, notice) = Keymap::load_from(&path);
844 assert_eq!(read, keymap);
845 let notice = notice.expect("a part-read file must say so");
846 assert!(notice.contains("line 2:"), "{notice}");
847 assert!(notice.contains("keybindings"), "{notice}");
848 std::fs::remove_dir_all(&dir).ok();
849 }
850
851 /// The other half of the same bug: a stroke the file cannot spell is refused
852 /// at the capture, before it can ever be written.
853 #[test]
854 fn only_a_stroke_the_file_can_spell_is_bindable() {
855 for (key, ctrl) in [
856 ("space", false),
857 ("=", false),
858 ("s", true),
859 ("escape", false),
860 ] {
861 assert!(chord(key, ctrl).bindable(), "{key}");
862 }
863 // gpui's name for shift+=, and the grammar's own separator.
864 assert!(!chord("+", false).bindable());
865 assert!(!chord("+", true).bindable());
866 // The rest of what `Chord::parse` will not take back.
867 assert!(!chord("", false).bindable());
868 assert!(!chord("X", false).bindable());
869 assert!(!chord("page up", false).bindable());
870 // A bindable chord is one `rebind_action` may keep: what it writes is
871 // what the next load reads, for every stroke that passes here.
872 let mut k = Keymap::defaults();
873 k.rebind_action(ActionId::Play, chord("=", true)).unwrap();
874 assert_eq!(whole(&emit(&k)), k);
875 }
876
877 #[test]
878 fn rebinding_refuses_to_steal_another_actions_stroke() {
879 let mut k = Keymap::defaults();
880 assert_eq!(
881 k.rebind_action(ActionId::Export, chord("space", false)),
882 Err(ActionId::Play)
883 );
884 // Refused means unchanged, on both sides of the conflict.
885 assert_eq!(k.lookup("e", false), Some(ActionId::Export));
886 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
887 // A free stroke takes, and the old one stops meaning anything.
888 assert_eq!(k.rebind_action(ActionId::Export, chord("w", true)), Ok(()));
889 assert_eq!(k.lookup("w", true), Some(ActionId::Export));
890 assert_eq!(k.lookup("e", false), None);
891 assert_eq!(k.display(ActionId::Export), "ctrl+w");
892 }
893
894 #[test]
895 fn a_rebound_action_keeps_only_the_new_stroke() {
896 let mut k = Keymap::defaults();
897 assert_eq!(k.display(ActionId::Delete), "x or delete");
898 // One stroke replaces the whole set: what the row showed is what went.
899 assert_eq!(k.rebind_action(ActionId::Delete, chord("d", true)), Ok(()));
900 assert_eq!(k.display(ActionId::Delete), "ctrl+d");
901 assert_eq!(k.lookup("x", false), None);
902 assert_eq!(k.lookup("delete", false), None);
903 assert_eq!(k.lookup("d", true), Some(ActionId::Delete));
904 // One of its own chords is not a conflict with itself -- it collapses
905 // the action onto that one.
906 assert_eq!(k.rebind_action(ActionId::Undo, chord("z", true)), Ok(()));
907 assert_eq!(k.display(ActionId::Undo), "ctrl+z");
908 assert_eq!(k.lookup("z", false), None);
909 // The action keeps its place in the display order, and the file keeps
910 // reading in that order too.
911 let order: Vec<_> = k.entries().iter().map(|b| b.action).collect();
912 assert_eq!(order, ActionId::ALL.to_vec());
913 assert_eq!(emit(&k), emit(&whole(&emit(&k))));
914 // Every action is now single-bound, so the file is one line each.
915 assert_eq!(k.entries().len(), ActionId::ALL.len());
916 }
917
918 #[test]
919 fn display_reads_as_a_person_would_say_it() {
920 let k = Keymap::defaults();
921 assert_eq!(k.display(ActionId::Play), "space");
922 assert_eq!(k.display(ActionId::Save), "ctrl+s");
923 assert_eq!(k.display(ActionId::Delete), "x or delete");
924 assert_eq!(k.display(ActionId::Undo), "z or ctrl+z");
925 // The one key whose common name is not gpui's.
926 assert_eq!(k.display(ActionId::CancelExport), "esc");
927 assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound");
928 // The label is the editor's column, and never the file's word for it.
929 assert_eq!(ActionId::CancelExport.label(), "Cancel export");
930 assert_eq!(ActionId::ALL.len(), 23);
931 }
932
933 #[test]
934 fn a_saved_keymap_comes_back_off_the_disk() {
935 // Its own directory, never the real config one: this test writes.
936 let dir = std::env::temp_dir().join(format!("edith-keymap-{}", std::process::id()));
937 let path = dir.join("edith").join("keybindings");
938 let mut written = Keymap::defaults();
939 written
940 .rebind_action(ActionId::Export, chord("w", true))
941 .unwrap();
942 // The config directory does not exist yet -- the first save makes it.
943 written.save_to(&path).unwrap();
944 let (read, notice) = Keymap::load_from(&path);
945 assert_eq!(notice, None);
946 assert_eq!(read, written);
947 assert_eq!(read.lookup("w", true), Some(ActionId::Export));
948 assert_eq!(read.lookup("e", false), None);
949 // The rename left nothing half-written behind.
950 assert!(!dir.join("edith").join("keybindings.part").exists());
951 // A file that is merely absent is not an error and says nothing.
952 let (fresh, notice) = Keymap::load_from(&dir.join("nothing-here"));
953 assert_eq!(fresh, Keymap::defaults());
954 assert_eq!(notice, None);
955 // A file that is not one at all falls back whole, and names its line.
956 std::fs::write(&path, "edith-keys 9\nplay space\n").unwrap();
957 let (fallback, notice) = Keymap::load_from(&path);
958 assert_eq!(fallback, Keymap::defaults());
959 let notice = notice.expect("a refused file must say so");
960 assert!(notice.contains("line 1:"), "{notice}");
961 assert!(notice.contains("keybindings"), "{notice}");
962 // One unusable line inside a good file costs that line only -- the
963 // defaults do not come back over the rebinds that read fine.
964 std::fs::write(&path, "edith-keys 1\nplay ctrl+alt+x\nexport ctrl+w\n").unwrap();
965 let (kept, notice) = Keymap::load_from(&path);
966 assert_eq!(kept.lookup("w", true), Some(ActionId::Export));
967 assert_eq!(kept.display(ActionId::Play), "unbound");
968 let notice = notice.expect("a part-read file must say so");
969 assert!(notice.contains("line 2:"), "{notice}");
970 assert!(notice.contains("keybindings"), "{notice}");
971 // Saving over it is a whole replacement, not an edit.
972 Keymap::defaults().save_to(&path).unwrap();
973 assert_eq!(Keymap::load_from(&path), (Keymap::defaults(), None));
974 std::fs::remove_dir_all(&dir).ok();
975 }
976
977 #[test]
978 fn the_config_path_follows_xdg_then_home() {
979 let p = |xdg: Option<&str>, home: Option<&str>| {
980 config_path_in(xdg.map(Into::into), home.map(Into::into))
981 };
982 assert_eq!(
983 p(Some("/x/config"), Some("/home/u")),
984 std::path::Path::new("/x/config/edith/keybindings")
985 );
986 assert_eq!(
987 p(None, Some("/home/u")),
988 std::path::Path::new("/home/u/.config/edith/keybindings")
989 );
990 // An empty XDG_CONFIG_HOME is one the spec says to ignore.
991 assert_eq!(
992 p(Some(""), Some("/home/u")),
993 std::path::Path::new("/home/u/.config/edith/keybindings")
994 );
995 // Nowhere to put it but here -- still never `/edith/keybindings`.
996 assert_eq!(
997 p(None, None),
998 std::path::Path::new(".config/edith/keybindings")
999 );
1000 }
1001}