forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB7f487c1Tahinli3 months ago659 commits

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