forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBa3e9dc2Tahinli3 months ago134 commits

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