//! The keymap: which stroke means which action, and the file it survives in. //! //! ```text //! edith-keys 1 //! play space //! delete x //! delete delete //! save ctrl+s //! ``` //! //! One line per binding, so an action bound to two strokes is two lines and the //! format needs no list syntax. A chord is `key` or `ctrl+key`, where `key` is //! exactly what gpui reports for the stroke (`escape`, not `esc`) -- the lookup //! compares against that string and nothing translates in between. What a //! *person* reads is [`Keymap::display`]'s business, and only there. //! //! The parser is strict and every refusal names its 1-based line, like the //! project file: this file is generated by the keybindings editor, so a line it //! did not generate is a corrupt file rather than a dialect. A missing file is //! not corrupt -- it means nobody has changed a key yet, and the defaults stand. //! //! Writing mirrors `engine::edith::save`: `.part`, fsync, rename, directory //! fsync, so an interrupted save cannot cost the bindings that were already //! there. // The UI consumes this module in a later step; until then nothing calls it and // every item here reads as dead. #![allow(dead_code)] use std::ffi::OsString; use std::io::Write; use std::path::{Path, PathBuf}; /// First line, exactly. The version is part of it, as in the project file. const MAGIC: &str = "edith-keys 1"; /// Everything a stroke can ask for. Not the mouse's actions: only what a key /// can reach is bindable. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum ActionId { Play, Export, Save, Copy, Paste, Cut, Regroup, Delete, Lift, Undo, ToggleMute, VolumeUp, VolumeDown, CancelExport, } impl ActionId { /// Display order everywhere -- the editor lists them in it and /// [`Keymap::defaults`] binds them in it. pub const ALL: [ActionId; 14] = [ ActionId::Play, ActionId::Export, ActionId::Save, ActionId::Copy, ActionId::Paste, ActionId::Cut, ActionId::Regroup, ActionId::Delete, ActionId::Lift, ActionId::Undo, ActionId::ToggleMute, ActionId::VolumeUp, ActionId::VolumeDown, ActionId::CancelExport, ]; /// What a person calls it. pub fn label(self) -> &'static str { match self { ActionId::Play => "Play / Pause", ActionId::Export => "Export", ActionId::Save => "Save", ActionId::Copy => "Copy", ActionId::Paste => "Paste", ActionId::Cut => "Cut", ActionId::Regroup => "Regroup", ActionId::Delete => "Delete", ActionId::Lift => "Lift (leave a gap)", ActionId::Undo => "Undo", ActionId::ToggleMute => "Mute / Unmute", ActionId::VolumeUp => "Volume up", ActionId::VolumeDown => "Volume down", ActionId::CancelExport => "Cancel export", } } /// What the file calls it: ASCII, no spaces, one spelling per variant and /// never the label, which is free to be reworded. fn name(self) -> &'static str { match self { ActionId::Play => "play", ActionId::Export => "export", ActionId::Save => "save", ActionId::Copy => "copy", ActionId::Paste => "paste", ActionId::Cut => "cut", ActionId::Regroup => "regroup", ActionId::Delete => "delete", ActionId::Lift => "lift", ActionId::Undo => "undo", ActionId::ToggleMute => "toggle-mute", ActionId::VolumeUp => "volume-up", ActionId::VolumeDown => "volume-down", ActionId::CancelExport => "cancel-export", } } fn from_name(name: &str) -> Option { Self::ALL.into_iter().find(|a| a.name() == name) } } /// A stroke as the key handler sees it: gpui's key name plus the one modifier /// this editor binds. Nothing else is a chord here -- shift and alt are part of /// the key name gpui reports, and a second modifier would need the file format /// to grow before it could be spelled. #[derive(Clone, PartialEq, Eq, Debug)] pub struct Chord { pub key: String, pub ctrl: bool, } impl Chord { /// The file's spelling, and the only one [`parse`] accepts back. fn text(&self) -> String { if self.ctrl { format!("ctrl+{}", self.key) } else { self.key.clone() } } /// The spelling a person reads. Identical to [`Chord::text`] but for the one /// key whose usual name is shorter than gpui's. Public because a /// keybindings row shows one chord, where [`Keymap::display`] shows every /// chord an action answers to. pub fn pretty(&self) -> String { let key = if self.key == "escape" { "esc" } else { &self.key }; if self.ctrl { format!("ctrl+{key}") } else { key.to_string() } } /// Strict: exactly one optional `ctrl+` and then a key gpui could have /// reported. A spelling this cannot emit back unchanged is refused rather /// than normalised, because the round-trip is what makes the file editable /// by hand at all. fn parse(text: &str, n: usize) -> Result { let (ctrl, key) = match text.strip_prefix("ctrl+") { Some(key) => (true, key), None => (false, text), }; if key.is_empty() || key.contains(' ') || key.contains('+') || key.chars().any(|c| c.is_ascii_uppercase()) { return Err(format!("line {n}: {text:?} is not a chord")); } Ok(Chord { key: key.to_string(), ctrl, }) } } /// One stroke, one action. Two strokes for the same action are two bindings. #[derive(Clone, PartialEq, Eq, Debug)] pub struct Binding { pub action: ActionId, pub chord: Chord, } /// Every binding in force, in display order. No chord appears twice -- that is /// the invariant [`Keymap::rebind_action`] and [`parse`] both defend, and it is what /// lets [`Keymap::lookup`] answer with the first match. #[derive(Clone, PartialEq, Eq, Debug)] pub struct Keymap { bindings: Vec, } impl Keymap { /// The bindings the editor has always had, in the order the editor lists /// them. Delete and undo get two strokes each because both have always /// answered to two. pub fn defaults() -> Self { let b = |action, key: &str, ctrl| Binding { action, chord: Chord { key: key.to_string(), ctrl, }, }; Keymap { bindings: vec![ b(ActionId::Play, "space", false), b(ActionId::Export, "e", false), b(ActionId::Save, "s", true), b(ActionId::Copy, "c", true), b(ActionId::Paste, "v", true), b(ActionId::Cut, "c", false), // The two lane keys, on the letters they are named after: both // were free, and neither is next to a key that edits. b(ActionId::Regroup, "g", false), b(ActionId::Delete, "x", false), b(ActionId::Delete, "delete", false), b(ActionId::Lift, "l", false), b(ActionId::Undo, "z", false), b(ActionId::Undo, "z", true), b(ActionId::ToggleMute, "m", false), // The unshifted pair, which is what gpui reports for those two // keys ("=" and "-", platform.rs:862): the volume keys every // player has, without asking for shift to make the "+". b(ActionId::VolumeUp, "=", false), b(ActionId::VolumeDown, "-", false), b(ActionId::CancelExport, "escape", false), ], } } /// What a stroke means, if anything. `key` is gpui's key name and `ctrl` its /// control modifier -- the pair the key handler already matches on. pub fn lookup(&self, key: &str, ctrl: bool) -> Option { self.bindings .iter() .find(|b| b.chord.ctrl == ctrl && b.chord.key == key) .map(|b| b.action) } /// Every stroke that reaches an action, as one readable phrase: `x or /// delete`. An action nobody can reach says so rather than reading blank. pub fn display(&self, action: ActionId) -> String { let strokes: Vec = self .bindings .iter() .filter(|b| b.action == action) .map(|b| b.chord.pretty()) .collect(); if strokes.is_empty() { "unbound".to_string() } else { strokes.join(" or ") } } /// Every binding, in display order. pub fn entries(&self) -> &[Binding] { &self.bindings } /// Makes `chord` the whole of what reaches `action`: its other chords go, so /// what the editor shows for an action is what a rebind replaced. Two /// strokes for one action stay expressible, but only in the file -- the /// parser takes as many lines per action as it is given. /// /// `Err` names the action that already holds the chord and nothing changes: /// two actions on one stroke would make the second unreachable, and silently /// stealing it is worse than refusing. A chord the action already holds is /// not a conflict with itself -- it collapses the action onto that one. pub fn rebind_action(&mut self, action: ActionId, chord: Chord) -> Result<(), ActionId> { if let Some(held) = self .bindings .iter() .find(|b| b.action != action && b.chord == chord) { return Err(held.action); } self.bindings.retain(|b| b.action != action); // Back into its own place in the display order rather than onto the end, // so the file and the editor keep reading in the order of `ALL`. let at = self .bindings .iter() .position(|b| rank(b.action) > rank(action)) .unwrap_or(self.bindings.len()); self.bindings.insert(at, Binding { action, chord }); Ok(()) } /// The keymap in force, and what to tell the user if the file could not be /// used. A file that is merely absent is the normal case and says nothing; /// anything else -- unreadable, or a line this parser refuses -- falls back /// to the defaults *and* is reported, because a keymap silently not applied /// is a keyboard that has quietly changed under the user. pub fn load() -> (Self, Option) { Self::load_from(&Self::config_path()) } /// All of [`Keymap::load`] but the path, which the config directory decides /// and a test must not be allowed to. fn load_from(path: &Path) -> (Self, Option) { let text = match std::fs::read_to_string(path) { Ok(text) => text, Err(e) if e.kind() == std::io::ErrorKind::NotFound => return (Self::defaults(), None), Err(e) => { return ( Self::defaults(), Some(format!( "KEYBINDINGS IGNORED — {}: {e} — the defaults are in force", path.display() )), ); } }; match parse(&text) { Ok(keymap) => (keymap, None), Err(e) => ( Self::defaults(), Some(format!( "KEYBINDINGS IGNORED — {}, {e} — the defaults are in force", path.display() )), ), } } /// Writes the keymap, atomically, creating the config directory if this is /// the first save. Until the rename the previous bindings are still the /// whole truth on disk. pub fn save(&self) -> std::io::Result<()> { self.save_to(&Self::config_path()) } /// All of [`Keymap::save`] but the path, for the same reason as /// [`Keymap::load_from`]. fn save_to(&self, path: &Path) -> std::io::Result<()> { let dir = path.parent().unwrap_or(Path::new(".")).to_path_buf(); std::fs::create_dir_all(&dir)?; let mut part = path.to_path_buf().into_os_string(); part.push(".part"); let part = PathBuf::from(part); let result = std::fs::File::create(&part) .and_then(|mut f| { f.write_all(emit(self).as_bytes())?; f.sync_all() }) .and_then(|()| std::fs::rename(&part, path)) .and_then(|()| std::fs::File::open(&dir)?.sync_all()); if result.is_err() { let _ = std::fs::remove_file(&part); } result } /// Where the bindings live: the XDG config directory, or `~/.config` when /// the desktop has not named one. pub fn config_path() -> PathBuf { config_path_in( std::env::var_os("XDG_CONFIG_HOME"), std::env::var_os("HOME"), ) } } /// Where an action sits in the display order, which is the order of /// [`ActionId::ALL`] and the order the file is written in. fn rank(action: ActionId) -> usize { ActionId::ALL .iter() .position(|a| *a == action) .unwrap_or(ActionId::ALL.len()) } /// The path rule, with the environment handed in so it can be checked. An /// `XDG_CONFIG_HOME` that is empty is one the spec says to ignore; with no /// `HOME` either there is nowhere but here, and a relative path is still better /// than dropping the file in `/`. fn config_path_in(xdg: Option, home: Option) -> PathBuf { let dir = xdg .filter(|v| !v.is_empty()) .map(PathBuf::from) .or_else(|| { home.filter(|v| !v.is_empty()) .map(|h| PathBuf::from(h).join(".config")) }) .unwrap_or_else(|| PathBuf::from(".config")); dir.join("edith").join("keybindings") } fn emit(keymap: &Keymap) -> String { let mut out = String::from(MAGIC); out.push('\n'); for b in &keymap.bindings { out.push_str(b.action.name()); out.push(' '); out.push_str(&b.chord.text()); out.push('\n'); } out } fn parse(text: &str) -> Result { // One trailing newline terminates the last line rather than starting an // empty one; a second is an empty line and is refused below. let body = text.strip_suffix('\n').unwrap_or(text); let mut lines = body.split('\n').enumerate(); let (_, first) = lines.next().unwrap_or((0, "")); if first != MAGIC { return Err(match first.strip_prefix("edith-keys ") { Some(v) => format!("line 1: unsupported version {v}"), None => "line 1: not a keybindings file".to_string(), }); } let mut bindings: Vec = Vec::new(); for (i, line) in lines { let n = i + 1; let Some((name, chord)) = line.split_once(' ') else { return Err(format!("line {n}: {line:?} is not ` `")); }; let action = ActionId::from_name(name) .ok_or_else(|| format!("line {n}: unknown action {name:?}"))?; let chord = Chord::parse(chord, n)?; // One stroke, one meaning: the second line to claim it would be the // dead one, and which of them died would depend on line order. if let Some(held) = bindings.iter().find(|b| b.chord == chord) { return Err(format!( "line {n}: {} is already {}'s", chord.text(), held.action.name() )); } bindings.push(Binding { action, chord }); } Ok(Keymap { bindings }) } #[cfg(test)] mod tests { use super::{ActionId, Chord, Keymap, config_path_in, emit, parse}; fn chord(key: &str, ctrl: bool) -> Chord { Chord { key: key.to_string(), ctrl, } } #[test] fn every_default_stroke_reaches_its_action() { let k = Keymap::defaults(); assert_eq!(k.entries().len(), 16); assert_eq!(k.lookup("space", false), Some(ActionId::Play)); assert_eq!(k.lookup("e", false), Some(ActionId::Export)); assert_eq!(k.lookup("s", true), Some(ActionId::Save)); assert_eq!(k.lookup("c", true), Some(ActionId::Copy)); assert_eq!(k.lookup("v", true), Some(ActionId::Paste)); assert_eq!(k.lookup("c", false), Some(ActionId::Cut)); assert_eq!(k.lookup("g", false), Some(ActionId::Regroup)); assert_eq!(k.lookup("x", false), Some(ActionId::Delete)); assert_eq!(k.lookup("delete", false), Some(ActionId::Delete)); assert_eq!(k.lookup("l", false), Some(ActionId::Lift)); assert_eq!(k.lookup("z", false), Some(ActionId::Undo)); assert_eq!(k.lookup("z", true), Some(ActionId::Undo)); assert_eq!(k.lookup("m", false), Some(ActionId::ToggleMute)); // The volume pair is the unshifted one, so neither needs a modifier // and neither is the "+" gpui reports for shift+=. assert_eq!(k.lookup("=", false), Some(ActionId::VolumeUp)); assert_eq!(k.lookup("-", false), Some(ActionId::VolumeDown)); assert_eq!(k.lookup("+", false), None); assert_eq!(k.lookup("escape", false), Some(ActionId::CancelExport)); // The modifier is half the chord: ctrl+e is not e. assert_eq!(k.lookup("e", true), None); assert_eq!(k.lookup("space", true), None); assert_eq!(k.lookup("q", false), None); // Nothing is bound twice, or lookup's first match would be a coin toss. for (i, a) in k.entries().iter().enumerate() { assert!( !k.entries()[i + 1..].iter().any(|b| b.chord == a.chord), "{:?} bound twice", a.chord ); } } #[test] fn a_file_survives_the_round_trip_exactly() { let text = emit(&Keymap::defaults()); assert!(text.starts_with("edith-keys 1\nplay space\n")); assert!(text.contains("save ctrl+s\n")); assert!(text.contains("cancel-export escape\n")); // Both directions: the file this writes is the file it reads back, and // a file read in comes out byte for byte as it went. assert_eq!(parse(&text), Ok(Keymap::defaults())); assert_eq!(emit(&parse(&text).unwrap()), text); let handwritten = "edith-keys 1\nundo ctrl+z\nplay space\n"; assert_eq!(emit(&parse(handwritten).unwrap()), handwritten); // A keymap that binds nothing is legal -- and unusable, which is the // user's business, not the parser's. assert_eq!(parse("edith-keys 1\n").unwrap().entries(), &[]); } #[test] fn every_refusal_names_its_line() { let err = |text: &str| parse(text).unwrap_err(); assert_eq!(err(""), "line 1: not a keybindings file"); assert_eq!(err("nonsense\n"), "line 1: not a keybindings file"); assert_eq!(err("edith-keys 2\n"), "line 1: unsupported version 2"); assert_eq!( err("edith-keys 1\nfly space\n"), "line 2: unknown action \"fly\"" ); assert_eq!( err("edith-keys 1\nplay space\nplayspace\n"), "line 3: \"playspace\" is not ` `" ); // An empty line is not optional whitespace, it is a line. assert_eq!( err("edith-keys 1\n\n"), "line 2: \"\" is not ` `" ); assert_eq!( err("edith-keys 1\nplay ctrl+alt+x\n"), "line 2: \"ctrl+alt+x\" is not a chord" ); assert_eq!( err("edith-keys 1\nplay ctrl+\n"), "line 2: \"ctrl+\" is not a chord" ); // gpui reports lowercase key names, so an uppercase one would simply // never match -- refused rather than quietly dead. assert_eq!( err("edith-keys 1\nplay X\n"), "line 2: \"X\" is not a chord" ); // The same stroke twice: whichever line lost would depend on order. assert_eq!( err("edith-keys 1\nplay space\ncut space\n"), "line 3: space is already play's" ); } #[test] fn rebinding_refuses_to_steal_another_actions_stroke() { let mut k = Keymap::defaults(); assert_eq!( k.rebind_action(ActionId::Export, chord("space", false)), Err(ActionId::Play) ); // Refused means unchanged, on both sides of the conflict. assert_eq!(k.lookup("e", false), Some(ActionId::Export)); assert_eq!(k.lookup("space", false), Some(ActionId::Play)); // A free stroke takes, and the old one stops meaning anything. assert_eq!(k.rebind_action(ActionId::Export, chord("w", true)), Ok(())); assert_eq!(k.lookup("w", true), Some(ActionId::Export)); assert_eq!(k.lookup("e", false), None); assert_eq!(k.display(ActionId::Export), "ctrl+w"); } #[test] fn a_rebound_action_keeps_only_the_new_stroke() { let mut k = Keymap::defaults(); assert_eq!(k.display(ActionId::Delete), "x or delete"); // One stroke replaces the whole set: what the row showed is what went. assert_eq!(k.rebind_action(ActionId::Delete, chord("d", true)), Ok(())); assert_eq!(k.display(ActionId::Delete), "ctrl+d"); assert_eq!(k.lookup("x", false), None); assert_eq!(k.lookup("delete", false), None); assert_eq!(k.lookup("d", true), Some(ActionId::Delete)); // One of its own chords is not a conflict with itself -- it collapses // the action onto that one. assert_eq!(k.rebind_action(ActionId::Undo, chord("z", true)), Ok(())); assert_eq!(k.display(ActionId::Undo), "ctrl+z"); assert_eq!(k.lookup("z", false), None); // The action keeps its place in the display order, and the file keeps // reading in that order too. let order: Vec<_> = k.entries().iter().map(|b| b.action).collect(); assert_eq!(order, ActionId::ALL.to_vec()); assert_eq!(emit(&k), emit(&parse(&emit(&k)).unwrap())); // Every action is now single-bound, so the file is one line each. assert_eq!(k.entries().len(), ActionId::ALL.len()); } #[test] fn display_reads_as_a_person_would_say_it() { let k = Keymap::defaults(); assert_eq!(k.display(ActionId::Play), "space"); assert_eq!(k.display(ActionId::Save), "ctrl+s"); assert_eq!(k.display(ActionId::Delete), "x or delete"); assert_eq!(k.display(ActionId::Undo), "z or ctrl+z"); // The one key whose common name is not gpui's. assert_eq!(k.display(ActionId::CancelExport), "esc"); assert_eq!( parse("edith-keys 1\n").unwrap().display(ActionId::Cut), "unbound" ); // The label is the editor's column, and never the file's word for it. assert_eq!(ActionId::CancelExport.label(), "Cancel export"); assert_eq!(ActionId::ALL.len(), 14); } #[test] fn a_saved_keymap_comes_back_off_the_disk() { // Its own directory, never the real config one: this test writes. let dir = std::env::temp_dir().join(format!("edith-keymap-{}", std::process::id())); let path = dir.join("edith").join("keybindings"); let mut written = Keymap::defaults(); written .rebind_action(ActionId::Export, chord("w", true)) .unwrap(); // The config directory does not exist yet -- the first save makes it. written.save_to(&path).unwrap(); let (read, notice) = Keymap::load_from(&path); assert_eq!(notice, None); assert_eq!(read, written); assert_eq!(read.lookup("w", true), Some(ActionId::Export)); assert_eq!(read.lookup("e", false), None); // The rename left nothing half-written behind. assert!(!dir.join("edith").join("keybindings.part").exists()); // A file that is merely absent is not an error and says nothing. let (fresh, notice) = Keymap::load_from(&dir.join("nothing-here")); assert_eq!(fresh, Keymap::defaults()); assert_eq!(notice, None); // A corrupt one names its line and still leaves a usable keymap. std::fs::write(&path, "edith-keys 1\nplay ctrl+alt+x\n").unwrap(); let (fallback, notice) = Keymap::load_from(&path); assert_eq!(fallback, Keymap::defaults()); let notice = notice.expect("a refused file must say so"); assert!(notice.contains("line 2:"), "{notice}"); assert!(notice.contains("keybindings"), "{notice}"); // Saving over it is a whole replacement, not an edit. Keymap::defaults().save_to(&path).unwrap(); assert_eq!(Keymap::load_from(&path), (Keymap::defaults(), None)); std::fs::remove_dir_all(&dir).ok(); } #[test] fn the_config_path_follows_xdg_then_home() { let p = |xdg: Option<&str>, home: Option<&str>| { config_path_in(xdg.map(Into::into), home.map(Into::into)) }; assert_eq!( p(Some("/x/config"), Some("/home/u")), std::path::Path::new("/x/config/edith/keybindings") ); assert_eq!( p(None, Some("/home/u")), std::path::Path::new("/home/u/.config/edith/keybindings") ); // An empty XDG_CONFIG_HOME is one the spec says to ignore. assert_eq!( p(Some(""), Some("/home/u")), std::path::Path::new("/home/u/.config/edith/keybindings") ); // Nowhere to put it but here -- still never `/edith/keybindings`. assert_eq!( p(None, None), std::path::Path::new(".config/edith/keybindings") ); } }