kimun-notes 0.24.2

A terminal-based notes application
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
use std::{collections::HashMap, fmt::Display};

use action_shortcuts::ActionShortcuts;
use itertools::Itertools;
use key_combo::{KeyCombo, KeyModifiers};
use key_strike::KeyStrike;
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers as CKeyMods};
use serde::{Deserialize, Serialize, de::Visitor, ser::SerializeMap};

pub mod action_shortcuts;
pub mod key_combo;
pub mod key_strike;
pub mod leader;
pub mod reachability;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyBindings {
    bindings: HashMap<KeyCombo, ActionShortcuts>,
}

impl Serialize for KeyBindings {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let kb_map = self.to_hashmap();
        let mut map = serializer.serialize_map(Some(kb_map.len()))?;
        for (k, v) in kb_map
            .iter()
            .sorted_by_key(|(action, _combo)| action.to_owned())
        {
            map.serialize_entry(&k, &v)?;
        }
        map.end()
    }
}

struct DeserializeKeyBindingsVisitor;
impl<'de> Visitor<'de> for DeserializeKeyBindingsVisitor {
    type Value = KeyBindings;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        formatter.write_str("a keybindings map of action names to lists of key combos")
    }
    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
    where
        A: serde::de::MapAccess<'de>,
    {
        use serde::de::{Error, IgnoredAny, IntoDeserializer};

        let mut bindings: HashMap<ActionShortcuts, Vec<KeyCombo>> =
            HashMap::with_capacity(map.size_hint().unwrap_or(0));

        loop {
            // Read the key as a raw String so a bad action name is recoverable.
            let key_str: String = match map.next_key::<String>() {
                Ok(Some(s)) => s,
                Ok(None) => break,
                Err(e) => return Err(e),
            };

            // Parse the action name; on failure, discard the value and continue.
            // The explicit error type pins the generic on `IntoDeserializer`.
            let action = match ActionShortcuts::deserialize(key_str.clone().into_deserializer()) {
                Ok(a) => a,
                Err(e) => {
                    let e: serde::de::value::Error = e;
                    let _ = map.next_value::<IgnoredAny>();
                    tracing::warn!(
                        "Skipping unknown action '{}' in keybindings config: {}",
                        key_str,
                        e
                    );
                    continue;
                }
            };

            match map.next_value::<Vec<KeyCombo>>() {
                Ok(value) => {
                    bindings.insert(action, value);
                }
                Err(e) => {
                    tracing::warn!("Skipping keybindings entry for action '{}': {}", action, e);
                }
            }
        }

        // Essential-action safety net: Quit must always have a binding.
        if !bindings.contains_key(&ActionShortcuts::Quit) {
            let quit_combo = default_quit_combo();

            let conflicting_action = bindings
                .iter()
                .find(|(_, combos)| combos.iter().any(|c| c == &quit_combo))
                .map(|(action, _)| action.clone());

            if let Some(other) = conflicting_action {
                return Err(A::Error::custom(format!(
                    "Quit action has no binding and the default combo Ctrl+Q is already mapped to '{}'. \
                     Add a valid Quit binding to your keybindings config.",
                    other
                )));
            }

            tracing::warn!("Quit action missing from keybindings; restoring default Ctrl+Q");
            bindings.insert(ActionShortcuts::Quit, vec![quit_combo]);
        }

        Ok(KeyBindings::from_hashmap(bindings))
    }
}

impl<'de> Deserialize<'de> for KeyBindings {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        deserializer.deserialize_map(DeserializeKeyBindingsVisitor)
    }
}

impl Display for KeyBindings {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut bindings: Vec<(ActionShortcuts, Vec<KeyCombo>)> = vec![];
        for (key, value) in &self.bindings {
            if let Some((_, combos)) = bindings
                .iter_mut()
                .find(|(shortcut, _combos)| shortcut.eq(value))
            {
                combos.push(key.to_owned());
                combos.sort();
            } else {
                bindings.push((value.to_owned(), vec![key.to_owned()]));
            }
        }

        bindings.sort_by_key(|(a, _v)| a.to_owned());
        for (key, value) in &bindings {
            writeln!(
                f,
                "{}: {}",
                key,
                value
                    .iter()
                    .map(|kc| kc.to_string())
                    .collect::<Vec<String>>()
                    .join(", ")
            )?;
        }

        Ok(())
    }
}

impl KeyBindings {
    pub fn empty() -> Self {
        KeyBindings {
            bindings: HashMap::default(),
        }
    }

    pub fn batch_add(&mut self) -> KeyBindBatch<'_> {
        KeyBindBatch {
            bindings: self,
            modifiers: KeyModifiers::default(),
        }
    }

    pub fn get_action(&self, combo: &KeyCombo) -> Option<ActionShortcuts> {
        self.bindings.get(combo).map(|a| a.to_owned())
    }

    /// Every combo bound to `action`. Empty when the user has unbound it —
    /// callers must treat that as "this chord does nothing", not as a cue to
    /// fall back to the default.
    pub fn combos_for(&self, action: &ActionShortcuts) -> Vec<KeyCombo> {
        self.bindings
            .iter()
            .filter(|(_, a)| *a == action)
            .map(|(combo, _)| *combo)
            .collect()
    }

    /// The display string of the combo bound to `action`, or `None`.
    ///
    /// `min`, not `find`: this feeds the footer hints, the F1 help and the
    /// cheatsheet, and a `HashMap` iterates in no particular order — so with
    /// two combos on one action, `find` returned a different chord from frame
    /// to frame and the footer flickered between them. Lowest [`KeyCombo`]
    /// wins, which is arbitrary but stable, and matches the order
    /// [`Self::to_hashmap`] already sorts each action's combos into.
    pub fn first_combo_for(&self, action: &ActionShortcuts) -> Option<String> {
        self.bindings
            .iter()
            .filter(|(_, a)| *a == action)
            .map(|(combo, _)| combo)
            .min()
            .map(|combo| combo.to_string())
    }

    pub fn to_hashmap(&self) -> HashMap<ActionShortcuts, Vec<KeyCombo>> {
        let mut bindings: HashMap<ActionShortcuts, Vec<KeyCombo>> = HashMap::new();
        for (combo, action) in &self.bindings {
            let entry = bindings.entry(action.to_owned()).or_default();
            entry.push(combo.to_owned());
            entry.sort();
        }
        bindings
    }

    pub fn from_hashmap(bindings: HashMap<ActionShortcuts, Vec<KeyCombo>>) -> KeyBindings {
        let mut kb = KeyBindings::empty();
        for (action, combos) in &bindings {
            tracing::debug!("from_hashmap: action={} combos={:?}", action, combos);
        }
        for (action, combos) in bindings {
            for combo in combos {
                let valid = combo.is_valid_binding();
                tracing::debug!(
                    "from_hashmap: combo='{}' key={:?} modifiers={:?} valid={}",
                    combo,
                    combo.key,
                    combo.modifiers,
                    valid
                );
                if valid {
                    kb.bindings.insert(combo.to_owned(), action.to_owned());
                } else {
                    tracing::warn!(
                        "Skipping invalid key combo '{}' for action '{}': \
                         only ctrl/alt (with optional shift) + a letter, digit, or \
                         punctuation key, or bare F1–F12 are supported",
                        combo,
                        action
                    );
                }
            }
        }
        kb
    }
}

/// Canonical default combo for [`ActionShortcuts::Quit`]. Sourced once so the
/// deserialize safety net and `settings::default_keybindings` can't
/// drift.
pub fn default_quit_combo() -> KeyCombo {
    KeyCombo::new(KeyModifiers::new().and_ctrl(), KeyStrike::KeyQ)
}

/// Canonical default combo for [`ActionShortcuts::YankRow`]. Sourced once for
/// the same reason as [`default_quit_combo`], plus one more: `SearchList` claims
/// this chord itself so every list surface yanks without per-panel wiring,
/// and it must be the same chord the shortcut tier advertises.
pub fn default_yank_combo() -> KeyCombo {
    KeyCombo::new(KeyModifiers::new().and_ctrl(), KeyStrike::KeyY)
}

pub struct KeyBindBatch<'k> {
    bindings: &'k mut KeyBindings,
    modifiers: KeyModifiers,
}

impl<'k> KeyBindBatch<'k> {
    pub fn with_shift(mut self) -> Self {
        self.modifiers.with_shift();
        self
    }
    pub fn with_ctrl(mut self) -> Self {
        self.modifiers.with_ctrl();
        self
    }
    pub fn with_alt(mut self) -> Self {
        self.modifiers.with_alt();
        self
    }
    /// Same as with_cmd, used for non-macOS
    pub fn with_meta(mut self) -> Self {
        self.modifiers.with_meta_cmd();
        self
    }
    pub fn with_cmd(mut self) -> Self {
        self.modifiers.with_meta_cmd();
        self
    }
    /// Bind `key` plus this batch's modifiers to `action`.
    ///
    /// The combo must still be free. Two `add` calls for one combo were
    /// last-wins and silent, which is how `Ctrl+L` came to be bound to both
    /// `Text(Link)` and `FocusEditor`: the first simply vanished, with no
    /// warning, and `combos_for(Text(Link))` answering "nothing" was the only
    /// trace. Every caller of this builder is a hand-written table, so a
    /// duplicate is a mistake *in that table* and worth a panic in tests. A
    /// user's config does not come through here — [`KeyBindings::from_hashmap`]
    /// inserts directly and keeps last-wins, because their keymap is theirs to
    /// contradict.
    pub fn add(self, key: KeyStrike, action: ActionShortcuts) -> KeyBindBatch<'k> {
        let combo = KeyCombo::new(self.modifiers, key);
        debug_assert!(
            !self.bindings.bindings.contains_key(&combo),
            "{combo} is already bound to {:?}, so binding it to {action:?} would drop that silently",
            self.bindings.bindings.get(&combo)
        );
        self.bindings.bindings.insert(combo, action);
        self
    }
}

/// Convert a crossterm [`KeyEvent`] into a [`KeyCombo`] for keybinding lookup.
///
/// Returns `None` for key codes that have no [`KeyStrike`] mapping (e.g. media keys).
/// `BackTab` (Shift+Tab) is normalised to `Tab` with the `shift` modifier set.
pub fn key_event_to_combo(event: &KeyEvent) -> Option<KeyCombo> {
    // Some terminals deliver Ctrl+letter as raw control characters (e.g. Ctrl+Q → '\x11')
    // without setting the CONTROL modifier.  Normalise them here so the rest of the
    // function sees an ordinary letter + an implied ctrl flag.
    let mut implied_ctrl = false;
    let key = match event.code {
        KeyCode::Char(c) => {
            // Compare on the full code point: `c as u8` truncates to the low byte,
            // so a non-ASCII char such as '理' (U+7406) would look like '\x06' and
            // fire Ctrl+F while typing.
            let code = u32::from(c);
            let c = if (1..=26).contains(&code) {
                implied_ctrl = true;
                char::from_u32(code + u32::from('a') - 1)
                    .expect("ASCII control code 1..=26 always maps to a letter")
            } else {
                c
            };
            match c.to_ascii_lowercase() {
                'a' => KeyStrike::KeyA,
                'b' => KeyStrike::KeyB,
                'c' => KeyStrike::KeyC,
                'd' => KeyStrike::KeyD,
                'e' => KeyStrike::KeyE,
                'f' => KeyStrike::KeyF,
                'g' => KeyStrike::KeyG,
                'h' => KeyStrike::KeyH,
                'i' => KeyStrike::KeyI,
                'j' => KeyStrike::KeyJ,
                'k' => KeyStrike::KeyK,
                'l' => KeyStrike::KeyL,
                'm' => KeyStrike::KeyM,
                'n' => KeyStrike::KeyN,
                'o' => KeyStrike::KeyO,
                'p' => KeyStrike::KeyP,
                'q' => KeyStrike::KeyQ,
                'r' => KeyStrike::KeyR,
                's' => KeyStrike::KeyS,
                't' => KeyStrike::KeyT,
                'u' => KeyStrike::KeyU,
                'v' => KeyStrike::KeyV,
                'w' => KeyStrike::KeyW,
                'x' => KeyStrike::KeyX,
                'y' => KeyStrike::KeyY,
                'z' => KeyStrike::KeyZ,
                '0' => KeyStrike::Digit0,
                '1' => KeyStrike::Digit1,
                '2' => KeyStrike::Digit2,
                '3' => KeyStrike::Digit3,
                '4' => KeyStrike::Digit4,
                '5' => KeyStrike::Digit5,
                '6' => KeyStrike::Digit6,
                '7' => KeyStrike::Digit7,
                '8' => KeyStrike::Digit8,
                '9' => KeyStrike::Digit9,
                ',' => KeyStrike::Comma,
                '.' => KeyStrike::Period,
                '/' => KeyStrike::Slash,
                ';' => KeyStrike::Semicolon,
                '\'' => KeyStrike::Quote,
                '[' => KeyStrike::BracketLeft,
                ']' => KeyStrike::BracketRight,
                '\\' => KeyStrike::Backslash,
                '`' => KeyStrike::Backquote,
                '-' => KeyStrike::Minus,
                '=' => KeyStrike::Equal,
                _ => return None,
            }
        }
        KeyCode::Enter => KeyStrike::Enter,
        KeyCode::Backspace => KeyStrike::Backspace,
        KeyCode::Tab | KeyCode::BackTab => KeyStrike::Tab,
        KeyCode::Esc => KeyStrike::Escape,
        KeyCode::Up => KeyStrike::ArrowUp,
        KeyCode::Down => KeyStrike::ArrowDown,
        KeyCode::Left => KeyStrike::ArrowLeft,
        KeyCode::Right => KeyStrike::ArrowRight,
        KeyCode::Home => KeyStrike::Home,
        KeyCode::End => KeyStrike::End,
        KeyCode::PageUp => KeyStrike::PageUp,
        KeyCode::PageDown => KeyStrike::PageDown,
        KeyCode::Delete => KeyStrike::Delete,
        KeyCode::Insert => KeyStrike::Insert,
        KeyCode::F(n) => match n {
            1 => KeyStrike::F1,
            2 => KeyStrike::F2,
            3 => KeyStrike::F3,
            4 => KeyStrike::F4,
            5 => KeyStrike::F5,
            6 => KeyStrike::F6,
            7 => KeyStrike::F7,
            8 => KeyStrike::F8,
            9 => KeyStrike::F9,
            10 => KeyStrike::F10,
            11 => KeyStrike::F11,
            12 => KeyStrike::F12,
            13 => KeyStrike::F13,
            14 => KeyStrike::F14,
            15 => KeyStrike::F15,
            16 => KeyStrike::F16,
            17 => KeyStrike::F17,
            18 => KeyStrike::F18,
            19 => KeyStrike::F19,
            20 => KeyStrike::F20,
            21 => KeyStrike::F21,
            22 => KeyStrike::F22,
            23 => KeyStrike::F23,
            24 => KeyStrike::F24,
            25 => KeyStrike::F25,
            _ => return None,
        },
        _ => return None,
    };

    let mut modifiers = KeyModifiers::default();
    if implied_ctrl || event.modifiers.contains(CKeyMods::CONTROL) {
        modifiers.with_ctrl();
    }
    // BackTab arrives as KeyCode::BackTab (no SHIFT bit set on some terminals).
    if event.modifiers.contains(CKeyMods::SHIFT) || matches!(event.code, KeyCode::BackTab) {
        modifiers.with_shift();
    }
    if event.modifiers.contains(CKeyMods::ALT) {
        modifiers.with_alt();
    }
    if event.modifiers.contains(CKeyMods::SUPER) || event.modifiers.contains(CKeyMods::META) {
        modifiers.with_meta_cmd();
    }

    Some(KeyCombo::new(modifiers, key))
}

#[cfg(test)]
mod tests {
    use super::{
        KeyBindings,
        action_shortcuts::{ActionShortcuts, TextAction},
        key_strike::KeyStrike,
    };

    /// `first_combo_for` feeds the footer, F1 and the cheatsheet, so it has
    /// to answer the same thing every time it is asked. It reads a `HashMap`,
    /// whose iteration order varies run to run and even call to call, so
    /// picking the first match made a two-chord action flicker between its
    /// chords mid-session.
    #[test]
    fn first_combo_for_is_stable_when_an_action_has_two_chords() {
        let mut kb = KeyBindings::empty();
        kb.batch_add()
            .with_ctrl()
            .add(KeyStrike::KeyB, ActionShortcuts::FocusSidebar);
        kb.batch_add()
            .with_alt()
            .add(KeyStrike::KeyY, ActionShortcuts::FocusSidebar);

        let first = kb
            .first_combo_for(&ActionShortcuts::FocusSidebar)
            .expect("bound twice");
        for _ in 0..50 {
            assert_eq!(
                kb.first_combo_for(&ActionShortcuts::FocusSidebar)
                    .as_deref(),
                Some(first.as_str())
            );
        }
        // And it is the lowest combo, not merely a stable one: `combos_for`
        // and `to_hashmap` sort the same way, so the three agree.
        let mut combos = kb.combos_for(&ActionShortcuts::FocusSidebar);
        combos.sort();
        assert_eq!(first, combos[0].to_string());
    }

    /// The guard on the builder. Without it a second `add` for one combo
    /// overwrote the first and said nothing — the bug that left `Text(Link)`
    /// and `Text(ToggleHeader)` with no combo at all for as long as they were
    /// in the default table.
    #[test]
    #[should_panic(expected = "would drop that silently")]
    fn a_duplicate_combo_in_one_table_panics() {
        KeyBindings::empty()
            .batch_add()
            .with_ctrl()
            .add(KeyStrike::KeyL, ActionShortcuts::Text(TextAction::Link))
            .add(KeyStrike::KeyL, ActionShortcuts::FocusEditor);
    }

    /// A user's keymap is theirs to contradict: two actions claiming one chord
    /// in a config resolves to one of them rather than killing the app.
    #[test]
    fn a_duplicate_combo_in_a_user_config_does_not() {
        let combo = super::KeyCombo::new(super::KeyModifiers::new().and_ctrl(), KeyStrike::KeyL);
        let kb = KeyBindings::from_hashmap(std::collections::HashMap::from([
            (ActionShortcuts::FocusEditor, vec![combo]),
            (ActionShortcuts::Text(TextAction::Link), vec![combo]),
        ]));
        assert!(
            kb.get_action(&combo).is_some(),
            "one of the two must win, and the app must still start"
        );
    }

    /// `SearchList` resolves its yank chords through this, so a rebinding has to
    /// come back out of it — otherwise the help dialog advertises one chord
    /// while the lists answer to another.
    #[test]
    fn combos_for_follows_a_rebinding() {
        let default = crate::settings::AppSettings::default().key_bindings;
        assert_eq!(
            default.combos_for(&ActionShortcuts::YankRow),
            vec![super::default_yank_combo()],
            "the default binding must be the shared literal"
        );

        let mut rebound = KeyBindings::empty();
        rebound
            .batch_add()
            .with_ctrl()
            .add(KeyStrike::KeyD, ActionShortcuts::YankRow);
        let combos = rebound.combos_for(&ActionShortcuts::YankRow);
        assert_eq!(combos.len(), 1);
        assert_eq!(combos[0].key, KeyStrike::KeyD);

        assert!(
            KeyBindings::empty()
                .combos_for(&ActionShortcuts::YankRow)
                .is_empty(),
            "unbinding must yield no chords, not a silent fallback to the default"
        );
    }

    /// Regression: `c as u8` truncated the code point, so Japanese (and any
    /// other) non-ASCII input was read as an ASCII control character and fired
    /// shortcuts — typing '理' (U+7406) sent Ctrl+F, '成' (U+6210) sent Ctrl+P.
    #[test]
    fn non_ascii_chars_are_not_mistaken_for_control_codes() {
        use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers as CKeyMods};

        for c in ['理', '成', 'あ', 'é'] {
            let event = KeyEvent::new(KeyCode::Char(c), CKeyMods::NONE);
            assert_eq!(
                super::key_event_to_combo(&event),
                None,
                "{c:?} is not a shortcut and must not resolve to one"
            );
        }
    }

    /// The raw control characters this normalisation exists for must keep
    /// implying Ctrl on terminals that deliver them without the modifier bit.
    #[test]
    fn ascii_control_chars_still_imply_ctrl() {
        use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers as CKeyMods};

        for (raw, letter) in [('\x06', 'f'), ('\x10', 'p')] {
            let raw_event = KeyEvent::new(KeyCode::Char(raw), CKeyMods::NONE);
            let letter_event = KeyEvent::new(KeyCode::Char(letter), CKeyMods::CONTROL);
            assert_eq!(
                super::key_event_to_combo(&raw_event),
                super::key_event_to_combo(&letter_event),
                "raw ASCII control char {raw:?} must resolve like Ctrl+{letter}"
            );
        }
    }

    #[test]
    fn serialize_key_binding() {
        let mut km = KeyBindings::empty();
        km.batch_add()
            .with_ctrl()
            .add(KeyStrike::KeyN, ActionShortcuts::NewJournal)
            .add(KeyStrike::KeyH, ActionShortcuts::Text(TextAction::Bold))
            .with_alt()
            .add(
                KeyStrike::KeyL,
                ActionShortcuts::Text(TextAction::Header(2)),
            );
        let km_str = toml::to_string(&km).unwrap();

        let expected = r#"NewJournal = ["ctrl&N"]
TextEditor-Bold = ["ctrl&H"]
TextEditor-Header2 = ["ctrl+alt&L"]
"#
        .to_string();
        assert_eq!(expected, km_str);
    }

    #[test]
    fn serialize_key_binding_double_assignment() {
        let mut km = KeyBindings::empty();
        km.batch_add()
            .with_ctrl()
            .add(KeyStrike::KeyN, ActionShortcuts::NewJournal)
            .add(KeyStrike::KeyH, ActionShortcuts::Text(TextAction::Bold))
            .with_alt()
            .add(KeyStrike::KeyL, ActionShortcuts::Text(TextAction::Bold));
        let km_str = toml::to_string(&km).unwrap();

        let expected = r#"NewJournal = ["ctrl&N"]
TextEditor-Bold = ["ctrl&H", "ctrl+alt&L"]
"#
        .to_string();
        assert_eq!(expected, km_str);
    }

    #[test]
    fn deserialize_key_binding_double_assignment() {
        let mut expected_km = KeyBindings::empty();
        expected_km
            .batch_add()
            .with_ctrl()
            .add(KeyStrike::KeyN, ActionShortcuts::NewJournal)
            .add(KeyStrike::KeyH, ActionShortcuts::Text(TextAction::Bold))
            .add(KeyStrike::KeyQ, ActionShortcuts::Quit)
            .with_alt()
            .add(KeyStrike::KeyL, ActionShortcuts::Text(TextAction::Bold));

        let km_str = r#"NewJournal = ["ctrl & N"]
TextEditor-Bold = ["ctrl & H", "ctrl+alt & L"]
Quit = ["ctrl & Q"]
"#
        .to_string();

        let km = toml::from_str(&km_str).unwrap();

        assert_eq!(expected_km, km);
    }

    #[test]
    fn deserialize_skips_entry_with_unknown_action() {
        let toml_str = r#"NewJournal = ["ctrl & N"]
NotARealAction = ["ctrl & X"]
Quit = ["ctrl & Q"]
"#;

        let km: KeyBindings = toml::from_str(toml_str).expect("should not error");

        let mut expected = KeyBindings::empty();
        expected
            .batch_add()
            .with_ctrl()
            .add(KeyStrike::KeyN, ActionShortcuts::NewJournal)
            .add(KeyStrike::KeyQ, ActionShortcuts::Quit);

        assert_eq!(expected, km);
    }

    #[test]
    fn deserialize_skips_entry_with_malformed_combo() {
        let toml_str = r#"NewJournal = ["ctrl & N"]
OpenNote = ["bogus & ZZZZ"]
Quit = ["ctrl & Q"]
"#;

        let km: KeyBindings = toml::from_str(toml_str).expect("should not error");

        let mut expected = KeyBindings::empty();
        expected
            .batch_add()
            .with_ctrl()
            .add(KeyStrike::KeyN, ActionShortcuts::NewJournal)
            .add(KeyStrike::KeyQ, ActionShortcuts::Quit);

        assert_eq!(expected, km);
    }

    #[test]
    fn deserialize_injects_default_quit_when_missing() {
        let toml_str = r#"NewJournal = ["ctrl & N"]
"#;

        let km: KeyBindings = toml::from_str(toml_str).expect("should not error");

        let mut expected = KeyBindings::empty();
        expected
            .batch_add()
            .with_ctrl()
            .add(KeyStrike::KeyN, ActionShortcuts::NewJournal)
            .add(KeyStrike::KeyQ, ActionShortcuts::Quit);

        assert_eq!(expected, km);
    }

    #[test]
    fn deserialize_errors_when_quit_missing_and_default_taken() {
        let toml_str = r#"OpenNote = ["ctrl & Q"]
"#;

        let result: Result<KeyBindings, _> = toml::from_str(toml_str);
        assert!(result.is_err(), "expected deserialize to fail");
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("Quit") && err_msg.contains("Ctrl+Q"),
            "error message should mention Quit and Ctrl+Q, got: {}",
            err_msg
        );
    }

    #[test]
    fn deserialize_recovers_quit_when_quit_entry_is_malformed() {
        let toml_str = r#"NewJournal = ["ctrl & N"]
Quit = ["bogus & ZZZZ"]
"#;

        let km: KeyBindings = toml::from_str(toml_str).expect("should not error");

        let mut expected = KeyBindings::empty();
        expected
            .batch_add()
            .with_ctrl()
            .add(KeyStrike::KeyN, ActionShortcuts::NewJournal)
            .add(KeyStrike::KeyQ, ActionShortcuts::Quit);

        assert_eq!(expected, km);
    }
}