forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBcc667e6Tahinli3 months ago285 commits

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