-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkeymap.rs
More file actions
1570 lines (1425 loc) · 56.2 KB
/
Copy pathkeymap.rs
File metadata and controls
1570 lines (1425 loc) · 56.2 KB
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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! User-configurable TUI keybindings.
//!
//! The [`KeyMap`] struct holds one list of bindings per **action**, not per
//! key. Views consult the map through small `matches` helpers on
//! [`KeyBinding`] / [`KeyChord`] so a single action can be triggered by any
//! number of equivalent key combinations.
//!
//! [`KeyMap::default`] defines the built-in bindings used when no user
//! override exists. Users override individual actions by adding a
//! `tui.keys` section to `~/.config/himitsu/config.yaml`:
//!
//! ```yaml
//! tui:
//! keys:
//! new_secret: ["F2", "ctrl+n"]
//! # Leader-key chord: press Ctrl+X, then s. Avoids terminal Ctrl+S
//! # collisions (XOFF).
//! save_secret: ["ctrl+x s"]
//! quit: ["esc", "ctrl+q"]
//! ```
//!
//! ## Chord syntax
//!
//! A binding string is one or more chord steps separated by whitespace.
//! Each step uses the canonical `<mod>+<mod>+<code>` form. A single-step
//! binding (`"ctrl+n"`) is just a degenerate chord. Multi-step chords
//! enter "pending" state on their first step — see [`KeyMap::dispatch`].
//!
//! Unknown entries fall back to their defaults; missing sections fall back
//! to [`KeyMap::default`]. Parsing happens at deserialisation time, so a
//! malformed binding string surfaces as a clear config error rather than a
//! silent no-op at runtime.
//!
//! ## Leader-key chords
//!
//! [`LEADER`] (`ctrl+x`) is the only chord prefix. Multi-step bindings must
//! start with it; the leader cannot be bound as a standalone action. After
//! the leader is pressed, the next key within [`CHORD_TIMEOUT_MS`] completes
//! or aborts the chord; otherwise the pending sequence cancels silently.
use std::fmt;
use std::time::Duration;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
/// Leader key for multi-step chords (`ctrl+x`). Every chord binding must
/// begin with this step; it cannot be used as a standalone binding.
pub const LEADER: KeyBinding = KeyBinding::ctrl('x');
/// Wall-clock window after the leader key during which the next keypress
/// completes the chord. Expiry clears the pending buffer silently.
pub const CHORD_TIMEOUT_MS: u64 = 1000;
/// [`Duration`] counterpart of [`CHORD_TIMEOUT_MS`] for deadline arithmetic.
pub const CHORD_TIMEOUT: Duration = Duration::from_millis(CHORD_TIMEOUT_MS);
/// A single chord step: a [`KeyCode`] plus a set of [`KeyModifiers`].
///
/// Serialises/deserialises from strings like `"ctrl+n"`, `"shift+tab"`,
/// `"esc"`, `"?"`, `"F2"`. The canonical string form is
/// `<mod>+<mod>+<code>`, lower-cased, modifiers first.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct KeyBinding {
pub code: KeyCode,
pub modifiers: KeyModifiers,
}
impl KeyBinding {
pub const fn new(code: KeyCode, modifiers: KeyModifiers) -> Self {
Self { code, modifiers }
}
/// Shortcut for a bare key with no modifiers.
pub const fn bare(code: KeyCode) -> Self {
Self::new(code, KeyModifiers::NONE)
}
/// Shortcut for `Ctrl+<ch>`.
pub const fn ctrl(ch: char) -> Self {
Self::new(KeyCode::Char(ch), KeyModifiers::CONTROL)
}
/// Is this binding the chord leader (`ctrl+x`)?
pub fn is_leader(self) -> bool {
self.code == KeyCode::Char('x') && self.modifiers.contains(KeyModifiers::CONTROL)
}
/// Does this binding match a live `KeyEvent`?
///
/// Ascii letters compare case-insensitively (`"y"`/`"Y"`, `"shift+y"`/
/// `"shift+Y"`, `"ctrl+y"`/`"ctrl+Y"` are equivalent). Shift is never
/// inferred from an uppercase letter — only an explicit `shift` modifier
/// counts. Bare bindings ignore an incidental `SHIFT` on the event.
pub fn matches(&self, key: &KeyEvent) -> bool {
// Mask away modifiers we don't track (e.g. META) so cross-platform
// events still match cleanly.
let tracked = KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SHIFT;
let event_mods = key.modifiers & tracked;
match (self.code, key.code) {
(KeyCode::Char(a), KeyCode::Char(b)) => {
if !a.eq_ignore_ascii_case(&b) {
return false;
}
if self.modifiers.contains(KeyModifiers::SHIFT) {
event_mods == self.modifiers
} else {
let strip = KeyModifiers::SHIFT;
(self.modifiers & !strip) == (event_mods & !strip)
}
}
// BackTab on one side is only equivalent to `Tab + Shift` on
// the other — never to a bare Tab. This lets a binding written
// as `"backtab"` match a terminal that produces
// `Tab + KeyModifiers::SHIFT` without collapsing `Tab` and
// `BackTab` into the same key.
(KeyCode::BackTab, KeyCode::Tab) => {
event_mods.contains(KeyModifiers::SHIFT)
&& (event_mods & !KeyModifiers::SHIFT)
== (self.modifiers & !KeyModifiers::SHIFT)
}
(KeyCode::Tab, KeyCode::BackTab) => {
self.modifiers.contains(KeyModifiers::SHIFT)
&& (event_mods & !KeyModifiers::SHIFT)
== (self.modifiers & !KeyModifiers::SHIFT)
}
(KeyCode::BackTab, KeyCode::BackTab) => {
let strip = KeyModifiers::SHIFT;
(self.modifiers & !strip) == (event_mods & !strip)
}
(a, b) => a == b && event_mods == self.modifiers,
}
}
/// Palette/help style: modifiers joined with `-` so punctuation key names
/// (`+`, `-`, `=`) are not confused with the separator.
pub fn display_dash_separated(self) -> String {
let mut parts: Vec<&str> = Vec::new();
if self.modifiers.contains(KeyModifiers::CONTROL) {
parts.push("ctrl");
}
if self.modifiers.contains(KeyModifiers::ALT) {
parts.push("alt");
}
if self.modifiers.contains(KeyModifiers::SHIFT) {
parts.push("shift");
}
let code = if self.modifiers.is_empty() {
code_to_string(self.code)
} else {
code_to_human_string(self.code)
};
if parts.is_empty() {
code
} else {
format!("{}-{}", parts.join("-"), code)
}
}
}
impl fmt::Display for KeyBinding {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut parts: Vec<&str> = Vec::new();
if self.modifiers.contains(KeyModifiers::CONTROL) {
parts.push("ctrl");
}
if self.modifiers.contains(KeyModifiers::ALT) {
parts.push("alt");
}
if self.modifiers.contains(KeyModifiers::SHIFT) {
parts.push("shift");
}
let code = code_to_string(self.code);
if parts.is_empty() {
write!(f, "{code}")
} else {
write!(f, "{}+{}", parts.join("+"), code)
}
}
}
fn code_to_string(code: KeyCode) -> String {
match code {
// The named form roundtrips: chord steps are whitespace-separated in
// the config format, so a literal ' ' would be unparseable.
KeyCode::Char(' ') => "space".to_string(),
KeyCode::Char(c) => c.to_string(),
KeyCode::Enter => "enter".to_string(),
KeyCode::Esc => "esc".to_string(),
KeyCode::Tab => "tab".to_string(),
KeyCode::BackTab => "backtab".to_string(),
KeyCode::Backspace => "backspace".to_string(),
KeyCode::Left => "left".to_string(),
KeyCode::Right => "right".to_string(),
KeyCode::Up => "up".to_string(),
KeyCode::Down => "down".to_string(),
KeyCode::Home => "home".to_string(),
KeyCode::End => "end".to_string(),
KeyCode::PageUp => "pageup".to_string(),
KeyCode::PageDown => "pagedown".to_string(),
KeyCode::Delete => "delete".to_string(),
KeyCode::Insert => "insert".to_string(),
KeyCode::F(n) => format!("f{n}"),
KeyCode::Null => "null".to_string(),
KeyCode::CapsLock => "capslock".to_string(),
KeyCode::ScrollLock => "scrolllock".to_string(),
KeyCode::NumLock => "numlock".to_string(),
KeyCode::PrintScreen => "printscreen".to_string(),
KeyCode::Pause => "pause".to_string(),
KeyCode::Menu => "menu".to_string(),
KeyCode::KeypadBegin => "keypadbegin".to_string(),
KeyCode::Media(_) | KeyCode::Modifier(_) => "unsupported".to_string(),
}
}
/// Punctuation keys rendered with modifier prefixes — avoids `ctrl--` etc.
fn code_to_human_string(code: KeyCode) -> String {
match code {
KeyCode::Char('+') => "plus".to_string(),
KeyCode::Char('-') => "minus".to_string(),
KeyCode::Char('=') => "equals".to_string(),
other => code_to_string(other),
}
}
impl std::str::FromStr for KeyBinding {
type Err = KeyBindingParseError;
fn from_str(input: &str) -> Result<Self, Self::Err> {
if input.is_empty() {
return Err(KeyBindingParseError::Empty);
}
// A lone '+' is itself a legal keycode ("plus"), so don't split it
// away if it's the only character.
if input == "+" {
return Ok(KeyBinding::bare(KeyCode::Char('+')));
}
let raw: Vec<&str> = input.split('+').collect();
let (mod_parts, code_part): (Vec<&str>, &str) = if raw.last() == Some(&"") {
let modifiers = raw[..raw.len() - 1].to_vec();
(modifiers[..modifiers.len().saturating_sub(1)].to_vec(), "+")
} else {
let last = *raw.last().unwrap();
(raw[..raw.len() - 1].to_vec(), last)
};
let mut modifiers = KeyModifiers::NONE;
for part in &mod_parts {
let normalised = part.trim().to_ascii_lowercase();
match normalised.as_str() {
"ctrl" | "control" | "c" => modifiers |= KeyModifiers::CONTROL,
"alt" | "meta" | "opt" | "option" | "a" => modifiers |= KeyModifiers::ALT,
"shift" | "s" => modifiers |= KeyModifiers::SHIFT,
"" => return Err(KeyBindingParseError::EmptyModifier(input.to_string())),
_ => {
return Err(KeyBindingParseError::UnknownModifier {
input: input.to_string(),
modifier: part.to_string(),
});
}
}
}
let code = parse_code(code_part).ok_or_else(|| KeyBindingParseError::UnknownCode {
input: input.to_string(),
code: code_part.to_string(),
})?;
let code = match code {
KeyCode::Char(c) if c.is_ascii_alphabetic() => KeyCode::Char(c.to_ascii_lowercase()),
other => other,
};
Ok(KeyBinding { code, modifiers })
}
}
fn parse_code(s: &str) -> Option<KeyCode> {
let lower = s.trim().to_ascii_lowercase();
match lower.as_str() {
"enter" | "return" | "ret" => Some(KeyCode::Enter),
"esc" | "escape" => Some(KeyCode::Esc),
"tab" => Some(KeyCode::Tab),
"backtab" => Some(KeyCode::BackTab),
"backspace" | "bs" => Some(KeyCode::Backspace),
"space" | "spc" => Some(KeyCode::Char(' ')),
"plus" => Some(KeyCode::Char('+')),
"minus" => Some(KeyCode::Char('-')),
"equals" | "eq" => Some(KeyCode::Char('=')),
"left" => Some(KeyCode::Left),
"right" => Some(KeyCode::Right),
"up" => Some(KeyCode::Up),
"down" => Some(KeyCode::Down),
"home" => Some(KeyCode::Home),
"end" => Some(KeyCode::End),
"pageup" | "pgup" => Some(KeyCode::PageUp),
"pagedown" | "pgdown" | "pgdn" => Some(KeyCode::PageDown),
"delete" | "del" => Some(KeyCode::Delete),
"insert" | "ins" => Some(KeyCode::Insert),
_ => {
if let Some(rest) = lower.strip_prefix('f')
&& let Ok(n) = rest.parse::<u8>()
&& (1..=24).contains(&n)
{
return Some(KeyCode::F(n));
}
let mut chars = s.chars();
let first = chars.next()?;
if chars.next().is_none() {
return Some(KeyCode::Char(first));
}
None
}
}
}
/// Errors returned when parsing a key-binding string.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum KeyBindingParseError {
Empty,
EmptyModifier(String),
UnknownModifier { input: String, modifier: String },
UnknownCode { input: String, code: String },
}
impl fmt::Display for KeyBindingParseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Empty => write!(f, "empty key binding string"),
Self::EmptyModifier(input) => {
write!(f, "empty modifier segment in binding '{input}'")
}
Self::UnknownModifier { input, modifier } => write!(
f,
"unknown modifier '{modifier}' in binding '{input}' \
(expected one of: ctrl, alt, shift)"
),
Self::UnknownCode { input, code } => {
write!(f, "unknown key code '{code}' in binding '{input}'")
}
}
}
}
impl std::error::Error for KeyBindingParseError {}
impl Serialize for KeyBinding {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&self.to_string())
}
}
impl<'de> Deserialize<'de> for KeyBinding {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let raw = String::deserialize(d)?;
raw.parse().map_err(serde::de::Error::custom)
}
}
// ── KeyChord ───────────────────────────────────────────────────────────────
/// A sequence of one or more [`KeyBinding`] steps.
///
/// A single-step chord (the default for most bindings) behaves exactly like
/// the underlying [`KeyBinding`]. Multi-step chords (e.g. `"ctrl+x s"`)
/// require the leader-key dispatcher to track pending state across events;
/// see [`KeyMap::dispatch`].
///
/// String form: chord steps separated by whitespace, each step in canonical
/// `<mod>+<mod>+<code>` form. Examples:
/// - `"ctrl+s"` — single-step, fires immediately.
/// - `"ctrl+x s"` — two-step leader chord: press Ctrl+X, then bare `s`.
/// - `"ctrl+x ctrl+s"` — two Ctrl-modified steps.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyChord {
steps: Vec<KeyBinding>,
}
impl KeyChord {
/// Construct a chord from a non-empty step list. Returns `None` for
/// an empty input — chords with zero steps are nonsensical.
pub fn try_new(steps: Vec<KeyBinding>) -> Option<Self> {
if steps.is_empty() {
None
} else {
Some(Self { steps })
}
}
/// Single-step chord wrapping a [`KeyBinding`].
pub fn single(binding: KeyBinding) -> Self {
Self {
steps: vec![binding],
}
}
/// Lift a sequence of live `KeyEvent`s into a chord. Ascii letters are
/// lower-cased to mirror [`KeyBinding::from_str`] so the resulting chord
/// round-trips cleanly through `Display`.
pub fn from_events(events: &[KeyEvent]) -> Option<Self> {
let steps: Vec<KeyBinding> = events
.iter()
.map(|ev| {
let code = match ev.code {
KeyCode::Char(c) if c.is_ascii_alphabetic() => {
KeyCode::Char(c.to_ascii_lowercase())
}
other => other,
};
KeyBinding::new(code, ev.modifiers)
})
.collect();
Self::try_new(steps)
}
/// Number of chord steps (always ≥ 1; chords with zero steps are
/// rejected at construction time, so [`Self::try_new`] returns
/// `Option`).
#[allow(clippy::len_without_is_empty)]
pub fn len(&self) -> usize {
self.steps.len()
}
pub fn is_single_step(&self) -> bool {
self.steps.len() == 1
}
/// All chord steps, in order.
pub fn steps(&self) -> &[KeyBinding] {
&self.steps
}
/// First chord step. Used to surface a "what to press to enter this
/// chord" hint without exposing the whole sequence.
pub fn first_step(&self) -> &KeyBinding {
&self.steps[0]
}
pub fn starts_with_leader(&self) -> bool {
self.steps.first().is_some_and(|step| step.is_leader())
}
/// Multi-step chord whose first step is [`LEADER`].
pub fn is_leader_chord(&self) -> bool {
!self.is_single_step() && self.starts_with_leader()
}
/// Does the supplied event sequence (length N) match the chord's first
/// N steps exactly? Useful for prefix-matching during chord dispatch.
pub fn matches_prefix(&self, events: &[KeyEvent]) -> bool {
if events.len() > self.steps.len() {
return false;
}
events
.iter()
.zip(self.steps.iter())
.all(|(ev, step)| step.matches(ev))
}
/// Does the supplied event sequence match the chord exactly (same
/// length, every step matches)?
pub fn matches_exact(&self, events: &[KeyEvent]) -> bool {
events.len() == self.steps.len() && self.matches_prefix(events)
}
}
impl fmt::Display for KeyChord {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (i, step) in self.steps.iter().enumerate() {
if i > 0 {
f.write_str(" ")?;
}
write!(f, "{step}")?;
}
Ok(())
}
}
impl std::str::FromStr for KeyChord {
type Err = KeyBindingParseError;
fn from_str(input: &str) -> Result<Self, Self::Err> {
let trimmed = input.trim();
if trimmed.is_empty() {
return Err(KeyBindingParseError::Empty);
}
let steps: Result<Vec<KeyBinding>, _> = trimmed
.split_whitespace()
.map(|step| step.parse::<KeyBinding>())
.collect();
let steps = steps?;
if steps.is_empty() {
return Err(KeyBindingParseError::Empty);
}
Ok(Self { steps })
}
}
impl Serialize for KeyChord {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&self.to_string())
}
}
impl<'de> Deserialize<'de> for KeyChord {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let raw = String::deserialize(d)?;
raw.parse().map_err(serde::de::Error::custom)
}
}
/// Single-step chords that participate in direct key matching. The chord
/// [`LEADER`] is excluded — it only opens multi-step sequences.
fn is_bindable_single_step(chord: &KeyChord) -> bool {
chord.is_single_step() && !chord.first_step().is_leader()
}
/// Helper so views can take either a `&Vec<KeyChord>` or `&[KeyChord]` and
/// test against a live `KeyEvent` with `.matches(&key)`.
///
/// Only **single-step** chords participate in this match. Multi-step chords
/// fire exclusively through [`KeyMap::dispatch`] at the app level — they
/// would be impossible to fire from a one-shot key match.
pub trait Bindings {
fn matches(&self, key: &KeyEvent) -> bool;
}
impl Bindings for Vec<KeyChord> {
fn matches(&self, key: &KeyEvent) -> bool {
self.iter()
.any(|c| is_bindable_single_step(c) && c.first_step().matches(key))
}
}
impl Bindings for [KeyChord] {
fn matches(&self, key: &KeyEvent) -> bool {
self.iter()
.any(|c| is_bindable_single_step(c) && c.first_step().matches(key))
}
}
// ── KeyAction + KeyMap ─────────────────────────────────────────────────────
/// First-class identifier for every keymap-driven action. Used by the chord
/// dispatcher to deliver completed multi-step bindings to the active view
/// without going through a synthesized [`KeyEvent`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyAction {
Quit,
Help,
CommandPalette,
NewSecret,
SwitchStore,
CopySelected,
/// In the search view: copy `himitsu read <ref>` for the selected row.
CopyRefSelected,
Outputs,
/// In the search view: collapse all secret paths to top-level folders.
CollapsePaths,
/// In the search view: expand all secret paths back to full depth.
ExpandPaths,
/// In the search view: toggle the secret-ref autocomplete popup.
ToggleAutocomplete,
/// In the search view: refine the query to the selected row's tag.
RefineTag,
/// In the search view: sort by the selected results column.
SortColumn,
Reveal,
CopyValue,
/// In the secret viewer: copy `himitsu read <ref>` for the open secret.
CopyRef,
Rekey,
Edit,
Delete,
Back,
SaveSecret,
NextField,
PrevField,
Cancel,
}
/// Outcome of feeding a key event to [`KeyMap::dispatch`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Dispatch {
/// The pending sequence plus this key uniquely match a complete chord.
/// The matching action fires; the dispatcher's pending buffer should
/// be cleared.
Match(KeyAction),
/// At least one chord is a strict prefix of the pending+key sequence.
/// The key should be added to the pending buffer; nothing fires yet.
Pending,
/// Neither a complete match nor a prefix. The pending buffer should be
/// cleared and the key should be processed as a normal (non-chord)
/// keystroke.
Unmatched,
}
/// User-configurable keybindings grouped by action.
///
/// Each field is a list of [`KeyChord`]s so multiple key combinations can
/// map to the same action. Unspecified fields fall back to
/// [`KeyMap::default`], which supplies the built-in bindings.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct KeyMap {
// ── Global ────────────────────────────────────────────────────────
pub quit: Vec<KeyChord>,
pub help: Vec<KeyChord>,
// ── Search view ──────────────────────────────────────────────────
pub command_palette: Vec<KeyChord>,
pub new_secret: Vec<KeyChord>,
pub switch_store: Vec<KeyChord>,
/// Copy the selected search result's value to the clipboard
/// (default: Ctrl+Y).
pub copy_selected: Vec<KeyChord>,
/// Copy `himitsu read <ref>` (the *command*, not the value) to the
/// clipboard for the selected row. Useful when sharing how to fetch a
/// secret without putting plaintext on the clipboard.
pub copy_ref_selected: Vec<KeyChord>,
/// Open the codegen browser. The serde aliases accept the pre-rename
/// `outputs` and `envs` config keys, so existing user keymaps keep
/// working.
#[serde(rename = "codegen", alias = "outputs", alias = "envs")]
pub outputs: Vec<KeyChord>,
/// Collapse all secret paths to top-level folders.
pub collapse_paths: Vec<KeyChord>,
/// Expand all secret paths to full depth.
pub expand_paths: Vec<KeyChord>,
/// Toggle the secret-ref autocomplete popup.
pub toggle_autocomplete: Vec<KeyChord>,
/// Refine the query to the selected row's tag.
pub refine_tag: Vec<KeyChord>,
/// Sort by the selected results column (default: `Ctrl+O`).
pub sort_column: Vec<KeyChord>,
// ── Secret viewer ────────────────────────────────────────────────
pub reveal: Vec<KeyChord>,
/// Copy the revealed value to the clipboard (default: `y`).
pub copy_value: Vec<KeyChord>,
/// Copy `himitsu read <ref>` (the *command*) to the clipboard for the
/// currently open secret.
pub copy_ref: Vec<KeyChord>,
pub rekey: Vec<KeyChord>,
pub edit: Vec<KeyChord>,
pub delete: Vec<KeyChord>,
pub back: Vec<KeyChord>,
// ── New-secret form ───────────────────────────────────────────────
pub save_secret: Vec<KeyChord>,
pub next_field: Vec<KeyChord>,
pub prev_field: Vec<KeyChord>,
pub cancel: Vec<KeyChord>,
}
impl Default for KeyMap {
fn default() -> Self {
let single = |b: KeyBinding| KeyChord::single(b);
let bare = |c: KeyCode| single(KeyBinding::bare(c));
let ctrl = |c: char| single(KeyBinding::ctrl(c));
let shift_char = |c: char| single(KeyBinding::new(KeyCode::Char(c), KeyModifiers::SHIFT));
let chord = |binding: KeyBinding| {
KeyChord::try_new(vec![KeyBinding::ctrl('x'), binding])
.expect("two-step leader chord is non-empty")
};
let chord_bare = |c: char| chord(KeyBinding::bare(KeyCode::Char(c)));
let chord_ctrl = |c: char| chord(KeyBinding::ctrl(c));
let chord_shift = |c: char| chord(KeyBinding::new(KeyCode::Char(c), KeyModifiers::SHIFT));
Self {
quit: vec![bare(KeyCode::Esc), ctrl('c')],
help: vec![chord_bare('?')],
command_palette: vec![ctrl('p')],
new_secret: vec![ctrl('n')],
switch_store: vec![chord_ctrl('s')],
copy_selected: vec![ctrl('y')],
copy_ref_selected: vec![chord_shift('y')],
outputs: vec![chord_shift('e')],
collapse_paths: vec![chord_bare('-')],
expand_paths: vec![chord_bare('+'), chord_bare('='), chord_ctrl('=')],
toggle_autocomplete: vec![chord_ctrl(' ')],
refine_tag: vec![chord_ctrl('t')],
sort_column: vec![ctrl('o')],
reveal: vec![bare(KeyCode::Char('r'))],
copy_value: vec![bare(KeyCode::Char('y'))],
copy_ref: vec![chord_shift('y')],
rekey: vec![shift_char('r')],
edit: vec![bare(KeyCode::Char('e'))],
delete: vec![bare(KeyCode::Char('d'))],
back: vec![bare(KeyCode::Esc)],
save_secret: vec![ctrl('s'), ctrl('w')],
next_field: vec![bare(KeyCode::Tab)],
prev_field: vec![bare(KeyCode::BackTab)],
cancel: vec![bare(KeyCode::Esc)],
}
}
}
// ── KeyRegistry ────────────────────────────────────────────────────────────
/// Which view's help screen lists a [`KeyAction`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Scope {
/// Available everywhere (quit, help).
Global,
/// Search view.
Search,
/// Secret viewer.
Viewer,
/// New-secret form.
NewSecretForm,
}
/// One registry row: everything every surface needs to know about a
/// [`KeyAction`] — its config field, its help text, which view's help
/// screen lists it, and the command-palette entry that shares it.
pub struct Row {
/// Accessor for the user-configurable chord list backing this action.
pub field: fn(&KeyMap) -> &Vec<KeyChord>,
/// Help-screen description.
pub help: &'static str,
/// Which view's help screen lists this action.
pub scope: Scope,
/// The command-palette command sharing this action, if any.
pub palette: Option<crate::tui::views::command_palette::Command>,
}
impl KeyAction {
/// Every action, in help-screen display order (grouped by scope). Used
/// to derive [`KeyMap::entries`] — an action missing here simply never
/// dispatches, which is loud, unlike the silent drift of the old
/// hand-maintained table.
pub const ALL: [KeyAction; 24] = [
// Global
KeyAction::Help,
KeyAction::Quit,
// Search view
KeyAction::CommandPalette,
KeyAction::NewSecret,
KeyAction::SwitchStore,
KeyAction::CopySelected,
KeyAction::CopyRefSelected,
KeyAction::Outputs,
KeyAction::CollapsePaths,
KeyAction::ExpandPaths,
KeyAction::ToggleAutocomplete,
KeyAction::RefineTag,
KeyAction::SortColumn,
// Secret viewer
KeyAction::Reveal,
KeyAction::CopyValue,
KeyAction::CopyRef,
KeyAction::Rekey,
KeyAction::Edit,
KeyAction::Delete,
KeyAction::Back,
// New-secret form
KeyAction::SaveSecret,
KeyAction::NextField,
KeyAction::PrevField,
KeyAction::Cancel,
];
}
/// The single source of truth tying a [`KeyAction`] to its config field,
/// help text, scope, and palette link. The exhaustive match means adding a
/// `KeyAction` variant without a row is a **compile error** — this replaces
/// the hand-synced `entries()` table, the per-view hardcoded help strings,
/// and the palette's hand-maintained action map.
pub fn row(action: KeyAction) -> Row {
use crate::tui::views::command_palette::Command;
match action {
KeyAction::Quit => Row {
field: |km| &km.quit,
help: "quit",
scope: Scope::Global,
palette: Some(Command::Quit),
},
KeyAction::Help => Row {
field: |km| &km.help,
help: "toggle this help",
scope: Scope::Global,
palette: Some(Command::Help),
},
KeyAction::CommandPalette => Row {
field: |km| &km.command_palette,
help: "open command palette",
scope: Scope::Search,
palette: None,
},
KeyAction::NewSecret => Row {
field: |km| &km.new_secret,
help: "new secret",
scope: Scope::Search,
palette: Some(Command::NewSecret),
},
KeyAction::SwitchStore => Row {
field: |km| &km.switch_store,
help: "switch store",
scope: Scope::Search,
palette: Some(Command::SwitchStore),
},
KeyAction::CopySelected => Row {
field: |km| &km.copy_selected,
help: "copy selection to clipboard",
scope: Scope::Search,
palette: None,
},
KeyAction::CopyRefSelected => Row {
field: |km| &km.copy_ref_selected,
help: "copy `himitsu read <ref>` command",
scope: Scope::Search,
palette: None,
},
KeyAction::Outputs => Row {
field: |km| &km.outputs,
help: "browse codegen",
scope: Scope::Search,
palette: Some(Command::Outputs),
},
KeyAction::CollapsePaths => Row {
field: |km| &km.collapse_paths,
help: "collapse paths to top-level folders",
scope: Scope::Search,
palette: None,
},
KeyAction::ExpandPaths => Row {
field: |km| &km.expand_paths,
help: "expand paths to full depth",
scope: Scope::Search,
palette: None,
},
KeyAction::ToggleAutocomplete => Row {
field: |km| &km.toggle_autocomplete,
help: "toggle ref autocomplete",
scope: Scope::Search,
palette: None,
},
KeyAction::RefineTag => Row {
field: |km| &km.refine_tag,
help: "refine to selected tag",
scope: Scope::Search,
palette: None,
},
KeyAction::SortColumn => Row {
field: |km| &km.sort_column,
help: "sort selected column",
scope: Scope::Search,
palette: None,
},
KeyAction::Reveal => Row {
field: |km| &km.reveal,
help: "reveal / hide value",
scope: Scope::Viewer,
palette: None,
},
KeyAction::CopyValue => Row {
field: |km| &km.copy_value,
help: "copy value to clipboard",
scope: Scope::Viewer,
palette: None,
},
KeyAction::CopyRef => Row {
field: |km| &km.copy_ref,
help: "copy `himitsu read <ref>` command",
scope: Scope::Viewer,
palette: None,
},
KeyAction::Rekey => Row {
field: |km| &km.rekey,
help: "rekey for current recipients",
scope: Scope::Viewer,
palette: None,
},
KeyAction::Edit => Row {
field: |km| &km.edit,
help: "edit value + metadata in $EDITOR",
scope: Scope::Viewer,
palette: None,
},
KeyAction::Delete => Row {
field: |km| &km.delete,
help: "delete secret (with confirm)",
scope: Scope::Viewer,
palette: None,
},
KeyAction::Back => Row {
field: |km| &km.back,
help: "back",
scope: Scope::Viewer,
palette: None,
},
KeyAction::SaveSecret => Row {
field: |km| &km.save_secret,
help: "save from any field",
scope: Scope::NewSecretForm,
palette: None,
},
KeyAction::NextField => Row {
field: |km| &km.next_field,
help: "next field (wraps)",
scope: Scope::NewSecretForm,
palette: None,
},
KeyAction::PrevField => Row {
field: |km| &km.prev_field,
help: "previous field (wraps)",
scope: Scope::NewSecretForm,
palette: None,
},
KeyAction::Cancel => Row {
field: |km| &km.cancel,
help: "cancel",
scope: Scope::NewSecretForm,
palette: None,
},
}
}
/// Live help rows for one scope: `(chords, description)` with the chord
/// display rendered from the CURRENT keymap, so user rebinds show up in
/// every help screen automatically.
pub fn help_rows(keymap: &KeyMap, scope: Scope) -> Vec<(String, String)> {
KeyAction::ALL
.into_iter()
.filter(|a| row(*a).scope == scope)
.map(|a| (chords_display(keymap, a), row(a).help.to_string()))
.collect()
}
/// One live help row for a single action — for views that compose their
/// help screens from individual rows rather than a whole scope.
pub fn help_row(keymap: &KeyMap, action: KeyAction) -> (String, String) {
(chords_display(keymap, action), row(action).help.to_string())
}
/// Human-facing display of every chord bound to `action`, joined with
/// ` / `. Modifier `+` separators within each step render as `-` to match
/// the command palette's established style (e.g. `ctrl+x -`).
pub fn chords_display(keymap: &KeyMap, action: KeyAction) -> String {
keymap
.chords_for(action)
.iter()
.map(|c| {
c.steps()
.iter()
.map(|step| step.display_dash_separated())
.collect::<Vec<_>>()
.join(" ")
})
.collect::<Vec<_>>()
.join(" / ")
}
impl KeyMap {
/// `(action, chords)` pairs across every keymap field, derived from
/// [`KeyAction::ALL`] and the registry [`row`]s — there is no second
/// table to keep in sync.
fn entries(&self) -> [(KeyAction, &Vec<KeyChord>); KeyAction::ALL.len()] {
KeyAction::ALL.map(|action| (action, (row(action).field)(self)))
}
/// Single-step direct lookup: find the action whose binding list
/// contains a single-step chord matching `key`. Returns the FIRST
/// matching action in [`Self::entries`] order; ties favour the action
/// declared earliest. Multi-step chords are NEVER returned here —
/// they fire only via [`Self::dispatch`].
pub fn action_for_key(&self, key: &KeyEvent) -> Option<KeyAction> {
for (action, chords) in self.entries() {
if chords
.iter()
.any(|c| is_bindable_single_step(c) && c.first_step().matches(key))
{
return Some(action);
}
}
None
}
/// View-scoped variant of [`Self::action_for_key`]: scan only the
/// listed actions, in the order given. Each view declares its own
/// priority slice (e.g. the secret viewer wants `Rekey` before
/// `Reveal` so `Shift+R` doesn't fall through to bare `r`); shared
/// here so the per-view helpers don't each rebuild the same iteration.
pub fn action_for_key_in(&self, key: &KeyEvent, priority: &[KeyAction]) -> Option<KeyAction> {
priority
.iter()
.copied()
.find(|&action| self.chords_for(action).matches(key))
}