forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB0563cbfTahinli2 months ago824 commits

keymap.rs1773 lines, 83.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/// The action list, written once: the enum and the display-order array come out
40/// of the same names, so an action added here is in [`ActionId::ALL`] by
41/// construction. It used to be two lists, and a variant added to one of them
42/// compiled, passed every test, and was simply missing from the keys card --
43/// the pointer-unreachable action this editor opened with.
44macro_rules! actions {
45 ($($(#[$note:meta])* $variant:ident),+ $(,)?) => {
46 /// Everything a stroke can ask for. Not the mouse's actions: only what a
47 /// key can reach is bindable.
48 #[derive(Clone, Copy, PartialEq, Eq, Debug)]
49 pub enum ActionId {
50 $($(#[$note])* $variant,)+
51 }
52
53 impl ActionId {
54 /// Display order everywhere -- the editor lists them in it and
55 /// [`Keymap::defaults`] binds them in it. Derived from the list
56 /// above, so there is no second place to forget.
57 pub const ALL: [ActionId; [$(stringify!($variant)),+].len()] =
58 [$(ActionId::$variant),+];
59 }
60 };
61}
62
63actions! {
64 Play,
65 /// Whether the active session -- the timeline or a library preview --
66 /// restarts from the top on reaching its end instead of stopping there.
67 /// Live exactly where Play is: a transport with nothing under it has
68 /// nothing to loop either.
69 Loop,
70 StepBack,
71 StepForward,
72 JumpBack,
73 JumpForward,
74 GoStart,
75 GoEnd,
76 /// The two that put the playhead on a *source* sync point -- the frames a
77 /// cut may be placed on for an export to copy the film's own coded pictures
78 /// instead of decoding and coding every one of them again. Playback keys by
79 /// what they do (they move the playhead and nothing else) and editing keys
80 /// by what they are for.
81 PrevSyncPoint,
82 NextSyncPoint,
83 /// Walks to the next cut (DESIGN.md §6): the odometer the cut readout
84 /// counts against.
85 WalkCutNext,
86 /// The pair's other half, one cut earlier.
87 WalkCutPrev,
88 /// [`ActionId::WalkCutNext`]'s stride-ten (DESIGN.md §6's "shift"): its
89 /// own action, not a modifier read off `WalkCutNext`, because gpui 0.2.2
90 /// never delivers a shift modifier alongside `.`/`,` (see [`Chord`]'s
91 /// doc) -- the *only* channel a stroke has back to [`Player::act`] is
92 /// which [`ActionId`] the keymap resolved it to, so the stride the
93 /// platform can't spell as a modifier is spelled as its own bound key
94 /// (`>`, what shift+. actually types) instead.
95 WalkCutNext10,
96 /// The pair's other half (`<`, what shift+, actually types).
97 WalkCutPrev10,
98 /// Marks the playhead as an export's in point. The out point wraps around
99 /// it if the mark lands past the current out ([`ordered_range`]).
100 SetIn,
101 /// The out point's pair. Ordered the same way against whatever in point
102 /// stands already.
103 SetOut,
104 /// Drops the mark: an export goes back to the whole timeline.
105 ClearRange,
106 Export,
107 Save,
108 Copy,
109 Paste,
110 Cut,
111 Regroup,
112 Detach,
113 Group,
114 Select,
115 SelectNext,
116 SelectPrev,
117 /// Every placement on every lane in one selection -- the companion of the
118 /// ctrl-click that builds a selection by hand, for the times everything
119 /// wants selecting at once.
120 SelectAll,
121 /// Bare escape with nothing else claiming it: empties a multi-clip
122 /// selection without touching picks, cards or fullscreen.
123 Deselect,
124 Delete,
125 Lift,
126 Color,
127 /// Where a clip sits, how big and which way up
128 /// ([`crate::transform_ui::TRANSFORM_BANDS`]) -- the geometry twin of
129 /// [`ActionId::Color`], filed right beside it.
130 Transform,
131 Fit,
132 Resolution,
133 ZoomIn,
134 ZoomOut,
135 ZoomFit,
136 Undo,
137 Redo,
138 AddVideoLane,
139 AddAudioLane,
140 RemoveVideoLane,
141 RemoveAudioLane,
142 AddSubtitleLane,
143 RemoveSubtitleLane,
144 /// The palette's own door: a file's subtitle tracks read into the list the
145 /// panel shows, which is where a lane's words are dragged *from*. Adding a
146 /// track to that list places nothing -- the pair above it is what makes the
147 /// timeline row a caption can land on.
148 ImportSubtitles,
149 /// The dock's own `Add files` verb (MOCK-SPEC "Dock" IMPORT section):
150 /// the file chooser, same door [`crate::Player::pick_and_import`] and a
151 /// drop on the window already use.
152 AddFiles,
153 /// The dock's `Paste path` verb: imports whatever file the OS clipboard
154 /// names ([`crate::Player::paste_file_path`]).
155 PasteFilePath,
156 ToggleMute,
157 VolumeUp,
158 VolumeDown,
159 Equalizer,
160 Speed,
161 Silence,
162 /// Crossfades the selected audio clip into its neighbour ([`Project::crossfade`]):
163 /// two adjacent clips picked on one lane, or a single pick faded into the
164 /// clip right after it.
165 Crossfade,
166 /// No-aim trim of the subject cut's in point, frame detents, at any zoom
167 /// (DESIGN.md §6), on its designed bare `[`. [`ActionId::SelectPrev`]
168 /// moved to `{` (what shift+[ actually types) to free it -- see
169 /// keymap.rs's own defaults.
170 TrimIn,
171 /// The pair's other half, the subject cut's out point, on its designed
172 /// bare `]` -- [`ActionId::SelectNext`] moved to `}` (what shift+]
173 /// actually types) for the same reason.
174 TrimOut,
175 /// Loop-trim: loops around the subject cut while trimming it (DESIGN.md
176 /// §6, "the modernized Avid trim mode").
177 LoopTrim,
178 /// The keyboard's own version of the pointer's drag-the-edge-to-a-spot
179 /// trim (debt #42: trim used to be pointer-only): snaps the subject
180 /// cut's in point straight to the playhead, one press, one undo step --
181 /// [`ActionId::TrimIn`]'s frame-detent nudge covers the other case. Bare
182 /// `[`/`{`/ctrl+`[` are all spoken for (nudge, select-prev, sync point),
183 /// so this takes the next rung of the same bracket family: ctrl held on
184 /// the shifted bracket, `ctrl+{` (what ctrl+shift+[ actually types).
185 TrimInToPlayhead,
186 /// The pair's other half, the subject cut's out point, on `ctrl+}`.
187 TrimOutToPlayhead,
188 /// Dissolves the selected video clip into its neighbour
189 /// ([`Project::set_transition_out`]): two adjacent clips picked on one
190 /// lane, or a single pick dissolved into the clip right after it. A
191 /// second press on a clip that already dissolves removes it instead.
192 Dissolve,
193 Mix,
194 ToggleSnap,
195 ToggleSubtitles,
196 /// Cut on the stand-ins or on the films themselves
197 /// ([`engine::proxy`]): what the picture is decoded from, and nothing
198 /// else -- the sound and every export stay the film's whichever way it
199 /// is set.
200 ToggleProxies,
201 /// Whether a film that wants a stand-in gets one made as it is imported
202 /// ([`engine::proxy::wanted`]): what is *encoded*, where the switch above
203 /// is what is decoded. With it off the switch above is also the ask -- it
204 /// starts the ones the project is missing.
205 ToggleAutoProxies,
206 /// The window's own colours, which belong to the person looking at them and
207 /// not to the project: a list of the palettes, opened here and from the
208 /// toolbar's Theme button. It was a build feature once, which made it a
209 /// choice only whoever compiled the binary could make.
210 Theme,
211 /// The whole window, borderless over the screen: a player's own control,
212 /// on the platform's own toggle ([`gpui::Window::toggle_fullscreen`]).
213 Fullscreen,
214 CancelExport,
215 /// Opens the actions card -- the list every other action is on. A door of
216 /// its own, because a card reachable only by a button in the panel is one a
217 /// hand on the keyboard has to leave the keyboard for.
218 ShowActions,
219 /// Saves the frame on screen to a PNG: whatever is showing, the timeline's
220 /// own picture or a library preview's, since both write through the one
221 /// `self.image` the atlas already holds.
222 Screenshot,
223 /// The cue plate's font and size -- a person's own preference, kept
224 /// beside the theme and not the project, and opened the same way.
225 SubtitleStyle,
226 /// The settings page: PROJECT rows (resolution, fps, sample-rate, HDR
227 /// tonemap, the mix) beside EDITOR rows (proxies, auto-proxies, subtitle
228 /// font) -- one door, two clearly-headed sections, per the split rule
229 /// that "anything that changes the rendered output or lives in the
230 /// project file is PROJECT; anything about this machine, this person,
231 /// this window is EDITOR." Always answerable, same as `Theme`: it is
232 /// about the editor and the project's own numbers, not about a clip.
233 Settings,
234 /// Moves the keyboard ring onto the dock (`ui::stance::Surface::Dock`,
235 /// the cycle's first stop): the door into keyboard-only navigation
236 /// (`ui::stance`'s Tab/Shift-Tab ring), which nothing else in the app
237 /// opens. Bare Tab stays [`ActionId::Select`] at the root the whole time
238 /// -- this only starts the ring, it never steals the clip-selection key.
239 FocusPanels,
240}
241
242impl ActionId {
243 /// What a person calls it.
244 pub fn label(self) -> &'static str {
245 match self {
246 ActionId::Play => "Play / Pause",
247 ActionId::Loop => "Loop the playhead's end",
248 ActionId::StepBack => "One frame back",
249 ActionId::StepForward => "One frame forward",
250 ActionId::JumpBack => "One second back",
251 ActionId::JumpForward => "One second forward",
252 ActionId::GoStart => "Go to the start",
253 ActionId::GoEnd => "Go to the last frame",
254 ActionId::PrevSyncPoint => "Previous sync point (a cut here is copied, not re-encoded)",
255 ActionId::NextSyncPoint => "Next sync point (a cut here is copied, not re-encoded)",
256 ActionId::WalkCutNext => "Walk to the next cut",
257 ActionId::WalkCutPrev => "Walk to the previous cut",
258 ActionId::WalkCutNext10 => "Walk ten cuts forward",
259 ActionId::WalkCutPrev10 => "Walk ten cuts back",
260 ActionId::SetIn => "Mark in (export range)",
261 ActionId::SetOut => "Mark out (export range)",
262 ActionId::ClearRange => "Clear the export range",
263 ActionId::Export => "Export",
264 ActionId::Save => "Save",
265 ActionId::Copy => "Copy",
266 ActionId::Paste => "Paste",
267 ActionId::Cut => "Cut",
268 ActionId::Regroup => "Regroup",
269 // Neither half's action: it takes the *pair* apart, and the menu
270 // that offers it hangs on whichever half was right-clicked -- worded
271 // from the picture's side it read as a video item on an audio clip.
272 ActionId::Detach => "Ungroup the selection (clips and captions)",
273 ActionId::Group => "Group the selection (ctrl-click the clips first)",
274 ActionId::Select => "Select the clip under the playhead (again for the next lane)",
275 ActionId::SelectNext => "Select the next clip in the lane",
276 ActionId::SelectPrev => "Select the previous clip in the lane",
277 ActionId::SelectAll => "Select everything (every clip and caption)",
278 ActionId::Deselect => "Clear the selection",
279 ActionId::Delete => "Delete",
280 ActionId::Lift => "Lift (leave a gap)",
281 ActionId::Color => "Colour…",
282 ActionId::Transform => "Transform — position, scale, rotation, crop",
283 ActionId::Fit => "Fit policy: fit → fill → stretch → centre",
284 ActionId::Resolution => "Project resolution: source → 2160p → 1080p → 720p → 480p",
285 ActionId::ZoomIn => "Zoom in on the timeline (around the playhead)",
286 ActionId::ZoomOut => "Zoom out of the timeline",
287 ActionId::ZoomFit => "Fit the whole timeline on screen",
288 ActionId::Undo => "Undo",
289 ActionId::Redo => "Redo",
290 ActionId::AddVideoLane => "Add a video track",
291 ActionId::AddAudioLane => "Add an audio track",
292 ActionId::RemoveVideoLane => "Remove the last video track (it must be empty)",
293 ActionId::RemoveAudioLane => "Remove the last audio track (it must be empty)",
294 ActionId::AddSubtitleLane => "Add a subtitle track",
295 ActionId::RemoveSubtitleLane => "Remove the last subtitle track (it must be empty)",
296 ActionId::ImportSubtitles => "Add subtitles from a file…",
297 ActionId::AddFiles => "Add files…",
298 ActionId::PasteFilePath => "Paste path (import the file it names)",
299 ActionId::ToggleMute => "Mute / Unmute",
300 ActionId::VolumeUp => "Volume up",
301 ActionId::VolumeDown => "Volume down",
302 ActionId::Equalizer => "Equalizer",
303 ActionId::Speed => "Speed (tape)…",
304 ActionId::Silence => "Silences: cut or speed up…",
305 ActionId::Crossfade => "Crossfade into the next clip",
306 ActionId::TrimIn => "Trim the subject cut's in point",
307 ActionId::TrimOut => "Trim the subject cut's out point",
308 ActionId::LoopTrim => "Loop-trim the subject cut",
309 ActionId::TrimInToPlayhead => "Trim the subject cut's in point to the playhead",
310 ActionId::TrimOutToPlayhead => "Trim the subject cut's out point to the playhead",
311 ActionId::Dissolve => "Dissolve into the next clip",
312 ActionId::Mix => "Mix: track volumes and the limiter…",
313 ActionId::ToggleSnap => "Snap on / off (edges, the playhead, the start)",
314 ActionId::ToggleSubtitles => "Subtitles on / off over the picture",
315 ActionId::ToggleProxies => "Proxies on / off for the picture",
316 ActionId::ToggleAutoProxies => "Make proxies on import: on / off",
317 ActionId::Theme => "Theme: the window's colours…",
318 ActionId::Fullscreen => "Fullscreen on / off",
319 ActionId::CancelExport => "Cancel export",
320 ActionId::ShowActions => "All actions and their keys…",
321 ActionId::Screenshot => "Save the frame on screen as a PNG",
322 ActionId::SubtitleStyle => "Subtitle style: font and size…",
323 ActionId::Settings => "Settings: project and editor…",
324 ActionId::FocusPanels => "Move keyboard focus between panels",
325 }
326 }
327
328 /// What the file calls it: ASCII, no spaces, one spelling per variant and
329 /// never the label, which is free to be reworded.
330 fn name(self) -> &'static str {
331 match self {
332 ActionId::Play => "play",
333 ActionId::Loop => "loop",
334 ActionId::StepBack => "step-back",
335 ActionId::StepForward => "step-forward",
336 ActionId::JumpBack => "jump-back",
337 ActionId::JumpForward => "jump-forward",
338 ActionId::GoStart => "go-start",
339 ActionId::GoEnd => "go-end",
340 ActionId::PrevSyncPoint => "prev-sync-point",
341 ActionId::NextSyncPoint => "next-sync-point",
342 ActionId::WalkCutNext => "walk-cut-next",
343 ActionId::WalkCutPrev => "walk-cut-prev",
344 ActionId::WalkCutNext10 => "walk-cut-next-10",
345 ActionId::WalkCutPrev10 => "walk-cut-prev-10",
346 ActionId::SetIn => "set-in",
347 ActionId::SetOut => "set-out",
348 ActionId::ClearRange => "clear-range",
349 ActionId::Export => "export",
350 ActionId::Save => "save",
351 ActionId::Copy => "copy",
352 ActionId::Paste => "paste",
353 ActionId::Cut => "cut",
354 ActionId::Regroup => "regroup",
355 ActionId::Detach => "detach",
356 ActionId::Group => "group",
357 ActionId::Select => "select",
358 ActionId::SelectNext => "select-next",
359 ActionId::SelectPrev => "select-prev",
360 ActionId::SelectAll => "select-all",
361 ActionId::Deselect => "deselect",
362 ActionId::Delete => "delete",
363 ActionId::Lift => "lift",
364 ActionId::Color => "color",
365 ActionId::Transform => "transform",
366 ActionId::Fit => "fit",
367 ActionId::Resolution => "resolution",
368 ActionId::ZoomIn => "zoom-in",
369 ActionId::ZoomOut => "zoom-out",
370 ActionId::ZoomFit => "zoom-fit",
371 ActionId::Undo => "undo",
372 ActionId::Redo => "redo",
373 ActionId::AddVideoLane => "add-video-lane",
374 ActionId::AddAudioLane => "add-audio-lane",
375 ActionId::RemoveVideoLane => "remove-video-lane",
376 ActionId::RemoveAudioLane => "remove-audio-lane",
377 ActionId::AddSubtitleLane => "add-subtitle-lane",
378 ActionId::RemoveSubtitleLane => "remove-subtitle-lane",
379 ActionId::ImportSubtitles => "import-subtitles",
380 ActionId::AddFiles => "add-files",
381 ActionId::PasteFilePath => "paste-file-path",
382 ActionId::ToggleMute => "toggle-mute",
383 ActionId::VolumeUp => "volume-up",
384 ActionId::VolumeDown => "volume-down",
385 ActionId::Equalizer => "equalizer",
386 ActionId::Speed => "speed",
387 ActionId::Silence => "silence",
388 ActionId::Crossfade => "crossfade",
389 ActionId::TrimIn => "trim-in",
390 ActionId::TrimOut => "trim-out",
391 ActionId::LoopTrim => "loop-trim",
392 ActionId::TrimInToPlayhead => "trim-in-to-playhead",
393 ActionId::TrimOutToPlayhead => "trim-out-to-playhead",
394 ActionId::Dissolve => "dissolve",
395 ActionId::Mix => "mix",
396 ActionId::ToggleSnap => "toggle-snap",
397 ActionId::ToggleSubtitles => "toggle-subtitles",
398 ActionId::ToggleProxies => "toggle-proxies",
399 ActionId::ToggleAutoProxies => "toggle-auto-proxies",
400 ActionId::Theme => "theme",
401 ActionId::Fullscreen => "fullscreen",
402 ActionId::CancelExport => "cancel-export",
403 ActionId::ShowActions => "show-actions",
404 ActionId::Screenshot => "screenshot",
405 ActionId::SubtitleStyle => "subtitle-style",
406 ActionId::Settings => "settings",
407 ActionId::FocusPanels => "focus-panels",
408 }
409 }
410
411 fn from_name(name: &str) -> Option<Self> {
412 Self::ALL.into_iter().find(|a| a.name() == name)
413 }
414
415 /// Which heading the keys menu files it under. Every action has one, so a
416 /// new action is listed the moment it exists -- there is no second list to
417 /// forget.
418 pub fn category(self) -> Category {
419 match self {
420 ActionId::Play
421 | ActionId::Loop
422 | ActionId::StepBack
423 | ActionId::StepForward
424 | ActionId::JumpBack
425 | ActionId::JumpForward
426 | ActionId::GoStart
427 | ActionId::GoEnd
428 | ActionId::PrevSyncPoint
429 | ActionId::NextSyncPoint
430 | ActionId::WalkCutNext
431 | ActionId::WalkCutPrev
432 | ActionId::WalkCutNext10
433 | ActionId::WalkCutPrev10
434 | ActionId::SetIn
435 | ActionId::SetOut
436 | ActionId::ClearRange => Category::Playback,
437 ActionId::Copy
438 | ActionId::Paste
439 | ActionId::Select
440 | ActionId::SelectNext
441 | ActionId::SelectPrev
442 | ActionId::SelectAll
443 | ActionId::Deselect
444 | ActionId::Delete
445 | ActionId::Lift
446 | ActionId::Color
447 | ActionId::Transform
448 | ActionId::Fit
449 // A rate is the clip's, not the sound's: it re-times the picture
450 // and the sound together, and the card opens on whichever half was
451 // clicked.
452 | ActionId::Speed
453 // The scan reads a clip's sound, but what it does is edit the
454 // timeline the clip is on -- it is a clip card like the three
455 // above it, opened on whichever half was picked.
456 | ActionId::Silence
457 | ActionId::Crossfade
458 | ActionId::TrimIn
459 | ActionId::TrimOut
460 | ActionId::LoopTrim
461 | ActionId::TrimInToPlayhead
462 | ActionId::TrimOutToPlayhead
463 | ActionId::Dissolve => Category::Clips,
464 // The project's own picture size is not a clip's business, and not
465 // a file operation either: it is what the viewer is looking at.
466 // Neither is how much of the timeline the panel shows: a zoom edits
467 // nothing, it magnifies.
468 // ...and whether the cues are drawn over that picture: a subtitle
469 // edits nothing either, it is part of what is being watched.
470 ActionId::Resolution
471 | ActionId::ZoomIn
472 | ActionId::ZoomOut
473 | ActionId::ZoomFit
474 | ActionId::ToggleSubtitles
475 // ...and which file the picture is decoded from, which changes
476 // nothing that is saved and nothing that is exported: a stand-in
477 // is what one watches while cutting, not what one delivers.
478 | ActionId::ToggleProxies
479 // ...and whether those stand-ins are made without being asked: the
480 // other half of the same switch, filed beside it so a card reader
481 // meets the pair the panel shows as a pair.
482 | ActionId::ToggleAutoProxies
483 // ...and what the whole window is painted in: it edits nothing at
484 // all, it is what one is looking *with*.
485 | ActionId::Theme
486 // ...and what the cue plate is drawn in: a person's own reading
487 // preference, same as the theme beside it.
488 | ActionId::SubtitleStyle
489 // ...and whether that window fills the screen: a way of looking,
490 // same as the zoom and the theme beside it.
491 | ActionId::Fullscreen
492 // The settings page: it changes no clip and no lane, only the
493 // project's own numbers and this window's preferences.
494 | ActionId::Settings
495 // Moves the ring, not a clip or a lane: the same "how one is
496 // looking/reaching, not what is being edited" shape as the rest
497 // of this heading.
498 | ActionId::FocusPanels => Category::View,
499 ActionId::Cut
500 | ActionId::Regroup
501 | ActionId::Detach
502 | ActionId::Group
503 | ActionId::Undo
504 | ActionId::Redo
505 | ActionId::AddVideoLane
506 | ActionId::AddAudioLane
507 | ActionId::RemoveVideoLane
508 // Not a view setting despite being a pointer aid: it decides where
509 // a drag actually lands, which is an edit and not a magnification.
510 | ActionId::ToggleSnap
511 // The subtitle pair is a track pair like the lanes above it: what
512 // they add is on the timeline and goes into the file an export
513 // writes, where the toggle two headings down only decides whether
514 // this window draws it.
515 | ActionId::AddSubtitleLane
516 | ActionId::RemoveSubtitleLane
517 // ...and the door that fills the palette those lanes are dragged
518 // from: it edits no lane, but what it brings in is the project's
519 // and is saved with it, which is not a view setting.
520 | ActionId::ImportSubtitles
521 | ActionId::RemoveAudioLane => Category::Editing,
522 ActionId::ToggleMute
523 | ActionId::VolumeUp
524 | ActionId::VolumeDown
525 | ActionId::Equalizer
526 // The mix is the project's sound -- what every track plays at and
527 // what the whole of it is held under -- where the three above it
528 // are this machine's monitoring. Both are audio, and the card says
529 // which is which.
530 | ActionId::Mix => Category::Audio,
531 // Under the heading the panel button sits in, beside the save and
532 // the export it stands next to on screen.
533 ActionId::Save
534 | ActionId::Export
535 | ActionId::CancelExport
536 | ActionId::ShowActions
537 // It writes a file like the three above it, and touches no edit
538 // list -- what an export's own allow-list already means it stays
539 // out of, not what puts it in this heading.
540 | ActionId::Screenshot
541 // The dock's import pair brings a file *in*, the same heading a
542 // file going *out* (Export, Save) already sits under.
543 | ActionId::AddFiles
544 | ActionId::PasteFilePath => Category::File,
545 }
546 }
547}
548
549/// A heading in the keys menu, and the order the headings come in.
550#[derive(Clone, Copy, PartialEq, Eq, Debug)]
551pub enum Category {
552 Playback,
553 Editing,
554 Clips,
555 Audio,
556 File,
557 View,
558}
559
560impl Category {
561 pub const ALL: [Category; 6] = [
562 Category::Playback,
563 Category::Editing,
564 Category::Clips,
565 Category::Audio,
566 Category::File,
567 Category::View,
568 ];
569
570 pub fn label(self) -> &'static str {
571 match self {
572 Category::Playback => "Playback",
573 Category::Editing => "Editing",
574 Category::Clips => "Clips",
575 Category::Audio => "Audio",
576 Category::File => "File",
577 Category::View => "View",
578 }
579 }
580}
581
582/// A stroke that works but nobody may rebind: the modal cards read the keyboard
583/// themselves, and what closes a card must not be a thing a user can take away.
584/// Listed here anyway, because the keys menu shows every stroke that works --
585/// `no_stroke_is_missing_from_the_keys_menu` reads the key handler's own source
586/// and fails on any key that reaches neither this table nor a binding.
587pub struct Fixed {
588 /// As a person reads it, which for a single key is [`Chord::pretty`]'s
589 /// spelling and for a family of keys is the family (`0–9`). A `String`
590 /// because one of them is generated: the codec row's keys are the export
591 /// card's own table, not a line typed a second time here.
592 pub chord: String,
593 pub label: &'static str,
594 pub category: Category,
595 /// What a hand with only a mouse does instead. Every stroke here is
596 /// card-local, and a card whose rows only a keyboard can reach is half this
597 /// editor's users locked out of it, so each row names the thing on its card
598 /// -- `every_action_is_reachable_without_the_keyboard` looks each id up in
599 /// the render's own source.
600 pub reach: Reach,
601}
602
603/// The pointer's answer to a fixed stroke.
604#[derive(Clone, Copy, PartialEq, Eq, Debug)]
605pub enum Reach {
606 /// The id of the element on the card that does the same thing by click or
607 /// by drag.
608 Click(&'static str),
609 /// Not an action a pointer takes: the way *out* of a card, and the hold
610 /// that only repeats what a drag already does continuously. A variant
611 /// rather than an omission, so a row with nothing to click is a decision
612 /// somebody wrote down instead of a line missing from a list.
613 Gesture,
614}
615
616pub static FIXED: std::sync::LazyLock<[Fixed; 27]> = std::sync::LazyLock::new(|| {
617 [
618 // Not a chord at all but a way of pressing one, and the only place the
619 // editor can say so: holding a key that moves a *value* runs it, and
620 // holding anything else still does what one press did.
621 Fixed {
622 chord: "hold ← → ↑ ↓".into(),
623 label: "Run a card's slider, or the volume and zoom keys, while held",
624 category: Category::View,
625 reach: Reach::Gesture,
626 },
627 Fixed {
628 chord: "esc".into(),
629 label: "Close this card or menu, or cancel a capture",
630 category: Category::View,
631 reach: Reach::Gesture,
632 },
633 // An open choice list is driven by the keyboard as well as clicked: the
634 // list is the door to a setting, and a door only a pointer opens is one
635 // half of this editor's users cannot use.
636 Fixed {
637 chord: "↑ ↓ enter".into(),
638 label: "Move through an open choice list, and take the row",
639 category: Category::View,
640 reach: Reach::Click("picker-row"),
641 },
642 Fixed {
643 chord: "n".into(),
644 label: "Say the export budget: 850k, 6.5M, 6.5 or 1.2G of file",
645 category: Category::File,
646 reach: Reach::Click("budget"),
647 },
648 Fixed {
649 chord: "− / + / ← →".into(),
650 label: "Move the export budget — shift steps whole megabits",
651 category: Category::File,
652 reach: Reach::Click("budget-track"),
653 },
654 Fixed {
655 chord: "0–9".into(),
656 label: "Type into an open field — the budget, or a clip's duration",
657 category: Category::File,
658 reach: Reach::Click("budget"),
659 },
660 Fixed {
661 chord: "backspace".into(),
662 label: "Erase a character in the budget or duration field",
663 category: Category::File,
664 reach: Reach::Click("budget"),
665 },
666 Fixed {
667 chord: "d".into(),
668 label: "Choose where the export is written",
669 category: Category::File,
670 reach: Reach::Click("destination"),
671 },
672 Fixed {
673 chord: "enter".into(),
674 label: "Start the export — or take the budget being typed",
675 category: Category::File,
676 reach: Reach::Click("export-confirm"),
677 },
678 // The equalizer card's own input, for the same reason the export card has
679 // its own: a band nothing but a drag can reach is a band half the users of
680 // this editor cannot move at all. Card-local, so none of them is bindable.
681 Fixed {
682 chord: "1–9, 0".into(),
683 label: "Pick an equalizer band",
684 category: Category::Audio,
685 reach: Reach::Click("eq-graph"),
686 },
687 Fixed {
688 chord: "up".into(),
689 label: "Raise the picked band 1 dB",
690 category: Category::Audio,
691 reach: Reach::Click("eq-gain-up"),
692 },
693 Fixed {
694 chord: "down".into(),
695 label: "Lower the picked band 1 dB",
696 category: Category::Audio,
697 reach: Reach::Click("eq-gain-down"),
698 },
699 Fixed {
700 chord: "← / →".into(),
701 label: "Move the picked band down or up in frequency",
702 category: Category::Audio,
703 reach: Reach::Click("eq-freq-up"),
704 },
705 Fixed {
706 chord: "shift ← / →".into(),
707 label: "Widen or narrow the picked band (its Q)",
708 category: Category::Audio,
709 reach: Reach::Click("eq-q-wider"),
710 },
711 Fixed {
712 chord: "a".into(),
713 label: "Add an equalizer band beside the picked one",
714 category: Category::Audio,
715 reach: Reach::Click("eq-add"),
716 },
717 Fixed {
718 chord: "x".into(),
719 label: "Remove the picked equalizer band",
720 category: Category::Audio,
721 reach: Reach::Click("eq-remove"),
722 },
723 Fixed {
724 chord: "f".into(),
725 label: "Flatten the picked band (double-click does the same)",
726 category: Category::Audio,
727 reach: Reach::Click("eq-flat-band"),
728 },
729 Fixed {
730 chord: "r".into(),
731 label: "Flatten every band",
732 category: Category::Audio,
733 reach: Reach::Click("eq-reset"),
734 },
735 Fixed {
736 chord: "s".into(),
737 label: "Show or hide the spectrum behind the curve",
738 category: Category::Audio,
739 reach: Reach::Click("eq-spectrum"),
740 },
741 // The colour card's own three, which mean nothing outside it -- the same
742 // card-local input the export card's digits are.
743 Fixed {
744 chord: "↑ / ↓".into(),
745 label: "Pick a colour slider",
746 category: Category::Clips,
747 reach: Reach::Click("color-row"),
748 },
749 Fixed {
750 chord: "← / →".into(),
751 label: "Move the picked colour slider",
752 category: Category::Clips,
753 reach: Reach::Click("color-bar"),
754 },
755 Fixed {
756 chord: "r".into(),
757 label: "Take the colour grade off the clip",
758 category: Category::Clips,
759 reach: Reach::Click("color-reset"),
760 },
761 // The transform card's own three, the same shape as the colour card's:
762 // up/down pick a band (position, scale, rotate, crop), left/right move
763 // it, and `r` resets to identity.
764 Fixed {
765 chord: "↑ / ↓".into(),
766 label: "Pick a transform band",
767 category: Category::Clips,
768 reach: Reach::Click("transform-row"),
769 },
770 Fixed {
771 chord: "← / →".into(),
772 label: "Move the picked transform band",
773 category: Category::Clips,
774 reach: Reach::Click("transform-bar"),
775 },
776 Fixed {
777 chord: "r".into(),
778 label: "Take the transform off the clip",
779 category: Category::Clips,
780 reach: Reach::Click("transform-reset"),
781 },
782 // The silence card's two apply keys. Card-local like every stroke above --
783 // they mean nothing while it is closed -- but the card is the one place in
784 // this editor where a key rewrites forty places at once, so both of them
785 // are listed rather than hidden in the card's own hint line.
786 Fixed {
787 chord: "enter".into(),
788 label: "Cut every silence the card found",
789 category: Category::Clips,
790 reach: Reach::Click("silence-apply"),
791 },
792 Fixed {
793 chord: "f".into(),
794 label: "Speed the silences up instead of cutting them",
795 category: Category::Clips,
796 reach: Reach::Click("silence-apply"),
797 },
798 ]
799});
800
801/// A stroke as the key handler sees it: gpui's key name plus the one
802/// modifier this editor binds. Nothing else is a chord here -- alt is part
803/// of the key name gpui reports, and a second modifier would need the file
804/// format to grow before it could be spelled.
805///
806/// There is no `shift` field. gpui 0.2.2 (linux/platform.rs:909-917) clears
807/// the shift modifier for any single-char key whose upper and lower case are
808/// the same -- every symbol key (`,` `.` `[` `]` `/` `=` ...) -- so a chord
809/// carrying `shift` could never be struck for any of them; the shifted
810/// stroke arrives instead as the key it types (`shift+.` is the key `>`).
811/// The one place this editor wanted shift on a symbol (the odometer's
812/// stride-ten, DESIGN.md §6) is bound on that literal key instead
813/// (`keymap.rs`'s own `defaults`), and a non-symbol key that wants shift
814/// (the EQ card's arrows) reads `event.keystroke.modifiers.shift` straight
815/// off the keystroke, upstream of this struct entirely -- so the field had
816/// zero production callers and is gone rather than kept dead.
817#[derive(Clone, PartialEq, Eq, Debug)]
818pub struct Chord {
819 pub key: String,
820 pub ctrl: bool,
821}
822
823impl Chord {
824 /// The file's spelling, and the only one [`parse`] accepts back.
825 fn text(&self) -> String {
826 if self.ctrl {
827 format!("ctrl+{}", self.key)
828 } else {
829 self.key.clone()
830 }
831 }
832
833 /// The spelling a person reads. Identical to [`Chord::text`] but for the one
834 /// key whose usual name is shorter than gpui's. Public because a
835 /// keybindings row shows one chord, where [`Keymap::display`] shows every
836 /// chord an action answers to.
837 pub fn pretty(&self) -> String {
838 let key = if self.key == "escape" {
839 "esc"
840 } else {
841 &self.key
842 };
843 if self.ctrl {
844 format!("ctrl+{key}")
845 } else {
846 key.to_string()
847 }
848 }
849
850 /// The spelling a badge with room for one token reads (MOCK-SPEC.md
851 /// "Spine": `del`, `z`, not `x or delete`, `ctrl+z`): `^` in place of
852 /// `ctrl+`, and the handful of key names whose everyday short form isn't
853 /// gpui's own (`delete` -> `del`, `escape` -> `esc`, `space` -> `spc`).
854 /// [`Chord::pretty`] stays the keys overlay's own spelling -- this is for
855 /// a glyph badge, not the full truth.
856 pub fn compact(&self) -> String {
857 let key = match self.key.as_str() {
858 "escape" => "esc",
859 "delete" => "del",
860 "space" => "spc",
861 other => other,
862 };
863 if self.ctrl {
864 format!("^{key}")
865 } else {
866 key.to_string()
867 }
868 }
869
870 /// Whether the file can carry this stroke and read it back as itself. gpui
871 /// reports strokes this format cannot spell -- shift+= arrives as the key
872 /// `"+"`, which is the chord grammar's own separator -- and binding one
873 /// would write a line the next load has to drop. Asked before a capture is
874 /// taken, so a stroke that cannot be saved is refused while the user is
875 /// still looking at the row.
876 pub fn bindable(&self) -> bool {
877 Chord::parse(&self.text(), 0).is_ok_and(|round_trip| round_trip == *self)
878 }
879
880 /// Strict: exactly one optional `ctrl+`, then a key gpui could have
881 /// reported. A spelling this cannot emit back unchanged is refused
882 /// rather than normalised, because the round-trip is what makes the file
883 /// editable by hand at all.
884 fn parse(text: &str, n: usize) -> Result<Self, String> {
885 let (ctrl, key) = match text.strip_prefix("ctrl+") {
886 Some(rest) => (true, rest),
887 None => (false, text),
888 };
889 if key.is_empty()
890 || key.contains(' ')
891 || key.contains('+')
892 || key.chars().any(|c| c.is_ascii_uppercase())
893 {
894 return Err(format!("line {n}: {text:?} is not a chord"));
895 }
896 Ok(Chord {
897 key: key.to_string(),
898 ctrl,
899 })
900 }
901}
902
903/// One stroke, one action. Two strokes for the same action are two bindings.
904#[derive(Clone, PartialEq, Eq, Debug)]
905pub struct Binding {
906 pub action: ActionId,
907 pub chord: Chord,
908}
909
910/// Every binding in force, in display order. No chord appears twice -- that is
911/// the invariant [`parse`] defends, and it is what lets [`Keymap::lookup`]
912/// answer with the first match.
913#[derive(Clone, PartialEq, Eq, Debug)]
914pub struct Keymap {
915 bindings: Vec<Binding>,
916}
917
918impl Keymap {
919 /// The bindings the editor has always had, in the order the editor lists
920 /// them. Delete and undo get two strokes each because both have always
921 /// answered to two.
922 pub fn defaults() -> Self {
923 let b = |action, key: &str, ctrl| Binding {
924 action,
925 chord: Chord {
926 key: key.to_string(),
927 ctrl,
928 },
929 };
930 Keymap {
931 bindings: vec![
932 b(ActionId::Play, "space", false),
933 // "r" for repeat, free and bare: its ctrl chord is already the
934 // project resolution, and the two read as a pair the way the
935 // mute and its level do.
936 b(ActionId::Loop, "r", false),
937 // Seeking without a pointer, on the keys every player already
938 // seeks with (gpui names them "left"/"right"/"home"/"end",
939 // platform.rs:872-877). The colour card reads the same arrows
940 // for its sliders, but a card answers the stroke and returns
941 // before the keymap is consulted at all -- so these move the
942 // playhead only while no card is open.
943 b(ActionId::StepBack, "left", false),
944 b(ActionId::StepForward, "right", false),
945 b(ActionId::JumpBack, "left", true),
946 b(ActionId::JumpForward, "right", true),
947 b(ActionId::GoStart, "home", false),
948 b(ActionId::GoEnd, "end", false),
949 // The sync-point pair, on the brackets that already mean "the
950 // one before / the one after" here (they select the clip either
951 // side) -- with ctrl, which was free on both, because these
952 // step through the same timeline by the source's own grid.
953 b(ActionId::PrevSyncPoint, "[", true),
954 b(ActionId::NextSyncPoint, "]", true),
955 // The cut odometer (DESIGN.md §6): bare walks one cut, shift
956 // strides ten. gpui 0.2.2 (linux/platform.rs:909-917) clears
957 // the shift modifier for any single-char key whose upper and
958 // lower case are the same -- every one of these symbols --
959 // so `shift+.` never arrives; what arrives instead is the
960 // key the shifted stroke actually types, `>`/`<`. Bound
961 // directly, on the same physical chord, since that is what
962 // the platform hands the key handler.
963 b(ActionId::WalkCutNext, ".", false),
964 b(ActionId::WalkCutPrev, ",", false),
965 b(ActionId::WalkCutNext10, ">", false),
966 b(ActionId::WalkCutPrev10, "<", false),
967 // The mark pair, on the letters every editor already means them
968 // by: bare, since a mark is set as often as a step and nothing
969 // else in this table answers to either.
970 b(ActionId::SetIn, "i", false),
971 b(ActionId::SetOut, "o", false),
972 // The clear takes the ctrl chord: not a stroke to hit setting
973 // one mark and reaching for the other. Free -- "u" bare is the
974 // silence card, and nothing else in this table answers to
975 // ctrl+u.
976 b(ActionId::ClearRange, "u", true),
977 b(ActionId::Export, "e", false),
978 b(ActionId::Save, "s", true),
979 b(ActionId::Copy, "c", true),
980 b(ActionId::Paste, "v", true),
981 // Split, on the bare letter DESIGN.md §6 names for it: the
982 // burst-use command owns the cheap key (§11's frequency
983 // argument). Bare "c" moves to AddSubtitleLane below, which
984 // frees up cleanly since a subtitle track also opens on its
985 // own initial: captions.
986 b(ActionId::Cut, "s", false),
987 // The two lane keys, on the letters they are named after: both
988 // were free, and neither is next to a key that edits.
989 b(ActionId::Regroup, "g", false),
990 // The pair that takes a take apart and puts it back: "d" for
991 // detach was free and is one press like the rest of the clip
992 // keys, and grouping two clips is the "g" that rejoins a cut one
993 // lane over -- the chord beside it, so the two read as one idea.
994 b(ActionId::Detach, "d", false),
995 b(ActionId::Group, "g", true),
996 // Selection without a pointer. Tab is what a keyboard already
997 // means by "move on to the next thing", and the two braces
998 // are the pair either side of it in the lane -- shift+tab is
999 // the obvious partner and is unspellable here, since a chord
1000 // carries only ctrl and `parse` refuses an uppercase key. Bare
1001 // brackets are DESIGN.md §6's own trim pair now, so selection
1002 // takes the braces the shifted brackets actually type: same
1003 // two keys, telling "walk the lane" apart from "trim the cut".
1004 b(ActionId::Select, "tab", false),
1005 // Same platform fact as the odometer above: shift+] never
1006 // arrives as shift+], it arrives as the key `}` (and shift+[
1007 // as `{`) -- bound on the literal the platform delivers.
1008 b(ActionId::SelectNext, "}", false),
1009 b(ActionId::SelectPrev, "{", false),
1010 // Select-all, on the chord every editor and every text field
1011 // already means it by -- which is why the audio-lane removal
1012 // below had to move off ctrl+a: a stroke that universal was
1013 // never really the removal's to keep.
1014 b(ActionId::SelectAll, "a", true),
1015 // Bare escape, last in the precedence chain behind every card,
1016 // search and fullscreen close (render.rs) -- just empties the
1017 // selection when nothing else claims the key.
1018 b(ActionId::Deselect, "escape", false),
1019 b(ActionId::Delete, "x", false),
1020 b(ActionId::Delete, "delete", false),
1021 b(ActionId::Lift, "l", false),
1022 // The c of colour is now AddSubtitleLane's (captions) and
1023 // ctrl+c is Copy, so the grade takes k: free, next to nothing
1024 // that edits, and one press like the
1025 // rest of the clip keys.
1026 b(ActionId::Color, "k", false),
1027 // The placement card takes the ctrl chord of the grade's own
1028 // key: the two sit beside each other on a clip and neither
1029 // steals a bare letter that already means something else.
1030 b(ActionId::Transform, "k", true),
1031 // The fit policy is a clip key like the grade beside it: "p" for
1032 // policy, free, and one press like the rest of them. The project
1033 // resolution is not a clip key and takes a ctrl chord, next to
1034 // nothing that edits and out of the way of a stray press --
1035 // it changes what every clip is composed onto.
1036 b(ActionId::Fit, "p", false),
1037 b(ActionId::Resolution, "r", true),
1038 // The zoom pair, on the chords every editor and every browser
1039 // magnifies with. The bare "=" and "-" are the volume keys, so
1040 // these take the ctrl versions of them -- and ctrl+0 is the
1041 // "back to 100%" of the same family, which here is the whole
1042 // timeline across the bed.
1043 b(ActionId::ZoomIn, "=", true),
1044 b(ActionId::ZoomOut, "-", true),
1045 b(ActionId::ZoomFit, "0", true),
1046 b(ActionId::Undo, "z", false),
1047 b(ActionId::Undo, "z", true),
1048 // Bare "y" is SubtitleStyle's, so redo takes only the ctrl
1049 // chord -- the conventional pairing with ctrl+z either way.
1050 b(ActionId::Redo, "y", true),
1051 // The unshifted initials of what they add. Both were free --
1052 // the copy and paste chords are the *ctrl* ones -- and a track
1053 // is added often enough to deserve a key that is one press.
1054 b(ActionId::AddVideoLane, "v", false),
1055 b(ActionId::AddAudioLane, "a", false),
1056 // ...and the pair that takes one back, on ctrl chords: removing
1057 // a track is not a stroke to hit by accident (the resolution key
1058 // is out of the way for the same reason). Ctrl+v would be the
1059 // matching initial and is the paste, so the video one takes the
1060 // key beside it.
1061 b(ActionId::RemoveVideoLane, "b", true),
1062 // Ctrl+a is the select-all above now, so the audio removal
1063 // takes the free key beside its own letter: "a" neighbours
1064 // "q" on the row, and ctrl+q was taken by nothing.
1065 b(ActionId::RemoveAudioLane, "q", true),
1066 // The subtitle pair reads the same way, on a different letter
1067 // now that bare "s" is split's (DESIGN.md §6): "c" is free
1068 // once split moves off it, and it is still an initial the
1069 // track answers to -- captions. The removal takes the other
1070 // letter subtitles already answer to here: "t" shows and
1071 // hides them, and ctrl+t takes one off the timeline.
1072 b(ActionId::AddSubtitleLane, "c", false),
1073 b(ActionId::RemoveSubtitleLane, "t", true),
1074 // Reading a file's tracks into the palette is not adding a
1075 // track to the timeline, so it is not the bare "s": ctrl+i, the
1076 // i of import, free and next to nothing that deletes.
1077 b(ActionId::ImportSubtitles, "i", true),
1078 // The dock's own import pair (MOCK-SPEC "Dock" IMPORT
1079 // section). Add files takes the chord the mock draws, ^o
1080 // (freed above): it is the burst-use command an editor
1081 // reaches for constantly, where the setting it displaces is
1082 // thrown once a project. Paste path stays off ^v -- that
1083 // chord is the timeline's own Paste, asked for far more
1084 // often while cutting than a clipboard path is pasted while
1085 // importing -- and takes ctrl+l instead, the browser's own
1086 // "go to this location" chord, which is what pasting a path
1087 // to jump straight to a file already is.
1088 b(ActionId::AddFiles, "o", true),
1089 b(ActionId::PasteFilePath, "l", true),
1090 b(ActionId::ToggleMute, "m", false),
1091 // The unshifted pair, which is what gpui reports for those two
1092 // keys ("=" and "-", platform.rs:862): the volume keys every
1093 // player has, without asking for shift to make the "+".
1094 b(ActionId::VolumeUp, "=", false),
1095 b(ActionId::VolumeDown, "-", false),
1096 // The one free letter that says the word: "e" is already the
1097 // export and an equalizer is the q in nobody else's way.
1098 b(ActionId::Equalizer, "q", false),
1099 // "s" is the save's ctrl chord, so the speed card takes the
1100 // unshifted letter beside it: "j" was free, sits under the
1101 // right hand with the other clip keys (k grades, l lifts), and
1102 // is not next to anything that deletes.
1103 b(ActionId::Speed, "j", false),
1104 // The silence card takes "u": free, sits with the other clip-card
1105 // keys under the right hand, and is nowhere near the two that
1106 // delete (x and delete) -- what it opens is a card that can cut
1107 // forty places at once.
1108 b(ActionId::Silence, "u", false),
1109 // Crossfade takes ctrl+f: the mnemonic letter for "fade", with
1110 // ctrl its own room now that plain "f" is the mix card's own
1111 // (below) -- the same letter, the modifier telling them apart.
1112 b(ActionId::Crossfade, "f", true),
1113 // DESIGN.md §6's own chords: bare `[` `]` are the no-aim trim
1114 // pair. SelectPrev/SelectNext moved to `{` `}` above to make
1115 // room -- the bare bracket trims the subject cut, the brace
1116 // (what the shifted bracket actually types) walks the
1117 // selection past it, so the family reads as one idea under
1118 // one pair of keys.
1119 b(ActionId::TrimIn, "[", false),
1120 b(ActionId::TrimOut, "]", false),
1121 // Loop-trim (DESIGN.md §6, "the modernized Avid trim mode"):
1122 // bare "/" was free.
1123 b(ActionId::LoopTrim, "/", false),
1124 // Trim-to-playhead (debt #42): the whole bracket family is
1125 // already spoken for -- bare `[`/`]` nudge, `{`/`}` walk the
1126 // selection, ctrl+`[`/ctrl+`]` jump sync points -- so this
1127 // takes the one rung left in the same family, ctrl held on
1128 // the shifted bracket (`ctrl+{`/`ctrl+}`, what
1129 // ctrl+shift+[/ctrl+shift+] actually type per this table's
1130 // own shift note above).
1131 b(ActionId::TrimInToPlayhead, "{", true),
1132 b(ActionId::TrimOutToPlayhead, "}", true),
1133 // Dissolve takes ctrl+x: the join it draws on the timeline is
1134 // an X (widgets.rs, dissolve_glyph) -- "d" itself is taken
1135 // both plain (Detach) and, in the keymap's own rebind test,
1136 // as the free chord it rebinds Delete onto, so this reaches
1137 // for the shape instead of the word.
1138 b(ActionId::Dissolve, "x", true),
1139 // The mix card takes "f", for the faders on it: "m" would be
1140 // the word but it is the monitoring mute, which is this
1141 // machine's volume and not the project's -- two things one key
1142 // must not mean.
1143 b(ActionId::Mix, "f", false),
1144 // The snap takes "n", which is what every other editor toggles
1145 // it with: free here, and nowhere near the two keys that delete.
1146 b(ActionId::ToggleSnap, "n", false),
1147 // The subtitles take "t", for the word: free, one press like
1148 // the rest of the things one *looks* at, and nowhere near the
1149 // two keys that delete.
1150 b(ActionId::ToggleSubtitles, "t", false),
1151 // The stand-ins take ctrl+p, the p of the word: the unshifted
1152 // one is the fit policy, and a ctrl chord is right for a switch
1153 // thrown once for a whole session rather than one wanted under
1154 // a hand -- the theme takes ctrl+h for that reason.
1155 b(ActionId::ToggleProxies, "p", true),
1156 // ctrl+o moved to Add files (below, with `ImportSubtitles` --
1157 // display order follows [`ActionId::ALL`]) per DESIGN §11's
1158 // frequency check: a burst-use import command over a
1159 // once-a-project setting. The auto-proxy switch takes "m"
1160 // instead, free and still a stand-in word ("make" -- what
1161 // the switch decides is whether one gets made on import).
1162 b(ActionId::ToggleAutoProxies, "m", true),
1163 // The theme takes ctrl+h -- the h of the word, since "t" is the
1164 // subtitles and ctrl+t takes one off -- and a ctrl chord because
1165 // it is a preference set once, not a stroke wanted under a hand
1166 // that is editing.
1167 b(ActionId::Theme, "h", true),
1168 // Every other player's key for it, and free here: nothing in
1169 // this table answers to "f11" (gpui lowercases the keysym
1170 // name it gets from xkb, same as "f1" below).
1171 b(ActionId::Fullscreen, "f11", false),
1172 // A chord, and the only escape in this table: bare `esc` is the
1173 // stroke a hand throws at anything on screen, and throwing it
1174 // at a running export used to delete an hour of encoding. The
1175 // key stays the one people look for -- the modifier is what
1176 // makes it an intention ([`crate::cancels_export`]).
1177 b(ActionId::CancelExport, "escape", true),
1178 // The help key (DESIGN.md §9, amended 2026-09-09): it swings
1179 // the dock to its KEYS tab, and a second press (or `escape`)
1180 // swings it back -- a toggle, not a hold, not a modal.
1181 // Its own key, not `shift+/`: gpui reports a shifted symbol as
1182 // the glyph itself, so `"?"` is what a stroke of it reports.
1183 b(ActionId::ShowActions, "?", false),
1184 // "w" is free entirely, bare and ctrl both -- nothing else in
1185 // this table answers to it.
1186 b(ActionId::Screenshot, "w", false),
1187 // Bare "y" is free entirely, and unshifted: a preference
1188 // opened as often as the theme, not a switch thrown once a
1189 // session.
1190 b(ActionId::SubtitleStyle, "y", false),
1191 // The consumer-editor convention (Cmd/Ctrl+,) -- free here:
1192 // bare "," is WalkCutPrev, and nothing else answers to the
1193 // ctrl chord.
1194 b(ActionId::Settings, ",", true),
1195 // The standard pane-cycle key on every desktop that has one
1196 // (browsers, IDEs) -- free here, and Tab itself cannot spell
1197 // this: bare Tab is already [`ActionId::Select`] at the root
1198 // (a bare-key rebind would steal clip selection), and its
1199 // shift pair is unspellable in this table's chord (`ctrl`
1200 // only, see [`ActionId::Select`]'s own comment above).
1201 b(ActionId::FocusPanels, "f6", false),
1202 ],
1203 }
1204 }
1205
1206 /// What a stroke means, if anything. `key` is gpui's key name and `ctrl` its
1207 /// control modifier -- the pair the key handler already matches on. There
1208 /// is no shift parameter: see [`Chord`]'s own doc for why.
1209 pub fn lookup(&self, key: &str, ctrl: bool) -> Option<ActionId> {
1210 self.bindings
1211 .iter()
1212 .find(|b| b.chord.ctrl == ctrl && b.chord.key == key)
1213 .map(|b| b.action)
1214 }
1215
1216 /// Every stroke that reaches an action, as one readable phrase: `x or
1217 /// delete`. An action nobody can reach says so rather than reading blank.
1218 pub fn display(&self, action: ActionId) -> String {
1219 let strokes: Vec<String> = self
1220 .bindings
1221 .iter()
1222 .filter(|b| b.action == action)
1223 .map(|b| b.chord.pretty())
1224 .collect();
1225 if strokes.is_empty() {
1226 "unbound".to_string()
1227 } else {
1228 strokes.join(" or ")
1229 }
1230 }
1231
1232 /// The primary chord for `action`, compact ([`Chord::compact`]) -- a
1233 /// badge that has room for one token, not [`Keymap::display`]'s sentence.
1234 /// The first bound stroke wins (`defaults`' own insertion order, and
1235 /// [`parse`]'s "no chord appears twice" leaves at most one anyway); an
1236 /// action with no stroke reads `--` rather than the unbound sentence,
1237 /// since a badge is not a warning.
1238 pub fn chord(&self, action: ActionId) -> String {
1239 self.bindings
1240 .iter()
1241 .find(|b| b.action == action)
1242 .map(|b| b.chord.compact())
1243 .unwrap_or_else(|| "--".to_string())
1244 }
1245
1246 /// Every binding, in display order.
1247 pub fn entries(&self) -> &[Binding] {
1248 &self.bindings
1249 }
1250
1251 /// The keymap in force, and what to tell the user if the file could not be
1252 /// used. A file that is merely absent is the normal case and says nothing;
1253 /// anything else -- unreadable, or a line this parser refuses -- falls back
1254 /// to the defaults *and* is reported, because a keymap silently not applied
1255 /// is a keyboard that has quietly changed under the user.
1256 pub fn load() -> (Self, Option<String>) {
1257 Self::load_from(&Self::config_path())
1258 }
1259
1260 /// All of [`Keymap::load`] but the path, which the config directory decides
1261 /// and a test must not be allowed to.
1262 fn load_from(path: &Path) -> (Self, Option<String>) {
1263 let text = match std::fs::read_to_string(path) {
1264 Ok(text) => text,
1265 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return (Self::defaults(), None),
1266 Err(e) => {
1267 return (
1268 Self::defaults(),
1269 Some(format!(
1270 "KEYBINDINGS IGNORED — {}: {e} — the defaults are in force",
1271 path.display()
1272 )),
1273 );
1274 }
1275 };
1276 match parse(&text) {
1277 Ok((keymap, dropped)) if dropped.is_empty() => (keymap, None),
1278 // The lines it could use are in force; the ones it could not are
1279 // named, and only those are lost.
1280 Ok((keymap, dropped)) => (
1281 keymap,
1282 Some(format!(
1283 "KEYBINDINGS PART-READ — {}, {} — those strokes are unbound",
1284 path.display(),
1285 dropped.join("; ")
1286 )),
1287 ),
1288 Err(e) => (
1289 Self::defaults(),
1290 Some(format!(
1291 "KEYBINDINGS IGNORED — {}, {e} — the defaults are in force",
1292 path.display()
1293 )),
1294 ),
1295 }
1296 }
1297
1298 /// Writes the keymap, atomically, creating the config directory if this is
1299 /// the first save. Until the rename the previous bindings are still the
1300 /// whole truth on disk.
1301 pub fn save(&self) -> std::io::Result<()> {
1302 self.save_to(&Self::config_path())
1303 }
1304
1305 /// All of [`Keymap::save`] but the path, for the same reason as
1306 /// [`Keymap::load_from`].
1307 fn save_to(&self, path: &Path) -> std::io::Result<()> {
1308 let dir = path.parent().unwrap_or(Path::new(".")).to_path_buf();
1309 std::fs::create_dir_all(&dir)?;
1310 let mut part = path.to_path_buf().into_os_string();
1311 part.push(".part");
1312 let part = PathBuf::from(part);
1313 let result = std::fs::File::create(&part)
1314 .and_then(|mut f| {
1315 f.write_all(emit(self).as_bytes())?;
1316 f.sync_all()
1317 })
1318 .and_then(|()| std::fs::rename(&part, path))
1319 .and_then(|()| std::fs::File::open(&dir)?.sync_all());
1320 if result.is_err() {
1321 let _ = std::fs::remove_file(&part);
1322 }
1323 result
1324 }
1325
1326 /// Where the bindings live: the XDG config directory, or `~/.config` when
1327 /// the desktop has not named one.
1328 pub fn config_path() -> PathBuf {
1329 config_path_in(
1330 std::env::var_os("XDG_CONFIG_HOME"),
1331 std::env::var_os("HOME"),
1332 )
1333 }
1334}
1335
1336/// The path rule, with the environment handed in so it can be checked. An
1337/// `XDG_CONFIG_HOME` that is empty is one the spec says to ignore; with no
1338/// `HOME` either there is nowhere but here, and a relative path is still better
1339/// than dropping the file in `/`.
1340fn config_path_in(xdg: Option<OsString>, home: Option<OsString>) -> PathBuf {
1341 let dir = xdg
1342 .filter(|v| !v.is_empty())
1343 .map(PathBuf::from)
1344 .or_else(|| {
1345 home.filter(|v| !v.is_empty())
1346 .map(|h| PathBuf::from(h).join(".config"))
1347 })
1348 .unwrap_or_else(|| PathBuf::from(".config"));
1349 dir.join("edith").join("keybindings")
1350}
1351
1352fn emit(keymap: &Keymap) -> String {
1353 let mut out = String::from(MAGIC);
1354 out.push('\n');
1355 for b in &keymap.bindings {
1356 out.push_str(b.action.name());
1357 out.push(' ');
1358 out.push_str(&b.chord.text());
1359 out.push('\n');
1360 }
1361 out
1362}
1363
1364/// The magic line is the whole of what makes this a keybindings file, so it is
1365/// the only thing refused outright. A *binding* line this parser cannot use is
1366/// dropped instead, and named in the returned warnings: one unusable line used
1367/// to cost every other rebind in the file, which is the user's data. What
1368/// survives is still exactly what emits back, so the by-hand round-trip holds
1369/// for every line that is kept.
1370fn parse(text: &str) -> Result<(Keymap, Vec<String>), String> {
1371 // One trailing newline terminates the last line rather than starting an
1372 // empty one; a second is an empty line and is refused below.
1373 let body = text.strip_suffix('\n').unwrap_or(text);
1374 let mut lines = body.split('\n').enumerate();
1375 let (_, first) = lines.next().unwrap_or((0, ""));
1376 if first != MAGIC {
1377 return Err(match first.strip_prefix("edith-keys ") {
1378 Some(v) => format!("line 1: unsupported version {v}"),
1379 None => "line 1: not a keybindings file".to_string(),
1380 });
1381 }
1382
1383 let mut bindings: Vec<Binding> = Vec::new();
1384 let mut dropped: Vec<String> = Vec::new();
1385 for (i, line) in lines {
1386 let n = i + 1;
1387 let Some((name, chord)) = line.split_once(' ') else {
1388 dropped.push(format!("line {n}: {line:?} is not `<action> <chord>`"));
1389 continue;
1390 };
1391 let Some(action) = ActionId::from_name(name) else {
1392 dropped.push(format!("line {n}: unknown action {name:?}"));
1393 continue;
1394 };
1395 let chord = match Chord::parse(chord, n) {
1396 Ok(chord) => chord,
1397 Err(e) => {
1398 dropped.push(e);
1399 continue;
1400 }
1401 };
1402 // One stroke, one meaning: the second line to claim it would be the
1403 // dead one, and which of them died would depend on line order. The
1404 // first line keeps the stroke, which is the order the file reads in.
1405 if let Some(held) = bindings.iter().find(|b| b.chord == chord) {
1406 dropped.push(format!(
1407 "line {n}: {} is already {}'s",
1408 chord.text(),
1409 held.action.name()
1410 ));
1411 continue;
1412 }
1413 bindings.push(Binding { action, chord });
1414 }
1415 Ok((Keymap { bindings }, dropped))
1416}
1417
1418#[cfg(test)]
1419mod tests {
1420 use engine::scratch::Scratch;
1421
1422 use super::{ActionId, Chord, Keymap, config_path_in, emit, parse};
1423
1424 fn chord(key: &str, ctrl: bool) -> Chord {
1425 Chord {
1426 key: key.to_string(),
1427 ctrl,
1428 }
1429 }
1430
1431 /// A file every line of which the parser could use -- what most assertions
1432 /// are about. A dropped line here is a failure, not a warning.
1433 fn whole(text: &str) -> Keymap {
1434 let (keymap, dropped) = parse(text).expect("a keybindings file");
1435 assert!(dropped.is_empty(), "unexpected dropped lines: {dropped:?}");
1436 keymap
1437 }
1438
1439 #[test]
1440 fn every_default_stroke_reaches_its_action() {
1441 let k = Keymap::defaults();
1442 assert_eq!(k.entries().len(), 78);
1443 // The cut odometer: bare walks one, `<`/`>` (what shift+,/shift+.
1444 // actually type) strides ten.
1445 assert_eq!(k.lookup(".", false), Some(ActionId::WalkCutNext));
1446 assert_eq!(k.lookup(",", false), Some(ActionId::WalkCutPrev));
1447 assert_eq!(k.lookup("/", false), Some(ActionId::LoopTrim));
1448 assert_eq!(k.lookup(">", false), Some(ActionId::WalkCutNext10));
1449 assert_eq!(k.lookup("<", false), Some(ActionId::WalkCutPrev10));
1450 // The trim pair, on its designed bare brackets (DESIGN.md §6).
1451 assert_eq!(k.lookup("[", false), Some(ActionId::TrimIn));
1452 assert_eq!(k.lookup("]", false), Some(ActionId::TrimOut));
1453 // Trim-to-playhead (debt #42): the same family, one rung further.
1454 assert_eq!(k.lookup("{", true), Some(ActionId::TrimInToPlayhead));
1455 assert_eq!(k.lookup("}", true), Some(ActionId::TrimOutToPlayhead));
1456 assert_eq!(k.lookup("f11", false), Some(ActionId::Fullscreen));
1457 assert_eq!(k.lookup("w", false), Some(ActionId::Screenshot));
1458 assert_eq!(k.lookup("y", false), Some(ActionId::SubtitleStyle));
1459 assert_eq!(k.lookup("p", true), Some(ActionId::ToggleProxies));
1460 assert_eq!(k.lookup("m", true), Some(ActionId::ToggleAutoProxies));
1461 assert_eq!(k.lookup("o", true), Some(ActionId::AddFiles));
1462 assert_eq!(k.lookup("l", true), Some(ActionId::PasteFilePath));
1463 assert_eq!(k.lookup("?", false), Some(ActionId::ShowActions));
1464 assert_eq!(k.lookup("h", true), Some(ActionId::Theme));
1465 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
1466 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two
1467 // ends of the timeline.
1468 assert_eq!(k.lookup("left", false), Some(ActionId::StepBack));
1469 assert_eq!(k.lookup("right", false), Some(ActionId::StepForward));
1470 assert_eq!(k.lookup("left", true), Some(ActionId::JumpBack));
1471 assert_eq!(k.lookup("right", true), Some(ActionId::JumpForward));
1472 assert_eq!(k.lookup("home", false), Some(ActionId::GoStart));
1473 assert_eq!(k.lookup("end", false), Some(ActionId::GoEnd));
1474 // ...and the source's own grid, which is neither a frame nor a second:
1475 // the brackets bare select the clip either side, with ctrl they step
1476 // the sync points a cut has to land on to be copied.
1477 assert_eq!(k.lookup("[", true), Some(ActionId::PrevSyncPoint));
1478 assert_eq!(k.lookup("]", true), Some(ActionId::NextSyncPoint));
1479 assert_eq!(k.lookup("}", false), Some(ActionId::SelectNext));
1480 assert_eq!(k.lookup("{", false), Some(ActionId::SelectPrev));
1481 assert_eq!(k.lookup("i", false), Some(ActionId::SetIn));
1482 assert_eq!(k.lookup("o", false), Some(ActionId::SetOut));
1483 assert_eq!(k.lookup("u", true), Some(ActionId::ClearRange));
1484 assert_eq!(k.lookup("e", false), Some(ActionId::Export));
1485 assert_eq!(k.lookup("s", true), Some(ActionId::Save));
1486 assert_eq!(k.lookup("c", true), Some(ActionId::Copy));
1487 assert_eq!(k.lookup("v", true), Some(ActionId::Paste));
1488 assert_eq!(k.lookup("s", false), Some(ActionId::Cut));
1489 assert_eq!(k.lookup("g", false), Some(ActionId::Regroup));
1490 // The take apart / put back pair beside it.
1491 assert_eq!(k.lookup("d", false), Some(ActionId::Detach));
1492 assert_eq!(k.lookup("g", true), Some(ActionId::Group));
1493 // The keyboard's way onto a clip, and the pair that walks the lane.
1494 assert_eq!(k.lookup("tab", false), Some(ActionId::Select));
1495 assert_eq!(k.lookup("}", false), Some(ActionId::SelectNext));
1496 assert_eq!(k.lookup("{", false), Some(ActionId::SelectPrev));
1497 assert_eq!(k.lookup("x", false), Some(ActionId::Delete));
1498 assert_eq!(k.lookup("delete", false), Some(ActionId::Delete));
1499 assert_eq!(k.lookup("l", false), Some(ActionId::Lift));
1500 assert_eq!(k.lookup("k", false), Some(ActionId::Color));
1501 assert_eq!(k.lookup("p", false), Some(ActionId::Fit));
1502 assert_eq!(k.lookup("r", true), Some(ActionId::Resolution));
1503 assert_eq!(k.lookup("z", false), Some(ActionId::Undo));
1504 assert_eq!(k.lookup("z", true), Some(ActionId::Undo));
1505 assert_eq!(k.lookup("y", true), Some(ActionId::Redo));
1506 // The track keys are the bare letters; the ctrl ones stay copy/paste.
1507 assert_eq!(k.lookup("v", false), Some(ActionId::AddVideoLane));
1508 assert_eq!(k.lookup("a", false), Some(ActionId::AddAudioLane));
1509 // ...and the ctrl ones take a track away, out of the way of a stray
1510 // press. Ctrl+v is the paste, so the video one sits beside it; ctrl+a
1511 // is the select-all every editor shares, so the audio one sits beside
1512 // its own letter instead.
1513 assert_eq!(k.lookup("b", true), Some(ActionId::RemoveVideoLane));
1514 assert_eq!(k.lookup("q", true), Some(ActionId::RemoveAudioLane));
1515 assert_eq!(k.lookup("a", true), Some(ActionId::SelectAll));
1516 // The subtitle pair, the third kind of track: the initial adds and the
1517 // subtitle letter's chord takes it back.
1518 assert_eq!(k.lookup("c", false), Some(ActionId::AddSubtitleLane));
1519 assert_eq!(k.lookup("t", true), Some(ActionId::RemoveSubtitleLane));
1520 // ...and the palette's own door, which adds no track to the timeline.
1521 assert_eq!(k.lookup("i", true), Some(ActionId::ImportSubtitles));
1522 assert_eq!(k.lookup("m", false), Some(ActionId::ToggleMute));
1523 assert_eq!(k.lookup("q", false), Some(ActionId::Equalizer));
1524 // The volume pair is the unshifted one, so neither needs a modifier
1525 // and neither is the "+" gpui reports for shift+=.
1526 assert_eq!(k.lookup("=", false), Some(ActionId::VolumeUp));
1527 assert_eq!(k.lookup("-", false), Some(ActionId::VolumeDown));
1528 assert_eq!(k.lookup("+", false), None);
1529 // The chord cancels an export; bare escape falls through to Deselect.
1530 assert_eq!(k.lookup("escape", true), Some(ActionId::CancelExport));
1531 assert_eq!(k.lookup("escape", false), Some(ActionId::Deselect));
1532 // The modifier is half the chord: ctrl+e is not e.
1533 assert_eq!(k.lookup("e", true), None);
1534 assert_eq!(k.lookup("space", true), None);
1535 assert_eq!(k.lookup("j", false), Some(ActionId::Speed));
1536 assert_eq!(k.lookup("u", false), Some(ActionId::Silence));
1537 assert_eq!(k.lookup("j", true), None);
1538 // Nothing is bound twice, or lookup's first match would be a coin toss.
1539 for (i, a) in k.entries().iter().enumerate() {
1540 assert!(
1541 !k.entries()[i + 1..].iter().any(|b| b.chord == a.chord),
1542 "{:?} bound twice",
1543 a.chord
1544 );
1545 }
1546 }
1547
1548 #[test]
1549 fn a_file_survives_the_round_trip_exactly() {
1550 let text = emit(&Keymap::defaults());
1551 assert!(text.starts_with("edith-keys 1\nplay space\n"));
1552 assert!(text.contains("save ctrl+s\n"));
1553 assert!(text.contains("cancel-export ctrl+escape\n"));
1554 // Both directions: the file this writes is the file it reads back, and
1555 // a file read in comes out byte for byte as it went.
1556 assert_eq!(whole(&text), Keymap::defaults());
1557 assert_eq!(emit(&whole(&text)), text);
1558 let handwritten = "edith-keys 1\nundo ctrl+z\nplay space\n";
1559 assert_eq!(emit(&whole(handwritten)), handwritten);
1560 // A keymap that binds nothing is legal -- and unusable, which is the
1561 // user's business, not the parser's.
1562 assert_eq!(whole("edith-keys 1\n").entries(), &[]);
1563 }
1564
1565 #[test]
1566 fn every_refusal_names_its_line() {
1567 // Only the first line refuses the whole file.
1568 let err = |text: &str| parse(text).unwrap_err();
1569 assert_eq!(err(""), "line 1: not a keybindings file");
1570 assert_eq!(err("nonsense\n"), "line 1: not a keybindings file");
1571 assert_eq!(err("edith-keys 2\n"), "line 1: unsupported version 2");
1572
1573 // Every other kind of bad line costs that line and nothing else.
1574 let dropped = |text: &str| parse(text).unwrap().1;
1575 assert_eq!(
1576 dropped("edith-keys 1\nfly space\n"),
1577 ["line 2: unknown action \"fly\""]
1578 );
1579 assert_eq!(
1580 dropped("edith-keys 1\nplay space\nplayspace\n"),
1581 ["line 3: \"playspace\" is not `<action> <chord>`"]
1582 );
1583 // An empty line is not optional whitespace, it is a line.
1584 assert_eq!(
1585 dropped("edith-keys 1\n\n"),
1586 ["line 2: \"\" is not `<action> <chord>`"]
1587 );
1588 assert_eq!(
1589 dropped("edith-keys 1\nplay ctrl+alt+x\n"),
1590 ["line 2: \"ctrl+alt+x\" is not a chord"]
1591 );
1592 assert_eq!(
1593 dropped("edith-keys 1\nplay ctrl+\n"),
1594 ["line 2: \"ctrl+\" is not a chord"]
1595 );
1596 // gpui reports lowercase key names, so an uppercase one would simply
1597 // never match -- dropped rather than quietly dead.
1598 assert_eq!(
1599 dropped("edith-keys 1\nplay X\n"),
1600 ["line 2: \"X\" is not a chord"]
1601 );
1602 // The same stroke twice: whichever line lost would depend on order, so
1603 // the second one is the one that goes.
1604 assert_eq!(
1605 dropped("edith-keys 1\nplay space\ncut space\n"),
1606 ["line 3: space is already play's"]
1607 );
1608 }
1609
1610 /// The rebind data-loss path: one line the parser cannot use must not cost
1611 /// the rebinds around it (a `capture` of shift+= wrote `play +`, and the
1612 /// next load threw the whole file away and went back to the defaults).
1613 #[test]
1614 fn one_bad_line_costs_only_that_line() {
1615 let text = "edith-keys 1\nplay +\nexport ctrl+w\ncut j\n";
1616 let (keymap, dropped) = parse(text).expect("the magic line is still good");
1617 assert_eq!(dropped, ["line 2: \"+\" is not a chord"]);
1618 // The lines around it are in force, which is the whole point.
1619 assert_eq!(keymap.lookup("w", true), Some(ActionId::Export));
1620 assert_eq!(keymap.lookup("j", false), Some(ActionId::Cut));
1621 // ...and the one that went is unbound, not silently something else.
1622 assert_eq!(keymap.display(ActionId::Play), "unbound");
1623 // What survives still round-trips: the kept lines emit back as read.
1624 assert_eq!(emit(&keymap), "edith-keys 1\nexport ctrl+w\ncut j\n");
1625
1626 // The notice names the line and the file, and the defaults do *not*
1627 // take over -- that was the data loss.
1628 let dir = Scratch::dir("edith-keymap-drop");
1629 let path = dir.join("edith").join("keybindings");
1630 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1631 std::fs::write(&path, text).unwrap();
1632 let (read, notice) = Keymap::load_from(&path);
1633 assert_eq!(read, keymap);
1634 let notice = notice.expect("a part-read file must say so");
1635 assert!(notice.contains("line 2:"), "{notice}");
1636 assert!(notice.contains("keybindings"), "{notice}");
1637 std::fs::remove_dir_all(&dir).ok();
1638 }
1639
1640 /// The other half of the same bug: a stroke the file cannot spell is refused
1641 /// at the capture, before it can ever be written.
1642 #[test]
1643 fn only_a_stroke_the_file_can_spell_is_bindable() {
1644 for (key, ctrl) in [
1645 ("space", false),
1646 ("=", false),
1647 ("s", true),
1648 ("escape", false),
1649 ] {
1650 assert!(chord(key, ctrl).bindable(), "{key}");
1651 }
1652 // gpui's name for shift+=, and the grammar's own separator.
1653 assert!(!chord("+", false).bindable());
1654 assert!(!chord("+", true).bindable());
1655 // The rest of what `Chord::parse` will not take back.
1656 assert!(!chord("", false).bindable());
1657 assert!(!chord("X", false).bindable());
1658 assert!(!chord("page up", false).bindable());
1659 // A bindable chord is one the file's own grammar can spell: what it
1660 // writes is what the next load reads, for every stroke that passes
1661 // here.
1662 let k = whole("edith-keys 1\nplay ctrl+w\n");
1663 assert_eq!(whole(&emit(&k)), k);
1664 }
1665
1666 #[test]
1667 fn display_reads_as_a_person_would_say_it() {
1668 let k = Keymap::defaults();
1669 assert_eq!(k.display(ActionId::Play), "space");
1670 assert_eq!(k.display(ActionId::Save), "ctrl+s");
1671 assert_eq!(k.display(ActionId::Delete), "x or delete");
1672 assert_eq!(k.display(ActionId::Undo), "z or ctrl+z");
1673 // The one key whose common name is not gpui's.
1674 assert_eq!(k.display(ActionId::CancelExport), "ctrl+esc");
1675 assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound");
1676 // The label is the editor's column, and never the file's word for it.
1677 assert_eq!(ActionId::CancelExport.label(), "Cancel export");
1678 assert_eq!(k.display(ActionId::ToggleSnap), "n");
1679 assert_eq!(k.display(ActionId::ShowActions), "?");
1680 assert_eq!(k.display(ActionId::ToggleSubtitles), "t");
1681 assert_eq!(k.display(ActionId::ZoomIn), "ctrl+=");
1682 }
1683
1684 /// [`Keymap::chord`] is the badge's one token, not [`Keymap::display`]'s
1685 /// sentence: the primary (first-bound) stroke only, `^` for ctrl, and the
1686 /// short names a glyph badge actually has room for.
1687 #[test]
1688 fn chord_is_the_primary_stroke_compact() {
1689 let k = Keymap::defaults();
1690 assert_eq!(k.chord(ActionId::Delete), "x");
1691 assert_eq!(k.chord(ActionId::Undo), "z");
1692 assert_eq!(k.chord(ActionId::AddFiles), "^o");
1693 assert_eq!(k.chord(ActionId::CancelExport), "^esc");
1694 assert_eq!(k.chord(ActionId::Play), "spc");
1695 assert_eq!(whole("edith-keys 1\n").chord(ActionId::Cut), "--");
1696 }
1697
1698 #[test]
1699 fn a_saved_keymap_comes_back_off_the_disk() {
1700 // Its own directory, never the real config one: this test writes.
1701 let dir = Scratch::dir("edith-keymap");
1702 let path = dir.join("edith").join("keybindings");
1703 // A defaults file with Export's own line swapped for a free stroke --
1704 // parsed rather than rebound, since nothing left in the API mutates
1705 // a `Keymap` in place.
1706 let text: String = emit(&Keymap::defaults())
1707 .lines()
1708 .filter(|l| !l.starts_with("export "))
1709 .chain(std::iter::once("export ctrl+w"))
1710 .collect::<Vec<_>>()
1711 .join("\n")
1712 + "\n";
1713 let written = whole(&text);
1714 // The config directory does not exist yet -- the first save makes it.
1715 written.save_to(&path).unwrap();
1716 let (read, notice) = Keymap::load_from(&path);
1717 assert_eq!(notice, None);
1718 assert_eq!(read, written);
1719 assert_eq!(read.lookup("w", true), Some(ActionId::Export));
1720 assert_eq!(read.lookup("e", false), None);
1721 // The rename left nothing half-written behind.
1722 assert!(!dir.join("edith").join("keybindings.part").exists());
1723 // A file that is merely absent is not an error and says nothing.
1724 let (fresh, notice) = Keymap::load_from(&dir.join("nothing-here"));
1725 assert_eq!(fresh, Keymap::defaults());
1726 assert_eq!(notice, None);
1727 // A file that is not one at all falls back whole, and names its line.
1728 std::fs::write(&path, "edith-keys 9\nplay space\n").unwrap();
1729 let (fallback, notice) = Keymap::load_from(&path);
1730 assert_eq!(fallback, Keymap::defaults());
1731 let notice = notice.expect("a refused file must say so");
1732 assert!(notice.contains("line 1:"), "{notice}");
1733 assert!(notice.contains("keybindings"), "{notice}");
1734 // One unusable line inside a good file costs that line only -- the
1735 // defaults do not come back over the rebinds that read fine.
1736 std::fs::write(&path, "edith-keys 1\nplay ctrl+alt+x\nexport ctrl+w\n").unwrap();
1737 let (kept, notice) = Keymap::load_from(&path);
1738 assert_eq!(kept.lookup("w", true), Some(ActionId::Export));
1739 assert_eq!(kept.display(ActionId::Play), "unbound");
1740 let notice = notice.expect("a part-read file must say so");
1741 assert!(notice.contains("line 2:"), "{notice}");
1742 assert!(notice.contains("keybindings"), "{notice}");
1743 // Saving over it is a whole replacement, not an edit.
1744 Keymap::defaults().save_to(&path).unwrap();
1745 assert_eq!(Keymap::load_from(&path), (Keymap::defaults(), None));
1746 std::fs::remove_dir_all(&dir).ok();
1747 }
1748
1749 #[test]
1750 fn the_config_path_follows_xdg_then_home() {
1751 let p = |xdg: Option<&str>, home: Option<&str>| {
1752 config_path_in(xdg.map(Into::into), home.map(Into::into))
1753 };
1754 assert_eq!(
1755 p(Some("/x/config"), Some("/home/u")),
1756 std::path::Path::new("/x/config/edith/keybindings")
1757 );
1758 assert_eq!(
1759 p(None, Some("/home/u")),
1760 std::path::Path::new("/home/u/.config/edith/keybindings")
1761 );
1762 // An empty XDG_CONFIG_HOME is one the spec says to ignore.
1763 assert_eq!(
1764 p(Some(""), Some("/home/u")),
1765 std::path::Path::new("/home/u/.config/edith/keybindings")
1766 );
1767 // Nowhere to put it but here -- still never `/edith/keybindings`.
1768 assert_eq!(
1769 p(None, None),
1770 std::path::Path::new(".config/edith/keybindings")
1771 );
1772 }
1773}