forge
Explore
Log in

Don't you dare go Hollow

Rebindable keybindings, single source of truth

Browse files at this commit

cad8d5af43792719b78a088210bdf610a7544946Ahmet Kaan GümüşParent: a981d4a
  • feat
    • rebindable keybindings, single source of truth
Show full message
✨ feat(keys): rebindable keybindings, single source of truth

Every shortcut lived in hardcoded match arms and tooltip strings.
New keymap module owns all bindings: dispatch, tooltips, hint line
and the Keys overlay all derive from it. Click a row, press a key
to rebind; conflicts rejected naming the holder. Persists to
XDG_CONFIG_HOME/edith/keybindings (strict line format, atomic
write, malformed file falls back to defaults with a notice).
Escape stays hardcoded as the way out of capture, overlay and
export — a rebindable exit could lock the user out.
crates/app/src/keymap.rsadded+587 -0
@@ -0,0 +1,587 @@
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 every refusal names its 1-based line, like the
18+//! project file: this file is generated by the keybindings editor, so a line it
19+//! did not generate is a corrupt file rather than a dialect. A missing file is
20+//! not corrupt -- it means nobody has changed a key yet, and the defaults stand.
21+//!
22+//! Writing mirrors `engine::edith::save`: `.part`, fsync, rename, directory
23+//! fsync, so an interrupted save cannot cost the bindings that were already
24+//! there.
25+
26+// The UI consumes this module in a later step; until then nothing calls it and
27+// every item here reads as dead.
28+#![allow(dead_code)]
29+
30+use std::ffi::OsString;
31+use std::io::Write;
32+use std::path::{Path, PathBuf};
33+
34+/// First line, exactly. The version is part of it, as in the project file.
35+const MAGIC: &str = "edith-keys 1";
36+
37+/// Everything a stroke can ask for. Not the mouse's actions: only what a key
38+/// can reach is bindable.
39+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
40+pub enum ActionId {
41+ Play,
42+ Export,
43+ Save,
44+ Copy,
45+ Paste,
46+ Cut,
47+ Delete,
48+ Undo,
49+ CancelExport,
50+}
51+
52+impl ActionId {
53+ /// Display order everywhere -- the editor lists them in it and
54+ /// [`Keymap::defaults`] binds them in it.
55+ pub const ALL: [ActionId; 9] = [
56+ ActionId::Play,
57+ ActionId::Export,
58+ ActionId::Save,
59+ ActionId::Copy,
60+ ActionId::Paste,
61+ ActionId::Cut,
62+ ActionId::Delete,
63+ ActionId::Undo,
64+ ActionId::CancelExport,
65+ ];
66+
67+ /// What a person calls it.
68+ pub fn label(self) -> &'static str {
69+ match self {
70+ ActionId::Play => "Play / Pause",
71+ ActionId::Export => "Export",
72+ ActionId::Save => "Save",
73+ ActionId::Copy => "Copy",
74+ ActionId::Paste => "Paste",
75+ ActionId::Cut => "Cut",
76+ ActionId::Delete => "Delete",
77+ ActionId::Undo => "Undo",
78+ ActionId::CancelExport => "Cancel export",
79+ }
80+ }
81+
82+ /// What the file calls it: ASCII, no spaces, one spelling per variant and
83+ /// never the label, which is free to be reworded.
84+ fn name(self) -> &'static str {
85+ match self {
86+ ActionId::Play => "play",
87+ ActionId::Export => "export",
88+ ActionId::Save => "save",
89+ ActionId::Copy => "copy",
90+ ActionId::Paste => "paste",
91+ ActionId::Cut => "cut",
92+ ActionId::Delete => "delete",
93+ ActionId::Undo => "undo",
94+ ActionId::CancelExport => "cancel-export",
95+ }
96+ }
97+
98+ fn from_name(name: &str) -> Option<Self> {
99+ Self::ALL.into_iter().find(|a| a.name() == name)
100+ }
101+}
102+
103+/// A stroke as the key handler sees it: gpui's key name plus the one modifier
104+/// this editor binds. Nothing else is a chord here -- shift and alt are part of
105+/// the key name gpui reports, and a second modifier would need the file format
106+/// to grow before it could be spelled.
107+#[derive(Clone, PartialEq, Eq, Debug)]
108+pub struct Chord {
109+ pub key: String,
110+ pub ctrl: bool,
111+}
112+
113+impl Chord {
114+ /// The file's spelling, and the only one [`parse`] accepts back.
115+ fn text(&self) -> String {
116+ if self.ctrl {
117+ format!("ctrl+{}", self.key)
118+ } else {
119+ self.key.clone()
120+ }
121+ }
122+
123+ /// The spelling a person reads. Identical to [`Chord::text`] but for the one
124+ /// key whose usual name is shorter than gpui's. Public because a
125+ /// keybindings row shows one chord, where [`Keymap::display`] shows every
126+ /// chord an action answers to.
127+ pub fn pretty(&self) -> String {
128+ let key = if self.key == "escape" {
129+ "esc"
130+ } else {
131+ &self.key
132+ };
133+ if self.ctrl {
134+ format!("ctrl+{key}")
135+ } else {
136+ key.to_string()
137+ }
138+ }
139+
140+ /// Strict: exactly one optional `ctrl+` and then a key gpui could have
141+ /// reported. A spelling this cannot emit back unchanged is refused rather
142+ /// than normalised, because the round-trip is what makes the file editable
143+ /// by hand at all.
144+ fn parse(text: &str, n: usize) -> Result<Self, String> {
145+ let (ctrl, key) = match text.strip_prefix("ctrl+") {
146+ Some(key) => (true, key),
147+ None => (false, text),
148+ };
149+ if key.is_empty()
150+ || key.contains(' ')
151+ || key.contains('+')
152+ || key.chars().any(|c| c.is_ascii_uppercase())
153+ {
154+ return Err(format!("line {n}: {text:?} is not a chord"));
155+ }
156+ Ok(Chord {
157+ key: key.to_string(),
158+ ctrl,
159+ })
160+ }
161+}
162+
163+/// One stroke, one action. Two strokes for the same action are two bindings.
164+#[derive(Clone, PartialEq, Eq, Debug)]
165+pub struct Binding {
166+ pub action: ActionId,
167+ pub chord: Chord,
168+}
169+
170+/// Every binding in force, in display order. No chord appears twice -- that is
171+/// the invariant [`Keymap::rebind`] and [`parse`] both defend, and it is what
172+/// lets [`Keymap::lookup`] answer with the first match.
173+#[derive(Clone, PartialEq, Eq, Debug)]
174+pub struct Keymap {
175+ bindings: Vec<Binding>,
176+}
177+
178+impl Keymap {
179+ /// The bindings the editor has always had, in the order the editor lists
180+ /// them. Delete and undo get two strokes each because both have always
181+ /// answered to two.
182+ pub fn defaults() -> Self {
183+ let b = |action, key: &str, ctrl| Binding {
184+ action,
185+ chord: Chord {
186+ key: key.to_string(),
187+ ctrl,
188+ },
189+ };
190+ Keymap {
191+ bindings: vec![
192+ b(ActionId::Play, "space", false),
193+ b(ActionId::Export, "e", false),
194+ b(ActionId::Save, "s", true),
195+ b(ActionId::Copy, "c", true),
196+ b(ActionId::Paste, "v", true),
197+ b(ActionId::Cut, "c", false),
198+ b(ActionId::Delete, "x", false),
199+ b(ActionId::Delete, "delete", false),
200+ b(ActionId::Undo, "z", false),
201+ b(ActionId::Undo, "z", true),
202+ b(ActionId::CancelExport, "escape", false),
203+ ],
204+ }
205+ }
206+
207+ /// What a stroke means, if anything. `key` is gpui's key name and `ctrl` its
208+ /// control modifier -- the pair the key handler already matches on.
209+ pub fn lookup(&self, key: &str, ctrl: bool) -> Option<ActionId> {
210+ self.bindings
211+ .iter()
212+ .find(|b| b.chord.ctrl == ctrl && b.chord.key == key)
213+ .map(|b| b.action)
214+ }
215+
216+ /// Every stroke that reaches an action, as one readable phrase: `x or
217+ /// delete`. An action nobody can reach says so rather than reading blank.
218+ pub fn display(&self, action: ActionId) -> String {
219+ let strokes: Vec<String> = self
220+ .bindings
221+ .iter()
222+ .filter(|b| b.action == action)
223+ .map(|b| b.chord.pretty())
224+ .collect();
225+ if strokes.is_empty() {
226+ "unbound".to_string()
227+ } else {
228+ strokes.join(" or ")
229+ }
230+ }
231+
232+ /// The bindings themselves, in display order. The index into this slice is
233+ /// what [`Keymap::rebind`] takes.
234+ pub fn entries(&self) -> &[Binding] {
235+ &self.bindings
236+ }
237+
238+ /// Puts `chord` on the binding at `index`. `Err` names the action that
239+ /// already holds the chord and nothing is changed: two actions on one stroke
240+ /// would make the second unreachable, and silently stealing it is worse than
241+ /// refusing. Rebinding a binding to the chord it already has is not a
242+ /// conflict with itself.
243+ ///
244+ /// `index` comes from [`Keymap::entries`], whose length never changes;
245+ /// anything else is a bug and panics like the slice index it is.
246+ pub fn rebind(&mut self, index: usize, chord: Chord) -> Result<(), ActionId> {
247+ if let Some(held) = self
248+ .bindings
249+ .iter()
250+ .enumerate()
251+ .find(|(i, b)| *i != index && b.chord == chord)
252+ {
253+ return Err(held.1.action);
254+ }
255+ self.bindings[index].chord = chord;
256+ Ok(())
257+ }
258+
259+ /// The keymap in force, and what to tell the user if the file could not be
260+ /// used. A file that is merely absent is the normal case and says nothing;
261+ /// anything else -- unreadable, or a line this parser refuses -- falls back
262+ /// to the defaults *and* is reported, because a keymap silently not applied
263+ /// is a keyboard that has quietly changed under the user.
264+ pub fn load() -> (Self, Option<String>) {
265+ Self::load_from(&Self::config_path())
266+ }
267+
268+ /// All of [`Keymap::load`] but the path, which the config directory decides
269+ /// and a test must not be allowed to.
270+ fn load_from(path: &Path) -> (Self, Option<String>) {
271+ let text = match std::fs::read_to_string(path) {
272+ Ok(text) => text,
273+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return (Self::defaults(), None),
274+ Err(e) => {
275+ return (
276+ Self::defaults(),
277+ Some(format!(
278+ "KEYBINDINGS IGNORED — {}: {e} — the defaults are in force",
279+ path.display()
280+ )),
281+ );
282+ }
283+ };
284+ match parse(&text) {
285+ Ok(keymap) => (keymap, None),
286+ Err(e) => (
287+ Self::defaults(),
288+ Some(format!(
289+ "KEYBINDINGS IGNORED — {}, {e} — the defaults are in force",
290+ path.display()
291+ )),
292+ ),
293+ }
294+ }
295+
296+ /// Writes the keymap, atomically, creating the config directory if this is
297+ /// the first save. Until the rename the previous bindings are still the
298+ /// whole truth on disk.
299+ pub fn save(&self) -> std::io::Result<()> {
300+ self.save_to(&Self::config_path())
301+ }
302+
303+ /// All of [`Keymap::save`] but the path, for the same reason as
304+ /// [`Keymap::load_from`].
305+ fn save_to(&self, path: &Path) -> std::io::Result<()> {
306+ let dir = path.parent().unwrap_or(Path::new(".")).to_path_buf();
307+ std::fs::create_dir_all(&dir)?;
308+ let mut part = path.to_path_buf().into_os_string();
309+ part.push(".part");
310+ let part = PathBuf::from(part);
311+ let result = std::fs::File::create(&part)
312+ .and_then(|mut f| {
313+ f.write_all(emit(self).as_bytes())?;
314+ f.sync_all()
315+ })
316+ .and_then(|()| std::fs::rename(&part, path))
317+ .and_then(|()| std::fs::File::open(&dir)?.sync_all());
318+ if result.is_err() {
319+ let _ = std::fs::remove_file(&part);
320+ }
321+ result
322+ }
323+
324+ /// Where the bindings live: the XDG config directory, or `~/.config` when
325+ /// the desktop has not named one.
326+ pub fn config_path() -> PathBuf {
327+ config_path_in(
328+ std::env::var_os("XDG_CONFIG_HOME"),
329+ std::env::var_os("HOME"),
330+ )
331+ }
332+}
333+
334+/// The path rule, with the environment handed in so it can be checked. An
335+/// `XDG_CONFIG_HOME` that is empty is one the spec says to ignore; with no
336+/// `HOME` either there is nowhere but here, and a relative path is still better
337+/// than dropping the file in `/`.
338+fn config_path_in(xdg: Option<OsString>, home: Option<OsString>) -> PathBuf {
339+ let dir = xdg
340+ .filter(|v| !v.is_empty())
341+ .map(PathBuf::from)
342+ .or_else(|| {
343+ home.filter(|v| !v.is_empty())
344+ .map(|h| PathBuf::from(h).join(".config"))
345+ })
346+ .unwrap_or_else(|| PathBuf::from(".config"));
347+ dir.join("edith").join("keybindings")
348+}
349+
350+fn emit(keymap: &Keymap) -> String {
351+ let mut out = String::from(MAGIC);
352+ out.push('\n');
353+ for b in &keymap.bindings {
354+ out.push_str(b.action.name());
355+ out.push(' ');
356+ out.push_str(&b.chord.text());
357+ out.push('\n');
358+ }
359+ out
360+}
361+
362+fn parse(text: &str) -> Result<Keymap, String> {
363+ // One trailing newline terminates the last line rather than starting an
364+ // empty one; a second is an empty line and is refused below.
365+ let body = text.strip_suffix('\n').unwrap_or(text);
366+ let mut lines = body.split('\n').enumerate();
367+ let (_, first) = lines.next().unwrap_or((0, ""));
368+ if first != MAGIC {
369+ return Err(match first.strip_prefix("edith-keys ") {
370+ Some(v) => format!("line 1: unsupported version {v}"),
371+ None => "line 1: not a keybindings file".to_string(),
372+ });
373+ }
374+
375+ let mut bindings: Vec<Binding> = Vec::new();
376+ for (i, line) in lines {
377+ let n = i + 1;
378+ let Some((name, chord)) = line.split_once(' ') else {
379+ return Err(format!("line {n}: {line:?} is not `<action> <chord>`"));
380+ };
381+ let action = ActionId::from_name(name)
382+ .ok_or_else(|| format!("line {n}: unknown action {name:?}"))?;
383+ let chord = Chord::parse(chord, n)?;
384+ // One stroke, one meaning: the second line to claim it would be the
385+ // dead one, and which of them died would depend on line order.
386+ if let Some(held) = bindings.iter().find(|b| b.chord == chord) {
387+ return Err(format!(
388+ "line {n}: {} is already {}'s",
389+ chord.text(),
390+ held.action.name()
391+ ));
392+ }
393+ bindings.push(Binding { action, chord });
394+ }
395+ Ok(Keymap { bindings })
396+}
397+
398+#[cfg(test)]
399+mod tests {
400+ use super::{ActionId, Chord, Keymap, config_path_in, emit, parse};
401+
402+ fn chord(key: &str, ctrl: bool) -> Chord {
403+ Chord {
404+ key: key.to_string(),
405+ ctrl,
406+ }
407+ }
408+
409+ #[test]
410+ fn every_default_stroke_reaches_its_action() {
411+ let k = Keymap::defaults();
412+ assert_eq!(k.entries().len(), 11);
413+ assert_eq!(k.lookup("space", false), Some(ActionId::Play));
414+ assert_eq!(k.lookup("e", false), Some(ActionId::Export));
415+ assert_eq!(k.lookup("s", true), Some(ActionId::Save));
416+ assert_eq!(k.lookup("c", true), Some(ActionId::Copy));
417+ assert_eq!(k.lookup("v", true), Some(ActionId::Paste));
418+ assert_eq!(k.lookup("c", false), Some(ActionId::Cut));
419+ assert_eq!(k.lookup("x", false), Some(ActionId::Delete));
420+ assert_eq!(k.lookup("delete", false), Some(ActionId::Delete));
421+ assert_eq!(k.lookup("z", false), Some(ActionId::Undo));
422+ assert_eq!(k.lookup("z", true), Some(ActionId::Undo));
423+ assert_eq!(k.lookup("escape", false), Some(ActionId::CancelExport));
424+ // The modifier is half the chord: ctrl+e is not e.
425+ assert_eq!(k.lookup("e", true), None);
426+ assert_eq!(k.lookup("space", true), None);
427+ assert_eq!(k.lookup("q", false), None);
428+ // Nothing is bound twice, or lookup's first match would be a coin toss.
429+ for (i, a) in k.entries().iter().enumerate() {
430+ assert!(
431+ !k.entries()[i + 1..].iter().any(|b| b.chord == a.chord),
432+ "{:?} bound twice",
433+ a.chord
434+ );
435+ }
436+ }
437+
438+ #[test]
439+ fn a_file_survives_the_round_trip_exactly() {
440+ let text = emit(&Keymap::defaults());
441+ assert!(text.starts_with("edith-keys 1\nplay space\n"));
442+ assert!(text.contains("save ctrl+s\n"));
443+ assert!(text.contains("cancel-export escape\n"));
444+ // Both directions: the file this writes is the file it reads back, and
445+ // a file read in comes out byte for byte as it went.
446+ assert_eq!(parse(&text), Ok(Keymap::defaults()));
447+ assert_eq!(emit(&parse(&text).unwrap()), text);
448+ let handwritten = "edith-keys 1\nundo ctrl+z\nplay space\n";
449+ assert_eq!(emit(&parse(handwritten).unwrap()), handwritten);
450+ // A keymap that binds nothing is legal -- and unusable, which is the
451+ // user's business, not the parser's.
452+ assert_eq!(parse("edith-keys 1\n").unwrap().entries(), &[]);
453+ }
454+
455+ #[test]
456+ fn every_refusal_names_its_line() {
457+ let err = |text: &str| parse(text).unwrap_err();
458+ assert_eq!(err(""), "line 1: not a keybindings file");
459+ assert_eq!(err("nonsense\n"), "line 1: not a keybindings file");
460+ assert_eq!(err("edith-keys 2\n"), "line 1: unsupported version 2");
461+ assert_eq!(
462+ err("edith-keys 1\nfly space\n"),
463+ "line 2: unknown action \"fly\""
464+ );
465+ assert_eq!(
466+ err("edith-keys 1\nplay space\nplayspace\n"),
467+ "line 3: \"playspace\" is not `<action> <chord>`"
468+ );
469+ // An empty line is not optional whitespace, it is a line.
470+ assert_eq!(
471+ err("edith-keys 1\n\n"),
472+ "line 2: \"\" is not `<action> <chord>`"
473+ );
474+ assert_eq!(
475+ err("edith-keys 1\nplay ctrl+alt+x\n"),
476+ "line 2: \"ctrl+alt+x\" is not a chord"
477+ );
478+ assert_eq!(
479+ err("edith-keys 1\nplay ctrl+\n"),
480+ "line 2: \"ctrl+\" is not a chord"
481+ );
482+ // gpui reports lowercase key names, so an uppercase one would simply
483+ // never match -- refused rather than quietly dead.
484+ assert_eq!(
485+ err("edith-keys 1\nplay X\n"),
486+ "line 2: \"X\" is not a chord"
487+ );
488+ // The same stroke twice: whichever line lost would depend on order.
489+ assert_eq!(
490+ err("edith-keys 1\nplay space\ncut space\n"),
491+ "line 3: space is already play's"
492+ );
493+ }
494+
495+ #[test]
496+ fn rebinding_refuses_to_steal_a_stroke() {
497+ let mut k = Keymap::defaults();
498+ // Index 1 is Export on `e`; `space` is Play's.
499+ assert_eq!(k.rebind(1, chord("space", false)), Err(ActionId::Play));
500+ assert_eq!(k.lookup("e", false), Some(ActionId::Export));
501+ // Its own chord is not a conflict with itself.
502+ assert_eq!(k.rebind(1, chord("e", false)), Ok(()));
503+ // A free stroke moves, and the old one stops meaning anything.
504+ assert_eq!(k.rebind(1, chord("w", true)), Ok(()));
505+ assert_eq!(k.lookup("w", true), Some(ActionId::Export));
506+ assert_eq!(k.lookup("e", false), None);
507+ // Even the action's own second stroke is a conflict: it would leave one
508+ // of the two bindings unreachable.
509+ assert_eq!(k.rebind(6, chord("delete", false)), Err(ActionId::Delete));
510+ }
511+
512+ #[test]
513+ fn display_reads_as_a_person_would_say_it() {
514+ let k = Keymap::defaults();
515+ assert_eq!(k.display(ActionId::Play), "space");
516+ assert_eq!(k.display(ActionId::Save), "ctrl+s");
517+ assert_eq!(k.display(ActionId::Delete), "x or delete");
518+ assert_eq!(k.display(ActionId::Undo), "z or ctrl+z");
519+ // The one key whose common name is not gpui's.
520+ assert_eq!(k.display(ActionId::CancelExport), "esc");
521+ assert_eq!(
522+ parse("edith-keys 1\n").unwrap().display(ActionId::Cut),
523+ "unbound"
524+ );
525+ // The label is the editor's column, and never the file's word for it.
526+ assert_eq!(ActionId::CancelExport.label(), "Cancel export");
527+ assert_eq!(ActionId::ALL.len(), 9);
528+ }
529+
530+ #[test]
531+ fn a_saved_keymap_comes_back_off_the_disk() {
532+ // Its own directory, never the real config one: this test writes.
533+ let dir = std::env::temp_dir().join(format!("edith-keymap-{}", std::process::id()));
534+ let path = dir.join("edith").join("keybindings");
535+ let mut written = Keymap::defaults();
536+ written.rebind(1, chord("w", true)).unwrap();
537+ // The config directory does not exist yet -- the first save makes it.
538+ written.save_to(&path).unwrap();
539+ let (read, notice) = Keymap::load_from(&path);
540+ assert_eq!(notice, None);
541+ assert_eq!(read, written);
542+ assert_eq!(read.lookup("w", true), Some(ActionId::Export));
543+ assert_eq!(read.lookup("e", false), None);
544+ // The rename left nothing half-written behind.
545+ assert!(!dir.join("edith").join("keybindings.part").exists());
546+ // A file that is merely absent is not an error and says nothing.
547+ let (fresh, notice) = Keymap::load_from(&dir.join("nothing-here"));
548+ assert_eq!(fresh, Keymap::defaults());
549+ assert_eq!(notice, None);
550+ // A corrupt one names its line and still leaves a usable keymap.
551+ std::fs::write(&path, "edith-keys 1\nplay ctrl+alt+x\n").unwrap();
552+ let (fallback, notice) = Keymap::load_from(&path);
553+ assert_eq!(fallback, Keymap::defaults());
554+ let notice = notice.expect("a refused file must say so");
555+ assert!(notice.contains("line 2:"), "{notice}");
556+ assert!(notice.contains("keybindings"), "{notice}");
557+ // Saving over it is a whole replacement, not an edit.
558+ Keymap::defaults().save_to(&path).unwrap();
559+ assert_eq!(Keymap::load_from(&path), (Keymap::defaults(), None));
560+ std::fs::remove_dir_all(&dir).ok();
561+ }
562+
563+ #[test]
564+ fn the_config_path_follows_xdg_then_home() {
565+ let p = |xdg: Option<&str>, home: Option<&str>| {
566+ config_path_in(xdg.map(Into::into), home.map(Into::into))
567+ };
568+ assert_eq!(
569+ p(Some("/x/config"), Some("/home/u")),
570+ std::path::Path::new("/x/config/edith/keybindings")
571+ );
572+ assert_eq!(
573+ p(None, Some("/home/u")),
574+ std::path::Path::new("/home/u/.config/edith/keybindings")
575+ );
576+ // An empty XDG_CONFIG_HOME is one the spec says to ignore.
577+ assert_eq!(
578+ p(Some(""), Some("/home/u")),
579+ std::path::Path::new("/home/u/.config/edith/keybindings")
580+ );
581+ // Nowhere to put it but here -- still never `/edith/keybindings`.
582+ assert_eq!(
583+ p(None, None),
584+ std::path::Path::new(".config/edith/keybindings")
585+ );
586+ }
587+}
crates/app/src/main.rsmodified+332 -47
@@ -1,3 +1,7 @@
1+mod keymap;
2+
3+use keymap::{ActionId, Keymap};
4+
1 use std::cell::Cell;5 use std::cell::Cell;
2 use std::path::PathBuf;6 use std::path::PathBuf;
3 use std::rc::Rc;7 use std::rc::Rc;
@@ -9,7 +13,7 @@ use gpui::{
9 AnyElement, App, Application, Bounds, ClickEvent, Context, FocusHandle, KeyDownEvent,13 AnyElement, App, Application, Bounds, ClickEvent, Context, FocusHandle, KeyDownEvent,
10 MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, RenderImage,14 MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, RenderImage,
11 SharedString, TitlebarOptions, Window, WindowBounds, WindowOptions, canvas, div, img, point,15 SharedString, TitlebarOptions, Window, WindowBounds, WindowOptions, canvas, div, img, point,
12- prelude::*, px, relative, rgb, size,16+ prelude::*, px, relative, rgb, rgba, size,
13 };17 };
14 18
15 /// Editor chrome: three grays and one accent, all darker than the picture so the19 /// Editor chrome: three grays and one accent, all darker than the picture so the
@@ -51,11 +55,15 @@ const RULER_HIT_H: f32 = HIT_MIN;
51 /// Wide enough for `HH:MM:SS:FF / HH:MM:SS:FF`, and fixed so changing digits55 /// Wide enough for `HH:MM:SS:FF / HH:MM:SS:FF`, and fixed so changing digits
52 /// cannot push the layout around.56 /// cannot push the layout around.
53 const TIME_W: f32 = 200.;57 const TIME_W: f32 = 200.;
54-/// The shortcuts no button carries; the rest ride on the buttons' tooltips.58+/// The keybindings card: 11 rows and a title inside a 360 px tall window.
55-/// Keys first: at a 640 px window the tail is what a truncation eats, and the59+const KEYS_W: f32 = 300.;
56-/// two hints at the end are also on the ruler's and Import's tooltips.60+const KEYS_ROW_H: f32 = 20.;
57-const KEY_HINTS: &str =61+
58- "ctrl+c copy · ctrl+v paste · z undo · click the bar to seek · drop a file to import";62+/// The one key name this file still spells out, and gpui's spelling of it: it
63+/// is the way out of a capture and out of the overlay, and both have to work
64+/// while the keymap itself is what is being changed -- so neither can go
65+/// through the keymap to find it.
66+const ESCAPE: &str = "escape";
59 67
60 struct Player {68 struct Player {
61 session: PlaybackSession,69 session: PlaybackSession,
@@ -87,7 +95,7 @@ struct Player {
87 scrubbing: bool,95 scrubbing: bool,
88 last_scrub: Instant,96 last_scrub: Instant,
89 last_target: u32,97 last_target: u32,
90- /// Playback was started once, on the first render. Space owns it after that.98+ /// Playback was started once, on the first render. The play binding owns it after that.
91 launched: bool,99 launched: bool,
92 /// The running export. While it owns the UI the editor is read-only.100 /// The running export. While it owns the UI the editor is read-only.
93 export: Option<ExportHandle>,101 export: Option<ExportHandle>,
@@ -99,10 +107,20 @@ struct Player {
99 /// Where an export writes. Built once from the source path, which is not107 /// Where an export writes. Built once from the source path, which is not
100 /// otherwise kept.108 /// otherwise kept.
101 export_path: PathBuf,109 export_path: PathBuf,
102- /// Where ctrl+s writes: the project this timeline was loaded from, or the110+ /// Where the save action writes: the project this timeline was loaded from,
103- /// one derived beside the media it started as. Saving twice overwrites the111+ /// or the one derived beside the media it started as. Saving twice
104- /// same file rather than making a second one.112+ /// overwrites the same file rather than making a second one.
105 project_path: PathBuf,113 project_path: PathBuf,
114+ /// Which stroke means what, and what every shortcut on screen is called.
115+ /// The one place either question is answered.
116+ keymap: Keymap,
117+ /// The keybindings overlay is up. While it is, it owns the keyboard and the
118+ /// pointer: a stroke or a click meant for a row must not also cut the
119+ /// timeline.
120+ keys_open: bool,
121+ /// The row waiting for a stroke, as an index into `keymap.entries()`. The
122+ /// next key that is neither escape nor a lone modifier *is* that binding.
123+ rebinding: Option<usize>,
106 /// What the last file action had to say. Holds its own bar above the panel124 /// What the last file action had to say. Holds its own bar above the panel
107 /// until it is answered -- any key retires it, so does a click on it -- so a125 /// until it is answered -- any key retires it, so does a click on it -- so a
108 /// failure is read in full instead of blinking past.126 /// failure is read in full instead of blinking past.
@@ -352,6 +370,33 @@ impl Player {
352 cx.notify();370 cx.notify();
353 }371 }
354 372
373+ /// The stroke a waiting row was after. A chord another action already holds
374+ /// is refused by the keymap and the row keeps waiting, so the next stroke is
375+ /// another try rather than a lost one. A binding that took holds either way:
376+ /// what a failed write costs is only the next run, which is what the notice
377+ /// is for.
378+ fn capture(&mut self, index: usize, key: &str, ctrl: bool) {
379+ let chord = keymap::Chord {
380+ key: key.to_string(),
381+ ctrl,
382+ };
383+ let text = match self.keymap.rebind(index, chord.clone()) {
384+ Ok(()) => {
385+ self.rebinding = None;
386+ match self.keymap.save() {
387+ Ok(()) => return,
388+ Err(e) => format!(
389+ "KEYBINDINGS NOT SAVED — {}: {e}",
390+ Keymap::config_path().display()
391+ ),
392+ }
393+ }
394+ Err(holder) => format!("ALREADY BOUND — {} is {}", chord.pretty(), holder.label()),
395+ };
396+ eprintln!("{text}");
397+ self.notice = Some(text.into());
398+ }
399+
355 /// Seeks to where the pointer sits along the ruler. `commit` is the press400 /// Seeks to where the pointer sits along the ruler. `commit` is the press
356 /// and the release, which must land exactly even when the throttle below401 /// and the release, which must land exactly even when the throttle below
357 /// would have skipped them.402 /// would have skipped them.
@@ -365,7 +410,7 @@ impl Player {
365 }410 }
366 }411 }
367 412
368- /// Space and the transport button share it: once the timeline is finished413+ /// The play binding and the transport button share it: once the timeline is finished
369 /// the only sensible "play" is from the top.414 /// the only sensible "play" is from the top.
370 fn toggle_or_restart(&mut self, cx: &mut Context<Self>) {415 fn toggle_or_restart(&mut self, cx: &mut Context<Self>) {
371 if self.exporting().is_some() {416 if self.exporting().is_some() {
@@ -478,36 +523,60 @@ impl Render for Player {
478 // Any key retires the last message, whatever it was -- and owes523 // Any key retires the last message, whatever it was -- and owes
479 // the repaint itself: a notice no longer keeps the render loop524 // the repaint itself: a notice no longer keeps the render loop
480 // alive, and the arms below that do notify are not all of them525 // alive, and the arms below that do notify are not all of them
481- // (an unbound key, or ctrl+c, changes nothing else).526+ // (an unbound key, or the copy chord, changes nothing else).
482 if this.notice.take().is_some() {527 if this.notice.take().is_some() {
483 cx.notify();528 cx.notify();
484 }529 }
485- // An export is reading the edit list every other key here would530+ let key = event.keystroke.key.as_str();
486- // change, so escape is the only one that means anything until531+ // A row is waiting for a stroke, and while it is, that stroke is
487- // it is over.532+ // data: it means the binding and nothing else, which is why this
533+ // answers before the export guard and before the keymap is
534+ // consulted at all.
535+ if let Some(index) = this.rebinding {
536+ if key == ESCAPE {
537+ this.rebinding = None;
538+ } else if !is_bare_modifier(key) {
539+ this.capture(index, key, event.keystroke.modifiers.control);
540+ }
541+ cx.notify();
542+ return;
543+ }
544+ // On linux gpui reports the copy chord as key "c" with the
545+ // control modifier set (the control code is mapped back), which
546+ // is why the keymap is keyed on the pair and never on the key
547+ // alone.
548+ let action = this.keymap.lookup(key, event.keystroke.modifiers.control);
549+ // An export is reading the edit list every other action here
550+ // would change, so cancelling is the only one that means
551+ // anything until it is over.
488 if this.exporting().is_some() {552 if this.exporting().is_some() {
489- if event.keystroke.key.as_str() == "escape" {553+ if cancels_export(key, action) {
490 this.cancel_export();554 this.cancel_export();
491 }555 }
492 cx.notify();556 cx.notify();
493 return;557 return;
494 }558 }
495- // On linux gpui reports ctrl-c as key "c" with the control559+ // The overlay owns the keyboard while it is up: a stroke aimed
496- // modifier set (the control code is mapped back), so the plain560+ // at a row must not also cut the timeline, and the way out of it
497- // and modified bindings are told apart here and nowhere else.561+ // is the same key that gets out of a capture.
498- match (562+ if this.keys_open {
499- event.keystroke.key.as_str(),563+ if key == ESCAPE {
500- event.keystroke.modifiers.control,564+ this.keys_open = false;
501- ) {565+ cx.notify();
502- ("space", _) => this.toggle_or_restart(cx),566+ }
503- ("e", false) => this.start_export(cx),567+ return;
504- ("s", true) => this.save_project(cx),568+ }
505- ("c", true) => this.copy_selected(),569+ match action {
506- ("v", true) => this.paste(cx),570+ Some(ActionId::Play) => this.toggle_or_restart(cx),
507- ("c", false) => this.cut(cx),571+ Some(ActionId::Export) => this.start_export(cx),
508- ("x", _) | ("delete", _) => this.delete_selected(cx),572+ Some(ActionId::Save) => this.save_project(cx),
509- ("z", _) => this.undo(cx),573+ Some(ActionId::Copy) => this.copy_selected(),
510- _ => {}574+ Some(ActionId::Paste) => this.paste(cx),
575+ Some(ActionId::Cut) => this.cut(cx),
576+ Some(ActionId::Delete) => this.delete_selected(cx),
577+ Some(ActionId::Undo) => this.undo(cx),
578+ // Nothing to cancel while nothing is exporting.
579+ Some(ActionId::CancelExport) | None => {}
511 }580 }
512 }))581 }))
513 // The whole window is the drop target: gpui turns an external file582 // The whole window is the drop target: gpui turns an external file
@@ -515,6 +584,13 @@ impl Render for Player {
515 // mouse-up to every hovered hitbox, and the root's is the only one584 // mouse-up to every hovered hitbox, and the root's is the only one
516 // that covers the picture as well as the panel.585 // that covers the picture as well as the panel.
517 .on_drop(cx.listener(|this, paths: &gpui::ExternalPaths, _, cx| {586 .on_drop(cx.listener(|this, paths: &gpui::ExternalPaths, _, cx| {
587+ // The overlay owns the pointer as well as the keyboard, and a
588+ // drop is a click the scrim cannot swallow: gpui delivers it to
589+ // the root's hitbox, which is under the scrim but is not a
590+ // sibling it can stop.
591+ if this.keys_open {
592+ return;
593+ }
518 for path in paths.paths() {594 for path in paths.paths() {
519 // A project replaces the timeline, media is appended to it.595 // A project replaces the timeline, media is appended to it.
520 if is_project(path) {596 if is_project(path) {
@@ -582,6 +658,8 @@ impl Render for Player {
582 // the picture nothing the rest of the time.658 // the picture nothing the rest of the time.
583 .children(self.notice_bar(cx))659 .children(self.notice_bar(cx))
584 .child(self.panel(position, duration, playing, cx))660 .child(self.panel(position, duration, playing, cx))
661+ // Last, so it is over everything -- it takes no room in the column.
662+ .children(self.keys_overlay(cx))
585 }663 }
586 }664 }
587 665
@@ -603,14 +681,31 @@ impl Player {
603 // percentage and the accent bar are the same number, so the playhead681 // percentage and the accent bar are the same number, so the playhead
604 // fill doubles as the progress bar for free.682 // fill doubles as the progress bar for free.
605 let exporting = self.exporting().is_some();683 let exporting = self.exporting().is_some();
684+ let key = |action| self.keymap.display(action);
606 let (hint, filled) = if let Some(export) = self.exporting() {685 let (hint, filled) = if let Some(export) = self.exporting() {
607 let progress = export.progress();686 let progress = export.progress();
608 (687 (
609- format!("EXPORTING {}% — esc cancels", (progress * 100.) as u32),688+ format!(
689+ "EXPORTING {}% — {} cancels",
690+ (progress * 100.) as u32,
691+ key(ActionId::CancelExport)
692+ ),
610 progress,693 progress,
611 )694 )
612 } else {695 } else {
613- (KEY_HINTS.to_string(), filled)696+ // The strokes no button carries; the rest ride on the buttons'
697+ // tooltips. Keys first: at a 640 px window the tail is what a
698+ // truncation eats, and the two hints at the end are also on the
699+ // ruler's and Import's tooltips.
700+ (
701+ format!(
702+ "{} copy · {} paste · {} undo · click the bar to seek · drop a file to import",
703+ key(ActionId::Copy),
704+ key(ActionId::Paste),
705+ key(ActionId::Undo)
706+ ),
707+ filled,
708+ )
614 };709 };
615 div()710 div()
616 .flex_none()711 .flex_none()
@@ -633,7 +728,7 @@ impl Player {
633 "transport",728 "transport",
634 Some(transport_glyph(playing).into_any_element()),729 Some(transport_glyph(playing).into_any_element()),
635 if playing { "Pause" } else { "Play" },730 if playing { "Pause" } else { "Play" },
636- "space",731+ key(ActionId::Play),
637 !exporting,732 !exporting,
638 cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_or_restart(cx)),733 cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_or_restart(cx)),
639 ))734 ))
@@ -642,7 +737,10 @@ impl Player {
642 "cut",737 "cut",
643 Some(cut_glyph().into_any_element()),738 Some(cut_glyph().into_any_element()),
644 "Cut",739 "Cut",
645- "c — splits the clip under the playhead",740+ format!(
741+ "{} — splits the clip under the playhead",
742+ key(ActionId::Cut)
743+ ),
646 !exporting,744 !exporting,
647 cx.listener(|this, _: &ClickEvent, _, cx| this.cut(cx)),745 cx.listener(|this, _: &ClickEvent, _, cx| this.cut(cx)),
648 ))746 ))
@@ -651,9 +749,9 @@ impl Player {
651 Some(delete_glyph().into_any_element()),749 Some(delete_glyph().into_any_element()),
652 "Delete",750 "Delete",
653 if self.selected.is_some() {751 if self.selected.is_some() {
654- "x or delete"752+ key(ActionId::Delete)
655 } else {753 } else {
656- "x or delete — click a clip below first"754+ format!("{} — click a clip below first", key(ActionId::Delete))
657 },755 },
658 !exporting && self.selected.is_some(),756 !exporting && self.selected.is_some(),
659 cx.listener(|this, _: &ClickEvent, _, cx| this.delete_selected(cx)),757 cx.listener(|this, _: &ClickEvent, _, cx| this.delete_selected(cx)),
@@ -663,7 +761,7 @@ impl Player {
663 "import",761 "import",
664 None,762 None,
665 "Import",763 "Import",
666- "opens a file chooser — or drop a file on the window",764+ "opens a file chooser — or drop a file on the window".to_string(),
667 !exporting,765 !exporting,
668 cx.listener(|this, _: &ClickEvent, _, cx| this.pick_and_import(cx)),766 cx.listener(|this, _: &ClickEvent, _, cx| this.pick_and_import(cx)),
669 ))767 ))
@@ -671,7 +769,10 @@ impl Player {
671 "export",769 "export",
672 None,770 None,
673 "Export",771 "Export",
674- "e — writes the timeline out beside the source",772+ format!(
773+ "{} — writes the timeline out beside the source",
774+ key(ActionId::Export)
775+ ),
675 self.export.is_none(),776 self.export.is_none(),
676 cx.listener(|this, _: &ClickEvent, _, cx| this.start_export(cx)),777 cx.listener(|this, _: &ClickEvent, _, cx| this.start_export(cx)),
677 ))778 ))
@@ -679,9 +780,24 @@ impl Player {
679 "save",780 "save",
680 None,781 None,
681 "Save",782 "Save",
682- "ctrl+s — writes the project file",783+ format!("{} — writes the project file", key(ActionId::Save)),
683 !exporting,784 !exporting,
684 cx.listener(|this, _: &ClickEvent, _, cx| this.save_project(cx)),785 cx.listener(|this, _: &ClickEvent, _, cx| this.save_project(cx)),
786+ ))
787+ // No shortcut of its own -- and closed while an export runs,
788+ // which is what keeps a waiting row from swallowing the
789+ // escape the progress line promises cancels the export.
790+ .child(control(
791+ "keys",
792+ None,
793+ "Keys",
794+ "show and change the keybindings".to_string(),
795+ !exporting,
796+ cx.listener(|this, _: &ClickEvent, _, cx| {
797+ this.keys_open = !this.keys_open;
798+ this.rebinding = None;
799+ cx.notify();
800+ }),
685 )),801 )),
686 )802 )
687 .child(803 .child(
@@ -785,11 +901,106 @@ impl Player {
785 )901 )
786 }902 }
787 903
904+ /// Every binding, and the way to change one: a row per entry, click it and
905+ /// the next stroke becomes its chord. Over the whole window, because while
906+ /// it is up nothing under it may answer -- the scrim stops the clicks
907+ /// (gpui dispatches mouse listeners topmost-first, window.rs:3705) and the
908+ /// key handler's own branch stops the strokes.
909+ ///
910+ /// Plain divs, like every control here: nothing in it takes focus, so the
911+ /// root is still the one reading the keyboard -- which is exactly what a
912+ /// waiting row depends on.
913+ fn keys_overlay(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
914+ if !self.keys_open {
915+ return None;
916+ }
917+ // The way out, spelled the way the rows spell a chord.
918+ let out = keymap::Chord {
919+ key: ESCAPE.to_string(),
920+ ctrl: false,
921+ }
922+ .pretty();
923+ let rows: Vec<_> = self
924+ .keymap
925+ .entries()
926+ .iter()
927+ .enumerate()
928+ .map(|(i, binding)| {
929+ let capturing = self.rebinding == Some(i);
930+ let out = out.clone();
931+ div()
932+ .id(("bind", i))
933+ .flex()
934+ .h(px(KEYS_ROW_H))
935+ .items_center()
936+ .justify_between()
937+ .gap(px(12.))
938+ .px(px(6.))
939+ .rounded(px(3.))
940+ .cursor_pointer()
941+ .hover(|s| s.bg(rgb(HOVER)))
942+ .when(capturing, |d| d.bg(rgb(SELECTED)))
943+ .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
944+ this.rebinding = Some(i);
945+ cx.notify();
946+ }))
947+ .child(binding.action.label())
948+ .child(if capturing {
949+ div()
950+ .text_color(rgb(INK_DIM))
951+ .child(format!("press a key — {out} cancels"))
952+ } else {
953+ div().child(binding.chord.pretty())
954+ })
955+ })
956+ .collect();
957+ Some(
958+ div()
959+ .absolute()
960+ .inset_0()
961+ .flex()
962+ .justify_center()
963+ .items_center()
964+ // The picture behind is out of reach, and looks it. The press is
965+ // swallowed here so a button under the scrim cannot take it.
966+ .bg(rgba(0x101010cc))
967+ .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| {
968+ cx.stop_propagation()
969+ })
970+ .child(
971+ div()
972+ .w(px(KEYS_W))
973+ .flex()
974+ .flex_col()
975+ .gap(px(2.))
976+ .p(px(12.))
977+ .rounded(px(6.))
978+ .bg(rgb(SURFACE))
979+ .child(
980+ div()
981+ .h(px(KEYS_ROW_H))
982+ .px(px(6.))
983+ .child("Keybindings — click a row, then press a key"),
984+ )
985+ .children(rows)
986+ // A refusal belongs where the click was: the notice bar
987+ // itself is under the scrim.
988+ .children(self.notice.clone().map(|notice| {
989+ div()
990+ .px(px(6.))
991+ .text_size(px(11.))
992+ .text_color(rgb(INK_DIM))
993+ .child(notice)
994+ })),
995+ ),
996+ )
997+ }
998+
788 /// The edit list made visible: one box per clip, sized by its share of the999 /// The edit list made visible: one box per clip, sized by its share of the
789 /// timeline. A cut adds a box without moving anything, a delete closes the1000 /// timeline. A cut adds a box without moving anything, a delete closes the
790 /// gap. A box has no room for a label at four clips, so the tooltip is where1001 /// gap. A box has no room for a label at four clips, so the tooltip is where
791 /// it says what clicking it does. Never focusable, so the root keeps focus1002 /// it says what clicking it does. Never focusable, so the root keeps focus
792- /// and space still works after a click (ledger:182).1003+ /// and the play binding still works after a click (ledger:182).
793 fn clips_lane(&self, duration: f64, cx: &mut Context<Self>) -> impl IntoElement {1004 fn clips_lane(&self, duration: f64, cx: &mut Context<Self>) -> impl IntoElement {
794 div()1005 div()
795 .flex_none()1006 .flex_none()
@@ -873,7 +1084,7 @@ fn export_path(source: impl Into<PathBuf>) -> PathBuf {
873 path1084 path
874 }1085 }
875 1086
876-/// Where ctrl+s goes when the timeline did not come from a project file: the1087+/// Where a save goes when the timeline did not come from a project file: the
877 /// media path with `.edith` for an extension, beside it like an export. A1088 /// media path with `.edith` for an extension, beside it like an export. A
878 /// project loaded from disk keeps its own path instead, so saving it twice1089 /// project loaded from disk keeps its own path instead, so saving it twice
879 /// writes the same file.1090 /// writes the same file.
@@ -906,6 +1117,27 @@ fn source_tint(source: usize) -> u32 {
906 SOURCE_TINTS[source % SOURCE_TINTS.len()]1117 SOURCE_TINTS[source % SOURCE_TINTS.len()]
907 }1118 }
908 1119
1120+/// Whether a stroke gets out of a running export. Escape does, whatever
1121+/// modifiers are held with it, for the same reason it gets out of a capture and
1122+/// out of the overlay: it is this window's way out, and a way out that only
1123+/// works with the right modifiers is not one. Whatever the keymap has on cancel
1124+/// works too, so rebinding it adds a way rather than replacing the one that
1125+/// always worked -- and that binding is still what the progress line shows.
1126+fn cancels_export(key: &str, action: Option<ActionId>) -> bool {
1127+ key == ESCAPE || action == Some(ActionId::CancelExport)
1128+}
1129+
1130+/// The keys that are only ever half a chord. gpui delivers a lone modifier
1131+/// press as a keystroke of its own, and taking one as a binding would leave an
1132+/// action that fires the moment the user reaches for any chord that uses it --
1133+/// so a capture waits through them instead.
1134+fn is_bare_modifier(key: &str) -> bool {
1135+ matches!(
1136+ key,
1137+ "control" | "shift" | "alt" | "super" | "platform" | "function" | "fn" | "meta" | "command"
1138+ )
1139+}
1140+
909 /// A clip's share of the lane. A timeline with no length reads as one full-width1141 /// A clip's share of the lane. A timeline with no length reads as one full-width
910 /// box rather than as NaN, which gpui would carry into layout.1142 /// box rather than as NaN, which gpui would carry into layout.
911 fn width_frac(len: f64, total: f64) -> f32 {1143 fn width_frac(len: f64, total: f64) -> f32 {
@@ -922,7 +1154,7 @@ fn control(
922 id: &'static str,1154 id: &'static str,
923 glyph: Option<AnyElement>,1155 glyph: Option<AnyElement>,
924 label: &'static str,1156 label: &'static str,
925- shortcut: &'static str,1157+ shortcut: String,
926 enabled: bool,1158 enabled: bool,
927 on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,1159 on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
928 ) -> impl IntoElement {1160 ) -> impl IntoElement {
@@ -1089,8 +1321,9 @@ fn timecode(t: f64, fps: f64) -> String {
1089 #[cfg(test)]1321 #[cfg(test)]
1090 mod tests {1322 mod tests {
1091 use super::{1323 use super::{
1092- CONTROL_H, HIT_MIN, LANE_H, RULER_HIT_H, SOURCE_TINTS, SURFACE, export_path, frac_along,1324+ CONTROL_H, HIT_MIN, KEYS_ROW_H, KEYS_W, LANE_H, RULER_HIT_H, SOURCE_TINTS, SURFACE,
1093- is_project, project_path, scrub_due, source_tint, timecode, width_frac,1325+ cancels_export, export_path, frac_along, is_bare_modifier, is_project, keymap,
1326+ project_path, scrub_due, source_tint, timecode, width_frac,
1094 };1327 };
1095 use gpui::{Bounds, Pixels, point, px, size};1328 use gpui::{Bounds, Pixels, point, px, size};
1096 use std::time::Duration;1329 use std::time::Duration;
@@ -1199,6 +1432,49 @@ mod tests {
1199 assert_eq!(width_frac(0., 0.), 1.);1432 assert_eq!(width_frac(0., 0.), 1.);
1200 }1433 }
1201 1434
1435+ #[test]
1436+ fn escape_gets_out_of_an_export_whatever_is_held_with_it() {
1437+ use keymap::ActionId;
1438+ // The regression this guards: looking the stroke up in the keymap made
1439+ // ctrl+escape mean nothing, and an export that a modifier could trap
1440+ // the user inside of is worse than an unbound chord.
1441+ assert!(cancels_export("escape", None));
1442+ assert!(cancels_export("escape", Some(ActionId::CancelExport)));
1443+ // A rebound cancel works as well -- it adds a way out, never replaces
1444+ // the one that always worked.
1445+ assert!(cancels_export("q", Some(ActionId::CancelExport)));
1446+ // Nothing else does, whatever it means outside an export.
1447+ assert!(!cancels_export("e", Some(ActionId::Export)));
1448+ assert!(!cancels_export("space", Some(ActionId::Play)));
1449+ assert!(!cancels_export("q", None));
1450+ }
1451+
1452+ #[test]
1453+ fn a_capture_waits_through_a_lone_modifier() {
1454+ // gpui delivers these on their own; taking one as a binding would make
1455+ // the action fire on the way to every chord that uses it.
1456+ for key in [
1457+ "control", "shift", "alt", "super", "platform", "function", "fn", "meta", "command",
1458+ ] {
1459+ assert!(is_bare_modifier(key), "{key}");
1460+ }
1461+ // Everything a binding is actually made of, escape included -- the
1462+ // capture branch turns that one away itself.
1463+ for key in ["c", "x", "space", "escape", "delete", "f1", "z"] {
1464+ assert!(!is_bare_modifier(key), "{key}");
1465+ }
1466+ }
1467+
1468+ #[test]
1469+ fn the_keybindings_card_fits_the_smallest_window() {
1470+ // A title line plus a row per default binding, inside the 640x360 the
1471+ // rest of the layout is already sized for.
1472+ let lines = keymap::Keymap::defaults().entries().len() as f32 + 1.;
1473+ // Rows, their 2 px gaps, the card's 12 px padding top and bottom.
1474+ assert!(lines * (KEYS_ROW_H + 2.) + 24. <= 360., "card too tall");
1475+ assert!(KEYS_W <= 640., "card too wide");
1476+ }
1477+
1202 #[test]1478 #[test]
1203 fn nothing_clickable_is_smaller_than_the_wcag_minimum() {1479 fn nothing_clickable_is_smaller_than_the_wcag_minimum() {
1204 // Every hit target in the panel, including the scrub strip -- whose bar1480 // Every hit target in the panel, including the scrub strip -- whose bar
@@ -1245,10 +1521,16 @@ fn main() {
1245 std::process::exit(1);1521 std::process::exit(1);
1246 }1522 }
1247 };1523 };
1524+ // A keymap file that cannot be read leaves the defaults in force, and takes
1525+ // the notice slot ahead of an import refusal below: it is about every key
1526+ // the window has, and the import refusal is on stderr either way.
1527+ let (keymap, mut notice) = Keymap::load();
1528+ if let Some(text) = &notice {
1529+ eprintln!("{text}");
1530+ }
1248 // The first file makes the timeline, the rest are appended to it. A refusal1531 // The first file makes the timeline, the rest are appended to it. A refusal
1249 // is not fatal -- the others still load -- but the window must not open1532 // is not fatal -- the others still load -- but the window must not open
1250 // silently pretending the file was taken, so the first one seeds the notice.1533 // silently pretending the file was taken, so the first one seeds the notice.
1251- let mut notice = None;
1252 for arg in std::env::args().skip(2) {1534 for arg in std::env::args().skip(2) {
1253 if let Err(e) = session.import(std::path::Path::new(&arg)) {1535 if let Err(e) = session.import(std::path::Path::new(&arg)) {
1254 let text = format!("IMPORT FAILED: {e}");1536 let text = format!("IMPORT FAILED: {e}");
@@ -1307,6 +1589,9 @@ fn main() {
1307 cancelling: false,1589 cancelling: false,
1308 export_path: out.clone(),1590 export_path: out.clone(),
1309 project_path: project.clone(),1591 project_path: project.clone(),
1592+ keymap: keymap.clone(),
1593+ keys_open: false,
1594+ rebinding: None,
1310 notice: notice.clone().map(SharedString::from),1595 notice: notice.clone().map(SharedString::from),
1311 displayed: 0,1596 displayed: 0,
1312 dropped: 0,1597 dropped: 0,