forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBf2bee6bTahinli2 months ago781 commits

keymap.rs1890 lines, 87.7 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
616/// The codec row's keys, from the export card's own table. Typed out here once,
617/// it named six of the seven codecs the same row's label advertised -- OGG had
618/// a key (`o`) that this card never said.
619fn codec_chord() -> String {
620 crate::FORMATS
621 .iter()
622 .map(|(_, stroke, ..)| *stroke)
623 .filter(|stroke| !stroke.is_empty())
624 .collect::<Vec<_>>()
625 .join(" / ")
626}
627
628/// The preset row's keys, from [`crate::ExportPreset::key`] -- `Custom`
629/// excepted, which shares Advanced's own `s` and so is that row's line, not a
630/// second one here.
631fn preset_chord() -> String {
632 crate::ExportPreset::ALL
633 .into_iter()
634 .filter(|p| *p != crate::ExportPreset::Custom)
635 .map(|p| p.key())
636 .collect::<Vec<_>>()
637 .join(" / ")
638}
639
640pub static FIXED: std::sync::LazyLock<[Fixed; 35]> = std::sync::LazyLock::new(|| {
641 [
642 // Not a chord at all but a way of pressing one, and the only place the
643 // editor can say so: holding a key that moves a *value* runs it, and
644 // holding anything else still does what one press did.
645 Fixed {
646 chord: "hold ← → ↑ ↓".into(),
647 label: "Run a card's slider, or the volume and zoom keys, while held",
648 category: Category::View,
649 reach: Reach::Gesture,
650 },
651 Fixed {
652 chord: "esc".into(),
653 label: "Close this card or menu, or cancel a capture",
654 category: Category::View,
655 reach: Reach::Gesture,
656 },
657 // An open choice list is driven by the keyboard as well as clicked: the
658 // list is the door to a setting, and a door only a pointer opens is one
659 // half of this editor's users cannot use.
660 Fixed {
661 chord: "↑ ↓ enter".into(),
662 label: "Move through an open choice list, and take the row",
663 category: Category::View,
664 reach: Reach::Click("picker-row"),
665 },
666 Fixed {
667 chord: "n".into(),
668 label: "Open the custom export bitrate field — ↑↓ step it",
669 category: Category::File,
670 reach: Reach::Click("quality"),
671 },
672 Fixed {
673 chord: "0–9".into(),
674 label: "Type into that field — nothing outside it",
675 category: Category::File,
676 reach: Reach::Click("mbps-up"),
677 },
678 Fixed {
679 chord: codec_chord(),
680 label: "Pick the export codec: H.264, AV1, HEVC, WAV, FLAC, MP3 or OGG",
681 category: Category::File,
682 reach: Reach::Click("format"),
683 },
684 // The rest of the export card's own rows, each on the letter its row is
685 // named after. They shadow the clip keys of the same letter while the card
686 // is up, exactly as its digits shadow nothing and its arrows would: a modal
687 // card owns the keyboard, and cutting a clip under it is not a thing that
688 // can happen anyway.
689 Fixed {
690 chord: "c".into(),
691 label: "Switch the export container: Matroska or MP4",
692 category: Category::File,
693 reach: Reach::Click("container"),
694 },
695 Fixed {
696 chord: "q".into(),
697 label: "Step through the export quality rows",
698 category: Category::File,
699 reach: Reach::Click("quality"),
700 },
701 Fixed {
702 chord: "b".into(),
703 label: "Step through the export sound bitrates",
704 category: Category::File,
705 reach: Reach::Click("sound"),
706 },
707 Fixed {
708 chord: "e".into(),
709 label: "Step the export encoder seat: Auto, Hardware or Software",
710 category: Category::File,
711 reach: Reach::Click("encoder"),
712 },
713 Fixed {
714 chord: "d".into(),
715 label: "Choose where the export is written",
716 category: Category::File,
717 reach: Reach::Click("destination"),
718 },
719 Fixed {
720 chord: preset_chord(),
721 label: "Pick an export bundle: Web, Small file, Master or Audio only",
722 category: Category::File,
723 reach: Reach::Click("preset"),
724 },
725 Fixed {
726 chord: "s".into(),
727 label: "Export card: open or close the Advanced pane",
728 category: Category::File,
729 reach: Reach::Click("export-advanced"),
730 },
731 Fixed {
732 chord: "g".into(),
733 label: "Export card: sections or one flat list",
734 category: Category::File,
735 reach: Reach::Click("export-layout"),
736 },
737 Fixed {
738 chord: "r".into(),
739 label: "Export card: the formats with no encoder as rows or as one line",
740 category: Category::File,
741 reach: Reach::Click("export-refusals"),
742 },
743 Fixed {
744 chord: "enter".into(),
745 label: "Start the export — or commit the bitrate field",
746 category: Category::File,
747 reach: Reach::Click("export-confirm"),
748 },
749 Fixed {
750 chord: "backspace".into(),
751 label: "Erase a digit in the bitrate field",
752 category: Category::File,
753 reach: Reach::Click("mbps-down"),
754 },
755 // The equalizer card's own input, for the same reason the export card has
756 // its own: a band nothing but a drag can reach is a band half the users of
757 // this editor cannot move at all. Card-local, so none of them is bindable.
758 Fixed {
759 chord: "1–9, 0".into(),
760 label: "Pick an equalizer band",
761 category: Category::Audio,
762 reach: Reach::Click("eq-graph"),
763 },
764 Fixed {
765 chord: "up".into(),
766 label: "Raise the picked band 1 dB",
767 category: Category::Audio,
768 reach: Reach::Click("eq-gain-up"),
769 },
770 Fixed {
771 chord: "down".into(),
772 label: "Lower the picked band 1 dB",
773 category: Category::Audio,
774 reach: Reach::Click("eq-gain-down"),
775 },
776 Fixed {
777 chord: "← / →".into(),
778 label: "Move the picked band down or up in frequency",
779 category: Category::Audio,
780 reach: Reach::Click("eq-freq-up"),
781 },
782 Fixed {
783 chord: "shift ← / →".into(),
784 label: "Widen or narrow the picked band (its Q)",
785 category: Category::Audio,
786 reach: Reach::Click("eq-q-wider"),
787 },
788 Fixed {
789 chord: "a".into(),
790 label: "Add an equalizer band beside the picked one",
791 category: Category::Audio,
792 reach: Reach::Click("eq-add"),
793 },
794 Fixed {
795 chord: "x".into(),
796 label: "Remove the picked equalizer band",
797 category: Category::Audio,
798 reach: Reach::Click("eq-remove"),
799 },
800 Fixed {
801 chord: "f".into(),
802 label: "Flatten the picked band (double-click does the same)",
803 category: Category::Audio,
804 reach: Reach::Click("eq-flat-band"),
805 },
806 Fixed {
807 chord: "r".into(),
808 label: "Flatten every band",
809 category: Category::Audio,
810 reach: Reach::Click("eq-reset"),
811 },
812 Fixed {
813 chord: "s".into(),
814 label: "Show or hide the spectrum behind the curve",
815 category: Category::Audio,
816 reach: Reach::Click("eq-spectrum"),
817 },
818 // The colour card's own three, which mean nothing outside it -- the same
819 // card-local input the export card's digits are.
820 Fixed {
821 chord: "↑ / ↓".into(),
822 label: "Pick a colour slider",
823 category: Category::Clips,
824 reach: Reach::Click("color-row"),
825 },
826 Fixed {
827 chord: "← / →".into(),
828 label: "Move the picked colour slider",
829 category: Category::Clips,
830 reach: Reach::Click("color-bar"),
831 },
832 Fixed {
833 chord: "r".into(),
834 label: "Take the colour grade off the clip",
835 category: Category::Clips,
836 reach: Reach::Click("color-reset"),
837 },
838 // The transform card's own three, the same shape as the colour card's:
839 // up/down pick a band (position, scale, rotate, crop), left/right move
840 // it, and `r` resets to identity.
841 Fixed {
842 chord: "↑ / ↓".into(),
843 label: "Pick a transform band",
844 category: Category::Clips,
845 reach: Reach::Click("transform-row"),
846 },
847 Fixed {
848 chord: "← / →".into(),
849 label: "Move the picked transform band",
850 category: Category::Clips,
851 reach: Reach::Click("transform-bar"),
852 },
853 Fixed {
854 chord: "r".into(),
855 label: "Take the transform off the clip",
856 category: Category::Clips,
857 reach: Reach::Click("transform-reset"),
858 },
859 // The silence card's two apply keys. Card-local like every stroke above --
860 // they mean nothing while it is closed -- but the card is the one place in
861 // this editor where a key rewrites forty places at once, so both of them
862 // are listed rather than hidden in the card's own hint line.
863 Fixed {
864 chord: "enter".into(),
865 label: "Cut every silence the card found",
866 category: Category::Clips,
867 reach: Reach::Click("silence-apply"),
868 },
869 Fixed {
870 chord: "f".into(),
871 label: "Speed the silences up instead of cutting them",
872 category: Category::Clips,
873 reach: Reach::Click("silence-apply"),
874 },
875 ]
876});
877
878/// A stroke as the key handler sees it: gpui's key name plus the one
879/// modifier this editor binds. Nothing else is a chord here -- alt is part
880/// of the key name gpui reports, and a second modifier would need the file
881/// format to grow before it could be spelled.
882///
883/// There is no `shift` field. gpui 0.2.2 (linux/platform.rs:909-917) clears
884/// the shift modifier for any single-char key whose upper and lower case are
885/// the same -- every symbol key (`,` `.` `[` `]` `/` `=` ...) -- so a chord
886/// carrying `shift` could never be struck for any of them; the shifted
887/// stroke arrives instead as the key it types (`shift+.` is the key `>`).
888/// The one place this editor wanted shift on a symbol (the odometer's
889/// stride-ten, DESIGN.md §6) is bound on that literal key instead
890/// (`keymap.rs`'s own `defaults`), and a non-symbol key that wants shift
891/// (the EQ card's arrows) reads `event.keystroke.modifiers.shift` straight
892/// off the keystroke, upstream of this struct entirely -- so the field had
893/// zero production callers and is gone rather than kept dead.
894#[derive(Clone, PartialEq, Eq, Debug)]
895pub struct Chord {
896 pub key: String,
897 pub ctrl: bool,
898}
899
900impl Chord {
901 /// The file's spelling, and the only one [`parse`] accepts back.
902 fn text(&self) -> String {
903 if self.ctrl {
904 format!("ctrl+{}", self.key)
905 } else {
906 self.key.clone()
907 }
908 }
909
910 /// The spelling a person reads. Identical to [`Chord::text`] but for the one
911 /// key whose usual name is shorter than gpui's. Public because a
912 /// keybindings row shows one chord, where [`Keymap::display`] shows every
913 /// chord an action answers to.
914 pub fn pretty(&self) -> String {
915 let key = if self.key == "escape" {
916 "esc"
917 } else {
918 &self.key
919 };
920 if self.ctrl {
921 format!("ctrl+{key}")
922 } else {
923 key.to_string()
924 }
925 }
926
927 /// The spelling a badge with room for one token reads (MOCK-SPEC.md
928 /// "Spine": `del`, `z`, not `x or delete`, `ctrl+z`): `^` in place of
929 /// `ctrl+`, and the handful of key names whose everyday short form isn't
930 /// gpui's own (`delete` -> `del`, `escape` -> `esc`, `space` -> `spc`).
931 /// [`Chord::pretty`] stays the keys overlay's own spelling -- this is for
932 /// a glyph badge, not the full truth.
933 pub fn compact(&self) -> String {
934 let key = match self.key.as_str() {
935 "escape" => "esc",
936 "delete" => "del",
937 "space" => "spc",
938 other => other,
939 };
940 if self.ctrl {
941 format!("^{key}")
942 } else {
943 key.to_string()
944 }
945 }
946
947 /// Whether the file can carry this stroke and read it back as itself. gpui
948 /// reports strokes this format cannot spell -- shift+= arrives as the key
949 /// `"+"`, which is the chord grammar's own separator -- and binding one
950 /// would write a line the next load has to drop. Asked before a capture is
951 /// taken, so a stroke that cannot be saved is refused while the user is
952 /// still looking at the row.
953 pub fn bindable(&self) -> bool {
954 Chord::parse(&self.text(), 0).is_ok_and(|round_trip| round_trip == *self)
955 }
956
957 /// Strict: exactly one optional `ctrl+`, then a key gpui could have
958 /// reported. A spelling this cannot emit back unchanged is refused
959 /// rather than normalised, because the round-trip is what makes the file
960 /// editable by hand at all.
961 fn parse(text: &str, n: usize) -> Result<Self, String> {
962 let (ctrl, key) = match text.strip_prefix("ctrl+") {
963 Some(rest) => (true, rest),
964 None => (false, text),
965 };
966 if key.is_empty()
967 || key.contains(' ')
968 || key.contains('+')
969 || key.chars().any(|c| c.is_ascii_uppercase())
970 {
971 return Err(format!("line {n}: {text:?} is not a chord"));
972 }
973 Ok(Chord {
974 key: key.to_string(),
975 ctrl,
976 })
977 }
978}
979
980/// One stroke, one action. Two strokes for the same action are two bindings.
981#[derive(Clone, PartialEq, Eq, Debug)]
982pub struct Binding {
983 pub action: ActionId,
984 pub chord: Chord,
985}
986
987/// Every binding in force, in display order. No chord appears twice -- that is
988/// the invariant [`parse`] defends, and it is what lets [`Keymap::lookup`]
989/// answer with the first match.
990#[derive(Clone, PartialEq, Eq, Debug)]
991pub struct Keymap {
992 bindings: Vec<Binding>,
993}
994
995impl Keymap {
996 /// The bindings the editor has always had, in the order the editor lists
997 /// them. Delete and undo get two strokes each because both have always
998 /// answered to two.
999 pub fn defaults() -> Self {
1000 let b = |action, key: &str, ctrl| Binding {
1001 action,
1002 chord: Chord {
1003 key: key.to_string(),
1004 ctrl,
1005 },
1006 };
1007 Keymap {
1008 bindings: vec![
1009 b(ActionId::Play, "space", false),
1010 // "r" for repeat, free and bare: its ctrl chord is already the
1011 // project resolution, and the two read as a pair the way the
1012 // mute and its level do.
1013 b(ActionId::Loop, "r", false),
1014 // Seeking without a pointer, on the keys every player already
1015 // seeks with (gpui names them "left"/"right"/"home"/"end",
1016 // platform.rs:872-877). The colour card reads the same arrows
1017 // for its sliders, but a card answers the stroke and returns
1018 // before the keymap is consulted at all -- so these move the
1019 // playhead only while no card is open.
1020 b(ActionId::StepBack, "left", false),
1021 b(ActionId::StepForward, "right", false),
1022 b(ActionId::JumpBack, "left", true),
1023 b(ActionId::JumpForward, "right", true),
1024 b(ActionId::GoStart, "home", false),
1025 b(ActionId::GoEnd, "end", false),
1026 // The sync-point pair, on the brackets that already mean "the
1027 // one before / the one after" here (they select the clip either
1028 // side) -- with ctrl, which was free on both, because these
1029 // step through the same timeline by the source's own grid.
1030 b(ActionId::PrevSyncPoint, "[", true),
1031 b(ActionId::NextSyncPoint, "]", true),
1032 // The cut odometer (DESIGN.md §6): bare walks one cut, shift
1033 // strides ten. gpui 0.2.2 (linux/platform.rs:909-917) clears
1034 // the shift modifier for any single-char key whose upper and
1035 // lower case are the same -- every one of these symbols --
1036 // so `shift+.` never arrives; what arrives instead is the
1037 // key the shifted stroke actually types, `>`/`<`. Bound
1038 // directly, on the same physical chord, since that is what
1039 // the platform hands the key handler.
1040 b(ActionId::WalkCutNext, ".", false),
1041 b(ActionId::WalkCutPrev, ",", false),
1042 b(ActionId::WalkCutNext10, ">", false),
1043 b(ActionId::WalkCutPrev10, "<", false),
1044 // The mark pair, on the letters every editor already means them
1045 // by: bare, since a mark is set as often as a step and nothing
1046 // else in this table answers to either.
1047 b(ActionId::SetIn, "i", false),
1048 b(ActionId::SetOut, "o", false),
1049 // The clear takes the ctrl chord: not a stroke to hit setting
1050 // one mark and reaching for the other. Free -- "u" bare is the
1051 // silence card, and nothing else in this table answers to
1052 // ctrl+u.
1053 b(ActionId::ClearRange, "u", true),
1054 b(ActionId::Export, "e", false),
1055 b(ActionId::Save, "s", true),
1056 b(ActionId::Copy, "c", true),
1057 b(ActionId::Paste, "v", true),
1058 // Split, on the bare letter DESIGN.md §6 names for it: the
1059 // burst-use command owns the cheap key (§11's frequency
1060 // argument). Bare "c" moves to AddSubtitleLane below, which
1061 // frees up cleanly since a subtitle track also opens on its
1062 // own initial: captions.
1063 b(ActionId::Cut, "s", false),
1064 // The two lane keys, on the letters they are named after: both
1065 // were free, and neither is next to a key that edits.
1066 b(ActionId::Regroup, "g", false),
1067 // The pair that takes a take apart and puts it back: "d" for
1068 // detach was free and is one press like the rest of the clip
1069 // keys, and grouping two clips is the "g" that rejoins a cut one
1070 // lane over -- the chord beside it, so the two read as one idea.
1071 b(ActionId::Detach, "d", false),
1072 b(ActionId::Group, "g", true),
1073 // Selection without a pointer. Tab is what a keyboard already
1074 // means by "move on to the next thing", and the two braces
1075 // are the pair either side of it in the lane -- shift+tab is
1076 // the obvious partner and is unspellable here, since a chord
1077 // carries only ctrl and `parse` refuses an uppercase key. Bare
1078 // brackets are DESIGN.md §6's own trim pair now, so selection
1079 // takes the braces the shifted brackets actually type: same
1080 // two keys, telling "walk the lane" apart from "trim the cut".
1081 b(ActionId::Select, "tab", false),
1082 // Same platform fact as the odometer above: shift+] never
1083 // arrives as shift+], it arrives as the key `}` (and shift+[
1084 // as `{`) -- bound on the literal the platform delivers.
1085 b(ActionId::SelectNext, "}", false),
1086 b(ActionId::SelectPrev, "{", false),
1087 // Select-all, on the chord every editor and every text field
1088 // already means it by -- which is why the audio-lane removal
1089 // below had to move off ctrl+a: a stroke that universal was
1090 // never really the removal's to keep.
1091 b(ActionId::SelectAll, "a", true),
1092 // Bare escape, last in the precedence chain behind every card,
1093 // search and fullscreen close (render.rs) -- just empties the
1094 // selection when nothing else claims the key.
1095 b(ActionId::Deselect, "escape", false),
1096 b(ActionId::Delete, "x", false),
1097 b(ActionId::Delete, "delete", false),
1098 b(ActionId::Lift, "l", false),
1099 // The c of colour is now AddSubtitleLane's (captions) and
1100 // ctrl+c is Copy, so the grade takes k: free, next to nothing
1101 // that edits, and one press like the
1102 // rest of the clip keys.
1103 b(ActionId::Color, "k", false),
1104 // The placement card takes the ctrl chord of the grade's own
1105 // key: the two sit beside each other on a clip and neither
1106 // steals a bare letter that already means something else.
1107 b(ActionId::Transform, "k", true),
1108 // The fit policy is a clip key like the grade beside it: "p" for
1109 // policy, free, and one press like the rest of them. The project
1110 // resolution is not a clip key and takes a ctrl chord, next to
1111 // nothing that edits and out of the way of a stray press --
1112 // it changes what every clip is composed onto.
1113 b(ActionId::Fit, "p", false),
1114 b(ActionId::Resolution, "r", true),
1115 // The zoom pair, on the chords every editor and every browser
1116 // magnifies with. The bare "=" and "-" are the volume keys, so
1117 // these take the ctrl versions of them -- and ctrl+0 is the
1118 // "back to 100%" of the same family, which here is the whole
1119 // timeline across the bed.
1120 b(ActionId::ZoomIn, "=", true),
1121 b(ActionId::ZoomOut, "-", true),
1122 b(ActionId::ZoomFit, "0", true),
1123 b(ActionId::Undo, "z", false),
1124 b(ActionId::Undo, "z", true),
1125 // Bare "y" is SubtitleStyle's, so redo takes only the ctrl
1126 // chord -- the conventional pairing with ctrl+z either way.
1127 b(ActionId::Redo, "y", true),
1128 // The unshifted initials of what they add. Both were free --
1129 // the copy and paste chords are the *ctrl* ones -- and a track
1130 // is added often enough to deserve a key that is one press.
1131 b(ActionId::AddVideoLane, "v", false),
1132 b(ActionId::AddAudioLane, "a", false),
1133 // ...and the pair that takes one back, on ctrl chords: removing
1134 // a track is not a stroke to hit by accident (the resolution key
1135 // is out of the way for the same reason). Ctrl+v would be the
1136 // matching initial and is the paste, so the video one takes the
1137 // key beside it.
1138 b(ActionId::RemoveVideoLane, "b", true),
1139 // Ctrl+a is the select-all above now, so the audio removal
1140 // takes the free key beside its own letter: "a" neighbours
1141 // "q" on the row, and ctrl+q was taken by nothing.
1142 b(ActionId::RemoveAudioLane, "q", true),
1143 // The subtitle pair reads the same way, on a different letter
1144 // now that bare "s" is split's (DESIGN.md §6): "c" is free
1145 // once split moves off it, and it is still an initial the
1146 // track answers to -- captions. The removal takes the other
1147 // letter subtitles already answer to here: "t" shows and
1148 // hides them, and ctrl+t takes one off the timeline.
1149 b(ActionId::AddSubtitleLane, "c", false),
1150 b(ActionId::RemoveSubtitleLane, "t", true),
1151 // Reading a file's tracks into the palette is not adding a
1152 // track to the timeline, so it is not the bare "s": ctrl+i, the
1153 // i of import, free and next to nothing that deletes.
1154 b(ActionId::ImportSubtitles, "i", true),
1155 // The dock's own import pair (MOCK-SPEC "Dock" IMPORT
1156 // section). Add files takes the chord the mock draws, ^o
1157 // (freed above): it is the burst-use command an editor
1158 // reaches for constantly, where the setting it displaces is
1159 // thrown once a project. Paste path stays off ^v -- that
1160 // chord is the timeline's own Paste, asked for far more
1161 // often while cutting than a clipboard path is pasted while
1162 // importing -- and takes ctrl+l instead, the browser's own
1163 // "go to this location" chord, which is what pasting a path
1164 // to jump straight to a file already is.
1165 b(ActionId::AddFiles, "o", true),
1166 b(ActionId::PasteFilePath, "l", true),
1167 b(ActionId::ToggleMute, "m", false),
1168 // The unshifted pair, which is what gpui reports for those two
1169 // keys ("=" and "-", platform.rs:862): the volume keys every
1170 // player has, without asking for shift to make the "+".
1171 b(ActionId::VolumeUp, "=", false),
1172 b(ActionId::VolumeDown, "-", false),
1173 // The one free letter that says the word: "e" is already the
1174 // export and an equalizer is the q in nobody else's way.
1175 b(ActionId::Equalizer, "q", false),
1176 // "s" is the save's ctrl chord, so the speed card takes the
1177 // unshifted letter beside it: "j" was free, sits under the
1178 // right hand with the other clip keys (k grades, l lifts), and
1179 // is not next to anything that deletes.
1180 b(ActionId::Speed, "j", false),
1181 // The silence card takes "u": free, sits with the other clip-card
1182 // keys under the right hand, and is nowhere near the two that
1183 // delete (x and delete) -- what it opens is a card that can cut
1184 // forty places at once.
1185 b(ActionId::Silence, "u", false),
1186 // Crossfade takes ctrl+f: the mnemonic letter for "fade", with
1187 // ctrl its own room now that plain "f" is the mix card's own
1188 // (below) -- the same letter, the modifier telling them apart.
1189 b(ActionId::Crossfade, "f", true),
1190 // DESIGN.md §6's own chords: bare `[` `]` are the no-aim trim
1191 // pair. SelectPrev/SelectNext moved to `{` `}` above to make
1192 // room -- the bare bracket trims the subject cut, the brace
1193 // (what the shifted bracket actually types) walks the
1194 // selection past it, so the family reads as one idea under
1195 // one pair of keys.
1196 b(ActionId::TrimIn, "[", false),
1197 b(ActionId::TrimOut, "]", false),
1198 // Loop-trim (DESIGN.md §6, "the modernized Avid trim mode"):
1199 // bare "/" was free.
1200 b(ActionId::LoopTrim, "/", false),
1201 // Trim-to-playhead (debt #42): the whole bracket family is
1202 // already spoken for -- bare `[`/`]` nudge, `{`/`}` walk the
1203 // selection, ctrl+`[`/ctrl+`]` jump sync points -- so this
1204 // takes the one rung left in the same family, ctrl held on
1205 // the shifted bracket (`ctrl+{`/`ctrl+}`, what
1206 // ctrl+shift+[/ctrl+shift+] actually type per this table's
1207 // own shift note above).
1208 b(ActionId::TrimInToPlayhead, "{", true),
1209 b(ActionId::TrimOutToPlayhead, "}", true),
1210 // Dissolve takes ctrl+x: the join it draws on the timeline is
1211 // an X (widgets.rs, dissolve_glyph) -- "d" itself is taken
1212 // both plain (Detach) and, in the keymap's own rebind test,
1213 // as the free chord it rebinds Delete onto, so this reaches
1214 // for the shape instead of the word.
1215 b(ActionId::Dissolve, "x", true),
1216 // The mix card takes "f", for the faders on it: "m" would be
1217 // the word but it is the monitoring mute, which is this
1218 // machine's volume and not the project's -- two things one key
1219 // must not mean.
1220 b(ActionId::Mix, "f", false),
1221 // The snap takes "n", which is what every other editor toggles
1222 // it with: free here, and nowhere near the two keys that delete.
1223 b(ActionId::ToggleSnap, "n", false),
1224 // The subtitles take "t", for the word: free, one press like
1225 // the rest of the things one *looks* at, and nowhere near the
1226 // two keys that delete.
1227 b(ActionId::ToggleSubtitles, "t", false),
1228 // The stand-ins take ctrl+p, the p of the word: the unshifted
1229 // one is the fit policy, and a ctrl chord is right for a switch
1230 // thrown once for a whole session rather than one wanted under
1231 // a hand -- the theme takes ctrl+h for that reason.
1232 b(ActionId::ToggleProxies, "p", true),
1233 // ctrl+o moved to Add files (below, with `ImportSubtitles` --
1234 // display order follows [`ActionId::ALL`]) per DESIGN §11's
1235 // frequency check: a burst-use import command over a
1236 // once-a-project setting. The auto-proxy switch takes "m"
1237 // instead, free and still a stand-in word ("make" -- what
1238 // the switch decides is whether one gets made on import).
1239 b(ActionId::ToggleAutoProxies, "m", true),
1240 // The theme takes ctrl+h -- the h of the word, since "t" is the
1241 // subtitles and ctrl+t takes one off -- and a ctrl chord because
1242 // it is a preference set once, not a stroke wanted under a hand
1243 // that is editing.
1244 b(ActionId::Theme, "h", true),
1245 // Every other player's key for it, and free here: nothing in
1246 // this table answers to "f11" (gpui lowercases the keysym
1247 // name it gets from xkb, same as "f1" below).
1248 b(ActionId::Fullscreen, "f11", false),
1249 // A chord, and the only escape in this table: bare `esc` is the
1250 // stroke a hand throws at anything on screen, and throwing it
1251 // at a running export used to delete an hour of encoding. The
1252 // key stays the one people look for -- the modifier is what
1253 // makes it an intention ([`crate::cancels_export`]).
1254 b(ActionId::CancelExport, "escape", true),
1255 // The help key (DESIGN.md §9): held, it opens the keys
1256 // overlay; released, it closes -- the room's own `on_key_up`
1257 // (`ui/stance.rs`) is what makes that a hold and not a latch.
1258 // Its own key, not `shift+/`: gpui reports a shifted symbol as
1259 // the glyph itself, so `"?"` is what a stroke of it reports.
1260 b(ActionId::ShowActions, "?", false),
1261 // "w" is free entirely, bare and ctrl both -- nothing else in
1262 // this table answers to it.
1263 b(ActionId::Screenshot, "w", false),
1264 // Bare "y" is free entirely, and unshifted: a preference
1265 // opened as often as the theme, not a switch thrown once a
1266 // session.
1267 b(ActionId::SubtitleStyle, "y", false),
1268 // The consumer-editor convention (Cmd/Ctrl+,) -- free here:
1269 // bare "," is WalkCutPrev, and nothing else answers to the
1270 // ctrl chord.
1271 b(ActionId::Settings, ",", true),
1272 // The standard pane-cycle key on every desktop that has one
1273 // (browsers, IDEs) -- free here, and Tab itself cannot spell
1274 // this: bare Tab is already [`ActionId::Select`] at the root
1275 // (a bare-key rebind would steal clip selection), and its
1276 // shift pair is unspellable in this table's chord (`ctrl`
1277 // only, see [`ActionId::Select`]'s own comment above).
1278 b(ActionId::FocusPanels, "f6", false),
1279 ],
1280 }
1281 }
1282
1283 /// What a stroke means, if anything. `key` is gpui's key name and `ctrl` its
1284 /// control modifier -- the pair the key handler already matches on. There
1285 /// is no shift parameter: see [`Chord`]'s own doc for why.
1286 pub fn lookup(&self, key: &str, ctrl: bool) -> Option<ActionId> {
1287 self.bindings
1288 .iter()
1289 .find(|b| b.chord.ctrl == ctrl && b.chord.key == key)
1290 .map(|b| b.action)
1291 }
1292
1293 /// Every stroke that reaches an action, as one readable phrase: `x or
1294 /// delete`. An action nobody can reach says so rather than reading blank.
1295 pub fn display(&self, action: ActionId) -> String {
1296 let strokes: Vec<String> = self
1297 .bindings
1298 .iter()
1299 .filter(|b| b.action == action)
1300 .map(|b| b.chord.pretty())
1301 .collect();
1302 if strokes.is_empty() {
1303 "unbound".to_string()
1304 } else {
1305 strokes.join(" or ")
1306 }
1307 }
1308
1309 /// The primary chord for `action`, compact ([`Chord::compact`]) -- a
1310 /// badge that has room for one token, not [`Keymap::display`]'s sentence.
1311 /// The first bound stroke wins (`defaults`' own insertion order, and
1312 /// [`parse`]'s "no chord appears twice" leaves at most one anyway); an
1313 /// action with no stroke reads `--` rather than the unbound sentence,
1314 /// since a badge is not a warning.
1315 pub fn chord(&self, action: ActionId) -> String {
1316 self.bindings
1317 .iter()
1318 .find(|b| b.action == action)
1319 .map(|b| b.chord.compact())
1320 .unwrap_or_else(|| "--".to_string())
1321 }
1322
1323 /// Every binding, in display order.
1324 pub fn entries(&self) -> &[Binding] {
1325 &self.bindings
1326 }
1327
1328 /// The keymap in force, and what to tell the user if the file could not be
1329 /// used. A file that is merely absent is the normal case and says nothing;
1330 /// anything else -- unreadable, or a line this parser refuses -- falls back
1331 /// to the defaults *and* is reported, because a keymap silently not applied
1332 /// is a keyboard that has quietly changed under the user.
1333 pub fn load() -> (Self, Option<String>) {
1334 Self::load_from(&Self::config_path())
1335 }
1336
1337 /// All of [`Keymap::load`] but the path, which the config directory decides
1338 /// and a test must not be allowed to.
1339 fn load_from(path: &Path) -> (Self, Option<String>) {
1340 let text = match std::fs::read_to_string(path) {
1341 Ok(text) => text,
1342 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return (Self::defaults(), None),
1343 Err(e) => {
1344 return (
1345 Self::defaults(),
1346 Some(format!(
1347 "KEYBINDINGS IGNORED — {}: {e} — the defaults are in force",
1348 path.display()
1349 )),
1350 );
1351 }
1352 };
1353 match parse(&text) {
1354 Ok((keymap, dropped)) if dropped.is_empty() => (keymap, None),
1355 // The lines it could use are in force; the ones it could not are
1356 // named, and only those are lost.
1357 Ok((keymap, dropped)) => (
1358 keymap,
1359 Some(format!(
1360 "KEYBINDINGS PART-READ — {}, {} — those strokes are unbound",
1361 path.display(),
1362 dropped.join("; ")
1363 )),
1364 ),
1365 Err(e) => (
1366 Self::defaults(),
1367 Some(format!(
1368 "KEYBINDINGS IGNORED — {}, {e} — the defaults are in force",
1369 path.display()
1370 )),
1371 ),
1372 }
1373 }
1374
1375 /// Writes the keymap, atomically, creating the config directory if this is
1376 /// the first save. Until the rename the previous bindings are still the
1377 /// whole truth on disk.
1378 pub fn save(&self) -> std::io::Result<()> {
1379 self.save_to(&Self::config_path())
1380 }
1381
1382 /// All of [`Keymap::save`] but the path, for the same reason as
1383 /// [`Keymap::load_from`].
1384 fn save_to(&self, path: &Path) -> std::io::Result<()> {
1385 let dir = path.parent().unwrap_or(Path::new(".")).to_path_buf();
1386 std::fs::create_dir_all(&dir)?;
1387 let mut part = path.to_path_buf().into_os_string();
1388 part.push(".part");
1389 let part = PathBuf::from(part);
1390 let result = std::fs::File::create(&part)
1391 .and_then(|mut f| {
1392 f.write_all(emit(self).as_bytes())?;
1393 f.sync_all()
1394 })
1395 .and_then(|()| std::fs::rename(&part, path))
1396 .and_then(|()| std::fs::File::open(&dir)?.sync_all());
1397 if result.is_err() {
1398 let _ = std::fs::remove_file(&part);
1399 }
1400 result
1401 }
1402
1403 /// Where the bindings live: the XDG config directory, or `~/.config` when
1404 /// the desktop has not named one.
1405 pub fn config_path() -> PathBuf {
1406 config_path_in(
1407 std::env::var_os("XDG_CONFIG_HOME"),
1408 std::env::var_os("HOME"),
1409 )
1410 }
1411}
1412
1413/// The path rule, with the environment handed in so it can be checked. An
1414/// `XDG_CONFIG_HOME` that is empty is one the spec says to ignore; with no
1415/// `HOME` either there is nowhere but here, and a relative path is still better
1416/// than dropping the file in `/`.
1417fn config_path_in(xdg: Option<OsString>, home: Option<OsString>) -> PathBuf {
1418 let dir = xdg
1419 .filter(|v| !v.is_empty())
1420 .map(PathBuf::from)
1421 .or_else(|| {
1422 home.filter(|v| !v.is_empty())
1423 .map(|h| PathBuf::from(h).join(".config"))
1424 })
1425 .unwrap_or_else(|| PathBuf::from(".config"));
1426 dir.join("edith").join("keybindings")
1427}
1428
1429fn emit(keymap: &Keymap) -> String {
1430 let mut out = String::from(MAGIC);
1431 out.push('\n');
1432 for b in &keymap.bindings {
1433 out.push_str(b.action.name());
1434 out.push(' ');
1435 out.push_str(&b.chord.text());
1436 out.push('\n');
1437 }
1438 out
1439}
1440
1441/// The magic line is the whole of what makes this a keybindings file, so it is
1442/// the only thing refused outright. A *binding* line this parser cannot use is
1443/// dropped instead, and named in the returned warnings: one unusable line used
1444/// to cost every other rebind in the file, which is the user's data. What
1445/// survives is still exactly what emits back, so the by-hand round-trip holds
1446/// for every line that is kept.
1447fn parse(text: &str) -> Result<(Keymap, Vec<String>), String> {
1448 // One trailing newline terminates the last line rather than starting an
1449 // empty one; a second is an empty line and is refused below.
1450 let body = text.strip_suffix('\n').unwrap_or(text);
1451 let mut lines = body.split('\n').enumerate();
1452 let (_, first) = lines.next().unwrap_or((0, ""));
1453 if first != MAGIC {
1454 return Err(match first.strip_prefix("edith-keys ") {
1455 Some(v) => format!("line 1: unsupported version {v}"),
1456 None => "line 1: not a keybindings file".to_string(),
1457 });
1458 }
1459
1460 let mut bindings: Vec<Binding> = Vec::new();
1461 let mut dropped: Vec<String> = Vec::new();
1462 for (i, line) in lines {
1463 let n = i + 1;
1464 let Some((name, chord)) = line.split_once(' ') else {
1465 dropped.push(format!("line {n}: {line:?} is not `<action> <chord>`"));
1466 continue;
1467 };
1468 let Some(action) = ActionId::from_name(name) else {
1469 dropped.push(format!("line {n}: unknown action {name:?}"));
1470 continue;
1471 };
1472 let chord = match Chord::parse(chord, n) {
1473 Ok(chord) => chord,
1474 Err(e) => {
1475 dropped.push(e);
1476 continue;
1477 }
1478 };
1479 // One stroke, one meaning: the second line to claim it would be the
1480 // dead one, and which of them died would depend on line order. The
1481 // first line keeps the stroke, which is the order the file reads in.
1482 if let Some(held) = bindings.iter().find(|b| b.chord == chord) {
1483 dropped.push(format!(
1484 "line {n}: {} is already {}'s",
1485 chord.text(),
1486 held.action.name()
1487 ));
1488 continue;
1489 }
1490 bindings.push(Binding { action, chord });
1491 }
1492 Ok((Keymap { bindings }, dropped))
1493}
1494
1495#[cfg(test)]
1496mod tests {
1497 use engine::scratch::Scratch;
1498
1499 use super::{ActionId, Chord, Keymap, config_path_in, emit, parse};
1500
1501 fn chord(key: &str, ctrl: bool) -> Chord {
1502 Chord {
1503 key: key.to_string(),
1504 ctrl,
1505 }
1506 }
1507
1508 /// A file every line of which the parser could use -- what most assertions
1509 /// are about. A dropped line here is a failure, not a warning.
1510 fn whole(text: &str) -> Keymap {
1511 let (keymap, dropped) = parse(text).expect("a keybindings file");
1512 assert!(dropped.is_empty(), "unexpected dropped lines: {dropped:?}");
1513 keymap
1514 }
1515
1516 #[test]
1517 fn every_default_stroke_reaches_its_action() {
1518 let k = Keymap::defaults();
1519 assert_eq!(k.entries().len(), 78);
1520 // The cut odometer: bare walks one, `<`/`>` (what shift+,/shift+.
1521 // actually type) strides ten.
1522 assert_eq!(k.lookup(".", false), Some(ActionId::WalkCutNext));
1523 assert_eq!(k.lookup(",", false), Some(ActionId::WalkCutPrev));
1524 assert_eq!(k.lookup("/", false), Some(ActionId::LoopTrim));
1525 assert_eq!(k.lookup(">", false), Some(ActionId::WalkCutNext10));
1526 assert_eq!(k.lookup("<", false), Some(ActionId::WalkCutPrev10));
1527 // The trim pair, on its designed bare brackets (DESIGN.md §6).
1528 assert_eq!(k.lookup("[", false), Some(ActionId::TrimIn));
1529 assert_eq!(k.lookup("]", false), Some(ActionId::TrimOut));
1530 // Trim-to-playhead (debt #42): the same family, one rung further.
1531 assert_eq!(k.lookup("{", true), Some(ActionId::TrimInToPlayhead));
1532 assert_eq!(k.lookup("}", true), Some(ActionId::TrimOutToPlayhead));
1533 assert_eq!(k.lookup("f11", false), Some(ActionId::Fullscreen));
1534 assert_eq!(k.lookup("w", false), Some(ActionId::Screenshot));
1535 assert_eq!(k.lookup("y", false), Some(ActionId::SubtitleStyle));
1536 assert_eq!(k.lookup("p", true), Some(ActionId::ToggleProxies));
1537 assert_eq!(k.lookup("m", true), Some(ActionId::ToggleAutoProxies));
1538 assert_eq!(k.lookup("o", true), Some(ActionId::AddFiles));
1539 assert_eq!(k.lookup("l", true), Some(ActionId::PasteFilePath));
1540 assert_eq!(k.lookup("?", false), Some(ActionId::ShowActions));
1541 assert_eq!(k.lookup("h", true), Some(ActionId::Theme));
1542 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
1543 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two
1544 // ends of the timeline.
1545 assert_eq!(k.lookup("left", false), Some(ActionId::StepBack));
1546 assert_eq!(k.lookup("right", false), Some(ActionId::StepForward));
1547 assert_eq!(k.lookup("left", true), Some(ActionId::JumpBack));
1548 assert_eq!(k.lookup("right", true), Some(ActionId::JumpForward));
1549 assert_eq!(k.lookup("home", false), Some(ActionId::GoStart));
1550 assert_eq!(k.lookup("end", false), Some(ActionId::GoEnd));
1551 // ...and the source's own grid, which is neither a frame nor a second:
1552 // the brackets bare select the clip either side, with ctrl they step
1553 // the sync points a cut has to land on to be copied.
1554 assert_eq!(k.lookup("[", true), Some(ActionId::PrevSyncPoint));
1555 assert_eq!(k.lookup("]", true), Some(ActionId::NextSyncPoint));
1556 assert_eq!(k.lookup("}", false), Some(ActionId::SelectNext));
1557 assert_eq!(k.lookup("{", false), Some(ActionId::SelectPrev));
1558 assert_eq!(k.lookup("i", false), Some(ActionId::SetIn));
1559 assert_eq!(k.lookup("o", false), Some(ActionId::SetOut));
1560 assert_eq!(k.lookup("u", true), Some(ActionId::ClearRange));
1561 assert_eq!(k.lookup("e", false), Some(ActionId::Export));
1562 assert_eq!(k.lookup("s", true), Some(ActionId::Save));
1563 assert_eq!(k.lookup("c", true), Some(ActionId::Copy));
1564 assert_eq!(k.lookup("v", true), Some(ActionId::Paste));
1565 assert_eq!(k.lookup("s", false), Some(ActionId::Cut));
1566 assert_eq!(k.lookup("g", false), Some(ActionId::Regroup));
1567 // The take apart / put back pair beside it.
1568 assert_eq!(k.lookup("d", false), Some(ActionId::Detach));
1569 assert_eq!(k.lookup("g", true), Some(ActionId::Group));
1570 // The keyboard's way onto a clip, and the pair that walks the lane.
1571 assert_eq!(k.lookup("tab", false), Some(ActionId::Select));
1572 assert_eq!(k.lookup("}", false), Some(ActionId::SelectNext));
1573 assert_eq!(k.lookup("{", false), Some(ActionId::SelectPrev));
1574 assert_eq!(k.lookup("x", false), Some(ActionId::Delete));
1575 assert_eq!(k.lookup("delete", false), Some(ActionId::Delete));
1576 assert_eq!(k.lookup("l", false), Some(ActionId::Lift));
1577 assert_eq!(k.lookup("k", false), Some(ActionId::Color));
1578 assert_eq!(k.lookup("p", false), Some(ActionId::Fit));
1579 assert_eq!(k.lookup("r", true), Some(ActionId::Resolution));
1580 assert_eq!(k.lookup("z", false), Some(ActionId::Undo));
1581 assert_eq!(k.lookup("z", true), Some(ActionId::Undo));
1582 assert_eq!(k.lookup("y", true), Some(ActionId::Redo));
1583 // The track keys are the bare letters; the ctrl ones stay copy/paste.
1584 assert_eq!(k.lookup("v", false), Some(ActionId::AddVideoLane));
1585 assert_eq!(k.lookup("a", false), Some(ActionId::AddAudioLane));
1586 // ...and the ctrl ones take a track away, out of the way of a stray
1587 // press. Ctrl+v is the paste, so the video one sits beside it; ctrl+a
1588 // is the select-all every editor shares, so the audio one sits beside
1589 // its own letter instead.
1590 assert_eq!(k.lookup("b", true), Some(ActionId::RemoveVideoLane));
1591 assert_eq!(k.lookup("q", true), Some(ActionId::RemoveAudioLane));
1592 assert_eq!(k.lookup("a", true), Some(ActionId::SelectAll));
1593 // The subtitle pair, the third kind of track: the initial adds and the
1594 // subtitle letter's chord takes it back.
1595 assert_eq!(k.lookup("c", false), Some(ActionId::AddSubtitleLane));
1596 assert_eq!(k.lookup("t", true), Some(ActionId::RemoveSubtitleLane));
1597 // ...and the palette's own door, which adds no track to the timeline.
1598 assert_eq!(k.lookup("i", true), Some(ActionId::ImportSubtitles));
1599 assert_eq!(k.lookup("m", false), Some(ActionId::ToggleMute));
1600 assert_eq!(k.lookup("q", false), Some(ActionId::Equalizer));
1601 // The volume pair is the unshifted one, so neither needs a modifier
1602 // and neither is the "+" gpui reports for shift+=.
1603 assert_eq!(k.lookup("=", false), Some(ActionId::VolumeUp));
1604 assert_eq!(k.lookup("-", false), Some(ActionId::VolumeDown));
1605 assert_eq!(k.lookup("+", false), None);
1606 // The chord cancels an export; bare escape falls through to Deselect.
1607 assert_eq!(k.lookup("escape", true), Some(ActionId::CancelExport));
1608 assert_eq!(k.lookup("escape", false), Some(ActionId::Deselect));
1609 // The modifier is half the chord: ctrl+e is not e.
1610 assert_eq!(k.lookup("e", true), None);
1611 assert_eq!(k.lookup("space", true), None);
1612 assert_eq!(k.lookup("j", false), Some(ActionId::Speed));
1613 assert_eq!(k.lookup("u", false), Some(ActionId::Silence));
1614 assert_eq!(k.lookup("j", true), None);
1615 // Nothing is bound twice, or lookup's first match would be a coin toss.
1616 for (i, a) in k.entries().iter().enumerate() {
1617 assert!(
1618 !k.entries()[i + 1..].iter().any(|b| b.chord == a.chord),
1619 "{:?} bound twice",
1620 a.chord
1621 );
1622 }
1623 }
1624
1625 #[test]
1626 fn a_file_survives_the_round_trip_exactly() {
1627 let text = emit(&Keymap::defaults());
1628 assert!(text.starts_with("edith-keys 1\nplay space\n"));
1629 assert!(text.contains("save ctrl+s\n"));
1630 assert!(text.contains("cancel-export ctrl+escape\n"));
1631 // Both directions: the file this writes is the file it reads back, and
1632 // a file read in comes out byte for byte as it went.
1633 assert_eq!(whole(&text), Keymap::defaults());
1634 assert_eq!(emit(&whole(&text)), text);
1635 let handwritten = "edith-keys 1\nundo ctrl+z\nplay space\n";
1636 assert_eq!(emit(&whole(handwritten)), handwritten);
1637 // A keymap that binds nothing is legal -- and unusable, which is the
1638 // user's business, not the parser's.
1639 assert_eq!(whole("edith-keys 1\n").entries(), &[]);
1640 }
1641
1642 #[test]
1643 fn every_refusal_names_its_line() {
1644 // Only the first line refuses the whole file.
1645 let err = |text: &str| parse(text).unwrap_err();
1646 assert_eq!(err(""), "line 1: not a keybindings file");
1647 assert_eq!(err("nonsense\n"), "line 1: not a keybindings file");
1648 assert_eq!(err("edith-keys 2\n"), "line 1: unsupported version 2");
1649
1650 // Every other kind of bad line costs that line and nothing else.
1651 let dropped = |text: &str| parse(text).unwrap().1;
1652 assert_eq!(
1653 dropped("edith-keys 1\nfly space\n"),
1654 ["line 2: unknown action \"fly\""]
1655 );
1656 assert_eq!(
1657 dropped("edith-keys 1\nplay space\nplayspace\n"),
1658 ["line 3: \"playspace\" is not `<action> <chord>`"]
1659 );
1660 // An empty line is not optional whitespace, it is a line.
1661 assert_eq!(
1662 dropped("edith-keys 1\n\n"),
1663 ["line 2: \"\" is not `<action> <chord>`"]
1664 );
1665 assert_eq!(
1666 dropped("edith-keys 1\nplay ctrl+alt+x\n"),
1667 ["line 2: \"ctrl+alt+x\" is not a chord"]
1668 );
1669 assert_eq!(
1670 dropped("edith-keys 1\nplay ctrl+\n"),
1671 ["line 2: \"ctrl+\" is not a chord"]
1672 );
1673 // gpui reports lowercase key names, so an uppercase one would simply
1674 // never match -- dropped rather than quietly dead.
1675 assert_eq!(
1676 dropped("edith-keys 1\nplay X\n"),
1677 ["line 2: \"X\" is not a chord"]
1678 );
1679 // The same stroke twice: whichever line lost would depend on order, so
1680 // the second one is the one that goes.
1681 assert_eq!(
1682 dropped("edith-keys 1\nplay space\ncut space\n"),
1683 ["line 3: space is already play's"]
1684 );
1685 }
1686
1687 /// The rebind data-loss path: one line the parser cannot use must not cost
1688 /// the rebinds around it (a `capture` of shift+= wrote `play +`, and the
1689 /// next load threw the whole file away and went back to the defaults).
1690 #[test]
1691 fn one_bad_line_costs_only_that_line() {
1692 let text = "edith-keys 1\nplay +\nexport ctrl+w\ncut j\n";
1693 let (keymap, dropped) = parse(text).expect("the magic line is still good");
1694 assert_eq!(dropped, ["line 2: \"+\" is not a chord"]);
1695 // The lines around it are in force, which is the whole point.
1696 assert_eq!(keymap.lookup("w", true), Some(ActionId::Export));
1697 assert_eq!(keymap.lookup("j", false), Some(ActionId::Cut));
1698 // ...and the one that went is unbound, not silently something else.
1699 assert_eq!(keymap.display(ActionId::Play), "unbound");
1700 // What survives still round-trips: the kept lines emit back as read.
1701 assert_eq!(emit(&keymap), "edith-keys 1\nexport ctrl+w\ncut j\n");
1702
1703 // The notice names the line and the file, and the defaults do *not*
1704 // take over -- that was the data loss.
1705 let dir = Scratch::dir("edith-keymap-drop");
1706 let path = dir.join("edith").join("keybindings");
1707 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1708 std::fs::write(&path, text).unwrap();
1709 let (read, notice) = Keymap::load_from(&path);
1710 assert_eq!(read, keymap);
1711 let notice = notice.expect("a part-read file must say so");
1712 assert!(notice.contains("line 2:"), "{notice}");
1713 assert!(notice.contains("keybindings"), "{notice}");
1714 std::fs::remove_dir_all(&dir).ok();
1715 }
1716
1717 /// The other half of the same bug: a stroke the file cannot spell is refused
1718 /// at the capture, before it can ever be written.
1719 #[test]
1720 fn only_a_stroke_the_file_can_spell_is_bindable() {
1721 for (key, ctrl) in [
1722 ("space", false),
1723 ("=", false),
1724 ("s", true),
1725 ("escape", false),
1726 ] {
1727 assert!(chord(key, ctrl).bindable(), "{key}");
1728 }
1729 // gpui's name for shift+=, and the grammar's own separator.
1730 assert!(!chord("+", false).bindable());
1731 assert!(!chord("+", true).bindable());
1732 // The rest of what `Chord::parse` will not take back.
1733 assert!(!chord("", false).bindable());
1734 assert!(!chord("X", false).bindable());
1735 assert!(!chord("page up", false).bindable());
1736 // A bindable chord is one the file's own grammar can spell: what it
1737 // writes is what the next load reads, for every stroke that passes
1738 // here.
1739 let k = whole("edith-keys 1\nplay ctrl+w\n");
1740 assert_eq!(whole(&emit(&k)), k);
1741 }
1742
1743 #[test]
1744 fn display_reads_as_a_person_would_say_it() {
1745 let k = Keymap::defaults();
1746 assert_eq!(k.display(ActionId::Play), "space");
1747 assert_eq!(k.display(ActionId::Save), "ctrl+s");
1748 assert_eq!(k.display(ActionId::Delete), "x or delete");
1749 assert_eq!(k.display(ActionId::Undo), "z or ctrl+z");
1750 // The one key whose common name is not gpui's.
1751 assert_eq!(k.display(ActionId::CancelExport), "ctrl+esc");
1752 assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound");
1753 // The label is the editor's column, and never the file's word for it.
1754 assert_eq!(ActionId::CancelExport.label(), "Cancel export");
1755 assert_eq!(k.display(ActionId::ToggleSnap), "n");
1756 assert_eq!(k.display(ActionId::ShowActions), "?");
1757 assert_eq!(k.display(ActionId::ToggleSubtitles), "t");
1758 assert_eq!(k.display(ActionId::ZoomIn), "ctrl+=");
1759 }
1760
1761 /// [`Keymap::chord`] is the badge's one token, not [`Keymap::display`]'s
1762 /// sentence: the primary (first-bound) stroke only, `^` for ctrl, and the
1763 /// short names a glyph badge actually has room for.
1764 #[test]
1765 fn chord_is_the_primary_stroke_compact() {
1766 let k = Keymap::defaults();
1767 assert_eq!(k.chord(ActionId::Delete), "x");
1768 assert_eq!(k.chord(ActionId::Undo), "z");
1769 assert_eq!(k.chord(ActionId::AddFiles), "^o");
1770 assert_eq!(k.chord(ActionId::CancelExport), "^esc");
1771 assert_eq!(k.chord(ActionId::Play), "spc");
1772 assert_eq!(whole("edith-keys 1\n").chord(ActionId::Cut), "--");
1773 }
1774
1775 /// The one row of [`FIXED`] that speaks for a whole table elsewhere: it
1776 /// named six keys for seven codecs, and OGG's `o` was a stroke the card
1777 /// never mentioned. The chord is generated from `FORMATS` now, and this
1778 /// holds the *label* to the same table -- a codec added there with no name
1779 /// in this row fails here rather than in a user's hands.
1780 #[test]
1781 fn the_codec_row_says_every_codec_the_export_card_offers() {
1782 let row = super::FIXED
1783 .iter()
1784 .find(|f| f.label.starts_with("Pick the export codec"))
1785 .expect("the codec row");
1786 let keys: Vec<&str> = row.chord.split(" / ").collect();
1787 for (boxes, stroke, label, _) in crate::FORMATS {
1788 if stroke.is_empty() {
1789 // A codec this program cannot write at all has no key and no
1790 // business in this row.
1791 assert!(boxes.is_empty(), "{label} has a box but no stroke");
1792 assert!(!keys.contains(&stroke));
1793 continue;
1794 }
1795 assert!(
1796 keys.contains(&stroke),
1797 "{label}'s key {stroke:?} is not in {:?}",
1798 row.chord
1799 );
1800 assert!(
1801 row.label.contains(label),
1802 "{label} is not named in {:?}",
1803 row.label
1804 );
1805 }
1806 assert_eq!(
1807 keys.len(),
1808 crate::FORMATS
1809 .iter()
1810 .filter(|(_, s, ..)| !s.is_empty())
1811 .count()
1812 );
1813 }
1814
1815 #[test]
1816 fn a_saved_keymap_comes_back_off_the_disk() {
1817 // Its own directory, never the real config one: this test writes.
1818 let dir = Scratch::dir("edith-keymap");
1819 let path = dir.join("edith").join("keybindings");
1820 // A defaults file with Export's own line swapped for a free stroke --
1821 // parsed rather than rebound, since nothing left in the API mutates
1822 // a `Keymap` in place.
1823 let text: String = emit(&Keymap::defaults())
1824 .lines()
1825 .filter(|l| !l.starts_with("export "))
1826 .chain(std::iter::once("export ctrl+w"))
1827 .collect::<Vec<_>>()
1828 .join("\n")
1829 + "\n";
1830 let written = whole(&text);
1831 // The config directory does not exist yet -- the first save makes it.
1832 written.save_to(&path).unwrap();
1833 let (read, notice) = Keymap::load_from(&path);
1834 assert_eq!(notice, None);
1835 assert_eq!(read, written);
1836 assert_eq!(read.lookup("w", true), Some(ActionId::Export));
1837 assert_eq!(read.lookup("e", false), None);
1838 // The rename left nothing half-written behind.
1839 assert!(!dir.join("edith").join("keybindings.part").exists());
1840 // A file that is merely absent is not an error and says nothing.
1841 let (fresh, notice) = Keymap::load_from(&dir.join("nothing-here"));
1842 assert_eq!(fresh, Keymap::defaults());
1843 assert_eq!(notice, None);
1844 // A file that is not one at all falls back whole, and names its line.
1845 std::fs::write(&path, "edith-keys 9\nplay space\n").unwrap();
1846 let (fallback, notice) = Keymap::load_from(&path);
1847 assert_eq!(fallback, Keymap::defaults());
1848 let notice = notice.expect("a refused file must say so");
1849 assert!(notice.contains("line 1:"), "{notice}");
1850 assert!(notice.contains("keybindings"), "{notice}");
1851 // One unusable line inside a good file costs that line only -- the
1852 // defaults do not come back over the rebinds that read fine.
1853 std::fs::write(&path, "edith-keys 1\nplay ctrl+alt+x\nexport ctrl+w\n").unwrap();
1854 let (kept, notice) = Keymap::load_from(&path);
1855 assert_eq!(kept.lookup("w", true), Some(ActionId::Export));
1856 assert_eq!(kept.display(ActionId::Play), "unbound");
1857 let notice = notice.expect("a part-read file must say so");
1858 assert!(notice.contains("line 2:"), "{notice}");
1859 assert!(notice.contains("keybindings"), "{notice}");
1860 // Saving over it is a whole replacement, not an edit.
1861 Keymap::defaults().save_to(&path).unwrap();
1862 assert_eq!(Keymap::load_from(&path), (Keymap::defaults(), None));
1863 std::fs::remove_dir_all(&dir).ok();
1864 }
1865
1866 #[test]
1867 fn the_config_path_follows_xdg_then_home() {
1868 let p = |xdg: Option<&str>, home: Option<&str>| {
1869 config_path_in(xdg.map(Into::into), home.map(Into::into))
1870 };
1871 assert_eq!(
1872 p(Some("/x/config"), Some("/home/u")),
1873 std::path::Path::new("/x/config/edith/keybindings")
1874 );
1875 assert_eq!(
1876 p(None, Some("/home/u")),
1877 std::path::Path::new("/home/u/.config/edith/keybindings")
1878 );
1879 // An empty XDG_CONFIG_HOME is one the spec says to ignore.
1880 assert_eq!(
1881 p(Some(""), Some("/home/u")),
1882 std::path::Path::new("/home/u/.config/edith/keybindings")
1883 );
1884 // Nowhere to put it but here -- still never `/edith/keybindings`.
1885 assert_eq!(
1886 p(None, None),
1887 std::path::Path::new(".config/edith/keybindings")
1888 );
1889 }
1890}