forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB978e685Tahinli3 months ago627 commits

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