forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBdff7d84Tahinli3 months ago58 commits

keymap.rs667 lines, 25.6 KiBHistoryRawDownload
1//! The keymap: which stroke means which action, and the file it survives in.
2//!
3//! ```text
4//! edith-keys 1
5//! play space
6//! delete x
7//! delete delete
8//! save ctrl+s
9//! ```
10//!
11//! One line per binding, so an action bound to two strokes is two lines and the
12//! format needs no list syntax. A chord is `key` or `ctrl+key`, where `key` is
13//! exactly what gpui reports for the stroke (`escape`, not `esc`) -- the lookup
14//! compares against that string and nothing translates in between. What a
15//! *person* reads is [`Keymap::display`]'s business, and only there.
16//!
17//! The parser is strict and 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
30use std::ffi::OsString;
31use std::io::Write;
32use std::path::{Path, PathBuf};
33
34/// First line, exactly. The version is part of it, as in the project file.
35const 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)]
40pub enum ActionId {
41 Play,
42 Export,
43 Save,
44 Copy,
45 Paste,
46 Cut,
47 Regroup,
48 Delete,
49 Lift,
50 Undo,
51 ToggleMute,
52 VolumeUp,
53 VolumeDown,
54 CancelExport,
55}
56
57impl ActionId {
58 /// Display order everywhere -- the editor lists them in it and
59 /// [`Keymap::defaults`] binds them in it.
60 pub const ALL: [ActionId; 14] = [
61 ActionId::Play,
62 ActionId::Export,
63 ActionId::Save,
64 ActionId::Copy,
65 ActionId::Paste,
66 ActionId::Cut,
67 ActionId::Regroup,
68 ActionId::Delete,
69 ActionId::Lift,
70 ActionId::Undo,
71 ActionId::ToggleMute,
72 ActionId::VolumeUp,
73 ActionId::VolumeDown,
74 ActionId::CancelExport,
75 ];
76
77 /// What a person calls it.
78 pub fn label(self) -> &'static str {
79 match self {
80 ActionId::Play => "Play / Pause",
81 ActionId::Export => "Export",
82 ActionId::Save => "Save",
83 ActionId::Copy => "Copy",
84 ActionId::Paste => "Paste",
85 ActionId::Cut => "Cut",
86 ActionId::Regroup => "Regroup",
87 ActionId::Delete => "Delete",
88 ActionId::Lift => "Lift (leave a gap)",
89 ActionId::Undo => "Undo",
90 ActionId::ToggleMute => "Mute / Unmute",
91 ActionId::VolumeUp => "Volume up",
92 ActionId::VolumeDown => "Volume down",
93 ActionId::CancelExport => "Cancel export",
94 }
95 }
96
97 /// What the file calls it: ASCII, no spaces, one spelling per variant and
98 /// never the label, which is free to be reworded.
99 fn name(self) -> &'static str {
100 match self {
101 ActionId::Play => "play",
102 ActionId::Export => "export",
103 ActionId::Save => "save",
104 ActionId::Copy => "copy",
105 ActionId::Paste => "paste",
106 ActionId::Cut => "cut",
107 ActionId::Regroup => "regroup",
108 ActionId::Delete => "delete",
109 ActionId::Lift => "lift",
110 ActionId::Undo => "undo",
111 ActionId::ToggleMute => "toggle-mute",
112 ActionId::VolumeUp => "volume-up",
113 ActionId::VolumeDown => "volume-down",
114 ActionId::CancelExport => "cancel-export",
115 }
116 }
117
118 fn from_name(name: &str) -> Option<Self> {
119 Self::ALL.into_iter().find(|a| a.name() == name)
120 }
121}
122
123/// A stroke as the key handler sees it: gpui's key name plus the one modifier
124/// this editor binds. Nothing else is a chord here -- shift and alt are part of
125/// the key name gpui reports, and a second modifier would need the file format
126/// to grow before it could be spelled.
127#[derive(Clone, PartialEq, Eq, Debug)]
128pub struct Chord {
129 pub key: String,
130 pub ctrl: bool,
131}
132
133impl Chord {
134 /// The file's spelling, and the only one [`parse`] accepts back.
135 fn text(&self) -> String {
136 if self.ctrl {
137 format!("ctrl+{}", self.key)
138 } else {
139 self.key.clone()
140 }
141 }
142
143 /// The spelling a person reads. Identical to [`Chord::text`] but for the one
144 /// key whose usual name is shorter than gpui's. Public because a
145 /// keybindings row shows one chord, where [`Keymap::display`] shows every
146 /// chord an action answers to.
147 pub fn pretty(&self) -> String {
148 let key = if self.key == "escape" {
149 "esc"
150 } else {
151 &self.key
152 };
153 if self.ctrl {
154 format!("ctrl+{key}")
155 } else {
156 key.to_string()
157 }
158 }
159
160 /// Strict: exactly one optional `ctrl+` and then a key gpui could have
161 /// reported. A spelling this cannot emit back unchanged is refused rather
162 /// than normalised, because the round-trip is what makes the file editable
163 /// by hand at all.
164 fn parse(text: &str, n: usize) -> Result<Self, String> {
165 let (ctrl, key) = match text.strip_prefix("ctrl+") {
166 Some(key) => (true, key),
167 None => (false, text),
168 };
169 if key.is_empty()
170 || key.contains(' ')
171 || key.contains('+')
172 || key.chars().any(|c| c.is_ascii_uppercase())
173 {
174 return Err(format!("line {n}: {text:?} is not a chord"));
175 }
176 Ok(Chord {
177 key: key.to_string(),
178 ctrl,
179 })
180 }
181}
182
183/// One stroke, one action. Two strokes for the same action are two bindings.
184#[derive(Clone, PartialEq, Eq, Debug)]
185pub struct Binding {
186 pub action: ActionId,
187 pub chord: Chord,
188}
189
190/// Every binding in force, in display order. No chord appears twice -- that is
191/// the invariant [`Keymap::rebind_action`] and [`parse`] both defend, and it is what
192/// lets [`Keymap::lookup`] answer with the first match.
193#[derive(Clone, PartialEq, Eq, Debug)]
194pub struct Keymap {
195 bindings: Vec<Binding>,
196}
197
198impl Keymap {
199 /// The bindings the editor has always had, in the order the editor lists
200 /// them. Delete and undo get two strokes each because both have always
201 /// answered to two.
202 pub fn defaults() -> Self {
203 let b = |action, key: &str, ctrl| Binding {
204 action,
205 chord: Chord {
206 key: key.to_string(),
207 ctrl,
208 },
209 };
210 Keymap {
211 bindings: vec![
212 b(ActionId::Play, "space", false),
213 b(ActionId::Export, "e", false),
214 b(ActionId::Save, "s", true),
215 b(ActionId::Copy, "c", true),
216 b(ActionId::Paste, "v", true),
217 b(ActionId::Cut, "c", false),
218 // The two lane keys, on the letters they are named after: both
219 // were free, and neither is next to a key that edits.
220 b(ActionId::Regroup, "g", false),
221 b(ActionId::Delete, "x", false),
222 b(ActionId::Delete, "delete", false),
223 b(ActionId::Lift, "l", false),
224 b(ActionId::Undo, "z", false),
225 b(ActionId::Undo, "z", true),
226 b(ActionId::ToggleMute, "m", false),
227 // The unshifted pair, which is what gpui reports for those two
228 // keys ("=" and "-", platform.rs:862): the volume keys every
229 // player has, without asking for shift to make the "+".
230 b(ActionId::VolumeUp, "=", false),
231 b(ActionId::VolumeDown, "-", false),
232 b(ActionId::CancelExport, "escape", false),
233 ],
234 }
235 }
236
237 /// What a stroke means, if anything. `key` is gpui's key name and `ctrl` its
238 /// control modifier -- the pair the key handler already matches on.
239 pub fn lookup(&self, key: &str, ctrl: bool) -> Option<ActionId> {
240 self.bindings
241 .iter()
242 .find(|b| b.chord.ctrl == ctrl && b.chord.key == key)
243 .map(|b| b.action)
244 }
245
246 /// Every stroke that reaches an action, as one readable phrase: `x or
247 /// delete`. An action nobody can reach says so rather than reading blank.
248 pub fn display(&self, action: ActionId) -> String {
249 let strokes: Vec<String> = self
250 .bindings
251 .iter()
252 .filter(|b| b.action == action)
253 .map(|b| b.chord.pretty())
254 .collect();
255 if strokes.is_empty() {
256 "unbound".to_string()
257 } else {
258 strokes.join(" or ")
259 }
260 }
261
262 /// Every binding, in display order.
263 pub fn entries(&self) -> &[Binding] {
264 &self.bindings
265 }
266
267 /// Makes `chord` the whole of what reaches `action`: its other chords go, so
268 /// what the editor shows for an action is what a rebind replaced. Two
269 /// strokes for one action stay expressible, but only in the file -- the
270 /// parser takes as many lines per action as it is given.
271 ///
272 /// `Err` names the action that already holds the chord and nothing changes:
273 /// two actions on one stroke would make the second unreachable, and silently
274 /// stealing it is worse than refusing. A chord the action already holds is
275 /// not a conflict with itself -- it collapses the action onto that one.
276 pub fn rebind_action(&mut self, action: ActionId, chord: Chord) -> Result<(), ActionId> {
277 if let Some(held) = self
278 .bindings
279 .iter()
280 .find(|b| b.action != action && b.chord == chord)
281 {
282 return Err(held.action);
283 }
284 self.bindings.retain(|b| b.action != action);
285 // Back into its own place in the display order rather than onto the end,
286 // so the file and the editor keep reading in the order of `ALL`.
287 let at = self
288 .bindings
289 .iter()
290 .position(|b| rank(b.action) > rank(action))
291 .unwrap_or(self.bindings.len());
292 self.bindings.insert(at, Binding { action, chord });
293 Ok(())
294 }
295
296 /// The keymap in force, and what to tell the user if the file could not be
297 /// used. A file that is merely absent is the normal case and says nothing;
298 /// anything else -- unreadable, or a line this parser refuses -- falls back
299 /// to the defaults *and* is reported, because a keymap silently not applied
300 /// is a keyboard that has quietly changed under the user.
301 pub fn load() -> (Self, Option<String>) {
302 Self::load_from(&Self::config_path())
303 }
304
305 /// All of [`Keymap::load`] but the path, which the config directory decides
306 /// and a test must not be allowed to.
307 fn load_from(path: &Path) -> (Self, Option<String>) {
308 let text = match std::fs::read_to_string(path) {
309 Ok(text) => text,
310 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return (Self::defaults(), None),
311 Err(e) => {
312 return (
313 Self::defaults(),
314 Some(format!(
315 "KEYBINDINGS IGNORED — {}: {e} — the defaults are in force",
316 path.display()
317 )),
318 );
319 }
320 };
321 match parse(&text) {
322 Ok(keymap) => (keymap, None),
323 Err(e) => (
324 Self::defaults(),
325 Some(format!(
326 "KEYBINDINGS IGNORED — {}, {e} — the defaults are in force",
327 path.display()
328 )),
329 ),
330 }
331 }
332
333 /// Writes the keymap, atomically, creating the config directory if this is
334 /// the first save. Until the rename the previous bindings are still the
335 /// whole truth on disk.
336 pub fn save(&self) -> std::io::Result<()> {
337 self.save_to(&Self::config_path())
338 }
339
340 /// All of [`Keymap::save`] but the path, for the same reason as
341 /// [`Keymap::load_from`].
342 fn save_to(&self, path: &Path) -> std::io::Result<()> {
343 let dir = path.parent().unwrap_or(Path::new(".")).to_path_buf();
344 std::fs::create_dir_all(&dir)?;
345 let mut part = path.to_path_buf().into_os_string();
346 part.push(".part");
347 let part = PathBuf::from(part);
348 let result = std::fs::File::create(&part)
349 .and_then(|mut f| {
350 f.write_all(emit(self).as_bytes())?;
351 f.sync_all()
352 })
353 .and_then(|()| std::fs::rename(&part, path))
354 .and_then(|()| std::fs::File::open(&dir)?.sync_all());
355 if result.is_err() {
356 let _ = std::fs::remove_file(&part);
357 }
358 result
359 }
360
361 /// Where the bindings live: the XDG config directory, or `~/.config` when
362 /// the desktop has not named one.
363 pub fn config_path() -> PathBuf {
364 config_path_in(
365 std::env::var_os("XDG_CONFIG_HOME"),
366 std::env::var_os("HOME"),
367 )
368 }
369}
370
371/// Where an action sits in the display order, which is the order of
372/// [`ActionId::ALL`] and the order the file is written in.
373fn rank(action: ActionId) -> usize {
374 ActionId::ALL
375 .iter()
376 .position(|a| *a == action)
377 .unwrap_or(ActionId::ALL.len())
378}
379
380/// The path rule, with the environment handed in so it can be checked. An
381/// `XDG_CONFIG_HOME` that is empty is one the spec says to ignore; with no
382/// `HOME` either there is nowhere but here, and a relative path is still better
383/// than dropping the file in `/`.
384fn config_path_in(xdg: Option<OsString>, home: Option<OsString>) -> PathBuf {
385 let dir = xdg
386 .filter(|v| !v.is_empty())
387 .map(PathBuf::from)
388 .or_else(|| {
389 home.filter(|v| !v.is_empty())
390 .map(|h| PathBuf::from(h).join(".config"))
391 })
392 .unwrap_or_else(|| PathBuf::from(".config"));
393 dir.join("edith").join("keybindings")
394}
395
396fn emit(keymap: &Keymap) -> String {
397 let mut out = String::from(MAGIC);
398 out.push('\n');
399 for b in &keymap.bindings {
400 out.push_str(b.action.name());
401 out.push(' ');
402 out.push_str(&b.chord.text());
403 out.push('\n');
404 }
405 out
406}
407
408fn parse(text: &str) -> Result<Keymap, String> {
409 // One trailing newline terminates the last line rather than starting an
410 // empty one; a second is an empty line and is refused below.
411 let body = text.strip_suffix('\n').unwrap_or(text);
412 let mut lines = body.split('\n').enumerate();
413 let (_, first) = lines.next().unwrap_or((0, ""));
414 if first != MAGIC {
415 return Err(match first.strip_prefix("edith-keys ") {
416 Some(v) => format!("line 1: unsupported version {v}"),
417 None => "line 1: not a keybindings file".to_string(),
418 });
419 }
420
421 let mut bindings: Vec<Binding> = Vec::new();
422 for (i, line) in lines {
423 let n = i + 1;
424 let Some((name, chord)) = line.split_once(' ') else {
425 return Err(format!("line {n}: {line:?} is not `<action> <chord>`"));
426 };
427 let action = ActionId::from_name(name)
428 .ok_or_else(|| format!("line {n}: unknown action {name:?}"))?;
429 let chord = Chord::parse(chord, n)?;
430 // One stroke, one meaning: the second line to claim it would be the
431 // dead one, and which of them died would depend on line order.
432 if let Some(held) = bindings.iter().find(|b| b.chord == chord) {
433 return Err(format!(
434 "line {n}: {} is already {}'s",
435 chord.text(),
436 held.action.name()
437 ));
438 }
439 bindings.push(Binding { action, chord });
440 }
441 Ok(Keymap { bindings })
442}
443
444#[cfg(test)]
445mod tests {
446 use super::{ActionId, Chord, Keymap, config_path_in, emit, parse};
447
448 fn chord(key: &str, ctrl: bool) -> Chord {
449 Chord {
450 key: key.to_string(),
451 ctrl,
452 }
453 }
454
455 #[test]
456 fn every_default_stroke_reaches_its_action() {
457 let k = Keymap::defaults();
458 assert_eq!(k.entries().len(), 16);
459 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
460 assert_eq!(k.lookup("e", false), Some(ActionId::Export));
461 assert_eq!(k.lookup("s", true), Some(ActionId::Save));
462 assert_eq!(k.lookup("c", true), Some(ActionId::Copy));
463 assert_eq!(k.lookup("v", true), Some(ActionId::Paste));
464 assert_eq!(k.lookup("c", false), Some(ActionId::Cut));
465 assert_eq!(k.lookup("g", false), Some(ActionId::Regroup));
466 assert_eq!(k.lookup("x", false), Some(ActionId::Delete));
467 assert_eq!(k.lookup("delete", false), Some(ActionId::Delete));
468 assert_eq!(k.lookup("l", false), Some(ActionId::Lift));
469 assert_eq!(k.lookup("z", false), Some(ActionId::Undo));
470 assert_eq!(k.lookup("z", true), Some(ActionId::Undo));
471 assert_eq!(k.lookup("m", false), Some(ActionId::ToggleMute));
472 // The volume pair is the unshifted one, so neither needs a modifier
473 // and neither is the "+" gpui reports for shift+=.
474 assert_eq!(k.lookup("=", false), Some(ActionId::VolumeUp));
475 assert_eq!(k.lookup("-", false), Some(ActionId::VolumeDown));
476 assert_eq!(k.lookup("+", false), None);
477 assert_eq!(k.lookup("escape", false), Some(ActionId::CancelExport));
478 // The modifier is half the chord: ctrl+e is not e.
479 assert_eq!(k.lookup("e", true), None);
480 assert_eq!(k.lookup("space", true), None);
481 assert_eq!(k.lookup("q", false), None);
482 // Nothing is bound twice, or lookup's first match would be a coin toss.
483 for (i, a) in k.entries().iter().enumerate() {
484 assert!(
485 !k.entries()[i + 1..].iter().any(|b| b.chord == a.chord),
486 "{:?} bound twice",
487 a.chord
488 );
489 }
490 }
491
492 #[test]
493 fn a_file_survives_the_round_trip_exactly() {
494 let text = emit(&Keymap::defaults());
495 assert!(text.starts_with("edith-keys 1\nplay space\n"));
496 assert!(text.contains("save ctrl+s\n"));
497 assert!(text.contains("cancel-export escape\n"));
498 // Both directions: the file this writes is the file it reads back, and
499 // a file read in comes out byte for byte as it went.
500 assert_eq!(parse(&text), Ok(Keymap::defaults()));
501 assert_eq!(emit(&parse(&text).unwrap()), text);
502 let handwritten = "edith-keys 1\nundo ctrl+z\nplay space\n";
503 assert_eq!(emit(&parse(handwritten).unwrap()), handwritten);
504 // A keymap that binds nothing is legal -- and unusable, which is the
505 // user's business, not the parser's.
506 assert_eq!(parse("edith-keys 1\n").unwrap().entries(), &[]);
507 }
508
509 #[test]
510 fn every_refusal_names_its_line() {
511 let err = |text: &str| parse(text).unwrap_err();
512 assert_eq!(err(""), "line 1: not a keybindings file");
513 assert_eq!(err("nonsense\n"), "line 1: not a keybindings file");
514 assert_eq!(err("edith-keys 2\n"), "line 1: unsupported version 2");
515 assert_eq!(
516 err("edith-keys 1\nfly space\n"),
517 "line 2: unknown action \"fly\""
518 );
519 assert_eq!(
520 err("edith-keys 1\nplay space\nplayspace\n"),
521 "line 3: \"playspace\" is not `<action> <chord>`"
522 );
523 // An empty line is not optional whitespace, it is a line.
524 assert_eq!(
525 err("edith-keys 1\n\n"),
526 "line 2: \"\" is not `<action> <chord>`"
527 );
528 assert_eq!(
529 err("edith-keys 1\nplay ctrl+alt+x\n"),
530 "line 2: \"ctrl+alt+x\" is not a chord"
531 );
532 assert_eq!(
533 err("edith-keys 1\nplay ctrl+\n"),
534 "line 2: \"ctrl+\" is not a chord"
535 );
536 // gpui reports lowercase key names, so an uppercase one would simply
537 // never match -- refused rather than quietly dead.
538 assert_eq!(
539 err("edith-keys 1\nplay X\n"),
540 "line 2: \"X\" is not a chord"
541 );
542 // The same stroke twice: whichever line lost would depend on order.
543 assert_eq!(
544 err("edith-keys 1\nplay space\ncut space\n"),
545 "line 3: space is already play's"
546 );
547 }
548
549 #[test]
550 fn rebinding_refuses_to_steal_another_actions_stroke() {
551 let mut k = Keymap::defaults();
552 assert_eq!(
553 k.rebind_action(ActionId::Export, chord("space", false)),
554 Err(ActionId::Play)
555 );
556 // Refused means unchanged, on both sides of the conflict.
557 assert_eq!(k.lookup("e", false), Some(ActionId::Export));
558 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
559 // A free stroke takes, and the old one stops meaning anything.
560 assert_eq!(k.rebind_action(ActionId::Export, chord("w", true)), Ok(()));
561 assert_eq!(k.lookup("w", true), Some(ActionId::Export));
562 assert_eq!(k.lookup("e", false), None);
563 assert_eq!(k.display(ActionId::Export), "ctrl+w");
564 }
565
566 #[test]
567 fn a_rebound_action_keeps_only_the_new_stroke() {
568 let mut k = Keymap::defaults();
569 assert_eq!(k.display(ActionId::Delete), "x or delete");
570 // One stroke replaces the whole set: what the row showed is what went.
571 assert_eq!(k.rebind_action(ActionId::Delete, chord("d", true)), Ok(()));
572 assert_eq!(k.display(ActionId::Delete), "ctrl+d");
573 assert_eq!(k.lookup("x", false), None);
574 assert_eq!(k.lookup("delete", false), None);
575 assert_eq!(k.lookup("d", true), Some(ActionId::Delete));
576 // One of its own chords is not a conflict with itself -- it collapses
577 // the action onto that one.
578 assert_eq!(k.rebind_action(ActionId::Undo, chord("z", true)), Ok(()));
579 assert_eq!(k.display(ActionId::Undo), "ctrl+z");
580 assert_eq!(k.lookup("z", false), None);
581 // The action keeps its place in the display order, and the file keeps
582 // reading in that order too.
583 let order: Vec<_> = k.entries().iter().map(|b| b.action).collect();
584 assert_eq!(order, ActionId::ALL.to_vec());
585 assert_eq!(emit(&k), emit(&parse(&emit(&k)).unwrap()));
586 // Every action is now single-bound, so the file is one line each.
587 assert_eq!(k.entries().len(), ActionId::ALL.len());
588 }
589
590 #[test]
591 fn display_reads_as_a_person_would_say_it() {
592 let k = Keymap::defaults();
593 assert_eq!(k.display(ActionId::Play), "space");
594 assert_eq!(k.display(ActionId::Save), "ctrl+s");
595 assert_eq!(k.display(ActionId::Delete), "x or delete");
596 assert_eq!(k.display(ActionId::Undo), "z or ctrl+z");
597 // The one key whose common name is not gpui's.
598 assert_eq!(k.display(ActionId::CancelExport), "esc");
599 assert_eq!(
600 parse("edith-keys 1\n").unwrap().display(ActionId::Cut),
601 "unbound"
602 );
603 // The label is the editor's column, and never the file's word for it.
604 assert_eq!(ActionId::CancelExport.label(), "Cancel export");
605 assert_eq!(ActionId::ALL.len(), 14);
606 }
607
608 #[test]
609 fn a_saved_keymap_comes_back_off_the_disk() {
610 // Its own directory, never the real config one: this test writes.
611 let dir = std::env::temp_dir().join(format!("edith-keymap-{}", std::process::id()));
612 let path = dir.join("edith").join("keybindings");
613 let mut written = Keymap::defaults();
614 written
615 .rebind_action(ActionId::Export, chord("w", true))
616 .unwrap();
617 // The config directory does not exist yet -- the first save makes it.
618 written.save_to(&path).unwrap();
619 let (read, notice) = Keymap::load_from(&path);
620 assert_eq!(notice, None);
621 assert_eq!(read, written);
622 assert_eq!(read.lookup("w", true), Some(ActionId::Export));
623 assert_eq!(read.lookup("e", false), None);
624 // The rename left nothing half-written behind.
625 assert!(!dir.join("edith").join("keybindings.part").exists());
626 // A file that is merely absent is not an error and says nothing.
627 let (fresh, notice) = Keymap::load_from(&dir.join("nothing-here"));
628 assert_eq!(fresh, Keymap::defaults());
629 assert_eq!(notice, None);
630 // A corrupt one names its line and still leaves a usable keymap.
631 std::fs::write(&path, "edith-keys 1\nplay ctrl+alt+x\n").unwrap();
632 let (fallback, notice) = Keymap::load_from(&path);
633 assert_eq!(fallback, Keymap::defaults());
634 let notice = notice.expect("a refused file must say so");
635 assert!(notice.contains("line 2:"), "{notice}");
636 assert!(notice.contains("keybindings"), "{notice}");
637 // Saving over it is a whole replacement, not an edit.
638 Keymap::defaults().save_to(&path).unwrap();
639 assert_eq!(Keymap::load_from(&path), (Keymap::defaults(), None));
640 std::fs::remove_dir_all(&dir).ok();
641 }
642
643 #[test]
644 fn the_config_path_follows_xdg_then_home() {
645 let p = |xdg: Option<&str>, home: Option<&str>| {
646 config_path_in(xdg.map(Into::into), home.map(Into::into))
647 };
648 assert_eq!(
649 p(Some("/x/config"), Some("/home/u")),
650 std::path::Path::new("/x/config/edith/keybindings")
651 );
652 assert_eq!(
653 p(None, Some("/home/u")),
654 std::path::Path::new("/home/u/.config/edith/keybindings")
655 );
656 // An empty XDG_CONFIG_HOME is one the spec says to ignore.
657 assert_eq!(
658 p(Some(""), Some("/home/u")),
659 std::path::Path::new("/home/u/.config/edith/keybindings")
660 );
661 // Nowhere to put it but here -- still never `/edith/keybindings`.
662 assert_eq!(
663 p(None, None),
664 std::path::Path::new(".config/edith/keybindings")
665 );
666 }
667}