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