1#![forbid(unsafe_code)]
2
3use web_time::{Duration, Instant};
88
89use crate::event::{KeyCode, KeyEvent, KeyEventKind, Modifiers};
90
91pub const DEFAULT_ESC_SEQ_TIMEOUT_MS: u64 = 250;
97
98pub const MIN_ESC_SEQ_TIMEOUT_MS: u64 = 150;
100
101pub const MAX_ESC_SEQ_TIMEOUT_MS: u64 = 400;
103
104pub const DEFAULT_ESC_DEBOUNCE_MS: u64 = 50;
106
107pub const MIN_ESC_DEBOUNCE_MS: u64 = 0;
109
110pub const MAX_ESC_DEBOUNCE_MS: u64 = 100;
112
113#[derive(Debug, Clone)]
144pub struct SequenceConfig {
145 pub esc_seq_timeout: Duration,
148
149 pub esc_debounce: Duration,
152
153 pub disable_sequences: bool,
157}
158
159impl Default for SequenceConfig {
160 fn default() -> Self {
161 Self {
162 esc_seq_timeout: Duration::from_millis(DEFAULT_ESC_SEQ_TIMEOUT_MS),
163 esc_debounce: Duration::from_millis(DEFAULT_ESC_DEBOUNCE_MS),
164 disable_sequences: false,
165 }
166 }
167}
168
169impl SequenceConfig {
170 #[must_use]
172 pub fn with_timeout(mut self, timeout: Duration) -> Self {
173 self.esc_seq_timeout = timeout;
174 self
175 }
176
177 #[must_use]
179 pub fn with_debounce(mut self, debounce: Duration) -> Self {
180 self.esc_debounce = debounce;
181 self
182 }
183
184 #[must_use]
186 pub fn disable_sequences(mut self) -> Self {
187 self.disable_sequences = true;
188 self
189 }
190
191 #[must_use]
200 pub fn from_env() -> Self {
201 let mut config = Self::default();
202
203 if let Ok(val) = std::env::var("FTUI_ESC_SEQ_TIMEOUT_MS")
204 && let Ok(ms) = val.parse::<u64>()
205 {
206 config.esc_seq_timeout = Duration::from_millis(ms);
207 }
208
209 if let Ok(val) = std::env::var("FTUI_ESC_DEBOUNCE_MS")
210 && let Ok(ms) = val.parse::<u64>()
211 {
212 config.esc_debounce = Duration::from_millis(ms);
213 }
214
215 if let Ok(val) = std::env::var("FTUI_DISABLE_ESC_SEQ") {
216 config.disable_sequences = val == "1" || val.eq_ignore_ascii_case("true");
217 }
218
219 config.validated()
220 }
221
222 #[must_use]
243 pub fn validated(mut self) -> Self {
244 let timeout_ms = self.esc_seq_timeout.as_millis() as u64;
246 let clamped_timeout = timeout_ms.clamp(MIN_ESC_SEQ_TIMEOUT_MS, MAX_ESC_SEQ_TIMEOUT_MS);
247 self.esc_seq_timeout = Duration::from_millis(clamped_timeout);
248
249 let debounce_ms = self.esc_debounce.as_millis() as u64;
251 let clamped_debounce = debounce_ms.clamp(MIN_ESC_DEBOUNCE_MS, MAX_ESC_DEBOUNCE_MS);
252
253 let final_debounce = clamped_debounce.min(clamped_timeout);
255 self.esc_debounce = Duration::from_millis(final_debounce);
256
257 self
258 }
259
260 #[must_use]
262 pub fn is_valid(&self) -> bool {
263 let timeout_ms = self.esc_seq_timeout.as_millis() as u64;
264 let debounce_ms = self.esc_debounce.as_millis() as u64;
265
266 (MIN_ESC_SEQ_TIMEOUT_MS..=MAX_ESC_SEQ_TIMEOUT_MS).contains(&timeout_ms)
267 && (MIN_ESC_DEBOUNCE_MS..=MAX_ESC_DEBOUNCE_MS).contains(&debounce_ms)
268 && debounce_ms <= timeout_ms
269 }
270}
271
272#[derive(Debug, Clone, Copy, PartialEq, Eq)]
278pub enum SequenceOutput {
279 Pending,
281
282 Esc,
284
285 EscEsc,
287
288 PassThrough,
290}
291
292#[derive(Debug, Clone, Copy, PartialEq, Eq)]
298enum DetectorState {
299 Idle,
301
302 AwaitingSecondEsc { first_esc_time: Instant },
304}
305
306#[derive(Debug)]
322pub struct SequenceDetector {
323 config: SequenceConfig,
324 state: DetectorState,
325}
326
327impl SequenceDetector {
328 #[must_use]
330 pub fn new(config: SequenceConfig) -> Self {
331 Self {
332 config,
333 state: DetectorState::Idle,
334 }
335 }
336
337 #[must_use]
339 pub fn with_defaults() -> Self {
340 Self::new(SequenceConfig::default())
341 }
342
343 pub fn feed(&mut self, event: &KeyEvent, now: Instant) -> SequenceOutput {
347 if event.kind != KeyEventKind::Press {
349 return SequenceOutput::PassThrough;
350 }
351
352 if self.config.disable_sequences {
354 return if event.code == KeyCode::Escape {
355 SequenceOutput::Esc
356 } else {
357 SequenceOutput::PassThrough
358 };
359 }
360
361 match self.state {
362 DetectorState::Idle => {
363 if event.code == KeyCode::Escape {
364 self.state = DetectorState::AwaitingSecondEsc {
366 first_esc_time: now,
367 };
368 SequenceOutput::Pending
369 } else {
370 SequenceOutput::PassThrough
372 }
373 }
374
375 DetectorState::AwaitingSecondEsc { first_esc_time } => {
376 let elapsed = now.saturating_duration_since(first_esc_time);
377
378 if event.code == KeyCode::Escape {
379 if elapsed <= self.config.esc_seq_timeout {
381 self.state = DetectorState::Idle;
383 SequenceOutput::EscEsc
384 } else {
385 self.state = DetectorState::AwaitingSecondEsc {
387 first_esc_time: now,
388 };
389 SequenceOutput::Esc
390 }
391 } else {
392 self.state = DetectorState::Idle;
395 SequenceOutput::Esc
397 }
398 }
399 }
400 }
401
402 pub fn check_timeout(&mut self, now: Instant) -> Option<SequenceOutput> {
410 if let DetectorState::AwaitingSecondEsc { first_esc_time } = self.state {
411 let elapsed = now.saturating_duration_since(first_esc_time);
412 if elapsed > self.config.esc_seq_timeout {
413 self.state = DetectorState::Idle;
414 return Some(SequenceOutput::Esc);
415 }
416 }
417 None
418 }
419
420 #[must_use]
422 pub fn is_pending(&self) -> bool {
423 matches!(self.state, DetectorState::AwaitingSecondEsc { .. })
424 }
425
426 pub fn reset(&mut self) {
430 self.state = DetectorState::Idle;
431 }
432
433 #[must_use]
435 pub fn config(&self) -> &SequenceConfig {
436 &self.config
437 }
438
439 pub fn set_config(&mut self, config: SequenceConfig) {
443 self.config = config;
444 }
445}
446
447#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
456pub struct AppState {
457 pub input_nonempty: bool,
459
460 pub task_running: bool,
462
463 pub modal_open: bool,
465
466 pub view_overlay: bool,
468}
469
470impl AppState {
471 #[must_use]
473 pub const fn new() -> Self {
474 Self {
475 input_nonempty: false,
476 task_running: false,
477 modal_open: false,
478 view_overlay: false,
479 }
480 }
481
482 #[must_use]
484 pub const fn with_input(mut self, nonempty: bool) -> Self {
485 self.input_nonempty = nonempty;
486 self
487 }
488
489 #[must_use]
491 pub const fn with_task(mut self, running: bool) -> Self {
492 self.task_running = running;
493 self
494 }
495
496 #[must_use]
498 pub const fn with_modal(mut self, open: bool) -> Self {
499 self.modal_open = open;
500 self
501 }
502
503 #[must_use]
505 pub const fn with_overlay(mut self, active: bool) -> Self {
506 self.view_overlay = active;
507 self
508 }
509
510 #[must_use]
512 pub const fn is_idle(&self) -> bool {
513 !self.input_nonempty && !self.task_running && !self.modal_open
514 }
515}
516
517#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
526pub enum Action {
527 ClearInput,
529
530 CancelTask,
532
533 DismissModal,
535
536 CloseOverlay,
538
539 ToggleTreeView,
541
542 Quit,
544
545 SoftQuit,
547
548 HardQuit,
550
551 Bell,
553
554 PassThrough,
558}
559
560impl Action {
561 #[must_use]
563 pub const fn consumes_event(&self) -> bool {
564 !matches!(self, Action::PassThrough)
565 }
566
567 #[must_use]
569 pub const fn is_quit(&self) -> bool {
570 matches!(self, Action::Quit | Action::SoftQuit | Action::HardQuit)
571 }
572}
573
574#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
580pub enum CtrlCIdleAction {
581 #[default]
583 Quit,
584
585 Noop,
587
588 Bell,
590}
591
592impl CtrlCIdleAction {
593 #[must_use]
595 pub fn from_str_opt(s: &str) -> Option<Self> {
596 match s.to_lowercase().as_str() {
597 "quit" => Some(Self::Quit),
598 "noop" | "none" | "ignore" => Some(Self::Noop),
599 "bell" | "beep" => Some(Self::Bell),
600 _ => None,
601 }
602 }
603
604 #[must_use]
606 pub const fn to_action(self) -> Option<Action> {
607 match self {
608 Self::Quit => Some(Action::Quit),
609 Self::Noop => None,
610 Self::Bell => Some(Action::Bell),
611 }
612 }
613}
614
615#[derive(Debug, Clone)]
661pub struct ActionConfig {
662 pub sequence_config: SequenceConfig,
664
665 pub ctrl_c_idle_action: CtrlCIdleAction,
671}
672
673impl Default for ActionConfig {
674 fn default() -> Self {
675 Self {
676 sequence_config: SequenceConfig::default(),
677 ctrl_c_idle_action: CtrlCIdleAction::Quit,
678 }
679 }
680}
681
682impl ActionConfig {
683 #[must_use]
685 pub fn with_sequence_config(mut self, config: SequenceConfig) -> Self {
686 self.sequence_config = config;
687 self
688 }
689
690 #[must_use]
692 pub fn with_ctrl_c_idle(mut self, action: CtrlCIdleAction) -> Self {
693 self.ctrl_c_idle_action = action;
694 self
695 }
696
697 #[must_use]
703 pub fn from_env() -> Self {
704 let mut config = Self {
705 sequence_config: SequenceConfig::from_env(),
706 ctrl_c_idle_action: CtrlCIdleAction::Quit,
707 };
708
709 if let Ok(val) = std::env::var("FTUI_CTRL_C_IDLE_ACTION")
710 && let Some(action) = CtrlCIdleAction::from_str_opt(&val)
711 {
712 config.ctrl_c_idle_action = action;
713 }
714
715 config
716 }
717
718 #[must_use]
722 pub fn validated(mut self) -> Self {
723 self.sequence_config = self.sequence_config.validated();
724 self
725 }
726}
727
728#[derive(Debug)]
770pub struct ActionMapper {
771 config: ActionConfig,
772 sequence_detector: SequenceDetector,
773}
774
775impl ActionMapper {
776 #[must_use]
778 pub fn new(config: ActionConfig) -> Self {
779 let sequence_detector = SequenceDetector::new(config.sequence_config.clone());
780 Self {
781 config,
782 sequence_detector,
783 }
784 }
785
786 #[must_use]
788 pub fn with_defaults() -> Self {
789 Self::new(ActionConfig::default())
790 }
791
792 #[must_use]
794 pub fn from_env() -> Self {
795 Self::new(ActionConfig::from_env())
796 }
797
798 pub fn map(&mut self, event: &KeyEvent, state: &AppState, now: Instant) -> Vec<Action> {
815 if event.kind != KeyEventKind::Press {
817 return vec![Action::PassThrough];
818 }
819
820 if event.code == KeyCode::Escape && event.modifiers == Modifiers::NONE {
822 return self.handle_esc_sequence(state, now).into_iter().collect();
823 }
824
825 let mut actions = Vec::with_capacity(2);
828 match self.sequence_detector.feed(event, now) {
829 SequenceOutput::Esc => {
830 if let Some(action) = self.resolve_single_esc(state)
831 && action != Action::PassThrough
832 {
833 actions.push(action);
834 }
835 }
836 SequenceOutput::EscEsc => return vec![Action::ToggleTreeView],
839 SequenceOutput::Pending | SequenceOutput::PassThrough => {}
840 }
841
842 let own = match event.code {
844 KeyCode::Char(c) if event.modifiers.contains(Modifiers::CTRL) => {
845 match c.to_ascii_lowercase() {
846 'c' => self.resolve_ctrl_c(state),
847 'd' => Some(Action::SoftQuit),
848 'q' => Some(Action::HardQuit),
849 _ => Some(Action::PassThrough),
850 }
851 }
852 _ => Some(Action::PassThrough),
853 };
854 actions.extend(own);
855 actions
856 }
857
858 fn handle_esc_sequence(&mut self, state: &AppState, now: Instant) -> Option<Action> {
860 let esc_event = KeyEvent::new(KeyCode::Escape);
861 let output = self.sequence_detector.feed(&esc_event, now);
862
863 match output {
864 SequenceOutput::Pending => {
865 None
868 }
869 SequenceOutput::Esc => {
870 self.resolve_single_esc(state)
872 }
873 SequenceOutput::EscEsc => {
874 Some(Action::ToggleTreeView)
876 }
877 SequenceOutput::PassThrough => {
878 Some(Action::PassThrough)
880 }
881 }
882 }
883
884 fn resolve_ctrl_c(&self, state: &AppState) -> Option<Action> {
886 if state.modal_open {
888 return Some(Action::DismissModal);
889 }
890
891 if state.input_nonempty {
893 return Some(Action::ClearInput);
894 }
895
896 if state.task_running {
898 return Some(Action::CancelTask);
899 }
900
901 self.config.ctrl_c_idle_action.to_action()
903 }
904
905 fn resolve_single_esc(&self, state: &AppState) -> Option<Action> {
907 if state.modal_open {
909 return Some(Action::DismissModal);
910 }
911
912 if state.view_overlay {
914 return Some(Action::CloseOverlay);
915 }
916
917 if state.input_nonempty {
919 return Some(Action::ClearInput);
920 }
921
922 if state.task_running {
924 return Some(Action::CancelTask);
925 }
926
927 Some(Action::PassThrough)
929 }
930
931 pub fn check_timeout(&mut self, state: &AppState, now: Instant) -> Option<Action> {
941 if let Some(SequenceOutput::Esc) = self.sequence_detector.check_timeout(now) {
942 return self.resolve_single_esc(state);
943 }
944 None
945 }
946
947 #[must_use]
949 pub fn is_pending_esc(&self) -> bool {
950 self.sequence_detector.is_pending()
951 }
952
953 pub fn reset(&mut self) {
957 self.sequence_detector.reset();
958 }
959
960 #[must_use]
962 pub fn config(&self) -> &ActionConfig {
963 &self.config
964 }
965
966 pub fn set_config(&mut self, config: ActionConfig) {
968 self.sequence_detector
969 .set_config(config.sequence_config.clone());
970 self.config = config;
971 }
972}
973
974use std::fmt;
1004use std::str::FromStr;
1005
1006#[derive(Debug, Clone, PartialEq, Eq)]
1008pub enum KeyParseError {
1009 EmptyKey,
1011 UnknownKey(String),
1013 UnknownModifier(String),
1015 TooManyKeys(usize),
1017}
1018
1019impl fmt::Display for KeyParseError {
1020 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1021 match self {
1022 Self::EmptyKey => f.write_str("empty key"),
1023 Self::UnknownKey(name) => write!(f, "unknown key `{name}`"),
1024 Self::UnknownModifier(name) => write!(f, "unknown modifier `{name}`"),
1025 Self::TooManyKeys(n) => {
1026 write!(f, "chord has {n} keys; the maximum is {}", Chord::MAX_LEN)
1027 }
1028 }
1029 }
1030}
1031
1032impl std::error::Error for KeyParseError {}
1033
1034#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1040pub struct KeyCombo {
1041 pub code: KeyCode,
1043 pub modifiers: Modifiers,
1045}
1046
1047impl KeyCombo {
1048 #[must_use]
1050 pub fn new(code: KeyCode, modifiers: Modifiers) -> Self {
1051 match code {
1052 KeyCode::Char(c) if c.is_alphabetic() && c.is_uppercase() => Self {
1053 code: KeyCode::Char(c.to_lowercase().next().unwrap_or(c)),
1054 modifiers: modifiers | Modifiers::SHIFT,
1055 },
1056 _ => Self { code, modifiers },
1057 }
1058 }
1059
1060 #[must_use]
1062 pub fn key(code: KeyCode) -> Self {
1063 Self::new(code, Modifiers::NONE)
1064 }
1065
1066 #[must_use]
1068 pub fn from_event(event: &KeyEvent) -> Self {
1069 Self::new(event.code, event.modifiers)
1070 }
1071
1072 #[must_use]
1074 pub fn matches(&self, event: &KeyEvent) -> bool {
1075 Self::from_event(event) == *self
1076 }
1077}
1078
1079fn shift_folds_into(c: char) -> bool {
1097 let mut upper = c.to_uppercase();
1098 match (upper.next(), upper.next()) {
1099 (Some(u), None) => u != c && u.to_lowercase().eq(std::iter::once(c)),
1100 _ => false,
1101 }
1102}
1103
1104impl fmt::Display for KeyCombo {
1105 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1106 let mut modifiers = self.modifiers;
1107 let key = match self.code {
1108 KeyCode::Char(c) if modifiers.contains(Modifiers::SHIFT) && shift_folds_into(c) => {
1109 modifiers.remove(Modifiers::SHIFT);
1110 c.to_uppercase().collect::<String>()
1111 }
1112 KeyCode::Char(' ') => "Space".to_string(),
1113 KeyCode::Char(c) => c.to_string(),
1114 KeyCode::Enter => "Enter".to_string(),
1115 KeyCode::Escape => "Esc".to_string(),
1116 KeyCode::Backspace => "Backspace".to_string(),
1117 KeyCode::Tab => "Tab".to_string(),
1118 KeyCode::BackTab => "BackTab".to_string(),
1119 KeyCode::Delete => "Delete".to_string(),
1120 KeyCode::Insert => "Insert".to_string(),
1121 KeyCode::Home => "Home".to_string(),
1122 KeyCode::End => "End".to_string(),
1123 KeyCode::PageUp => "PageUp".to_string(),
1124 KeyCode::PageDown => "PageDown".to_string(),
1125 KeyCode::Up => "Up".to_string(),
1126 KeyCode::Down => "Down".to_string(),
1127 KeyCode::Left => "Left".to_string(),
1128 KeyCode::Right => "Right".to_string(),
1129 KeyCode::F(n) => format!("F{n}"),
1130 KeyCode::Null => "Null".to_string(),
1131 KeyCode::MediaPlayPause => "MediaPlayPause".to_string(),
1132 KeyCode::MediaStop => "MediaStop".to_string(),
1133 KeyCode::MediaNextTrack => "MediaNextTrack".to_string(),
1134 KeyCode::MediaPrevTrack => "MediaPrevTrack".to_string(),
1135 };
1136 for (flag, name) in [
1137 (Modifiers::CTRL, "Ctrl"),
1138 (Modifiers::ALT, "Alt"),
1139 (Modifiers::SHIFT, "Shift"),
1140 (Modifiers::SUPER, "Super"),
1141 ] {
1142 if modifiers.contains(flag) {
1143 write!(f, "{name}+")?;
1144 }
1145 }
1146 f.write_str(&key)
1147 }
1148}
1149
1150fn parse_key_name(name: &str) -> Result<KeyCode, KeyParseError> {
1155 let mut chars = name.chars();
1156 if let (Some(c), None) = (chars.next(), chars.next()) {
1157 return Ok(KeyCode::Char(c));
1158 }
1159 let lower = name.to_ascii_lowercase();
1160 let code = match lower.as_str() {
1161 "enter" | "return" => KeyCode::Enter,
1162 "esc" | "escape" => KeyCode::Escape,
1163 "backspace" => KeyCode::Backspace,
1164 "tab" => KeyCode::Tab,
1165 "backtab" => KeyCode::BackTab,
1166 "delete" | "del" => KeyCode::Delete,
1167 "insert" | "ins" => KeyCode::Insert,
1168 "home" => KeyCode::Home,
1169 "end" => KeyCode::End,
1170 "pageup" | "pgup" => KeyCode::PageUp,
1171 "pagedown" | "pgdn" => KeyCode::PageDown,
1172 "up" => KeyCode::Up,
1173 "down" => KeyCode::Down,
1174 "left" => KeyCode::Left,
1175 "right" => KeyCode::Right,
1176 "space" => KeyCode::Char(' '),
1177 "null" => KeyCode::Null,
1178 "mediaplaypause" => KeyCode::MediaPlayPause,
1179 "mediastop" => KeyCode::MediaStop,
1180 "medianexttrack" => KeyCode::MediaNextTrack,
1181 "mediaprevtrack" => KeyCode::MediaPrevTrack,
1182 other => {
1183 if let Some(digits) = other.strip_prefix('f')
1184 && let Ok(n) = digits.parse::<u8>()
1185 && (1..=24).contains(&n)
1186 {
1187 KeyCode::F(n)
1188 } else {
1189 return Err(KeyParseError::UnknownKey(name.to_string()));
1190 }
1191 }
1192 };
1193 Ok(code)
1194}
1195
1196impl FromStr for KeyCombo {
1197 type Err = KeyParseError;
1198
1199 fn from_str(s: &str) -> Result<Self, Self::Err> {
1203 let s = s.trim_matches(|c: char| c.is_ascii_whitespace());
1210 if s.is_empty() {
1211 return Err(KeyParseError::EmptyKey);
1212 }
1213 let (modifier_part, key_part) = if s == "+" {
1214 ("", "+")
1215 } else if let Some(stripped) = s.strip_suffix('+') {
1216 (stripped.trim_end_matches('+'), "+")
1217 } else if let Some((modifiers, key)) = s.rsplit_once('+') {
1218 (modifiers, key)
1219 } else {
1220 ("", s)
1221 };
1222 let mut modifiers = Modifiers::NONE;
1223 for part in modifier_part.split('+').filter(|p| !p.is_empty()) {
1224 modifiers |= match part.to_ascii_lowercase().as_str() {
1225 "ctrl" | "control" => Modifiers::CTRL,
1226 "alt" | "opt" | "option" => Modifiers::ALT,
1227 "shift" => Modifiers::SHIFT,
1228 "super" | "cmd" | "meta" | "win" => Modifiers::SUPER,
1229 _ => return Err(KeyParseError::UnknownModifier(part.to_string())),
1230 };
1231 }
1232 if key_part.is_empty() {
1233 return Err(KeyParseError::EmptyKey);
1234 }
1235 Ok(Self::new(parse_key_name(key_part)?, modifiers))
1236 }
1237}
1238
1239#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1241pub struct Chord(Vec<KeyCombo>);
1242
1243impl Chord {
1244 pub const MAX_LEN: usize = 4;
1246
1247 #[must_use]
1249 pub fn single(combo: KeyCombo) -> Self {
1250 Self(vec![combo])
1251 }
1252
1253 pub fn new(combos: Vec<KeyCombo>) -> Result<Self, KeyParseError> {
1255 if combos.is_empty() {
1256 Err(KeyParseError::EmptyKey)
1257 } else if combos.len() > Self::MAX_LEN {
1258 Err(KeyParseError::TooManyKeys(combos.len()))
1259 } else {
1260 Ok(Self(combos))
1261 }
1262 }
1263
1264 pub fn parse(s: &str) -> Result<Self, KeyParseError> {
1266 s.parse()
1267 }
1268
1269 #[must_use]
1271 pub fn combos(&self) -> &[KeyCombo] {
1272 &self.0
1273 }
1274
1275 #[must_use]
1277 pub fn len(&self) -> usize {
1278 self.0.len()
1279 }
1280
1281 #[must_use]
1284 pub fn is_empty(&self) -> bool {
1285 self.0.is_empty()
1286 }
1287
1288 #[must_use]
1290 pub fn is_prefix_of(&self, other: &Self) -> bool {
1291 self.0.len() < other.0.len() && other.0.starts_with(&self.0)
1292 }
1293}
1294
1295impl FromStr for Chord {
1296 type Err = KeyParseError;
1297
1298 fn from_str(s: &str) -> Result<Self, Self::Err> {
1299 let combos = s
1300 .split_whitespace()
1301 .map(str::parse)
1302 .collect::<Result<Vec<KeyCombo>, _>>()?;
1303 Self::new(combos)
1304 }
1305}
1306
1307impl fmt::Display for Chord {
1308 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1309 for (i, combo) in self.0.iter().enumerate() {
1310 if i > 0 {
1311 f.write_str(" ")?;
1312 }
1313 write!(f, "{combo}")?;
1314 }
1315 Ok(())
1316 }
1317}
1318
1319#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
1321#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1322pub enum Priority {
1323 #[default]
1325 Global = 0,
1326 Mode = 1,
1328 Widget = 2,
1330}
1331
1332#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1334pub struct ContextId(pub u32);
1335
1336#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1338pub struct BindingId(pub u32);
1339
1340impl fmt::Display for BindingId {
1341 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1342 write!(f, "#{}", self.0)
1343 }
1344}
1345
1346#[derive(Debug, Clone)]
1348pub struct Binding<A> {
1349 pub id: BindingId,
1351 pub chord: Chord,
1353 pub action: A,
1355 pub priority: Priority,
1357 pub context: Option<ContextId>,
1359 pub label: Option<String>,
1361}
1362
1363pub const MIN_CHORD_TIMEOUT_MS: u64 = 200;
1365pub const MAX_CHORD_TIMEOUT_MS: u64 = 5000;
1367pub const DEFAULT_CHORD_TIMEOUT_MS: u64 = 1000;
1369
1370#[derive(Debug, Clone)]
1372pub struct KeyMapConfig {
1373 pub chord_timeout: Duration,
1375 pub esc: SequenceConfig,
1377}
1378
1379impl Default for KeyMapConfig {
1380 fn default() -> Self {
1381 Self {
1382 chord_timeout: Duration::from_millis(DEFAULT_CHORD_TIMEOUT_MS),
1383 esc: SequenceConfig::default(),
1384 }
1385 }
1386}
1387
1388impl KeyMapConfig {
1389 #[must_use]
1391 pub fn with_chord_timeout(mut self, timeout: Duration) -> Self {
1392 let ms = timeout.as_millis().clamp(
1393 u128::from(MIN_CHORD_TIMEOUT_MS),
1394 u128::from(MAX_CHORD_TIMEOUT_MS),
1395 );
1396 self.chord_timeout = Duration::from_millis(ms as u64);
1397 self
1398 }
1399
1400 #[must_use]
1402 pub fn with_esc(mut self, esc: SequenceConfig) -> Self {
1403 self.esc = esc;
1404 self
1405 }
1406}
1407
1408#[derive(Debug, Clone, Copy)]
1410pub struct Lookup<'a, A> {
1411 pub exact: Option<&'a Binding<A>>,
1413 pub longer: usize,
1416}
1417
1418impl<A> Lookup<'_, A> {
1419 #[must_use]
1421 pub fn is_none(&self) -> bool {
1422 self.exact.is_none() && self.longer == 0
1423 }
1424}
1425
1426#[derive(Debug, Clone, PartialEq, Eq)]
1428pub enum Conflict {
1429 Shadowed {
1431 winner: BindingId,
1432 loser: BindingId,
1433 chord: Chord,
1434 },
1435 PrefixCollision {
1438 short: BindingId,
1439 long: BindingId,
1440 short_chord: Chord,
1441 long_chord: Chord,
1442 },
1443 Duplicate {
1445 first: BindingId,
1446 second: BindingId,
1447 chord: Chord,
1448 },
1449}
1450
1451#[derive(Debug, Clone, Default, PartialEq, Eq)]
1453pub struct ConflictReport {
1454 pub items: Vec<Conflict>,
1456}
1457
1458impl ConflictReport {
1459 #[must_use]
1461 pub fn is_empty(&self) -> bool {
1462 self.items.is_empty()
1463 }
1464
1465 #[must_use]
1467 pub fn len(&self) -> usize {
1468 self.items.len()
1469 }
1470}
1471
1472impl fmt::Display for ConflictReport {
1473 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1474 for item in &self.items {
1475 match item {
1476 Conflict::Shadowed {
1477 winner,
1478 loser,
1479 chord,
1480 } => writeln!(
1481 f,
1482 "warning: binding {winner} shadows binding {loser} on `{chord}` (higher priority)"
1483 )?,
1484 Conflict::PrefixCollision {
1485 short,
1486 long,
1487 short_chord,
1488 long_chord,
1489 } => writeln!(
1490 f,
1491 "warning: binding {short} (`{short_chord}`) is a prefix of binding {long} (`{long_chord}`); it fires only after the chord timeout or a non-extending key"
1492 )?,
1493 Conflict::Duplicate {
1494 first,
1495 second,
1496 chord,
1497 } => writeln!(
1498 f,
1499 "warning: bindings {first} and {second} both bind `{chord}` at the same priority; the later one wins"
1500 )?,
1501 }
1502 }
1503 Ok(())
1504 }
1505}
1506
1507#[derive(Debug, Clone)]
1510pub struct KeyMap<A> {
1511 bindings: Vec<Binding<A>>,
1512 contexts: Vec<String>,
1513 config: KeyMapConfig,
1514 next_id: u32,
1515}
1516
1517impl<A> Default for KeyMap<A> {
1518 fn default() -> Self {
1519 Self::new()
1520 }
1521}
1522
1523impl<A> KeyMap<A> {
1524 #[must_use]
1526 pub fn new() -> Self {
1527 Self::with_config(KeyMapConfig::default())
1528 }
1529
1530 #[must_use]
1532 pub fn with_config(config: KeyMapConfig) -> Self {
1533 Self {
1534 bindings: Vec::new(),
1535 contexts: Vec::new(),
1536 config,
1537 next_id: 0,
1538 }
1539 }
1540
1541 #[must_use]
1543 pub fn config(&self) -> &KeyMapConfig {
1544 &self.config
1545 }
1546
1547 pub fn context(&mut self, name: &str) -> ContextId {
1549 if let Some(index) = self.contexts.iter().position(|n| n == name) {
1550 return ContextId(index as u32);
1551 }
1552 self.contexts.push(name.to_string());
1553 ContextId((self.contexts.len() - 1) as u32)
1554 }
1555
1556 #[must_use]
1558 pub fn context_name(&self, id: ContextId) -> Option<&str> {
1559 self.contexts.get(id.0 as usize).map(String::as_str)
1560 }
1561
1562 pub fn bind(&mut self, chord: Chord, action: A) -> BindingId {
1564 self.bind_in(chord, action, Priority::Global, None)
1565 }
1566
1567 pub fn bind_in(
1569 &mut self,
1570 chord: Chord,
1571 action: A,
1572 priority: Priority,
1573 context: Option<ContextId>,
1574 ) -> BindingId {
1575 let id = BindingId(self.next_id);
1576 self.next_id += 1;
1577 self.bindings.push(Binding {
1578 id,
1579 chord,
1580 action,
1581 priority,
1582 context,
1583 label: None,
1584 });
1585 id
1586 }
1587
1588 pub fn set_label(&mut self, id: BindingId, label: impl Into<String>) -> bool {
1590 match self.bindings.iter_mut().find(|b| b.id == id) {
1591 Some(binding) => {
1592 binding.label = Some(label.into());
1593 true
1594 }
1595 None => false,
1596 }
1597 }
1598
1599 pub fn unbind(&mut self, id: BindingId) -> Option<Binding<A>> {
1601 let index = self.bindings.iter().position(|b| b.id == id)?;
1602 Some(self.bindings.remove(index))
1603 }
1604
1605 #[must_use]
1607 pub fn bindings(&self) -> &[Binding<A>] {
1608 &self.bindings
1609 }
1610
1611 #[must_use]
1613 pub fn get(&self, id: BindingId) -> Option<&Binding<A>> {
1614 self.bindings.iter().find(|b| b.id == id)
1615 }
1616
1617 #[must_use]
1619 pub fn len(&self) -> usize {
1620 self.bindings.len()
1621 }
1622
1623 #[must_use]
1625 pub fn is_empty(&self) -> bool {
1626 self.bindings.is_empty()
1627 }
1628
1629 fn applies(binding: &Binding<A>, active: &[ContextId]) -> bool {
1630 binding
1631 .context
1632 .is_none_or(|context| active.contains(&context))
1633 }
1634
1635 fn rank(binding: &Binding<A>) -> (bool, Priority, BindingId) {
1638 (binding.context.is_some(), binding.priority, binding.id)
1639 }
1640
1641 #[must_use]
1645 pub fn lookup(&self, chord: &Chord, active: &[ContextId]) -> Lookup<'_, A> {
1646 let mut exact: Option<&Binding<A>> = None;
1647 let mut longer = 0;
1648 for binding in &self.bindings {
1649 if !Self::applies(binding, active) {
1650 continue;
1651 }
1652 if binding.chord == *chord {
1653 if exact.is_none_or(|current| Self::rank(binding) > Self::rank(current)) {
1654 exact = Some(binding);
1655 }
1656 } else if chord.is_prefix_of(&binding.chord) {
1657 longer += 1;
1658 }
1659 }
1660 Lookup { exact, longer }
1661 }
1662
1663 #[must_use]
1665 pub fn conflicts(&self) -> ConflictReport {
1666 let mut items = Vec::new();
1667 for (i, a) in self.bindings.iter().enumerate() {
1668 for b in &self.bindings[i + 1..] {
1669 if a.chord == b.chord {
1670 if a.context != b.context {
1671 continue;
1673 }
1674 if a.priority == b.priority {
1675 items.push(Conflict::Duplicate {
1676 first: a.id,
1677 second: b.id,
1678 chord: a.chord.clone(),
1679 });
1680 } else {
1681 let (winner, loser) = if a.priority > b.priority {
1682 (a.id, b.id)
1683 } else {
1684 (b.id, a.id)
1685 };
1686 items.push(Conflict::Shadowed {
1687 winner,
1688 loser,
1689 chord: a.chord.clone(),
1690 });
1691 }
1692 } else if a.chord.is_prefix_of(&b.chord) {
1693 items.push(Conflict::PrefixCollision {
1694 short: a.id,
1695 long: b.id,
1696 short_chord: a.chord.clone(),
1697 long_chord: b.chord.clone(),
1698 });
1699 } else if b.chord.is_prefix_of(&a.chord) {
1700 items.push(Conflict::PrefixCollision {
1701 short: b.id,
1702 long: a.id,
1703 short_chord: b.chord.clone(),
1704 long_chord: a.chord.clone(),
1705 });
1706 }
1707 }
1708 }
1709 ConflictReport { items }
1710 }
1711}
1712
1713#[derive(Debug, Clone, PartialEq, Eq)]
1715pub enum Dispatch<A> {
1716 Action {
1718 action: A,
1719 binding: BindingId,
1720 chord: Chord,
1721 },
1722 Pending { prefix: Chord },
1724 Unbound(KeyEvent),
1726 Expired { prefix: Chord },
1728 Esc(SequenceOutput),
1730}
1731
1732#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1734pub struct DispatchStats {
1735 pub dispatched: u64,
1737 pub pending: u64,
1739 pub expired: u64,
1741 pub unbound: u64,
1743 pub esc: u64,
1745}
1746
1747fn action_dispatch<A: Clone>(binding: &Binding<A>, chord: Chord) -> Dispatch<A> {
1748 Dispatch::Action {
1749 action: binding.action.clone(),
1750 binding: binding.id,
1751 chord,
1752 }
1753}
1754
1755#[derive(Debug)]
1762pub struct KeyDispatcher<A> {
1763 map: KeyMap<A>,
1764 pending: Vec<KeyCombo>,
1765 pending_since: Option<Instant>,
1766 esc: SequenceDetector,
1767 active_contexts: Vec<ContextId>,
1768 stats: DispatchStats,
1769}
1770
1771impl<A: Clone> KeyDispatcher<A> {
1772 #[must_use]
1774 pub fn new(map: KeyMap<A>) -> Self {
1775 let esc = SequenceDetector::new(map.config().esc.clone());
1776 Self {
1777 map,
1778 pending: Vec::new(),
1779 pending_since: None,
1780 esc,
1781 active_contexts: Vec::new(),
1782 stats: DispatchStats::default(),
1783 }
1784 }
1785
1786 #[must_use]
1788 pub fn map(&self) -> &KeyMap<A> {
1789 &self.map
1790 }
1791
1792 pub fn map_mut(&mut self) -> &mut KeyMap<A> {
1794 &mut self.map
1795 }
1796
1797 pub fn set_active_contexts(&mut self, contexts: &[ContextId]) {
1799 self.active_contexts.clear();
1800 self.active_contexts.extend_from_slice(contexts);
1801 }
1802
1803 #[must_use]
1805 pub fn active_contexts(&self) -> &[ContextId] {
1806 &self.active_contexts
1807 }
1808
1809 #[must_use]
1811 pub fn pending_prefix(&self) -> Option<Chord> {
1812 Chord::new(self.pending.clone()).ok()
1813 }
1814
1815 #[must_use]
1817 pub fn stats(&self) -> DispatchStats {
1818 self.stats
1819 }
1820
1821 pub fn reset(&mut self) {
1823 self.pending.clear();
1824 self.pending_since = None;
1825 self.esc.reset();
1826 }
1827
1828 pub fn feed(&mut self, key: &KeyEvent, now: Instant) -> Vec<Dispatch<A>> {
1830 let mut out = Vec::with_capacity(2);
1831
1832 if key.code == KeyCode::Escape {
1833 if key.kind == KeyEventKind::Press {
1834 self.flush_pending(&mut out, false);
1835 }
1836 match self.esc.feed(key, now) {
1837 SequenceOutput::PassThrough => {}
1839 output => {
1840 self.dispatch_esc(output, &mut out);
1841 return out;
1842 }
1843 }
1844 } else if key.kind == KeyEventKind::Press && self.esc.is_pending() {
1845 let output = self.esc.feed(key, now);
1848 self.dispatch_esc(output, &mut out);
1849 }
1850
1851 match key.kind {
1852 KeyEventKind::Release => {
1853 self.stats.unbound += 1;
1854 out.push(Dispatch::Unbound(*key));
1855 return out;
1856 }
1857 KeyEventKind::Repeat => {
1858 let single = Chord::single(KeyCombo::from_event(key));
1860 let fired = if self.pending.is_empty() {
1861 self.map
1862 .lookup(&single, &self.active_contexts)
1863 .exact
1864 .map(|binding| action_dispatch(binding, single))
1865 } else {
1866 None
1867 };
1868 match fired {
1869 Some(dispatch) => {
1870 self.stats.dispatched += 1;
1871 out.push(dispatch);
1872 }
1873 None => {
1874 self.stats.unbound += 1;
1875 out.push(Dispatch::Unbound(*key));
1876 }
1877 }
1878 return out;
1879 }
1880 KeyEventKind::Press => {}
1881 }
1882
1883 if let Some(since) = self.pending_since
1884 && now.saturating_duration_since(since) >= self.map.config.chord_timeout
1885 {
1886 self.flush_pending(&mut out, true);
1887 }
1888
1889 let combo = KeyCombo::from_event(key);
1890 if self.try_extend(combo, now, &mut out) {
1891 return out;
1892 }
1893
1894 if !self.pending.is_empty() {
1897 self.flush_pending(&mut out, false);
1898 if self.try_extend(combo, now, &mut out) {
1899 return out;
1900 }
1901 }
1902
1903 self.stats.unbound += 1;
1904 out.push(Dispatch::Unbound(*key));
1905 out
1906 }
1907
1908 pub fn tick(&mut self, now: Instant) -> Vec<Dispatch<A>> {
1910 let mut out = Vec::new();
1911 if let Some(since) = self.pending_since
1912 && now.saturating_duration_since(since) >= self.map.config.chord_timeout
1913 {
1914 self.flush_pending(&mut out, true);
1915 }
1916 if let Some(output) = self.esc.check_timeout(now) {
1917 self.dispatch_esc(output, &mut out);
1918 }
1919 out
1920 }
1921
1922 fn try_extend(&mut self, combo: KeyCombo, now: Instant, out: &mut Vec<Dispatch<A>>) -> bool {
1925 if self.pending.len() >= Chord::MAX_LEN {
1926 return false;
1927 }
1928 let mut candidate = self.pending.clone();
1929 candidate.push(combo);
1930 let chord = Chord(candidate);
1931 let lookup = self.map.lookup(&chord, &self.active_contexts);
1932 if let Some(binding) = lookup.exact
1933 && lookup.longer == 0
1934 {
1935 let dispatch = action_dispatch(binding, chord);
1936 self.pending.clear();
1937 self.pending_since = None;
1938 self.stats.dispatched += 1;
1939 out.push(dispatch);
1940 return true;
1941 }
1942 if lookup.exact.is_some() || lookup.longer > 0 {
1943 self.pending.clone_from(&chord.0);
1944 self.pending_since = Some(now);
1945 self.stats.pending += 1;
1946 out.push(Dispatch::Pending { prefix: chord });
1947 return true;
1948 }
1949 false
1950 }
1951
1952 fn flush_pending(&mut self, out: &mut Vec<Dispatch<A>>, timed_out: bool) {
1955 if self.pending.is_empty() {
1956 return;
1957 }
1958 let prefix = Chord(std::mem::take(&mut self.pending));
1959 self.pending_since = None;
1960 let fired = self
1961 .map
1962 .lookup(&prefix, &self.active_contexts)
1963 .exact
1964 .map(|binding| action_dispatch(binding, prefix.clone()));
1965 match fired {
1966 Some(dispatch) => {
1967 if timed_out {
1968 self.stats.expired += 1;
1969 out.push(Dispatch::Expired { prefix });
1970 }
1971 self.stats.dispatched += 1;
1972 out.push(dispatch);
1973 }
1974 None => {
1975 self.stats.expired += 1;
1976 out.push(Dispatch::Expired { prefix });
1977 }
1978 }
1979 }
1980
1981 fn dispatch_esc(&mut self, output: SequenceOutput, out: &mut Vec<Dispatch<A>>) {
1984 let esc = KeyCombo::key(KeyCode::Escape);
1985 let bound = match output {
1986 SequenceOutput::Esc => Some(Chord::single(esc)),
1987 SequenceOutput::EscEsc => Chord::new(vec![esc, esc]).ok(),
1988 SequenceOutput::Pending | SequenceOutput::PassThrough => None,
1989 };
1990 let fired = bound.and_then(|chord| {
1991 self.map
1992 .lookup(&chord, &self.active_contexts)
1993 .exact
1994 .map(|binding| action_dispatch(binding, chord.clone()))
1995 });
1996 match fired {
1997 Some(dispatch) => {
1998 self.stats.dispatched += 1;
1999 out.push(dispatch);
2000 }
2001 None => {
2002 self.stats.esc += 1;
2003 out.push(Dispatch::Esc(output));
2004 }
2005 }
2006 }
2007}
2008
2009#[cfg(feature = "serde")]
2033#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
2034#[serde(deny_unknown_fields)]
2035pub struct KeyMapFile<A> {
2036 #[serde(default = "default_chord_timeout_ms")]
2038 pub chord_timeout_ms: u64,
2039 #[serde(default = "Vec::new")]
2041 pub bindings: Vec<BindingFile<A>>,
2042}
2043
2044#[cfg(feature = "serde")]
2045fn default_chord_timeout_ms() -> u64 {
2046 DEFAULT_CHORD_TIMEOUT_MS
2047}
2048
2049#[cfg(feature = "serde")]
2051#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
2052#[serde(deny_unknown_fields)]
2053pub struct BindingFile<A> {
2054 pub chord: String,
2056 pub action: A,
2058 #[serde(default)]
2060 pub priority: Priority,
2061 #[serde(default, skip_serializing_if = "Option::is_none")]
2063 pub context: Option<String>,
2064 #[serde(default, skip_serializing_if = "Option::is_none")]
2066 pub label: Option<String>,
2067}
2068
2069#[cfg(feature = "serde")]
2071#[derive(Debug, Clone, PartialEq, Eq)]
2072pub enum KeyMapFileError {
2073 Chord {
2075 index: usize,
2077 chord: String,
2079 source: KeyParseError,
2081 },
2082}
2083
2084#[cfg(feature = "serde")]
2085impl fmt::Display for KeyMapFileError {
2086 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2087 match self {
2088 Self::Chord {
2089 index,
2090 chord,
2091 source,
2092 } => write!(f, "binding {index} (`{chord}`): {source}"),
2093 }
2094 }
2095}
2096
2097#[cfg(feature = "serde")]
2098impl std::error::Error for KeyMapFileError {}
2099
2100#[cfg(feature = "serde")]
2101impl<A: Clone> KeyMap<A> {
2102 #[must_use]
2104 pub fn to_file(&self) -> KeyMapFile<A> {
2105 KeyMapFile {
2106 chord_timeout_ms: self.config.chord_timeout.as_millis() as u64,
2107 bindings: self
2108 .bindings
2109 .iter()
2110 .map(|binding| BindingFile {
2111 chord: binding.chord.to_string(),
2112 action: binding.action.clone(),
2113 priority: binding.priority,
2114 context: binding
2115 .context
2116 .and_then(|id| self.context_name(id))
2117 .map(str::to_string),
2118 label: binding.label.clone(),
2119 })
2120 .collect(),
2121 }
2122 }
2123
2124 pub fn from_file(file: KeyMapFile<A>) -> Result<Self, KeyMapFileError> {
2127 let config = KeyMapConfig::default()
2128 .with_chord_timeout(Duration::from_millis(file.chord_timeout_ms));
2129 let mut map = Self::with_config(config);
2130 for (index, entry) in file.bindings.into_iter().enumerate() {
2131 let chord = Chord::parse(&entry.chord).map_err(|source| KeyMapFileError::Chord {
2132 index,
2133 chord: entry.chord.clone(),
2134 source,
2135 })?;
2136 let context = entry.context.as_deref().map(|name| map.context(name));
2137 let id = map.bind_in(chord, entry.action, entry.priority, context);
2138 if let Some(label) = entry.label {
2139 map.set_label(id, label);
2140 }
2141 }
2142 Ok(map)
2143 }
2144}
2145
2146#[cfg(feature = "serde")]
2147impl<A: Clone + serde::Serialize> serde::Serialize for KeyMap<A> {
2148 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2149 self.to_file().serialize(serializer)
2150 }
2151}
2152
2153#[cfg(feature = "serde")]
2154impl<'de, A: Clone + serde::Deserialize<'de>> serde::Deserialize<'de> for KeyMap<A> {
2155 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2156 let file = KeyMapFile::<A>::deserialize(deserializer)?;
2157 Self::from_file(file).map_err(serde::de::Error::custom)
2158 }
2159}
2160
2161#[cfg(test)]
2162mod keymap_tests {
2163 use super::*;
2164 use proptest::prelude::*;
2165
2166 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
2167 enum Act {
2168 GoTop,
2169 Help,
2170 Save,
2171 Quit,
2172 Submit,
2173 Newline,
2174 Global,
2175 Mode,
2176 Widget,
2177 Down,
2178 }
2179
2180 fn press(c: char) -> KeyEvent {
2181 KeyEvent::new(KeyCode::Char(c))
2182 }
2183
2184 fn kind(mut event: KeyEvent, kind: KeyEventKind) -> KeyEvent {
2185 event.kind = kind;
2186 event
2187 }
2188
2189 fn ms(n: u64) -> Duration {
2190 Duration::from_millis(n)
2191 }
2192
2193 fn chord(s: &str) -> Chord {
2194 Chord::parse(s).unwrap_or_else(|e| panic!("{s}: {e}"))
2195 }
2196
2197 fn actions<A: Clone>(dispatches: &[Dispatch<A>]) -> Vec<A> {
2198 dispatches
2199 .iter()
2200 .filter_map(|d| match d {
2201 Dispatch::Action { action, .. } => Some(action.clone()),
2202 _ => None,
2203 })
2204 .collect()
2205 }
2206
2207 #[test]
2211 fn shift_stays_a_modifier_when_uppercasing_would_not_round_trip() {
2212 let shifted = |c| KeyCombo::new(KeyCode::Char(c), Modifiers::SHIFT);
2213
2214 assert_eq!(shifted('中').to_string(), "Shift+中");
2217 assert_eq!(shifted('ß').to_string(), "Shift+ß");
2220 assert_eq!(shifted('ı').to_string(), "Shift+ı");
2223 assert_eq!(shifted('a').to_string(), "A");
2225
2226 for c in ['中', 'ß', 'ı', 'a'] {
2227 let combo = shifted(c);
2228 let text = combo.to_string();
2229 assert_eq!(text.parse::<KeyCombo>().unwrap(), combo, "{text:?}");
2230 }
2231 }
2232
2233 #[test]
2236 fn a_unicode_space_is_a_key_and_not_padding() {
2237 let nbsp = KeyCode::Char('\u{a0}');
2238 let alt_space = KeyCombo::new(nbsp, Modifiers::ALT);
2239 let text = alt_space.to_string();
2240 assert_eq!(text.parse::<KeyCombo>().unwrap(), alt_space);
2242 assert_ne!(
2243 text.parse::<KeyCombo>().unwrap(),
2244 KeyCombo::new(KeyCode::Char('+'), Modifiers::ALT)
2245 );
2246
2247 assert_eq!(
2249 "\u{a0}".parse::<KeyCombo>().unwrap(),
2250 KeyCombo::new(nbsp, Modifiers::NONE)
2251 );
2252 assert_eq!(
2254 " Ctrl+x \t".parse::<KeyCombo>().unwrap(),
2255 KeyCombo::new(KeyCode::Char('x'), Modifiers::CTRL)
2256 );
2257 }
2258
2259 #[test]
2260 fn combo_parse_display_and_normalization() {
2261 let ctrl_x: KeyCombo = "Ctrl+x".parse().unwrap();
2262 assert_eq!(ctrl_x, KeyCombo::new(KeyCode::Char('x'), Modifiers::CTRL));
2263 assert_eq!(ctrl_x.to_string(), "Ctrl+x");
2264
2265 let shift_a: KeyCombo = "shift+a".parse().unwrap();
2267 assert_eq!(shift_a, "A".parse().unwrap());
2268 assert_eq!(shift_a, KeyCombo::new(KeyCode::Char('A'), Modifiers::SHIFT));
2269 assert_eq!(shift_a.to_string(), "A");
2270
2271 assert_eq!("F12".parse::<KeyCombo>().unwrap().code, KeyCode::F(12));
2272 assert_eq!(
2273 "Space".parse::<KeyCombo>().unwrap().code,
2274 KeyCode::Char(' ')
2275 );
2276 assert_eq!(
2277 "Ctrl+Alt+Delete".parse::<KeyCombo>().unwrap().to_string(),
2278 "Ctrl+Alt+Delete"
2279 );
2280 assert_eq!(
2281 "Shift+Tab".parse::<KeyCombo>().unwrap().to_string(),
2282 "Shift+Tab"
2283 );
2284 assert_eq!("+".parse::<KeyCombo>().unwrap().code, KeyCode::Char('+'));
2286 let ctrl_plus: KeyCombo = "Ctrl++".parse().unwrap();
2287 assert_eq!(
2288 ctrl_plus,
2289 KeyCombo::new(KeyCode::Char('+'), Modifiers::CTRL)
2290 );
2291
2292 assert_eq!(
2293 "Hyper+x".parse::<KeyCombo>(),
2294 Err(KeyParseError::UnknownModifier("Hyper".into()))
2295 );
2296 assert_eq!(
2297 "Banana".parse::<KeyCombo>(),
2298 Err(KeyParseError::UnknownKey("Banana".into()))
2299 );
2300 assert_eq!("".parse::<KeyCombo>(), Err(KeyParseError::EmptyKey));
2301 assert_eq!(
2302 "F0".parse::<KeyCombo>(),
2303 Err(KeyParseError::UnknownKey("F0".into()))
2304 );
2305 }
2306
2307 #[test]
2308 fn chord_parse_prefix_and_limits() {
2309 let gg = chord("g g");
2310 let g = chord("g");
2311 assert_eq!(gg.len(), 2);
2312 assert_eq!(gg.to_string(), "g g");
2313 assert!(g.is_prefix_of(&gg));
2314 assert!(!gg.is_prefix_of(&g));
2315 assert!(!g.is_prefix_of(&g), "a chord is not its own prefix");
2316 assert_eq!(chord("Ctrl+x Ctrl+s").to_string(), "Ctrl+x Ctrl+s");
2317 assert_eq!(Chord::parse(""), Err(KeyParseError::EmptyKey));
2318 assert_eq!(
2319 Chord::parse("a b c d e"),
2320 Err(KeyParseError::TooManyKeys(5))
2321 );
2322 }
2323
2324 #[test]
2325 fn chord_completes_within_timeout() {
2326 let mut map = KeyMap::new();
2327 map.bind(chord("g g"), Act::GoTop);
2328 map.bind(chord("x"), Act::Save);
2329 let mut dispatcher = KeyDispatcher::new(map);
2330 let t0 = Instant::now();
2331
2332 let first = dispatcher.feed(&press('g'), t0);
2333 assert_eq!(first, vec![Dispatch::Pending { prefix: chord("g") }]);
2334 assert_eq!(dispatcher.pending_prefix(), Some(chord("g")));
2335 assert!(
2336 dispatcher.tick(t0 + ms(300)).is_empty(),
2337 "still inside the timeout"
2338 );
2339
2340 let second = dispatcher.feed(&press('g'), t0 + ms(300));
2341 assert_eq!(actions(&second), vec![Act::GoTop]);
2342 assert_eq!(dispatcher.pending_prefix(), None);
2343 assert_eq!(dispatcher.stats().dispatched, 1);
2344 assert_eq!(dispatcher.stats().pending, 1);
2345 }
2346
2347 #[test]
2348 fn chord_expires_after_timeout() {
2349 let mut map = KeyMap::new();
2351 map.bind(chord("g g"), Act::GoTop);
2352 map.bind(chord("g"), Act::Help);
2353 let mut dispatcher = KeyDispatcher::new(map);
2354 let t0 = Instant::now();
2355 assert_eq!(
2356 dispatcher.feed(&press('g'), t0),
2357 vec![Dispatch::Pending { prefix: chord("g") }]
2358 );
2359 assert!(dispatcher.tick(t0 + ms(999)).is_empty());
2360 let expired = dispatcher.tick(t0 + ms(1000));
2361 assert_eq!(expired[0], Dispatch::Expired { prefix: chord("g") });
2362 assert_eq!(actions(&expired), vec![Act::Help]);
2363 assert_eq!(dispatcher.stats().expired, 1);
2364
2365 let mut map = KeyMap::new();
2367 map.bind(chord("g g"), Act::GoTop);
2368 let mut dispatcher = KeyDispatcher::new(map);
2369 dispatcher.feed(&press('g'), t0);
2370 assert_eq!(
2371 dispatcher.tick(t0 + ms(5000)),
2372 vec![Dispatch::Expired { prefix: chord("g") }]
2373 );
2374 assert_eq!(dispatcher.pending_prefix(), None);
2375 }
2376
2377 #[test]
2378 fn single_key_fires_while_chord_pending() {
2379 let mut map = KeyMap::new();
2380 map.bind(chord("g g"), Act::GoTop);
2381 map.bind(chord("x"), Act::Save);
2382 let mut dispatcher = KeyDispatcher::new(map);
2383 let t0 = Instant::now();
2384 dispatcher.feed(&press('g'), t0);
2385 let out = dispatcher.feed(&press('x'), t0 + ms(10));
2386 assert_eq!(out[0], Dispatch::Expired { prefix: chord("g") });
2387 assert_eq!(
2388 actions(&out),
2389 vec![Act::Save],
2390 "x is never blocked by the pending g"
2391 );
2392
2393 let mut map = KeyMap::new();
2395 map.bind(chord("g g"), Act::GoTop);
2396 map.bind(chord("g"), Act::Help);
2397 map.bind(chord("x"), Act::Save);
2398 let mut dispatcher = KeyDispatcher::new(map);
2399 dispatcher.feed(&press('g'), t0);
2400 let out = dispatcher.feed(&press('x'), t0 + ms(10));
2401 assert_eq!(actions(&out), vec![Act::Help, Act::Save]);
2402
2403 let mut map = KeyMap::new();
2405 map.bind(chord("g g"), Act::GoTop);
2406 map.bind(chord("z z"), Act::Quit);
2407 let mut dispatcher = KeyDispatcher::new(map);
2408 dispatcher.feed(&press('g'), t0);
2409 let out = dispatcher.feed(&press('z'), t0 + ms(10));
2410 assert_eq!(
2411 out,
2412 vec![
2413 Dispatch::Expired { prefix: chord("g") },
2414 Dispatch::Pending { prefix: chord("z") }
2415 ]
2416 );
2417 }
2418
2419 #[test]
2420 fn prefix_with_own_binding_fires_on_flush() {
2421 let mut map = KeyMap::new();
2426 let one = map.bind(chord("g"), Act::Help);
2427 map.bind(chord("g g"), Act::GoTop);
2428 let mut dispatcher = KeyDispatcher::new(map);
2429 let t0 = Instant::now();
2430
2431 assert_eq!(
2432 dispatcher.feed(&press('g'), t0),
2433 vec![Dispatch::Pending { prefix: chord("g") }]
2434 );
2435 let out = dispatcher.feed(&press('x'), t0 + ms(10));
2436 assert_eq!(
2437 out,
2438 vec![
2439 Dispatch::Action {
2440 action: Act::Help,
2441 binding: one,
2442 chord: chord("g"),
2443 },
2444 Dispatch::Unbound(press('x')),
2445 ]
2446 );
2447 assert_eq!(dispatcher.pending_prefix(), None);
2448 assert_eq!(
2449 dispatcher.stats().expired,
2450 0,
2451 "a bound prefix flushed by a non-extending key does not expire"
2452 );
2453 assert_eq!(dispatcher.stats().dispatched, 1);
2454 }
2455
2456 #[test]
2457 fn widget_beats_mode_beats_global() {
2458 let mut map = KeyMap::new();
2459 let g = map.bind_in(chord("s"), Act::Global, Priority::Global, None);
2460 let m = map.bind_in(chord("s"), Act::Mode, Priority::Mode, None);
2461 let w = map.bind_in(chord("s"), Act::Widget, Priority::Widget, None);
2462 let lookup = map.lookup(&chord("s"), &[]);
2463 assert_eq!(lookup.exact.map(|b| b.id), Some(w));
2464 assert_eq!(lookup.longer, 0);
2465
2466 let mut dispatcher = KeyDispatcher::new(map);
2467 assert_eq!(
2468 actions(&dispatcher.feed(&press('s'), Instant::now())),
2469 vec![Act::Widget]
2470 );
2471
2472 let report = dispatcher.map().conflicts();
2473 assert_eq!(report.len(), 3, "{report}");
2474 assert!(report.items.contains(&Conflict::Shadowed {
2475 winner: w,
2476 loser: g,
2477 chord: chord("s")
2478 }));
2479 assert!(report.items.contains(&Conflict::Shadowed {
2480 winner: m,
2481 loser: g,
2482 chord: chord("s")
2483 }));
2484 assert!(report.items.contains(&Conflict::Shadowed {
2485 winner: w,
2486 loser: m,
2487 chord: chord("s")
2488 }));
2489 assert_eq!(report.to_string().lines().count(), 3);
2490
2491 dispatcher.map_mut().unbind(w);
2493 assert_eq!(
2494 actions(&dispatcher.feed(&press('s'), Instant::now())),
2495 vec![Act::Mode]
2496 );
2497 }
2498
2499 #[test]
2500 fn active_context_beats_contextless_even_at_lower_priority() {
2501 let mut map = KeyMap::new();
2502 let text_input = map.context("text_input");
2503 assert_eq!(map.context("text_input"), text_input, "interned once");
2504 assert_eq!(map.context_name(text_input), Some("text_input"));
2505 map.bind_in(chord("Enter"), Act::Submit, Priority::Widget, None);
2506 map.bind_in(
2507 chord("Enter"),
2508 Act::Newline,
2509 Priority::Global,
2510 Some(text_input),
2511 );
2512 assert!(
2513 map.conflicts().is_empty(),
2514 "a context override is not a conflict"
2515 );
2516
2517 let mut dispatcher = KeyDispatcher::new(map);
2518 let enter = KeyEvent::new(KeyCode::Enter);
2519 let t0 = Instant::now();
2520 assert_eq!(actions(&dispatcher.feed(&enter, t0)), vec![Act::Submit]);
2521 dispatcher.set_active_contexts(&[text_input]);
2522 assert_eq!(actions(&dispatcher.feed(&enter, t0)), vec![Act::Newline]);
2523 dispatcher.set_active_contexts(&[]);
2524 assert_eq!(actions(&dispatcher.feed(&enter, t0)), vec![Act::Submit]);
2525 }
2526
2527 #[test]
2528 fn conflicts_reports_shadowed_prefix_and_duplicate() {
2529 let mut map = KeyMap::new();
2530 let long = map.bind(chord("g g"), Act::GoTop);
2531 let short = map.bind(chord("g"), Act::Help);
2532 let q1 = map.bind(chord("q"), Act::Quit);
2533 let q2 = map.bind(chord("q"), Act::Quit);
2534 map.set_label(q2, "quit");
2535 assert_eq!(map.get(q2).and_then(|b| b.label.as_deref()), Some("quit"));
2536
2537 let report = map.conflicts();
2538 assert_eq!(report.len(), 2, "{report}");
2539 assert_eq!(
2540 report.items[0],
2541 Conflict::PrefixCollision {
2542 short,
2543 long,
2544 short_chord: chord("g"),
2545 long_chord: chord("g g"),
2546 }
2547 );
2548 assert_eq!(
2549 report.items[1],
2550 Conflict::Duplicate {
2551 first: q1,
2552 second: q2,
2553 chord: chord("q")
2554 }
2555 );
2556 let text = report.to_string();
2557 assert_eq!(text.lines().count(), 2);
2558 assert!(
2559 text.contains("warning: binding #1 (`g`) is a prefix of binding #0 (`g g`)"),
2560 "{text}"
2561 );
2562 assert!(text.contains("the later one wins"), "{text}");
2563
2564 assert_eq!(map.lookup(&chord("q"), &[]).exact.map(|b| b.id), Some(q2));
2566 }
2567
2568 #[test]
2569 fn repeat_refires_single_key_binding_but_never_extends_a_chord() {
2570 let mut map = KeyMap::new();
2571 map.bind(chord("j"), Act::Down);
2572 map.bind(chord("g g"), Act::GoTop);
2573 let mut dispatcher = KeyDispatcher::new(map);
2574 let t0 = Instant::now();
2575
2576 let held = kind(press('j'), KeyEventKind::Repeat);
2577 assert_eq!(actions(&dispatcher.feed(&held, t0)), vec![Act::Down]);
2578
2579 dispatcher.feed(&press('g'), t0);
2580 let repeat_g = kind(press('g'), KeyEventKind::Repeat);
2581 assert_eq!(
2582 dispatcher.feed(&repeat_g, t0 + ms(10)),
2583 vec![Dispatch::Unbound(repeat_g)]
2584 );
2585 assert_eq!(
2586 dispatcher.pending_prefix(),
2587 Some(chord("g")),
2588 "repeat left the prefix alone"
2589 );
2590
2591 let released = kind(press('j'), KeyEventKind::Release);
2592 assert_eq!(
2593 dispatcher.feed(&released, t0 + ms(20)),
2594 vec![Dispatch::Unbound(released)]
2595 );
2596 }
2597
2598 #[test]
2599 fn esc_goes_through_the_sequence_detector() {
2600 let mut map = KeyMap::new();
2601 map.bind(chord("Esc"), Act::Quit);
2602 map.bind(chord("Esc Esc"), Act::Help);
2603 map.bind(chord("g g"), Act::GoTop);
2604 let mut dispatcher = KeyDispatcher::new(map);
2605 let esc = KeyEvent::new(KeyCode::Escape);
2606 let t0 = Instant::now();
2607
2608 assert_eq!(
2610 dispatcher.feed(&esc, t0),
2611 vec![Dispatch::Esc(SequenceOutput::Pending)]
2612 );
2613 assert_eq!(actions(&dispatcher.tick(t0 + ms(300))), vec![Act::Quit]);
2614
2615 let t1 = t0 + ms(1000);
2617 dispatcher.feed(&esc, t1);
2618 assert_eq!(
2619 actions(&dispatcher.feed(&esc, t1 + ms(100))),
2620 vec![Act::Help]
2621 );
2622
2623 let t2 = t0 + ms(3000);
2625 dispatcher.feed(&press('g'), t2);
2626 let out = dispatcher.feed(&esc, t2 + ms(10));
2627 assert_eq!(out[0], Dispatch::Expired { prefix: chord("g") });
2628 assert_eq!(dispatcher.pending_prefix(), None);
2629
2630 let mut plain = KeyDispatcher::new(KeyMap::<Act>::new());
2632 plain.feed(&esc, t0);
2633 assert_eq!(
2634 plain.tick(t0 + ms(300)),
2635 vec![Dispatch::Esc(SequenceOutput::Esc)]
2636 );
2637 }
2638
2639 #[test]
2643 fn key_inside_the_esc_window_follows_the_resolved_esc() {
2644 let mut map = KeyMap::new();
2645 map.bind(chord("Esc"), Act::Mode);
2646 map.bind(chord("j"), Act::Down);
2647 let mut dispatcher = KeyDispatcher::new(map);
2648 let esc = KeyEvent::new(KeyCode::Escape);
2649 let t0 = Instant::now();
2650
2651 dispatcher.feed(&esc, t0);
2652 assert_eq!(
2653 actions(&dispatcher.feed(&press('j'), t0 + ms(50))),
2654 vec![Act::Mode, Act::Down]
2655 );
2656 assert!(dispatcher.tick(t0 + ms(300)).is_empty());
2657
2658 let mut plain = KeyMap::new();
2660 plain.bind(chord("j"), Act::Down);
2661 let mut plain = KeyDispatcher::new(plain);
2662 plain.feed(&esc, t0);
2663 let out = plain.feed(&press('j'), t0 + ms(50));
2664 assert_eq!(out[0], Dispatch::Esc(SequenceOutput::Esc));
2665 assert_eq!(actions(&out), vec![Act::Down]);
2666 }
2667
2668 #[cfg(feature = "serde")]
2672 #[test]
2673 fn keymap_round_trips_through_toml_and_json() {
2674 #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
2675 enum Action {
2676 Quit,
2677 Save,
2678 Newline,
2679 }
2680
2681 let mut map = KeyMap::with_config(KeyMapConfig::default().with_chord_timeout(ms(750)));
2682 let editor = map.context("editor");
2683 let quit = map.bind(chord("q"), Action::Quit);
2684 map.set_label(quit, "quit");
2685 map.bind_in(chord("Ctrl+x Ctrl+s"), Action::Save, Priority::Mode, None);
2686 map.bind_in(
2687 chord("Enter"),
2688 Action::Newline,
2689 Priority::Widget,
2690 Some(editor),
2691 );
2692
2693 let text = toml::to_string(&map).expect("serialize to TOML");
2694 assert!(text.contains("chord_timeout_ms = 750"), "{text}");
2695 assert!(text.contains("chord = \"Ctrl+x Ctrl+s\""), "{text}");
2696 assert!(text.contains("context = \"editor\""), "{text}");
2697 assert!(text.contains("label = \"quit\""), "{text}");
2698
2699 let back: KeyMap<Action> = toml::from_str(&text).expect("parse TOML");
2700 assert_eq!(back.config().chord_timeout, ms(750));
2701 assert_eq!(back.len(), 3);
2702 assert_eq!(back.bindings()[0].label.as_deref(), Some("quit"));
2703 assert_eq!(back.bindings()[1].priority, Priority::Mode);
2704 assert_eq!(back.bindings()[1].chord, chord("Ctrl+x Ctrl+s"));
2705 let editor_back = back.bindings()[2].context.expect("context restored");
2706 assert_eq!(back.context_name(editor_back), Some("editor"));
2707 assert_eq!(
2708 back.lookup(&chord("Enter"), &[editor_back])
2709 .exact
2710 .map(|b| &b.action),
2711 Some(&Action::Newline)
2712 );
2713 assert!(
2714 back.lookup(&chord("Enter"), &[]).is_none(),
2715 "the context binding stays inactive outside its context"
2716 );
2717
2718 let json = serde_json::to_string(&map).expect("serialize to JSON");
2719 let back_json: KeyMap<Action> = serde_json::from_str(&json).expect("parse JSON");
2720 assert_eq!(back_json.len(), 3);
2721 assert_eq!(back_json.bindings()[2].action, Action::Newline);
2722
2723 let bad =
2724 "chord_timeout_ms = 500\n\n[[bindings]]\nchord = \"Hyper+q\"\naction = \"Quit\"\n";
2725 let err = toml::from_str::<KeyMap<Action>>(bad)
2726 .expect_err("bad chord must fail")
2727 .to_string();
2728 assert!(err.contains("binding 0") && err.contains("Hyper"), "{err}");
2729
2730 let minimal: KeyMap<Action> =
2731 toml::from_str("[[bindings]]\nchord = \"q\"\naction = \"Quit\"\n")
2732 .expect("defaults fill in");
2733 assert_eq!(minimal.config().chord_timeout, ms(DEFAULT_CHORD_TIMEOUT_MS));
2734 assert_eq!(minimal.bindings()[0].priority, Priority::Global);
2735 }
2736
2737 #[cfg(feature = "serde")]
2740 #[test]
2741 fn toml_rejects_unknown_field_and_bad_chord() {
2742 #[derive(Debug, Clone, serde::Deserialize)]
2743 enum Action {
2744 Quit,
2745 }
2746
2747 let unknown_top =
2748 toml::from_str::<KeyMap<Action>>("chord_timeout_ms = 500\ntypo_field = 3\n")
2749 .expect_err("an unknown top-level field must be rejected")
2750 .to_string();
2751 assert!(unknown_top.contains("typo_field"), "{unknown_top}");
2752
2753 let unknown_binding = toml::from_str::<KeyMap<Action>>(
2754 "[[bindings]]\nchord = \"q\"\naction = \"Quit\"\nchrod = \"x\"\n",
2755 )
2756 .expect_err("an unknown binding field must be rejected")
2757 .to_string();
2758 assert!(unknown_binding.contains("chrod"), "{unknown_binding}");
2759
2760 let bad_chord = toml::from_str::<KeyMap<Action>>(
2761 "[[bindings]]\nchord = \"Nope+q\"\naction = \"Quit\"\n",
2762 )
2763 .expect_err("a bad chord must be rejected")
2764 .to_string();
2765 assert!(
2766 bad_chord.contains("binding 0") && bad_chord.contains("Nope"),
2767 "{bad_chord}"
2768 );
2769 }
2770
2771 #[cfg(feature = "serde")]
2775 #[test]
2776 fn toml_example_in_docs_parses() {
2777 #[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
2778 enum Action {
2779 Save,
2780 Newline,
2781 Top,
2782 }
2783
2784 const EXAMPLE: &str = include_str!("../tests/fixtures/keymap_example.toml");
2785 let map: KeyMap<Action> =
2786 toml::from_str(EXAMPLE).expect("documented keymap example must parse");
2787
2788 assert_eq!(map.config().chord_timeout, ms(750));
2789 assert_eq!(map.len(), 3);
2790
2791 let save = &map.bindings()[0];
2792 assert_eq!(save.action, Action::Save);
2793 assert_eq!(save.chord, chord("Ctrl+x Ctrl+s"));
2794 assert_eq!(save.priority, Priority::Mode);
2795 assert_eq!(save.label.as_deref(), Some("save"));
2796
2797 let newline = &map.bindings()[1];
2798 assert_eq!(newline.action, Action::Newline);
2799 assert_eq!(newline.priority, Priority::Widget);
2800 let editor = newline.context.expect("editor context restored");
2801 assert_eq!(map.context_name(editor), Some("editor"));
2802 assert_eq!(
2803 map.lookup(&chord("Enter"), &[editor])
2804 .exact
2805 .map(|binding| &binding.action),
2806 Some(&Action::Newline)
2807 );
2808 assert!(
2809 map.lookup(&chord("Enter"), &[]).is_none(),
2810 "the editor binding stays inactive outside its context"
2811 );
2812
2813 assert_eq!(map.bindings()[2].chord, chord("g g"));
2814 assert_eq!(map.bindings()[2].action, Action::Top);
2815 let report = map.conflicts();
2816 assert!(report.is_empty(), "{report}");
2817 }
2818
2819 #[test]
2820 fn spec_defaults_match_code() {
2821 const SPEC: &str = include_str!("../../../docs/spec/keybinding-policy.md");
2822 assert_eq!(DEFAULT_CHORD_TIMEOUT_MS, 1000);
2823 assert_eq!(DEFAULT_ESC_SEQ_TIMEOUT_MS, 250);
2824 assert!(
2825 SPEC.contains("chord_timeout_ms = 1000") || SPEC.contains("chord_timeout_ms: 1000"),
2826 "keybinding-policy.md must document the 1000 ms default chord timeout"
2827 );
2828 assert!(
2829 SPEC.lines()
2830 .any(|line| line.contains("250") && (line.contains("Esc") || line.contains("esc"))),
2831 "keybinding-policy.md must document the 250 ms Esc sequence timeout"
2832 );
2833 }
2834
2835 fn arb_code() -> impl Strategy<Value = KeyCode> {
2836 prop_oneof![
2837 prop::sample::select(vec![
2838 'a', 'b', 'q', 'x', 'z', 'A', 'Q', '1', '9', '+', '-', '.', '/', ' ',
2839 'ß', 'ı', '中', 'é', 'İ', '\u{a0}', ])
2848 .prop_map(KeyCode::Char),
2849 (1u8..=24).prop_map(KeyCode::F),
2850 prop::sample::select(vec![
2851 KeyCode::Enter,
2852 KeyCode::Escape,
2853 KeyCode::Backspace,
2854 KeyCode::Tab,
2855 KeyCode::BackTab,
2856 KeyCode::Delete,
2857 KeyCode::Insert,
2858 KeyCode::Home,
2859 KeyCode::End,
2860 KeyCode::PageUp,
2861 KeyCode::PageDown,
2862 KeyCode::Up,
2863 KeyCode::Down,
2864 KeyCode::Left,
2865 KeyCode::Right,
2866 KeyCode::Null,
2867 KeyCode::MediaPlayPause,
2868 KeyCode::MediaStop,
2869 KeyCode::MediaNextTrack,
2870 KeyCode::MediaPrevTrack,
2871 ]),
2872 ]
2873 }
2874
2875 fn arb_mods() -> impl Strategy<Value = Modifiers> {
2876 (0u8..16).prop_map(|bits| {
2877 let mut modifiers = Modifiers::NONE;
2878 if bits & 0b0001 != 0 {
2879 modifiers |= Modifiers::CTRL;
2880 }
2881 if bits & 0b0010 != 0 {
2882 modifiers |= Modifiers::ALT;
2883 }
2884 if bits & 0b0100 != 0 {
2885 modifiers |= Modifiers::SHIFT;
2886 }
2887 if bits & 0b1000 != 0 {
2888 modifiers |= Modifiers::SUPER;
2889 }
2890 modifiers
2891 })
2892 }
2893
2894 fn arb_small_chord() -> impl Strategy<Value = Chord> {
2895 prop::collection::vec(
2896 prop::sample::select(vec!['a', 'b', 'c', 'd'])
2897 .prop_map(|c| KeyCombo::key(KeyCode::Char(c))),
2898 1..=3usize,
2899 )
2900 .prop_map(|combos| Chord::new(combos).expect("1..=3 combos is a valid chord"))
2901 }
2902
2903 fn arb_key() -> impl Strategy<Value = KeyEvent> {
2904 let code = prop_oneof![
2905 Just(KeyCode::Char('a')),
2906 Just(KeyCode::Char('b')),
2907 Just(KeyCode::Char('c')),
2908 Just(KeyCode::Enter),
2909 Just(KeyCode::Escape),
2910 ];
2911 let kind = prop_oneof![
2912 Just(KeyEventKind::Press),
2913 Just(KeyEventKind::Repeat),
2914 Just(KeyEventKind::Release),
2915 ];
2916 (code, kind).prop_map(|(code, kind)| KeyEvent {
2917 code,
2918 modifiers: Modifiers::NONE,
2919 kind,
2920 })
2921 }
2922
2923 proptest! {
2924 #![proptest_config(ProptestConfig::with_cases(1000))]
2925
2926 #[test]
2929 fn every_fed_key_yields_a_dispatch(
2930 keys in proptest::collection::vec(arb_key(), 1..20),
2931 gaps in proptest::collection::vec(0u64..1500, 1..20),
2932 ) {
2933 let mut map = KeyMap::new();
2934 map.bind(chord("a b"), Act::GoTop);
2935 map.bind(chord("a"), Act::Help);
2936 map.bind(chord("c c c"), Act::Save);
2937 map.bind(chord("Enter"), Act::Submit);
2938 let mut dispatcher = KeyDispatcher::new(map);
2939 let mut now = Instant::now();
2940 for (key, gap) in keys.iter().zip(gaps.iter().cycle()) {
2941 now += ms(*gap);
2942 let out = dispatcher.feed(key, now);
2943 prop_assert!(!out.is_empty(), "{key:?} produced nothing");
2944 let _ = dispatcher.tick(now);
2945 }
2946 let _ = dispatcher.tick(now + ms(10_000));
2947 prop_assert_eq!(dispatcher.pending_prefix(), None);
2948 let stats = dispatcher.stats();
2949 prop_assert!(
2950 stats.dispatched + stats.pending + stats.expired + stats.unbound + stats.esc > 0
2951 );
2952 }
2953
2954 #[test]
2957 fn combo_display_parse_round_trip(code in arb_code(), mods in arb_mods()) {
2958 let combo = KeyCombo::new(code, mods);
2959 let text = combo.to_string();
2960 let parsed: KeyCombo = text
2961 .parse()
2962 .unwrap_or_else(|e| panic!("`{text}` did not re-parse: {e}"));
2963 prop_assert_eq!(parsed, combo, "text = `{}`", text);
2964 }
2965
2966 #[test]
2969 fn lookup_is_deterministic_under_shuffle(
2970 raw in prop::collection::vec((arb_small_chord(), any::<u64>()), 1..12),
2971 queries in prop::collection::vec(arb_small_chord(), 1..8),
2972 ) {
2973 let mut seen = std::collections::BTreeSet::new();
2976 let mut entries: Vec<(Chord, u64)> = Vec::new();
2977 for (ch, key) in raw {
2978 if seen.insert(ch.to_string()) {
2979 entries.push((ch, key));
2980 }
2981 }
2982 let build = |order: &[(Chord, u64)]| {
2983 let mut map = KeyMap::new();
2984 for (ch, _) in order {
2985 map.bind(ch.clone(), ch.to_string());
2986 }
2987 map
2988 };
2989 let in_order = build(&entries);
2990 let mut shuffled = entries.clone();
2991 shuffled.sort_by_key(|(_, key)| *key);
2992 let reordered = build(&shuffled);
2993 for query in &queries {
2994 let a = in_order.lookup(query, &[]);
2995 let b = reordered.lookup(query, &[]);
2996 prop_assert_eq!(
2997 a.exact.map(|binding| binding.action.clone()),
2998 b.exact.map(|binding| binding.action.clone()),
2999 "winner changed for `{}`",
3000 query
3001 );
3002 prop_assert_eq!(a.longer, b.longer, "longer count changed for `{}`", query);
3003 }
3004 }
3005 }
3006}
3007
3008#[cfg(test)]
3009mod tests {
3010 use super::*;
3011
3012 fn now() -> Instant {
3013 Instant::now()
3014 }
3015
3016 fn esc_press() -> KeyEvent {
3017 KeyEvent::new(KeyCode::Escape)
3018 }
3019
3020 fn key_press(code: KeyCode) -> KeyEvent {
3021 KeyEvent::new(code)
3022 }
3023
3024 fn esc_release() -> KeyEvent {
3025 KeyEvent::new(KeyCode::Escape).with_kind(KeyEventKind::Release)
3026 }
3027
3028 const MS_50: Duration = Duration::from_millis(50);
3029 const MS_100: Duration = Duration::from_millis(100);
3030 const MS_200: Duration = Duration::from_millis(200);
3031 const MS_300: Duration = Duration::from_millis(300);
3032
3033 #[test]
3036 fn single_esc_returns_pending() {
3037 let mut detector = SequenceDetector::with_defaults();
3038 let t = now();
3039
3040 let output = detector.feed(&esc_press(), t);
3041 assert_eq!(output, SequenceOutput::Pending);
3042 assert!(detector.is_pending());
3043 }
3044
3045 #[test]
3046 fn esc_esc_within_timeout() {
3047 let mut detector = SequenceDetector::with_defaults();
3048 let t = now();
3049
3050 detector.feed(&esc_press(), t);
3051 let output = detector.feed(&esc_press(), t + MS_100);
3052
3053 assert_eq!(output, SequenceOutput::EscEsc);
3054 assert!(!detector.is_pending());
3055 }
3056
3057 #[test]
3058 fn esc_esc_at_timeout_boundary() {
3059 let mut detector = SequenceDetector::with_defaults();
3060 let t = now();
3061
3062 detector.feed(&esc_press(), t);
3063 let output = detector.feed(&esc_press(), t + Duration::from_millis(250));
3065
3066 assert_eq!(output, SequenceOutput::EscEsc);
3067 }
3068
3069 #[test]
3070 fn esc_esc_past_timeout() {
3071 let mut detector = SequenceDetector::with_defaults();
3072 let t = now();
3073
3074 detector.feed(&esc_press(), t);
3075 let output = detector.feed(&esc_press(), t + Duration::from_millis(251));
3077
3078 assert_eq!(output, SequenceOutput::Esc);
3080 assert!(detector.is_pending()); }
3082
3083 #[test]
3084 fn timeout_check_emits_pending_esc() {
3085 let mut detector = SequenceDetector::with_defaults();
3086 let t = now();
3087
3088 detector.feed(&esc_press(), t);
3089
3090 assert!(detector.check_timeout(t + MS_200).is_none());
3092 assert!(detector.is_pending());
3093
3094 let output = detector.check_timeout(t + Duration::from_millis(251));
3096 assert_eq!(output, Some(SequenceOutput::Esc));
3097 assert!(!detector.is_pending());
3098 }
3099
3100 #[test]
3101 fn other_key_interrupts_sequence() {
3102 let mut detector = SequenceDetector::with_defaults();
3103 let t = now();
3104
3105 detector.feed(&esc_press(), t);
3106 let output = detector.feed(&key_press(KeyCode::Char('a')), t + MS_100);
3107
3108 assert_eq!(output, SequenceOutput::Esc);
3110 assert!(!detector.is_pending());
3111 }
3112
3113 #[test]
3114 fn non_esc_key_passes_through() {
3115 let mut detector = SequenceDetector::with_defaults();
3116 let t = now();
3117
3118 let output = detector.feed(&key_press(KeyCode::Char('x')), t);
3119 assert_eq!(output, SequenceOutput::PassThrough);
3120 }
3121
3122 #[test]
3123 fn release_event_passes_through() {
3124 let mut detector = SequenceDetector::with_defaults();
3125 let t = now();
3126
3127 let output = detector.feed(&esc_release(), t);
3128 assert_eq!(output, SequenceOutput::PassThrough);
3129 assert!(!detector.is_pending());
3130 }
3131
3132 #[test]
3133 fn release_during_pending_passes_through() {
3134 let mut detector = SequenceDetector::with_defaults();
3135 let t = now();
3136
3137 detector.feed(&esc_press(), t);
3138 let output = detector.feed(&esc_release(), t + MS_50);
3139
3140 assert_eq!(output, SequenceOutput::PassThrough);
3142 assert!(detector.is_pending());
3143 }
3144
3145 #[test]
3148 fn custom_timeout() {
3149 let config = SequenceConfig::default().with_timeout(Duration::from_millis(100));
3150 let mut detector = SequenceDetector::new(config);
3151 let t = now();
3152
3153 detector.feed(&esc_press(), t);
3154 let output = detector.feed(&esc_press(), t + Duration::from_millis(150));
3156
3157 assert_eq!(output, SequenceOutput::Esc);
3158 }
3159
3160 #[test]
3161 fn disabled_sequences() {
3162 let config = SequenceConfig::default().disable_sequences();
3163 let mut detector = SequenceDetector::new(config);
3164 let t = now();
3165
3166 let output = detector.feed(&esc_press(), t);
3168 assert_eq!(output, SequenceOutput::Esc);
3169 assert!(!detector.is_pending());
3170
3171 let output = detector.feed(&esc_press(), t + MS_50);
3173 assert_eq!(output, SequenceOutput::Esc);
3174 }
3175
3176 #[test]
3177 fn disabled_sequences_passthrough() {
3178 let config = SequenceConfig::default().disable_sequences();
3179 let mut detector = SequenceDetector::new(config);
3180 let t = now();
3181
3182 let output = detector.feed(&key_press(KeyCode::Char('a')), t);
3183 assert_eq!(output, SequenceOutput::PassThrough);
3184 }
3185
3186 #[test]
3187 fn config_default_values() {
3188 let config = SequenceConfig::default();
3189 assert_eq!(config.esc_seq_timeout, Duration::from_millis(250));
3190 assert_eq!(config.esc_debounce, Duration::from_millis(50));
3191 assert!(!config.disable_sequences);
3192 }
3193
3194 #[test]
3195 fn config_builder_chain() {
3196 let config = SequenceConfig::default()
3197 .with_timeout(Duration::from_millis(300))
3198 .with_debounce(Duration::from_millis(100))
3199 .disable_sequences();
3200
3201 assert_eq!(config.esc_seq_timeout, Duration::from_millis(300));
3202 assert_eq!(config.esc_debounce, Duration::from_millis(100));
3203 assert!(config.disable_sequences);
3204 }
3205
3206 #[test]
3209 fn reset_clears_pending() {
3210 let mut detector = SequenceDetector::with_defaults();
3211 let t = now();
3212
3213 detector.feed(&esc_press(), t);
3214 assert!(detector.is_pending());
3215
3216 detector.reset();
3217 assert!(!detector.is_pending());
3218
3219 let output = detector.feed(&esc_press(), t + MS_100);
3221 assert_eq!(output, SequenceOutput::Pending);
3222 }
3223
3224 #[test]
3225 fn reset_discards_pending_esc() {
3226 let mut detector = SequenceDetector::with_defaults();
3227 let t = now();
3228
3229 detector.feed(&esc_press(), t);
3230 detector.reset();
3231
3232 assert!(detector.check_timeout(t + MS_300).is_none());
3234 }
3235
3236 #[test]
3239 fn rapid_triple_esc() {
3240 let mut detector = SequenceDetector::with_defaults();
3241 let t = now();
3242
3243 let out1 = detector.feed(&esc_press(), t);
3245 assert_eq!(out1, SequenceOutput::Pending);
3246
3247 let out2 = detector.feed(&esc_press(), t + MS_50);
3249 assert_eq!(out2, SequenceOutput::EscEsc);
3250
3251 let out3 = detector.feed(&esc_press(), t + MS_100);
3253 assert_eq!(out3, SequenceOutput::Pending);
3254 }
3255
3256 #[test]
3257 fn alternating_esc_and_key() {
3258 let mut detector = SequenceDetector::with_defaults();
3259 let t = now();
3260
3261 detector.feed(&esc_press(), t);
3263
3264 let out1 = detector.feed(&key_press(KeyCode::Char('a')), t + MS_50);
3266 assert_eq!(out1, SequenceOutput::Esc);
3267
3268 let out2 = detector.feed(&esc_press(), t + MS_100);
3270 assert_eq!(out2, SequenceOutput::Pending);
3271
3272 let out3 = detector.feed(&key_press(KeyCode::Char('b')), t + MS_200);
3274 assert_eq!(out3, SequenceOutput::Esc);
3275 }
3276
3277 #[test]
3278 fn enter_key_interrupts() {
3279 let mut detector = SequenceDetector::with_defaults();
3280 let t = now();
3281
3282 detector.feed(&esc_press(), t);
3283 let output = detector.feed(&key_press(KeyCode::Enter), t + MS_100);
3284
3285 assert_eq!(output, SequenceOutput::Esc);
3286 }
3287
3288 #[test]
3289 fn function_key_interrupts() {
3290 let mut detector = SequenceDetector::with_defaults();
3291 let t = now();
3292
3293 detector.feed(&esc_press(), t);
3294 let output = detector.feed(&key_press(KeyCode::F(1)), t + MS_100);
3295
3296 assert_eq!(output, SequenceOutput::Esc);
3297 }
3298
3299 #[test]
3300 fn arrow_key_interrupts() {
3301 let mut detector = SequenceDetector::with_defaults();
3302 let t = now();
3303
3304 detector.feed(&esc_press(), t);
3305 let output = detector.feed(&key_press(KeyCode::Up), t + MS_100);
3306
3307 assert_eq!(output, SequenceOutput::Esc);
3308 }
3309
3310 #[test]
3311 fn config_getter_and_setter() {
3312 let mut detector = SequenceDetector::with_defaults();
3313 assert_eq!(
3314 detector.config().esc_seq_timeout,
3315 Duration::from_millis(250)
3316 );
3317
3318 let new_config = SequenceConfig::default().with_timeout(Duration::from_millis(500));
3319 detector.set_config(new_config);
3320
3321 assert_eq!(
3322 detector.config().esc_seq_timeout,
3323 Duration::from_millis(500)
3324 );
3325 }
3326
3327 #[test]
3328 fn set_config_preserves_pending_state() {
3329 let mut detector = SequenceDetector::with_defaults();
3330 let t = now();
3331
3332 detector.feed(&esc_press(), t);
3333 assert!(detector.is_pending());
3334
3335 detector.set_config(SequenceConfig::default().with_timeout(Duration::from_millis(500)));
3337
3338 assert!(detector.is_pending());
3340
3341 let output = detector.feed(&esc_press(), t + MS_300);
3343 assert_eq!(output, SequenceOutput::EscEsc); }
3345
3346 #[test]
3347 fn debug_format() {
3348 let detector = SequenceDetector::with_defaults();
3349 let dbg = format!("{:?}", detector);
3350 assert!(dbg.contains("SequenceDetector"));
3351 }
3352
3353 #[test]
3354 fn config_debug_format() {
3355 let config = SequenceConfig::default();
3356 let dbg = format!("{:?}", config);
3357 assert!(dbg.contains("SequenceConfig"));
3358 }
3359
3360 #[test]
3361 fn output_debug_and_eq() {
3362 assert_eq!(SequenceOutput::Pending, SequenceOutput::Pending);
3363 assert_eq!(SequenceOutput::Esc, SequenceOutput::Esc);
3364 assert_eq!(SequenceOutput::EscEsc, SequenceOutput::EscEsc);
3365 assert_eq!(SequenceOutput::PassThrough, SequenceOutput::PassThrough);
3366 assert_ne!(SequenceOutput::Esc, SequenceOutput::EscEsc);
3367
3368 let dbg = format!("{:?}", SequenceOutput::EscEsc);
3369 assert!(dbg.contains("EscEsc"));
3370 }
3371
3372 #[test]
3375 fn no_stuck_state() {
3376 let mut detector = SequenceDetector::with_defaults();
3377 let t = now();
3378
3379 for i in 0..100 {
3381 let offset = Duration::from_millis(i * 10);
3382 if i % 3 == 0 {
3383 detector.feed(&esc_press(), t + offset);
3384 } else {
3385 detector.feed(&key_press(KeyCode::Char('x')), t + offset);
3386 }
3387 }
3388
3389 detector.check_timeout(t + Duration::from_secs(2));
3391
3392 assert!(!detector.is_pending());
3394 }
3395
3396 #[test]
3397 fn deterministic_output() {
3398 let config = SequenceConfig::default();
3400 let t = now();
3401
3402 let mut d1 = SequenceDetector::new(config.clone());
3403 let mut d2 = SequenceDetector::new(config);
3404
3405 let events = [
3406 (esc_press(), t),
3407 (esc_press(), t + MS_100),
3408 (key_press(KeyCode::Char('a')), t + MS_200),
3409 (esc_press(), t + MS_300),
3410 ];
3411
3412 for (event, time) in &events {
3413 let out1 = d1.feed(event, *time);
3414 let out2 = d2.feed(event, *time);
3415 assert_eq!(out1, out2);
3416 }
3417 }
3418
3419 mod action_mapper_tests {
3424 use super::*;
3425 use crate::event::Modifiers;
3426
3427 fn ctrl_c() -> KeyEvent {
3428 KeyEvent::new(KeyCode::Char('c')).with_modifiers(Modifiers::CTRL)
3429 }
3430
3431 fn ctrl_d() -> KeyEvent {
3432 KeyEvent::new(KeyCode::Char('d')).with_modifiers(Modifiers::CTRL)
3433 }
3434
3435 fn ctrl_q() -> KeyEvent {
3436 KeyEvent::new(KeyCode::Char('q')).with_modifiers(Modifiers::CTRL)
3437 }
3438
3439 fn idle_state() -> AppState {
3440 AppState::default()
3441 }
3442
3443 fn input_state() -> AppState {
3444 AppState::new().with_input(true)
3445 }
3446
3447 fn task_state() -> AppState {
3448 AppState::new().with_task(true)
3449 }
3450
3451 fn modal_state() -> AppState {
3452 AppState::new().with_modal(true)
3453 }
3454
3455 fn overlay_state() -> AppState {
3456 AppState::new().with_overlay(true)
3457 }
3458
3459 #[test]
3462 fn test_ctrl_c_clears_nonempty_input() {
3463 let mut mapper = ActionMapper::with_defaults();
3464 let t = now();
3465
3466 let action = mapper.map(&ctrl_c(), &input_state(), t);
3467 assert_eq!(action, [Action::ClearInput]);
3468 }
3469
3470 #[test]
3471 fn test_ctrl_c_cancels_running_task() {
3472 let mut mapper = ActionMapper::with_defaults();
3473 let t = now();
3474
3475 let action = mapper.map(&ctrl_c(), &task_state(), t);
3476 assert_eq!(action, [Action::CancelTask]);
3477 }
3478
3479 #[test]
3480 fn test_ctrl_c_quits_when_idle() {
3481 let mut mapper = ActionMapper::with_defaults();
3482 let t = now();
3483
3484 let action = mapper.map(&ctrl_c(), &idle_state(), t);
3485 assert_eq!(action, [Action::Quit]);
3486 }
3487
3488 #[test]
3489 fn test_ctrl_c_dismisses_modal() {
3490 let mut mapper = ActionMapper::with_defaults();
3491 let t = now();
3492
3493 let action = mapper.map(&ctrl_c(), &modal_state(), t);
3494 assert_eq!(action, [Action::DismissModal]);
3495 }
3496
3497 #[test]
3498 fn test_ctrl_c_modal_priority_over_input() {
3499 let mut mapper = ActionMapper::with_defaults();
3500 let t = now();
3501
3502 let state = AppState::new().with_modal(true).with_input(true);
3504 let action = mapper.map(&ctrl_c(), &state, t);
3505 assert_eq!(action, [Action::DismissModal]);
3506 }
3507
3508 #[test]
3509 fn test_ctrl_c_input_priority_over_task() {
3510 let mut mapper = ActionMapper::with_defaults();
3511 let t = now();
3512
3513 let state = AppState::new().with_input(true).with_task(true);
3514 let action = mapper.map(&ctrl_c(), &state, t);
3515 assert_eq!(action, [Action::ClearInput]);
3516 }
3517
3518 #[test]
3519 fn test_ctrl_c_idle_config_noop() {
3520 let config = ActionConfig::default().with_ctrl_c_idle(CtrlCIdleAction::Noop);
3521 let mut mapper = ActionMapper::new(config);
3522 let t = now();
3523
3524 let action = mapper.map(&ctrl_c(), &idle_state(), t);
3525 assert!(action.is_empty(), "Noop resolves to no action: {action:?}");
3526 }
3527
3528 #[test]
3529 fn test_ctrl_c_idle_config_bell() {
3530 let config = ActionConfig::default().with_ctrl_c_idle(CtrlCIdleAction::Bell);
3531 let mut mapper = ActionMapper::new(config);
3532 let t = now();
3533
3534 let action = mapper.map(&ctrl_c(), &idle_state(), t);
3535 assert_eq!(action, [Action::Bell]);
3536 }
3537
3538 #[test]
3541 fn test_ctrl_d_soft_quit() {
3542 let mut mapper = ActionMapper::with_defaults();
3543 let t = now();
3544
3545 let action = mapper.map(&ctrl_d(), &idle_state(), t);
3546 assert_eq!(action, [Action::SoftQuit]);
3547 }
3548
3549 #[test]
3550 fn test_ctrl_d_ignores_state() {
3551 let mut mapper = ActionMapper::with_defaults();
3552 let t = now();
3553
3554 let action = mapper.map(&ctrl_d(), &modal_state(), t);
3556 assert_eq!(action, [Action::SoftQuit]);
3557
3558 let action = mapper.map(&ctrl_d(), &input_state(), t);
3559 assert_eq!(action, [Action::SoftQuit]);
3560 }
3561
3562 #[test]
3563 fn test_ctrl_q_hard_quit() {
3564 let mut mapper = ActionMapper::with_defaults();
3565 let t = now();
3566
3567 let action = mapper.map(&ctrl_q(), &idle_state(), t);
3568 assert_eq!(action, [Action::HardQuit]);
3569 }
3570
3571 #[test]
3572 fn test_ctrl_q_ignores_state() {
3573 let mut mapper = ActionMapper::with_defaults();
3574 let t = now();
3575
3576 let action = mapper.map(&ctrl_q(), &modal_state(), t);
3578 assert_eq!(action, [Action::HardQuit]);
3579 }
3580
3581 #[test]
3584 fn test_esc_dismisses_modal() {
3585 let mut mapper = ActionMapper::with_defaults();
3586 let t = now();
3587
3588 let action1 = mapper.map(&esc_press(), &modal_state(), t);
3590 assert!(action1.is_empty(), "a lone Esc waits: {action1:?}");
3591
3592 let action2 = mapper.check_timeout(&modal_state(), t + MS_300);
3594 assert_eq!(action2, Some(Action::DismissModal));
3595 }
3596
3597 #[test]
3598 fn test_esc_clears_input_no_modal() {
3599 let mut mapper = ActionMapper::with_defaults();
3600 let t = now();
3601
3602 mapper.map(&esc_press(), &input_state(), t);
3603 let action = mapper.check_timeout(&input_state(), t + MS_300);
3604 assert_eq!(action, Some(Action::ClearInput));
3605 }
3606
3607 #[test]
3608 fn test_esc_cancels_task_empty_input() {
3609 let mut mapper = ActionMapper::with_defaults();
3610 let t = now();
3611
3612 mapper.map(&esc_press(), &task_state(), t);
3613 let action = mapper.check_timeout(&task_state(), t + MS_300);
3614 assert_eq!(action, Some(Action::CancelTask));
3615 }
3616
3617 #[test]
3618 fn test_esc_closes_overlay() {
3619 let mut mapper = ActionMapper::with_defaults();
3620 let t = now();
3621
3622 mapper.map(&esc_press(), &overlay_state(), t);
3623 let action = mapper.check_timeout(&overlay_state(), t + MS_300);
3624 assert_eq!(action, Some(Action::CloseOverlay));
3625 }
3626
3627 #[test]
3628 fn test_esc_modal_priority_over_overlay() {
3629 let mut mapper = ActionMapper::with_defaults();
3630 let t = now();
3631
3632 let state = AppState::new().with_modal(true).with_overlay(true);
3633 mapper.map(&esc_press(), &state, t);
3634 let action = mapper.check_timeout(&state, t + MS_300);
3635 assert_eq!(action, Some(Action::DismissModal));
3636 }
3637
3638 #[test]
3639 fn test_esc_passthrough_when_idle() {
3640 let mut mapper = ActionMapper::with_defaults();
3641 let t = now();
3642
3643 mapper.map(&esc_press(), &idle_state(), t);
3644 let action = mapper.check_timeout(&idle_state(), t + MS_300);
3645 assert_eq!(action, Some(Action::PassThrough));
3646 }
3647
3648 #[test]
3651 fn test_esc_esc_within_timeout() {
3652 let mut mapper = ActionMapper::with_defaults();
3653 let t = now();
3654
3655 mapper.map(&esc_press(), &idle_state(), t);
3656 let action = mapper.map(&esc_press(), &idle_state(), t + MS_100);
3657 assert_eq!(action, [Action::ToggleTreeView]);
3658 }
3659
3660 #[test]
3661 fn test_esc_esc_ignores_state() {
3662 let mut mapper = ActionMapper::with_defaults();
3663 let t = now();
3664
3665 mapper.map(&esc_press(), &modal_state(), t);
3667 let action = mapper.map(&esc_press(), &modal_state(), t + MS_100);
3668 assert_eq!(action, [Action::ToggleTreeView]);
3669 }
3670
3671 #[test]
3672 fn test_esc_esc_timeout_expired() {
3673 let mut mapper = ActionMapper::with_defaults();
3674 let t = now();
3675
3676 mapper.map(&esc_press(), &input_state(), t);
3677 let action = mapper.map(&esc_press(), &input_state(), t + MS_300);
3679
3680 assert_eq!(action, [Action::ClearInput]);
3682 assert!(mapper.is_pending_esc());
3683 }
3684
3685 #[test]
3688 fn test_esc_then_other_key_keeps_the_key() {
3689 let mut mapper = ActionMapper::with_defaults();
3690 let t = now();
3691
3692 mapper.map(&esc_press(), &input_state(), t);
3693 let action = mapper.map(&key_press(KeyCode::Char('j')), &input_state(), t + MS_50);
3694
3695 assert_eq!(action, [Action::ClearInput, Action::PassThrough]);
3697 assert!(!mapper.is_pending_esc());
3698 }
3699
3700 #[test]
3701 fn test_idle_esc_then_other_key_passes_only_the_key() {
3702 let mut mapper = ActionMapper::with_defaults();
3703 let t = now();
3704
3705 mapper.map(&esc_press(), &idle_state(), t);
3706 let action = mapper.map(&key_press(KeyCode::Char('j')), &idle_state(), t + MS_50);
3707
3708 assert_eq!(action, [Action::PassThrough]);
3710 }
3711
3712 #[test]
3713 fn test_esc_then_policy_key_applies_both_in_order() {
3714 let mut mapper = ActionMapper::with_defaults();
3715 let t = now();
3716
3717 mapper.map(&esc_press(), &overlay_state(), t);
3718 let action = mapper.map(&ctrl_q(), &overlay_state(), t + MS_50);
3719 assert_eq!(action, [Action::CloseOverlay, Action::HardQuit]);
3720
3721 assert_eq!(mapper.check_timeout(&overlay_state(), t + MS_300), None);
3723 }
3724
3725 #[test]
3726 fn test_esc_then_modified_esc_completes_the_sequence() {
3727 let mut mapper = ActionMapper::with_defaults();
3728 let t = now();
3729
3730 mapper.map(&esc_press(), &idle_state(), t);
3731 let shift_esc = KeyEvent::new(KeyCode::Escape).with_modifiers(Modifiers::SHIFT);
3732 let action = mapper.map(&shift_esc, &idle_state(), t + MS_50);
3733 assert_eq!(action, [Action::ToggleTreeView]);
3734 }
3735
3736 #[test]
3739 fn test_regular_key_passthrough() {
3740 let mut mapper = ActionMapper::with_defaults();
3741 let t = now();
3742
3743 let action = mapper.map(&key_press(KeyCode::Char('x')), &idle_state(), t);
3744 assert_eq!(action, [Action::PassThrough]);
3745 }
3746
3747 #[test]
3748 fn test_release_event_passthrough() {
3749 let mut mapper = ActionMapper::with_defaults();
3750 let t = now();
3751
3752 let release = KeyEvent::new(KeyCode::Char('x')).with_kind(KeyEventKind::Release);
3753 let action = mapper.map(&release, &idle_state(), t);
3754 assert_eq!(action, [Action::PassThrough]);
3755 }
3756
3757 #[test]
3760 fn test_app_state_builders() {
3761 let state = AppState::new()
3762 .with_input(true)
3763 .with_task(true)
3764 .with_modal(true)
3765 .with_overlay(true);
3766
3767 assert!(state.input_nonempty);
3768 assert!(state.task_running);
3769 assert!(state.modal_open);
3770 assert!(state.view_overlay);
3771 assert!(!state.is_idle());
3772 }
3773
3774 #[test]
3775 fn test_app_state_is_idle() {
3776 assert!(AppState::default().is_idle());
3777 assert!(!AppState::new().with_input(true).is_idle());
3778 assert!(!AppState::new().with_task(true).is_idle());
3779 assert!(!AppState::new().with_modal(true).is_idle());
3780 assert!(AppState::new().with_overlay(true).is_idle());
3782 }
3783
3784 #[test]
3787 fn test_action_consumes_event() {
3788 assert!(Action::ClearInput.consumes_event());
3789 assert!(Action::CancelTask.consumes_event());
3790 assert!(Action::Quit.consumes_event());
3791 assert!(!Action::PassThrough.consumes_event());
3792 }
3793
3794 #[test]
3795 fn test_action_is_quit() {
3796 assert!(Action::Quit.is_quit());
3797 assert!(Action::SoftQuit.is_quit());
3798 assert!(Action::HardQuit.is_quit());
3799 assert!(!Action::ClearInput.is_quit());
3800 assert!(!Action::PassThrough.is_quit());
3801 }
3802
3803 #[test]
3806 fn test_ctrl_c_idle_action_from_str() {
3807 assert_eq!(
3808 CtrlCIdleAction::from_str_opt("quit"),
3809 Some(CtrlCIdleAction::Quit)
3810 );
3811 assert_eq!(
3812 CtrlCIdleAction::from_str_opt("QUIT"),
3813 Some(CtrlCIdleAction::Quit)
3814 );
3815 assert_eq!(
3816 CtrlCIdleAction::from_str_opt("noop"),
3817 Some(CtrlCIdleAction::Noop)
3818 );
3819 assert_eq!(
3820 CtrlCIdleAction::from_str_opt("none"),
3821 Some(CtrlCIdleAction::Noop)
3822 );
3823 assert_eq!(
3824 CtrlCIdleAction::from_str_opt("ignore"),
3825 Some(CtrlCIdleAction::Noop)
3826 );
3827 assert_eq!(
3828 CtrlCIdleAction::from_str_opt("bell"),
3829 Some(CtrlCIdleAction::Bell)
3830 );
3831 assert_eq!(
3832 CtrlCIdleAction::from_str_opt("beep"),
3833 Some(CtrlCIdleAction::Bell)
3834 );
3835 assert_eq!(CtrlCIdleAction::from_str_opt("invalid"), None);
3836 }
3837
3838 #[test]
3839 fn test_ctrl_c_idle_action_to_action() {
3840 assert_eq!(CtrlCIdleAction::Quit.to_action(), Some(Action::Quit));
3841 assert_eq!(CtrlCIdleAction::Noop.to_action(), None);
3842 assert_eq!(CtrlCIdleAction::Bell.to_action(), Some(Action::Bell));
3843 }
3844
3845 #[test]
3846 fn test_action_config_builder() {
3847 let config = ActionConfig::default()
3848 .with_sequence_config(SequenceConfig::default().with_timeout(MS_100))
3849 .with_ctrl_c_idle(CtrlCIdleAction::Bell);
3850
3851 assert_eq!(config.sequence_config.esc_seq_timeout, MS_100);
3852 assert_eq!(config.ctrl_c_idle_action, CtrlCIdleAction::Bell);
3853 }
3854
3855 #[test]
3858 fn test_mapper_reset() {
3859 let mut mapper = ActionMapper::with_defaults();
3860 let t = now();
3861
3862 mapper.map(&esc_press(), &idle_state(), t);
3863 assert!(mapper.is_pending_esc());
3864
3865 mapper.reset();
3866 assert!(!mapper.is_pending_esc());
3867 }
3868
3869 #[test]
3872 fn test_deterministic_action_mapping() {
3873 let t = now();
3874
3875 let mut m1 = ActionMapper::with_defaults();
3876 let mut m2 = ActionMapper::with_defaults();
3877
3878 let events = [
3879 (ctrl_c(), input_state()),
3880 (ctrl_d(), modal_state()),
3881 (ctrl_q(), idle_state()),
3882 ];
3883
3884 for (event, state) in &events {
3885 let a1 = m1.map(event, state, t);
3886 let a2 = m2.map(event, state, t);
3887 assert_eq!(a1, a2);
3888 }
3889 }
3890
3891 #[test]
3892 fn test_uppercase_ctrl_keys() {
3893 let mut mapper = ActionMapper::with_defaults();
3894 let t = now();
3895
3896 let ctrl_c_upper = KeyEvent::new(KeyCode::Char('C')).with_modifiers(Modifiers::CTRL);
3898 let action = mapper.map(&ctrl_c_upper, &idle_state(), t);
3899 assert_eq!(action, [Action::Quit]);
3900 }
3901
3902 #[test]
3905 fn test_sequence_config_validation_clamps_high_timeout() {
3906 let config = SequenceConfig::default()
3907 .with_timeout(Duration::from_millis(1000)) .validated();
3909
3910 assert_eq!(config.esc_seq_timeout.as_millis(), 400);
3912 }
3913
3914 #[test]
3915 fn test_sequence_config_validation_clamps_low_timeout() {
3916 let config = SequenceConfig::default()
3917 .with_timeout(Duration::from_millis(50)) .validated();
3919
3920 assert_eq!(config.esc_seq_timeout.as_millis(), 150);
3922 }
3923
3924 #[test]
3925 fn test_sequence_config_validation_clamps_high_debounce() {
3926 let config = SequenceConfig::default()
3927 .with_debounce(Duration::from_millis(200)) .validated();
3929
3930 assert_eq!(config.esc_debounce.as_millis(), 100);
3932 }
3933
3934 #[test]
3935 fn test_sequence_config_validation_debounce_not_exceeds_timeout() {
3936 let config = SequenceConfig::default()
3937 .with_timeout(Duration::from_millis(150))
3938 .with_debounce(Duration::from_millis(200)) .validated();
3940
3941 assert!(config.esc_debounce <= config.esc_seq_timeout);
3945 }
3946
3947 #[test]
3948 fn test_sequence_config_is_valid() {
3949 assert!(SequenceConfig::default().is_valid());
3950
3951 let invalid = SequenceConfig::default().with_timeout(Duration::from_millis(500));
3953 assert!(!invalid.is_valid());
3954
3955 assert!(invalid.validated().is_valid());
3957 }
3958
3959 #[test]
3960 fn test_sequence_config_constants() {
3961 assert_eq!(DEFAULT_ESC_SEQ_TIMEOUT_MS, 250);
3963 assert_eq!(MIN_ESC_SEQ_TIMEOUT_MS, 150);
3964 assert_eq!(MAX_ESC_SEQ_TIMEOUT_MS, 400);
3965 assert_eq!(DEFAULT_ESC_DEBOUNCE_MS, 50);
3966 assert_eq!(MIN_ESC_DEBOUNCE_MS, 0);
3967 assert_eq!(MAX_ESC_DEBOUNCE_MS, 100);
3968 }
3969
3970 #[test]
3971 fn test_action_config_validated() {
3972 let config = ActionConfig::default()
3973 .with_sequence_config(
3974 SequenceConfig::default().with_timeout(Duration::from_millis(1000)),
3975 )
3976 .validated();
3977
3978 assert_eq!(config.sequence_config.esc_seq_timeout.as_millis(), 400);
3980 }
3981 }
3982}