1use std::{collections::HashMap, fmt::Display};
2
3use action_shortcuts::ActionShortcuts;
4use itertools::Itertools;
5use key_combo::{KeyCombo, KeyModifiers};
6use key_strike::KeyStrike;
7use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers as CKeyMods};
8use serde::{Deserialize, Serialize, de::Visitor, ser::SerializeMap};
9
10pub mod action_shortcuts;
11pub mod key_combo;
12pub mod key_strike;
13pub mod leader;
14
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct KeyBindings {
17 bindings: HashMap<KeyCombo, ActionShortcuts>,
18}
19
20impl Serialize for KeyBindings {
21 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
22 where
23 S: serde::Serializer,
24 {
25 let kb_map = self.to_hashmap();
26 let mut map = serializer.serialize_map(Some(kb_map.len()))?;
27 for (k, v) in kb_map
28 .iter()
29 .sorted_by_key(|(action, _combo)| action.to_owned())
30 {
31 map.serialize_entry(&k, &v)?;
32 }
33 map.end()
34 }
35}
36
37struct DeserializeKeyBindingsVisitor;
38impl<'de> Visitor<'de> for DeserializeKeyBindingsVisitor {
39 type Value = KeyBindings;
40
41 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
42 formatter.write_str("a keybindings map of action names to lists of key combos")
43 }
44 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
45 where
46 A: serde::de::MapAccess<'de>,
47 {
48 use serde::de::{Error, IgnoredAny, IntoDeserializer};
49
50 let mut bindings: HashMap<ActionShortcuts, Vec<KeyCombo>> =
51 HashMap::with_capacity(map.size_hint().unwrap_or(0));
52
53 loop {
54 let key_str: String = match map.next_key::<String>() {
56 Ok(Some(s)) => s,
57 Ok(None) => break,
58 Err(e) => return Err(e),
59 };
60
61 let action = match ActionShortcuts::deserialize(key_str.clone().into_deserializer()) {
64 Ok(a) => a,
65 Err(e) => {
66 let e: serde::de::value::Error = e;
67 let _ = map.next_value::<IgnoredAny>();
68 tracing::warn!(
69 "Skipping unknown action '{}' in keybindings config: {}",
70 key_str,
71 e
72 );
73 continue;
74 }
75 };
76
77 match map.next_value::<Vec<KeyCombo>>() {
78 Ok(value) => {
79 bindings.insert(action, value);
80 }
81 Err(e) => {
82 tracing::warn!("Skipping keybindings entry for action '{}': {}", action, e);
83 }
84 }
85 }
86
87 if !bindings.contains_key(&ActionShortcuts::Quit) {
89 let quit_combo = default_quit_combo();
90
91 let conflicting_action = bindings
92 .iter()
93 .find(|(_, combos)| combos.iter().any(|c| c == &quit_combo))
94 .map(|(action, _)| action.clone());
95
96 if let Some(other) = conflicting_action {
97 return Err(A::Error::custom(format!(
98 "Quit action has no binding and the default combo Ctrl+Q is already mapped to '{}'. \
99 Add a valid Quit binding to your keybindings config.",
100 other
101 )));
102 }
103
104 tracing::warn!("Quit action missing from keybindings; restoring default Ctrl+Q");
105 bindings.insert(ActionShortcuts::Quit, vec![quit_combo]);
106 }
107
108 Ok(KeyBindings::from_hashmap(bindings))
109 }
110}
111
112impl<'de> Deserialize<'de> for KeyBindings {
113 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
114 where
115 D: serde::Deserializer<'de>,
116 {
117 deserializer.deserialize_map(DeserializeKeyBindingsVisitor)
118 }
119}
120
121impl Display for KeyBindings {
122 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123 let mut bindings: Vec<(ActionShortcuts, Vec<KeyCombo>)> = vec![];
124 for (key, value) in &self.bindings {
125 if let Some((_, combos)) = bindings
126 .iter_mut()
127 .find(|(shortcut, _combos)| shortcut.eq(value))
128 {
129 combos.push(key.to_owned());
130 combos.sort();
131 } else {
132 bindings.push((value.to_owned(), vec![key.to_owned()]));
133 }
134 }
135
136 bindings.sort_by_key(|(a, _v)| a.to_owned());
137 for (key, value) in &bindings {
138 writeln!(
139 f,
140 "{}: {}",
141 key,
142 value
143 .iter()
144 .map(|kc| kc.to_string())
145 .collect::<Vec<String>>()
146 .join(", ")
147 )?;
148 }
149
150 Ok(())
151 }
152}
153
154impl KeyBindings {
155 pub fn empty() -> Self {
156 KeyBindings {
157 bindings: HashMap::default(),
158 }
159 }
160
161 pub fn batch_add(&mut self) -> KeyBindBatch<'_> {
162 KeyBindBatch {
163 bindings: self,
164 modifiers: KeyModifiers::default(),
165 }
166 }
167
168 pub fn get_action(&self, combo: &KeyCombo) -> Option<ActionShortcuts> {
169 self.bindings.get(combo).map(|a| a.to_owned())
170 }
171
172 pub fn combos_for(&self, action: &ActionShortcuts) -> Vec<KeyCombo> {
176 self.bindings
177 .iter()
178 .filter(|(_, a)| *a == action)
179 .map(|(combo, _)| *combo)
180 .collect()
181 }
182
183 pub fn first_combo_for(&self, action: &ActionShortcuts) -> Option<String> {
185 self.bindings
186 .iter()
187 .find(|(_, a)| *a == action)
188 .map(|(combo, _)| combo.to_string())
189 }
190
191 pub fn to_hashmap(&self) -> HashMap<ActionShortcuts, Vec<KeyCombo>> {
192 let mut bindings: HashMap<ActionShortcuts, Vec<KeyCombo>> = HashMap::new();
193 for (combo, action) in &self.bindings {
194 let entry = bindings.entry(action.to_owned()).or_default();
195 entry.push(combo.to_owned());
196 entry.sort();
197 }
198 bindings
199 }
200
201 pub fn from_hashmap(bindings: HashMap<ActionShortcuts, Vec<KeyCombo>>) -> KeyBindings {
202 let mut kb = KeyBindings::empty();
203 for (action, combos) in &bindings {
204 tracing::debug!("from_hashmap: action={} combos={:?}", action, combos);
205 }
206 for (action, combos) in bindings {
207 for combo in combos {
208 let valid = combo.is_valid_binding();
209 tracing::debug!(
210 "from_hashmap: combo='{}' key={:?} modifiers={:?} valid={}",
211 combo,
212 combo.key,
213 combo.modifiers,
214 valid
215 );
216 if valid {
217 kb.bindings.insert(combo.to_owned(), action.to_owned());
218 } else {
219 tracing::warn!(
220 "Skipping invalid key combo '{}' for action '{}': \
221 only ctrl/alt (with optional shift) + a letter, digit, or \
222 punctuation key, or bare F1–F12 are supported",
223 combo,
224 action
225 );
226 }
227 }
228 }
229 kb
230 }
231}
232
233pub fn default_quit_combo() -> KeyCombo {
237 KeyCombo::new(KeyModifiers::new().and_ctrl(), KeyStrike::KeyQ)
238}
239
240pub fn default_yank_combo() -> KeyCombo {
245 KeyCombo::new(KeyModifiers::new().and_ctrl(), KeyStrike::KeyY)
246}
247
248pub struct KeyBindBatch<'k> {
249 bindings: &'k mut KeyBindings,
250 modifiers: KeyModifiers,
251}
252
253impl<'k> KeyBindBatch<'k> {
254 pub fn with_shift(mut self) -> Self {
255 self.modifiers.with_shift();
256 self
257 }
258 pub fn with_ctrl(mut self) -> Self {
259 self.modifiers.with_ctrl();
260 self
261 }
262 pub fn with_alt(mut self) -> Self {
263 self.modifiers.with_alt();
264 self
265 }
266 pub fn with_meta(mut self) -> Self {
268 self.modifiers.with_meta_cmd();
269 self
270 }
271 pub fn with_cmd(mut self) -> Self {
272 self.modifiers.with_meta_cmd();
273 self
274 }
275 pub fn add(self, key: KeyStrike, action: ActionShortcuts) -> KeyBindBatch<'k> {
276 self.bindings
277 .bindings
278 .insert(KeyCombo::new(self.modifiers, key), action);
279 self
280 }
281}
282
283pub fn key_event_to_combo(event: &KeyEvent) -> Option<KeyCombo> {
288 let mut implied_ctrl = false;
292 let key = match event.code {
293 KeyCode::Char(c) => {
294 let c = if c as u8 >= 1 && c as u8 <= 26 {
295 implied_ctrl = true;
296 (c as u8 + b'a' - 1) as char
297 } else {
298 c
299 };
300 match c.to_ascii_lowercase() {
301 'a' => KeyStrike::KeyA,
302 'b' => KeyStrike::KeyB,
303 'c' => KeyStrike::KeyC,
304 'd' => KeyStrike::KeyD,
305 'e' => KeyStrike::KeyE,
306 'f' => KeyStrike::KeyF,
307 'g' => KeyStrike::KeyG,
308 'h' => KeyStrike::KeyH,
309 'i' => KeyStrike::KeyI,
310 'j' => KeyStrike::KeyJ,
311 'k' => KeyStrike::KeyK,
312 'l' => KeyStrike::KeyL,
313 'm' => KeyStrike::KeyM,
314 'n' => KeyStrike::KeyN,
315 'o' => KeyStrike::KeyO,
316 'p' => KeyStrike::KeyP,
317 'q' => KeyStrike::KeyQ,
318 'r' => KeyStrike::KeyR,
319 's' => KeyStrike::KeyS,
320 't' => KeyStrike::KeyT,
321 'u' => KeyStrike::KeyU,
322 'v' => KeyStrike::KeyV,
323 'w' => KeyStrike::KeyW,
324 'x' => KeyStrike::KeyX,
325 'y' => KeyStrike::KeyY,
326 'z' => KeyStrike::KeyZ,
327 '0' => KeyStrike::Digit0,
328 '1' => KeyStrike::Digit1,
329 '2' => KeyStrike::Digit2,
330 '3' => KeyStrike::Digit3,
331 '4' => KeyStrike::Digit4,
332 '5' => KeyStrike::Digit5,
333 '6' => KeyStrike::Digit6,
334 '7' => KeyStrike::Digit7,
335 '8' => KeyStrike::Digit8,
336 '9' => KeyStrike::Digit9,
337 ',' => KeyStrike::Comma,
338 '.' => KeyStrike::Period,
339 '/' => KeyStrike::Slash,
340 ';' => KeyStrike::Semicolon,
341 '\'' => KeyStrike::Quote,
342 '[' => KeyStrike::BracketLeft,
343 ']' => KeyStrike::BracketRight,
344 '\\' => KeyStrike::Backslash,
345 '`' => KeyStrike::Backquote,
346 '-' => KeyStrike::Minus,
347 '=' => KeyStrike::Equal,
348 _ => return None,
349 }
350 }
351 KeyCode::Enter => KeyStrike::Enter,
352 KeyCode::Backspace => KeyStrike::Backspace,
353 KeyCode::Tab | KeyCode::BackTab => KeyStrike::Tab,
354 KeyCode::Esc => KeyStrike::Escape,
355 KeyCode::Up => KeyStrike::ArrowUp,
356 KeyCode::Down => KeyStrike::ArrowDown,
357 KeyCode::Left => KeyStrike::ArrowLeft,
358 KeyCode::Right => KeyStrike::ArrowRight,
359 KeyCode::Home => KeyStrike::Home,
360 KeyCode::End => KeyStrike::End,
361 KeyCode::PageUp => KeyStrike::PageUp,
362 KeyCode::PageDown => KeyStrike::PageDown,
363 KeyCode::Delete => KeyStrike::Delete,
364 KeyCode::Insert => KeyStrike::Insert,
365 KeyCode::F(n) => match n {
366 1 => KeyStrike::F1,
367 2 => KeyStrike::F2,
368 3 => KeyStrike::F3,
369 4 => KeyStrike::F4,
370 5 => KeyStrike::F5,
371 6 => KeyStrike::F6,
372 7 => KeyStrike::F7,
373 8 => KeyStrike::F8,
374 9 => KeyStrike::F9,
375 10 => KeyStrike::F10,
376 11 => KeyStrike::F11,
377 12 => KeyStrike::F12,
378 13 => KeyStrike::F13,
379 14 => KeyStrike::F14,
380 15 => KeyStrike::F15,
381 16 => KeyStrike::F16,
382 17 => KeyStrike::F17,
383 18 => KeyStrike::F18,
384 19 => KeyStrike::F19,
385 20 => KeyStrike::F20,
386 21 => KeyStrike::F21,
387 22 => KeyStrike::F22,
388 23 => KeyStrike::F23,
389 24 => KeyStrike::F24,
390 25 => KeyStrike::F25,
391 _ => return None,
392 },
393 _ => return None,
394 };
395
396 let mut modifiers = KeyModifiers::default();
397 if implied_ctrl || event.modifiers.contains(CKeyMods::CONTROL) {
398 modifiers.with_ctrl();
399 }
400 if event.modifiers.contains(CKeyMods::SHIFT) || matches!(event.code, KeyCode::BackTab) {
402 modifiers.with_shift();
403 }
404 if event.modifiers.contains(CKeyMods::ALT) {
405 modifiers.with_alt();
406 }
407 if event.modifiers.contains(CKeyMods::SUPER) || event.modifiers.contains(CKeyMods::META) {
408 modifiers.with_meta_cmd();
409 }
410
411 Some(KeyCombo::new(modifiers, key))
412}
413
414#[cfg(test)]
415mod tests {
416 use super::{
417 KeyBindings,
418 action_shortcuts::{ActionShortcuts, TextAction},
419 key_strike::KeyStrike,
420 };
421
422 #[test]
426 fn combos_for_follows_a_rebinding() {
427 let default = crate::settings::AppSettings::default().key_bindings;
428 assert_eq!(
429 default.combos_for(&ActionShortcuts::YankRow),
430 vec![super::default_yank_combo()],
431 "the default binding must be the shared literal"
432 );
433
434 let mut rebound = KeyBindings::empty();
435 rebound
436 .batch_add()
437 .with_ctrl()
438 .add(KeyStrike::KeyD, ActionShortcuts::YankRow);
439 let combos = rebound.combos_for(&ActionShortcuts::YankRow);
440 assert_eq!(combos.len(), 1);
441 assert_eq!(combos[0].key, KeyStrike::KeyD);
442
443 assert!(
444 KeyBindings::empty()
445 .combos_for(&ActionShortcuts::YankRow)
446 .is_empty(),
447 "unbinding must yield no chords, not a silent fallback to the default"
448 );
449 }
450
451 #[test]
452 fn serialize_key_binding() {
453 let mut km = KeyBindings::empty();
454 km.batch_add()
455 .with_ctrl()
456 .add(KeyStrike::KeyN, ActionShortcuts::NewJournal)
457 .add(KeyStrike::KeyH, ActionShortcuts::Text(TextAction::Bold))
458 .with_alt()
459 .add(
460 KeyStrike::KeyL,
461 ActionShortcuts::Text(TextAction::Header(2)),
462 );
463 let km_str = toml::to_string(&km).unwrap();
464
465 let expected = r#"NewJournal = ["ctrl&N"]
466TextEditor-Bold = ["ctrl&H"]
467TextEditor-Header2 = ["ctrl+alt&L"]
468"#
469 .to_string();
470 assert_eq!(expected, km_str);
471 }
472
473 #[test]
474 fn serialize_key_binding_double_assignment() {
475 let mut km = KeyBindings::empty();
476 km.batch_add()
477 .with_ctrl()
478 .add(KeyStrike::KeyN, ActionShortcuts::NewJournal)
479 .add(KeyStrike::KeyH, ActionShortcuts::Text(TextAction::Bold))
480 .with_alt()
481 .add(KeyStrike::KeyL, ActionShortcuts::Text(TextAction::Bold));
482 let km_str = toml::to_string(&km).unwrap();
483
484 let expected = r#"NewJournal = ["ctrl&N"]
485TextEditor-Bold = ["ctrl&H", "ctrl+alt&L"]
486"#
487 .to_string();
488 assert_eq!(expected, km_str);
489 }
490
491 #[test]
492 fn deserialize_key_binding_double_assignment() {
493 let mut expected_km = KeyBindings::empty();
494 expected_km
495 .batch_add()
496 .with_ctrl()
497 .add(KeyStrike::KeyN, ActionShortcuts::NewJournal)
498 .add(KeyStrike::KeyH, ActionShortcuts::Text(TextAction::Bold))
499 .add(KeyStrike::KeyQ, ActionShortcuts::Quit)
500 .with_alt()
501 .add(KeyStrike::KeyL, ActionShortcuts::Text(TextAction::Bold));
502
503 let km_str = r#"NewJournal = ["ctrl & N"]
504TextEditor-Bold = ["ctrl & H", "ctrl+alt & L"]
505Quit = ["ctrl & Q"]
506"#
507 .to_string();
508
509 let km = toml::from_str(&km_str).unwrap();
510
511 assert_eq!(expected_km, km);
512 }
513
514 #[test]
515 fn deserialize_skips_entry_with_unknown_action() {
516 let toml_str = r#"NewJournal = ["ctrl & N"]
517NotARealAction = ["ctrl & X"]
518Quit = ["ctrl & Q"]
519"#;
520
521 let km: KeyBindings = toml::from_str(toml_str).expect("should not error");
522
523 let mut expected = KeyBindings::empty();
524 expected
525 .batch_add()
526 .with_ctrl()
527 .add(KeyStrike::KeyN, ActionShortcuts::NewJournal)
528 .add(KeyStrike::KeyQ, ActionShortcuts::Quit);
529
530 assert_eq!(expected, km);
531 }
532
533 #[test]
534 fn deserialize_skips_entry_with_malformed_combo() {
535 let toml_str = r#"NewJournal = ["ctrl & N"]
536OpenNote = ["bogus & ZZZZ"]
537Quit = ["ctrl & Q"]
538"#;
539
540 let km: KeyBindings = toml::from_str(toml_str).expect("should not error");
541
542 let mut expected = KeyBindings::empty();
543 expected
544 .batch_add()
545 .with_ctrl()
546 .add(KeyStrike::KeyN, ActionShortcuts::NewJournal)
547 .add(KeyStrike::KeyQ, ActionShortcuts::Quit);
548
549 assert_eq!(expected, km);
550 }
551
552 #[test]
553 fn deserialize_injects_default_quit_when_missing() {
554 let toml_str = r#"NewJournal = ["ctrl & N"]
555"#;
556
557 let km: KeyBindings = toml::from_str(toml_str).expect("should not error");
558
559 let mut expected = KeyBindings::empty();
560 expected
561 .batch_add()
562 .with_ctrl()
563 .add(KeyStrike::KeyN, ActionShortcuts::NewJournal)
564 .add(KeyStrike::KeyQ, ActionShortcuts::Quit);
565
566 assert_eq!(expected, km);
567 }
568
569 #[test]
570 fn deserialize_errors_when_quit_missing_and_default_taken() {
571 let toml_str = r#"OpenNote = ["ctrl & Q"]
572"#;
573
574 let result: Result<KeyBindings, _> = toml::from_str(toml_str);
575 assert!(result.is_err(), "expected deserialize to fail");
576 let err_msg = result.unwrap_err().to_string();
577 assert!(
578 err_msg.contains("Quit") && err_msg.contains("Ctrl+Q"),
579 "error message should mention Quit and Ctrl+Q, got: {}",
580 err_msg
581 );
582 }
583
584 #[test]
585 fn deserialize_recovers_quit_when_quit_entry_is_malformed() {
586 let toml_str = r#"NewJournal = ["ctrl & N"]
587Quit = ["bogus & ZZZZ"]
588"#;
589
590 let km: KeyBindings = toml::from_str(toml_str).expect("should not error");
591
592 let mut expected = KeyBindings::empty();
593 expected
594 .batch_add()
595 .with_ctrl()
596 .add(KeyStrike::KeyN, ActionShortcuts::NewJournal)
597 .add(KeyStrike::KeyQ, ActionShortcuts::Quit);
598
599 assert_eq!(expected, km);
600 }
601}