Skip to main content

ftui_core/
keybinding.rs

1#![forbid(unsafe_code)]
2
3//! Keybinding sequence detection and action mapping.
4//!
5//! This module implements the keybinding policy specification (bd-2vne.1) for
6//! detecting multi-key sequences like Esc Esc and mapping keys to actions based
7//! on application state.
8//!
9//! # Key Concepts
10//!
11//! - **SequenceDetector**: State machine that detects Esc Esc sequences with
12//!   configurable timeout. Single Esc is emitted after timeout or when another
13//!   key is pressed.
14//!
15//! - **SequenceConfig**: Configuration for sequence detection including timeout
16//!   windows and debounce settings.
17//!
18//! - **ActionMapper**: Maps key events to high-level actions based on application
19//!   state (input buffer, running tasks, modals, overlays). Integrates with
20//!   SequenceDetector to handle Esc sequences.
21//!
22//! - **AppState**: Runtime state flags that affect action resolution.
23//!
24//! - **Action**: High-level commands like ClearInput, CancelTask, ToggleTreeView.
25//!
26//! # State Machine
27//!
28//! ```text
29//!                                     ┌─────────────────────────────────────┐
30//!                                     │                                     │
31//!                                     ▼                                     │
32//! ┌──────────┐   Esc   ┌────────────────────┐  timeout    ┌─────────┐      │
33//! │  Idle    │───────▶│  AwaitingSecondEsc  │────────────▶│ Emit(Esc)│      │
34//! └──────────┘         └────────────────────┘              └─────────┘      │
35//!      ▲                        │                                           │
36//!      │                        │ Esc (within timeout)                      │
37//!      │                        ▼                                           │
38//!      │               ┌─────────────────┐                                  │
39//!      │               │ Emit(EscEsc)    │──────────────────────────────────┘
40//!      │               └─────────────────┘
41//!      │
42//!      │  other key
43//!      └───────────────────────────────────────────────────────────────────
44//! ```
45//!
46//! # Example
47//!
48//! ```
49//! use std::time::{Duration, Instant};
50//! use ftui_core::keybinding::{SequenceDetector, SequenceConfig, SequenceOutput};
51//! use ftui_core::event::{KeyCode, KeyEvent, Modifiers, KeyEventKind};
52//!
53//! let mut detector = SequenceDetector::new(SequenceConfig::default());
54//! let now = Instant::now();
55//!
56//! // First Esc: starts the sequence
57//! let esc = KeyEvent::new(KeyCode::Escape);
58//! let output = detector.feed(&esc, now);
59//! assert!(matches!(output, SequenceOutput::Pending));
60//!
61//! // Second Esc within timeout: emits EscEsc
62//! let later = now + Duration::from_millis(100);
63//! let output = detector.feed(&esc, later);
64//! assert!(matches!(output, SequenceOutput::EscEsc));
65//! ```
66//!
67//! # Action Mapping Example
68//!
69//! ```
70//! use std::time::Instant;
71//! use ftui_core::keybinding::{ActionMapper, ActionConfig, AppState, Action};
72//! use ftui_core::event::{KeyCode, KeyEvent, Modifiers};
73//!
74//! let mut mapper = ActionMapper::new(ActionConfig::default());
75//! let now = Instant::now();
76//!
77//! // Ctrl+C with non-empty input: clears input
78//! let state = AppState { input_nonempty: true, ..Default::default() };
79//! let ctrl_c = KeyEvent::new(KeyCode::Char('c')).with_modifiers(Modifiers::CTRL);
80//! assert_eq!(mapper.map(&ctrl_c, &state, now), [Action::ClearInput]);
81//!
82//! // Ctrl+C with empty input and no task: quits (by default)
83//! let idle_state = AppState::default();
84//! assert_eq!(mapper.map(&ctrl_c, &idle_state, now), [Action::Quit]);
85//! ```
86
87use web_time::{Duration, Instant};
88
89use crate::event::{KeyCode, KeyEvent, KeyEventKind, Modifiers};
90
91// ---------------------------------------------------------------------------
92// Configuration Constants
93// ---------------------------------------------------------------------------
94
95/// Default timeout for detecting Esc Esc sequence.
96pub const DEFAULT_ESC_SEQ_TIMEOUT_MS: u64 = 250;
97
98/// Minimum allowed value for Esc sequence timeout.
99pub const MIN_ESC_SEQ_TIMEOUT_MS: u64 = 150;
100
101/// Maximum allowed value for Esc sequence timeout.
102pub const MAX_ESC_SEQ_TIMEOUT_MS: u64 = 400;
103
104/// Default debounce before emitting single Esc.
105pub const DEFAULT_ESC_DEBOUNCE_MS: u64 = 50;
106
107/// Minimum allowed value for Esc debounce.
108pub const MIN_ESC_DEBOUNCE_MS: u64 = 0;
109
110/// Maximum allowed value for Esc debounce.
111pub const MAX_ESC_DEBOUNCE_MS: u64 = 100;
112
113// ---------------------------------------------------------------------------
114// Configuration
115// ---------------------------------------------------------------------------
116
117/// Configuration for the sequence detector.
118///
119/// # Timing Defaults
120///
121/// | Setting | Default | Range | Description |
122/// |---------|---------|-------|-------------|
123/// | `esc_seq_timeout` | 250ms | 150-400ms | Window for detecting Esc Esc |
124/// | `esc_debounce` | 50ms | 0-100ms | Minimum wait before single Esc |
125///
126/// # Environment Variables
127///
128/// | Variable | Type | Default | Description |
129/// |----------|------|---------|-------------|
130/// | `FTUI_ESC_SEQ_TIMEOUT_MS` | u64 | 250 | Esc Esc detection window |
131/// | `FTUI_ESC_DEBOUNCE_MS` | u64 | 50 | Minimum Esc wait |
132/// | `FTUI_DISABLE_ESC_SEQ` | bool | false | Disable multi-key sequences |
133///
134/// # Example
135///
136/// ```bash
137/// # Faster double-tap detection (200ms window)
138/// export FTUI_ESC_SEQ_TIMEOUT_MS=200
139///
140/// # Disable Esc Esc entirely (for strict terminals)
141/// export FTUI_DISABLE_ESC_SEQ=1
142/// ```
143#[derive(Debug, Clone)]
144pub struct SequenceConfig {
145    /// Maximum gap between Esc presses to detect Esc Esc sequence.
146    /// Default: 250ms.
147    pub esc_seq_timeout: Duration,
148
149    /// Minimum debounce before emitting single Esc.
150    /// Default: 50ms.
151    pub esc_debounce: Duration,
152
153    /// Whether to disable multi-key sequences entirely.
154    /// When true, all Esc keys are immediately emitted as single Esc.
155    /// Default: false.
156    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    /// Create a new config with custom timeout.
171    #[must_use]
172    pub fn with_timeout(mut self, timeout: Duration) -> Self {
173        self.esc_seq_timeout = timeout;
174        self
175    }
176
177    /// Create a new config with custom debounce.
178    #[must_use]
179    pub fn with_debounce(mut self, debounce: Duration) -> Self {
180        self.esc_debounce = debounce;
181        self
182    }
183
184    /// Disable sequence detection (treat all Esc as single).
185    #[must_use]
186    pub fn disable_sequences(mut self) -> Self {
187        self.disable_sequences = true;
188        self
189    }
190
191    /// Load config from environment variables.
192    ///
193    /// Reads:
194    /// - `FTUI_ESC_SEQ_TIMEOUT_MS`: Esc Esc detection window in milliseconds
195    /// - `FTUI_ESC_DEBOUNCE_MS`: Minimum Esc wait in milliseconds
196    /// - `FTUI_DISABLE_ESC_SEQ`: Set to "1" or "true" to disable sequences
197    ///
198    /// Values are automatically clamped to valid ranges.
199    #[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    /// Validate and clamp values to safe ranges.
223    ///
224    /// Returns a new config with:
225    /// - `esc_seq_timeout` clamped to 150-400ms
226    /// - `esc_debounce` clamped to 0-100ms
227    /// - `esc_debounce` <= `esc_seq_timeout` (debounce is capped at timeout)
228    ///
229    /// # Example
230    ///
231    /// ```
232    /// use ftui_core::keybinding::SequenceConfig;
233    /// use std::time::Duration;
234    ///
235    /// let config = SequenceConfig::default()
236    ///     .with_timeout(Duration::from_millis(1000))  // Too high
237    ///     .validated();
238    ///
239    /// // Clamped to max 400ms
240    /// assert_eq!(config.esc_seq_timeout.as_millis(), 400);
241    /// ```
242    #[must_use]
243    pub fn validated(mut self) -> Self {
244        // Clamp timeout to valid range
245        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        // Clamp debounce to valid range
250        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        // Ensure debounce <= timeout (debounce shouldn't exceed the timeout window)
254        let final_debounce = clamped_debounce.min(clamped_timeout);
255        self.esc_debounce = Duration::from_millis(final_debounce);
256
257        self
258    }
259
260    /// Check if values are within valid ranges.
261    #[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// ---------------------------------------------------------------------------
273// Sequence Output
274// ---------------------------------------------------------------------------
275
276/// Output from the sequence detector after processing a key event.
277#[derive(Debug, Clone, Copy, PartialEq, Eq)]
278pub enum SequenceOutput {
279    /// No action yet; waiting for timeout or more input.
280    Pending,
281
282    /// Single Escape key was detected.
283    Esc,
284
285    /// Double Escape (Esc Esc) sequence was detected.
286    EscEsc,
287
288    /// Pass through the original key event (not part of a sequence).
289    PassThrough,
290}
291
292// ---------------------------------------------------------------------------
293// Sequence Detector
294// ---------------------------------------------------------------------------
295
296/// Internal state of the sequence detector.
297#[derive(Debug, Clone, Copy, PartialEq, Eq)]
298enum DetectorState {
299    /// Idle: waiting for input.
300    Idle,
301
302    /// First Esc received; waiting for second or timeout.
303    AwaitingSecondEsc { first_esc_time: Instant },
304}
305
306/// Stateful detector for multi-key sequences (currently Esc Esc).
307///
308/// This detector transforms a stream of [`KeyEvent`]s into [`SequenceOutput`]s,
309/// detecting Esc Esc sequences with configurable timeout handling.
310///
311/// # Usage
312///
313/// Call [`feed`](SequenceDetector::feed) for each key event. The detector returns:
314/// - `Pending`: First Esc received, waiting for more input or timeout.
315/// - `Esc`: Single Esc was detected (after timeout or other key).
316/// - `EscEsc`: Double Esc sequence was detected.
317/// - `PassThrough`: Key is not Esc, pass through to normal handling.
318///
319/// Call [`check_timeout`](SequenceDetector::check_timeout) periodically (e.g., on
320/// tick) to emit pending single Esc after timeout expires.
321#[derive(Debug)]
322pub struct SequenceDetector {
323    config: SequenceConfig,
324    state: DetectorState,
325}
326
327impl SequenceDetector {
328    /// Create a new sequence detector with the given configuration.
329    #[must_use]
330    pub fn new(config: SequenceConfig) -> Self {
331        Self {
332            config,
333            state: DetectorState::Idle,
334        }
335    }
336
337    /// Create a new sequence detector with default configuration.
338    #[must_use]
339    pub fn with_defaults() -> Self {
340        Self::new(SequenceConfig::default())
341    }
342
343    /// Process a key event and return the sequence output.
344    ///
345    /// Only key press events are considered; repeat and release are ignored.
346    pub fn feed(&mut self, event: &KeyEvent, now: Instant) -> SequenceOutput {
347        // Only process press events
348        if event.kind != KeyEventKind::Press {
349            return SequenceOutput::PassThrough;
350        }
351
352        // If sequences are disabled, handle Esc immediately
353        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                    // First Esc: transition to awaiting second
365                    self.state = DetectorState::AwaitingSecondEsc {
366                        first_esc_time: now,
367                    };
368                    SequenceOutput::Pending
369                } else {
370                    // Non-Esc key: pass through
371                    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                    // Second Esc received
380                    if elapsed <= self.config.esc_seq_timeout {
381                        // Within timeout: emit EscEsc
382                        self.state = DetectorState::Idle;
383                        SequenceOutput::EscEsc
384                    } else {
385                        // Past timeout: first Esc already timed out, this starts new
386                        self.state = DetectorState::AwaitingSecondEsc {
387                            first_esc_time: now,
388                        };
389                        SequenceOutput::Esc
390                    }
391                } else {
392                    // Other key received: emit pending Esc, then pass through
393                    // The caller should handle the Esc first, then re-feed this key
394                    self.state = DetectorState::Idle;
395                    // Return Esc; caller must re-feed the current key
396                    SequenceOutput::Esc
397                }
398            }
399        }
400    }
401
402    /// Check for timeout and emit pending Esc if expired.
403    ///
404    /// Call this periodically (e.g., on tick) to handle the case where
405    /// the user pressed Esc once and is waiting.
406    ///
407    /// Returns `Some(SequenceOutput::Esc)` if timeout expired,
408    /// `None` otherwise.
409    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    /// Whether the detector is waiting for a second Esc.
421    #[must_use]
422    pub fn is_pending(&self) -> bool {
423        matches!(self.state, DetectorState::AwaitingSecondEsc { .. })
424    }
425
426    /// Reset the detector to idle state.
427    ///
428    /// Any pending Esc is discarded.
429    pub fn reset(&mut self) {
430        self.state = DetectorState::Idle;
431    }
432
433    /// Get a reference to the current configuration.
434    #[must_use]
435    pub fn config(&self) -> &SequenceConfig {
436        &self.config
437    }
438
439    /// Update the configuration.
440    ///
441    /// Does not reset pending state.
442    pub fn set_config(&mut self, config: SequenceConfig) {
443        self.config = config;
444    }
445}
446
447// ---------------------------------------------------------------------------
448// Application State
449// ---------------------------------------------------------------------------
450
451/// Runtime state flags that affect keybinding resolution.
452///
453/// These flags are queried at the moment a key event is resolved to an action.
454/// The priority of actions changes based on these flags per the policy spec.
455#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
456pub struct AppState {
457    /// True if the text input buffer contains characters.
458    pub input_nonempty: bool,
459
460    /// True if a background task/command is executing.
461    pub task_running: bool,
462
463    /// True if a modal dialog or overlay is visible.
464    pub modal_open: bool,
465
466    /// True if a secondary view (tree, debug, HUD) is active.
467    pub view_overlay: bool,
468}
469
470impl AppState {
471    /// Create a new state with all flags false.
472    #[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    /// Set input_nonempty flag.
483    #[must_use]
484    pub const fn with_input(mut self, nonempty: bool) -> Self {
485        self.input_nonempty = nonempty;
486        self
487    }
488
489    /// Set task_running flag.
490    #[must_use]
491    pub const fn with_task(mut self, running: bool) -> Self {
492        self.task_running = running;
493        self
494    }
495
496    /// Set modal_open flag.
497    #[must_use]
498    pub const fn with_modal(mut self, open: bool) -> Self {
499        self.modal_open = open;
500        self
501    }
502
503    /// Set view_overlay flag.
504    #[must_use]
505    pub const fn with_overlay(mut self, active: bool) -> Self {
506        self.view_overlay = active;
507        self
508    }
509
510    /// Check if in idle state (no input, no task, no modal).
511    #[must_use]
512    pub const fn is_idle(&self) -> bool {
513        !self.input_nonempty && !self.task_running && !self.modal_open
514    }
515}
516
517// ---------------------------------------------------------------------------
518// Actions
519// ---------------------------------------------------------------------------
520
521/// High-level actions that can result from keybinding resolution.
522///
523/// These actions are returned by the [`ActionMapper`] and should be handled
524/// by the application's event loop.
525#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
526pub enum Action {
527    /// Empty the input buffer, keep cursor at start.
528    ClearInput,
529
530    /// Send cancel signal to running task, update status.
531    CancelTask,
532
533    /// Close topmost modal, return focus to parent.
534    DismissModal,
535
536    /// Deactivate view overlay (tree view, debug HUD).
537    CloseOverlay,
538
539    /// Toggle the tree/file view overlay.
540    ToggleTreeView,
541
542    /// Clean exit via quit command.
543    Quit,
544
545    /// Quit if idle, otherwise cancel current operation.
546    SoftQuit,
547
548    /// Immediate quit (bypass confirmation if any).
549    HardQuit,
550
551    /// Emit terminal bell (BEL character).
552    Bell,
553
554    /// Forward event to focused widget/input.
555    ///
556    /// This indicates the key should be passed through to normal input handling.
557    PassThrough,
558}
559
560impl Action {
561    /// Check if this action consumes the event (vs passing through).
562    #[must_use]
563    pub const fn consumes_event(&self) -> bool {
564        !matches!(self, Action::PassThrough)
565    }
566
567    /// Check if this is a quit-related action.
568    #[must_use]
569    pub const fn is_quit(&self) -> bool {
570        matches!(self, Action::Quit | Action::SoftQuit | Action::HardQuit)
571    }
572}
573
574// ---------------------------------------------------------------------------
575// Ctrl+C Idle Action
576// ---------------------------------------------------------------------------
577
578/// Behavior when Ctrl+C is pressed with empty input and no running task.
579#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
580pub enum CtrlCIdleAction {
581    /// Exit the application.
582    #[default]
583    Quit,
584
585    /// Do nothing.
586    Noop,
587
588    /// Emit terminal bell (BEL).
589    Bell,
590}
591
592impl CtrlCIdleAction {
593    /// Parse from string (environment variable value).
594    #[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    /// Convert to the corresponding Action (or None for Noop).
605    #[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// ---------------------------------------------------------------------------
616// Action Configuration
617// ---------------------------------------------------------------------------
618
619/// Configuration for action mapping behavior.
620///
621/// This struct combines sequence detection settings with keybinding behavior
622/// configuration. It controls how keys like Ctrl+C, Ctrl+D, Esc, and Esc Esc
623/// are interpreted based on application state.
624///
625/// # Environment Variables
626///
627/// | Variable | Type | Default | Description |
628/// |----------|------|---------|-------------|
629/// | `FTUI_CTRL_C_IDLE_ACTION` | string | "quit" | Action when Ctrl+C in idle state |
630/// | `FTUI_ESC_SEQ_TIMEOUT_MS` | u64 | 250 | Esc Esc detection window |
631/// | `FTUI_ESC_DEBOUNCE_MS` | u64 | 50 | Minimum Esc wait |
632/// | `FTUI_DISABLE_ESC_SEQ` | bool | false | Disable Esc Esc sequences |
633///
634/// # Example: Configure via environment
635///
636/// ```bash
637/// # Make Ctrl+C do nothing when idle (instead of quit)
638/// export FTUI_CTRL_C_IDLE_ACTION=noop
639///
640/// # Or make it beep
641/// export FTUI_CTRL_C_IDLE_ACTION=bell
642///
643/// # Faster double-Esc detection
644/// export FTUI_ESC_SEQ_TIMEOUT_MS=200
645/// ```
646///
647/// # Example: Configure in code
648///
649/// ```
650/// use ftui_core::keybinding::{ActionConfig, CtrlCIdleAction, SequenceConfig};
651/// use std::time::Duration;
652///
653/// let config = ActionConfig::default()
654///     .with_ctrl_c_idle(CtrlCIdleAction::Bell)
655///     .with_sequence_config(
656///         SequenceConfig::default()
657///             .with_timeout(Duration::from_millis(200))
658///     );
659/// ```
660#[derive(Debug, Clone)]
661pub struct ActionConfig {
662    /// Sequence detection configuration (timeouts, debounce, disable flag).
663    pub sequence_config: SequenceConfig,
664
665    /// Action when Ctrl+C pressed with empty input and no task.
666    ///
667    /// - `Quit` (default): Exit the application
668    /// - `Noop`: Do nothing
669    /// - `Bell`: Emit terminal bell
670    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    /// Create config with custom sequence settings.
684    #[must_use]
685    pub fn with_sequence_config(mut self, config: SequenceConfig) -> Self {
686        self.sequence_config = config;
687        self
688    }
689
690    /// Set Ctrl+C idle action.
691    #[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    /// Load config from environment variables.
698    ///
699    /// Reads:
700    /// - `FTUI_CTRL_C_IDLE_ACTION`: "quit", "noop", or "bell"
701    /// - Plus all environment variables from [`SequenceConfig::from_env`]
702    #[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    /// Validate and return a config with clamped sequence values.
719    ///
720    /// Delegates to [`SequenceConfig::validated`] for timing bounds.
721    #[must_use]
722    pub fn validated(mut self) -> Self {
723        self.sequence_config = self.sequence_config.validated();
724        self
725    }
726}
727
728// ---------------------------------------------------------------------------
729// Action Mapper
730// ---------------------------------------------------------------------------
731
732/// Maps key events to high-level actions based on application state.
733///
734/// The `ActionMapper` integrates the sequence detector and implements the
735/// priority table from the keybinding policy specification (bd-2vne.1).
736///
737/// # Priority Order
738///
739/// Actions are resolved in priority order (first match wins):
740///
741/// | Priority | Condition | Key | Action |
742/// |----------|-----------|-----|--------|
743/// | 1 | `modal_open` | Esc | DismissModal |
744/// | 2 | `modal_open` | Ctrl+C | DismissModal |
745/// | 3 | `input_nonempty` | Ctrl+C | ClearInput |
746/// | 4 | `task_running` | Ctrl+C | CancelTask |
747/// | 5 | idle | Ctrl+C | Quit (configurable) |
748/// | 6 | `view_overlay` | Esc | CloseOverlay |
749/// | 7 | `input_nonempty` | Esc | ClearInput |
750/// | 8 | `task_running` | Esc | CancelTask |
751/// | 9 | always | Esc Esc | ToggleTreeView |
752/// | 10 | always | Ctrl+D | SoftQuit |
753/// | 11 | always | Ctrl+Q | HardQuit |
754///
755/// # Usage
756///
757/// ```
758/// use std::time::Instant;
759/// use ftui_core::keybinding::{ActionMapper, ActionConfig, AppState, Action};
760/// use ftui_core::event::{KeyCode, KeyEvent, Modifiers};
761///
762/// let mut mapper = ActionMapper::new(ActionConfig::default());
763/// let now = Instant::now();
764/// let state = AppState::default();
765///
766/// let key = KeyEvent::new(KeyCode::Char('q')).with_modifiers(Modifiers::CTRL);
767/// assert_eq!(mapper.map(&key, &state, now), [Action::HardQuit]);
768/// ```
769#[derive(Debug)]
770pub struct ActionMapper {
771    config: ActionConfig,
772    sequence_detector: SequenceDetector,
773}
774
775impl ActionMapper {
776    /// Create a new action mapper with the given configuration.
777    #[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    /// Create a new action mapper with default configuration.
787    #[must_use]
788    pub fn with_defaults() -> Self {
789        Self::new(ActionConfig::default())
790    }
791
792    /// Create a new action mapper loading config from environment.
793    #[must_use]
794    pub fn from_env() -> Self {
795        Self::new(ActionConfig::from_env())
796    }
797
798    /// Map a key event to the actions it resolves to, in the order to apply them.
799    ///
800    /// Usually one action. Empty while a lone Esc waits for a possible second
801    /// Esc (drive [`check_timeout`](Self::check_timeout) on ticks), or when the
802    /// resolved action is a no-op (e.g. Ctrl+C when idle with
803    /// [`CtrlCIdleAction::Noop`]). Two when the key interrupts a pending Esc
804    /// that has an action in `state`: the Esc's action first, then this key's
805    /// own; both are resolved against the same `state`. An Esc with no action
806    /// (idle) contributes nothing, as it does on timeout, so
807    /// [`Action::PassThrough`] always means: handle `event` itself.
808    ///
809    /// # Arguments
810    ///
811    /// * `event` - The key event to process
812    /// * `state` - Current application state flags
813    /// * `now` - Current timestamp for sequence detection
814    pub fn map(&mut self, event: &KeyEvent, state: &AppState, now: Instant) -> Vec<Action> {
815        // Only process press events
816        if event.kind != KeyEventKind::Press {
817            return vec![Action::PassThrough];
818        }
819
820        // Handle Escape through sequence detector
821        if event.code == KeyCode::Escape && event.modifiers == Modifiers::NONE {
822            return self.handle_esc_sequence(state, now).into_iter().collect();
823        }
824
825        // Any other key ends a pending Esc, which takes effect first: "emit
826        // pending Esc first, then process" (keybinding policy).
827        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            // The detector ignores modifiers: a modified Esc that completes
837            // `Esc Esc` belongs to the sequence and has no action of its own.
838            SequenceOutput::EscEsc => return vec![Action::ToggleTreeView],
839            SequenceOutput::Pending | SequenceOutput::PassThrough => {}
840        }
841
842        // Ctrl+C, Ctrl+D and Ctrl+Q have policy actions; other keys pass through.
843        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    /// Handle Escape key through the sequence detector.
859    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                // First Esc received, waiting for second
866                // Don't emit action yet; the event loop should call check_timeout
867                None
868            }
869            SequenceOutput::Esc => {
870                // Single Esc detected (either timeout or past timeout second Esc)
871                self.resolve_single_esc(state)
872            }
873            SequenceOutput::EscEsc => {
874                // Double Esc sequence detected
875                Some(Action::ToggleTreeView)
876            }
877            SequenceOutput::PassThrough => {
878                // Should not happen for Esc
879                Some(Action::PassThrough)
880            }
881        }
882    }
883
884    /// Resolve Ctrl+C based on state.
885    fn resolve_ctrl_c(&self, state: &AppState) -> Option<Action> {
886        // Priority 2: modal_open -> DismissModal
887        if state.modal_open {
888            return Some(Action::DismissModal);
889        }
890
891        // Priority 3: input_nonempty -> ClearInput
892        if state.input_nonempty {
893            return Some(Action::ClearInput);
894        }
895
896        // Priority 4: task_running -> CancelTask
897        if state.task_running {
898            return Some(Action::CancelTask);
899        }
900
901        // Priority 5: idle -> configurable action
902        self.config.ctrl_c_idle_action.to_action()
903    }
904
905    /// Resolve single Esc based on state.
906    fn resolve_single_esc(&self, state: &AppState) -> Option<Action> {
907        // Priority 1: modal_open -> DismissModal
908        if state.modal_open {
909            return Some(Action::DismissModal);
910        }
911
912        // Priority 6: view_overlay -> CloseOverlay
913        if state.view_overlay {
914            return Some(Action::CloseOverlay);
915        }
916
917        // Priority 7: input_nonempty -> ClearInput
918        if state.input_nonempty {
919            return Some(Action::ClearInput);
920        }
921
922        // Priority 8: task_running -> CancelTask
923        if state.task_running {
924            return Some(Action::CancelTask);
925        }
926
927        // No action for Esc in idle state
928        Some(Action::PassThrough)
929    }
930
931    /// Check for sequence timeout and return pending action if expired.
932    ///
933    /// Call this periodically (e.g., on tick) to handle single Esc after
934    /// the timeout window closes.
935    ///
936    /// # Arguments
937    ///
938    /// * `state` - Current application state flags
939    /// * `now` - Current timestamp
940    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    /// Whether the mapper is waiting for a second Esc.
948    #[must_use]
949    pub fn is_pending_esc(&self) -> bool {
950        self.sequence_detector.is_pending()
951    }
952
953    /// Reset the sequence detector state.
954    ///
955    /// Any pending Esc is discarded.
956    pub fn reset(&mut self) {
957        self.sequence_detector.reset();
958    }
959
960    /// Get a reference to the current configuration.
961    #[must_use]
962    pub fn config(&self) -> &ActionConfig {
963        &self.config
964    }
965
966    /// Update the configuration.
967    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
974// ---------------------------------------------------------------------------
975// Tests
976// ---------------------------------------------------------------------------
977
978// ===========================================================================
979// Declarative keymaps: combos, chords, priorities, contexts, conflict
980// detection, and a chord-aware dispatcher
981// ===========================================================================
982//
983// Resolution order, in prose (the keybinding policy spec copies this):
984//
985// 1. A key press extends the pending prefix. If the extended chord is bound
986//    and no longer bound chord starts with it, the binding fires at once.
987//    If a longer bound chord starts with it (`g` while `g g` is bound), the
988//    dispatcher waits: the exact binding fires on the chord timeout or when a
989//    key arrives that cannot extend the chord, so single-key shortcuts are
990//    never blocked, only delayed while a real chord is possible.
991// 2. A key that cannot extend the pending prefix flushes it (the prefix
992//    fires if it is bound, otherwise it is reported as expired) and is then
993//    processed on its own.
994// 3. Among bindings for the same chord, one attached to an active context
995//    beats a context-free one, then the higher `Priority` wins, then the most
996//    recently bound. `KeyMap::conflicts` reports every case that needs the
997//    tie-break so shadowing is visible instead of silent.
998// 4. `Repeat` events re-fire a single-key binding but never extend a chord;
999//    `Release` events are reported as unbound.
1000// 5. `Esc` goes through the embedded `SequenceDetector` (one Esc timer per
1001//    dispatcher); `Esc` and `Esc Esc` can be bound like any chord.
1002
1003use std::fmt;
1004use std::str::FromStr;
1005
1006/// Why a key, combo, or chord string could not be parsed.
1007#[derive(Debug, Clone, PartialEq, Eq)]
1008pub enum KeyParseError {
1009    /// The key name (or the whole chord) was empty.
1010    EmptyKey,
1011    /// A key name that matches no [`KeyCode`].
1012    UnknownKey(String),
1013    /// A modifier name other than `Ctrl`, `Alt`, `Shift`, `Super`.
1014    UnknownModifier(String),
1015    /// More than [`Chord::MAX_LEN`] combos in one chord.
1016    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/// A single key press with its modifiers (`Ctrl+x`, `Shift+Tab`, `F12`, `g`).
1035///
1036/// Combos are normalized so that `Shift+a`, `A`, and a terminal that reports
1037/// `Char('A')` with the Shift bit all compare equal: alphabetic characters
1038/// are stored lowercase with [`Modifiers::SHIFT`] set.
1039#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1040pub struct KeyCombo {
1041    /// The key.
1042    pub code: KeyCode,
1043    /// Modifier keys held.
1044    pub modifiers: Modifiers,
1045}
1046
1047impl KeyCombo {
1048    /// Build a normalized combo.
1049    #[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    /// A combo without modifiers.
1061    #[must_use]
1062    pub fn key(code: KeyCode) -> Self {
1063        Self::new(code, Modifiers::NONE)
1064    }
1065
1066    /// The combo a key event represents (its kind is ignored).
1067    #[must_use]
1068    pub fn from_event(event: &KeyEvent) -> Self {
1069        Self::new(event.code, event.modifiers)
1070    }
1071
1072    /// Whether `event` presses this combo (any kind).
1073    #[must_use]
1074    pub fn matches(&self, event: &KeyEvent) -> bool {
1075        Self::from_event(event) == *self
1076    }
1077}
1078
1079/// Whether writing `c` uppercased is a faithful way to spell its SHIFT.
1080///
1081/// [`KeyCombo::new`] canonicalizes an uppercase letter to lowercase plus
1082/// SHIFT, and [`Display`](fmt::Display) inverts that by uppercasing and
1083/// dropping the modifier. The inverse only exists when uppercasing gives
1084/// exactly one character, different from `c`, that lowercases back to it.
1085/// Three kinds of letter break it, and `is_alphabetic()` admits all three:
1086///
1087/// - Caseless ones. `中` uppercases to itself, so the SHIFT simply vanished
1088///   and `Shift+中` printed as `中`.
1089/// - Ones whose uppercase is several characters. `ß` uppercases to `SS`,
1090///   which is not a key name, so `Shift+ß` printed as `SS` and no longer
1091///   parsed at all.
1092/// - Ones that do not lowercase back. `ı` uppercases to `I`, which
1093///   lowercases to `i`, so the round trip would land on the wrong letter.
1094///
1095/// In each case SHIFT stays a modifier and the letter is printed as itself.
1096fn 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
1150/// Parse a key name: a single character, or a named key (case-insensitive:
1151/// `Enter`, `Esc`, `Tab`, `BackTab`, `Backspace`, `Delete`, `Insert`, `Home`,
1152/// `End`, `PageUp`, `PageDown`, `Up`, `Down`, `Left`, `Right`, `Space`,
1153/// `F1`..`F24`, media keys).
1154fn 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    /// Parse `Ctrl+x`, `Shift+Tab`, `F12`, `g`, `Ctrl++` (the plus key).
1200    /// Modifier names are case-insensitive (`Ctrl`/`Control`, `Alt`/`Opt`/
1201    /// `Option`, `Shift`, `Super`/`Cmd`/`Meta`/`Win`).
1202    fn from_str(s: &str) -> Result<Self, Self::Err> {
1203        // Only ASCII whitespace pads a binding in a config file. `trim()`
1204        // takes Unicode whitespace too, which ate the key itself whenever the
1205        // key *was* one: macOS sends U+00A0 for Option+Space, and
1206        // `"Alt+\u{a0}"` trimmed to `"Alt+"`, which the trailing-plus branch
1207        // below then read as the plus key. A bare `"\u{a0}"` trimmed to
1208        // nothing and failed as an empty key.
1209        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/// One to [`Chord::MAX_LEN`] combos pressed in sequence (`g g`, `Ctrl+x Ctrl+s`).
1240#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1241pub struct Chord(Vec<KeyCombo>);
1242
1243impl Chord {
1244    /// Longest supported chord.
1245    pub const MAX_LEN: usize = 4;
1246
1247    /// A one-combo chord.
1248    #[must_use]
1249    pub fn single(combo: KeyCombo) -> Self {
1250        Self(vec![combo])
1251    }
1252
1253    /// Build a chord from combos (1..=[`Chord::MAX_LEN`]).
1254    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    /// Parse a whitespace-separated chord such as `"g g"` or `"Ctrl+x Ctrl+s"`.
1265    pub fn parse(s: &str) -> Result<Self, KeyParseError> {
1266        s.parse()
1267    }
1268
1269    /// The combos in order.
1270    #[must_use]
1271    pub fn combos(&self) -> &[KeyCombo] {
1272        &self.0
1273    }
1274
1275    /// Number of combos.
1276    #[must_use]
1277    pub fn len(&self) -> usize {
1278        self.0.len()
1279    }
1280
1281    /// Never true for a chord built through the constructors; provided for
1282    /// API completeness.
1283    #[must_use]
1284    pub fn is_empty(&self) -> bool {
1285        self.0.is_empty()
1286    }
1287
1288    /// Whether this chord is a strict prefix of `other` (`g` of `g g`).
1289    #[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/// Binding priority level; higher wins for the same chord.
1320#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
1321#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1322pub enum Priority {
1323    /// Application-wide default.
1324    #[default]
1325    Global = 0,
1326    /// Active when the app is in a particular mode.
1327    Mode = 1,
1328    /// Owned by the focused widget.
1329    Widget = 2,
1330}
1331
1332/// An interned context name (see [`KeyMap::context`]).
1333#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1334pub struct ContextId(pub u32);
1335
1336/// Identifier of one binding inside a [`KeyMap`].
1337#[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/// One chord bound to an action.
1347#[derive(Debug, Clone)]
1348pub struct Binding<A> {
1349    /// Identifier assigned by the map.
1350    pub id: BindingId,
1351    /// The chord that triggers the action.
1352    pub chord: Chord,
1353    /// The action to dispatch.
1354    pub action: A,
1355    /// Priority level.
1356    pub priority: Priority,
1357    /// Context the binding is limited to (`None` = always applicable).
1358    pub context: Option<ContextId>,
1359    /// Human-readable label for help bars and conflict reports.
1360    pub label: Option<String>,
1361}
1362
1363/// Lower bound of the chord timeout (ms).
1364pub const MIN_CHORD_TIMEOUT_MS: u64 = 200;
1365/// Upper bound of the chord timeout (ms).
1366pub const MAX_CHORD_TIMEOUT_MS: u64 = 5000;
1367/// Default chord timeout (ms).
1368pub const DEFAULT_CHORD_TIMEOUT_MS: u64 = 1000;
1369
1370/// Timing configuration of a [`KeyMap`].
1371#[derive(Debug, Clone)]
1372pub struct KeyMapConfig {
1373    /// How long a pending chord prefix waits for its next key.
1374    pub chord_timeout: Duration,
1375    /// Esc / Esc Esc detection settings for the dispatcher's detector.
1376    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    /// Set the chord timeout, clamped to `200..=5000` ms.
1390    #[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    /// Set the Esc sequence configuration.
1401    #[must_use]
1402    pub fn with_esc(mut self, esc: SequenceConfig) -> Self {
1403        self.esc = esc;
1404        self
1405    }
1406}
1407
1408/// Result of [`KeyMap::lookup`].
1409#[derive(Debug, Clone, Copy)]
1410pub struct Lookup<'a, A> {
1411    /// The winning binding for exactly this chord, if any.
1412    pub exact: Option<&'a Binding<A>>,
1413    /// Number of applicable bindings whose chord starts with this chord and
1414    /// is longer (a pending prefix must wait for them).
1415    pub longer: usize,
1416}
1417
1418impl<A> Lookup<'_, A> {
1419    /// Neither an exact binding nor a longer chord.
1420    #[must_use]
1421    pub fn is_none(&self) -> bool {
1422        self.exact.is_none() && self.longer == 0
1423    }
1424}
1425
1426/// A binding conflict found by [`KeyMap::conflicts`].
1427#[derive(Debug, Clone, PartialEq, Eq)]
1428pub enum Conflict {
1429    /// Same chord, same context, different priority: `winner` hides `loser`.
1430    Shadowed {
1431        winner: BindingId,
1432        loser: BindingId,
1433        chord: Chord,
1434    },
1435    /// `short` is a strict prefix of `long`, so `short` fires only after the
1436    /// chord timeout or a non-extending key.
1437    PrefixCollision {
1438        short: BindingId,
1439        long: BindingId,
1440        short_chord: Chord,
1441        long_chord: Chord,
1442    },
1443    /// Same chord, context and priority: the later binding wins.
1444    Duplicate {
1445        first: BindingId,
1446        second: BindingId,
1447        chord: Chord,
1448    },
1449}
1450
1451/// Every conflict in a map, with a one-line warning per item.
1452#[derive(Debug, Clone, Default, PartialEq, Eq)]
1453pub struct ConflictReport {
1454    /// The conflicts, in map order.
1455    pub items: Vec<Conflict>,
1456}
1457
1458impl ConflictReport {
1459    /// No conflicts.
1460    #[must_use]
1461    pub fn is_empty(&self) -> bool {
1462        self.items.is_empty()
1463    }
1464
1465    /// Number of conflicts.
1466    #[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/// A declarative binding map: chords to actions with priorities and
1508/// contexts. Actions are any `Clone` type (usually an app enum).
1509#[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    /// An empty map with default timing.
1525    #[must_use]
1526    pub fn new() -> Self {
1527        Self::with_config(KeyMapConfig::default())
1528    }
1529
1530    /// An empty map with the given timing.
1531    #[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    /// Timing configuration.
1542    #[must_use]
1543    pub fn config(&self) -> &KeyMapConfig {
1544        &self.config
1545    }
1546
1547    /// Intern a context name; the same name always yields the same id.
1548    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    /// Name of an interned context.
1557    #[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    /// Bind a chord at [`Priority::Global`] with no context.
1563    pub fn bind(&mut self, chord: Chord, action: A) -> BindingId {
1564        self.bind_in(chord, action, Priority::Global, None)
1565    }
1566
1567    /// Bind a chord with an explicit priority and optional context.
1568    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    /// Attach a label to a binding; `false` if the id is unknown.
1589    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    /// Remove a binding.
1600    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    /// All bindings in bind order.
1606    #[must_use]
1607    pub fn bindings(&self) -> &[Binding<A>] {
1608        &self.bindings
1609    }
1610
1611    /// A binding by id.
1612    #[must_use]
1613    pub fn get(&self, id: BindingId) -> Option<&Binding<A>> {
1614        self.bindings.iter().find(|b| b.id == id)
1615    }
1616
1617    /// Number of bindings.
1618    #[must_use]
1619    pub fn len(&self) -> usize {
1620        self.bindings.len()
1621    }
1622
1623    /// Whether the map has no bindings.
1624    #[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    /// Ranking used to pick a winner among bindings for the same chord:
1636    /// active context beats none, then priority, then recency.
1637    fn rank(binding: &Binding<A>) -> (bool, Priority, BindingId) {
1638        (binding.context.is_some(), binding.priority, binding.id)
1639    }
1640
1641    /// Resolve `chord` against the bindings applicable under `active`
1642    /// contexts: the winning exact binding and how many longer bound chords
1643    /// start with it.
1644    #[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    /// Report shadowed, duplicate, and prefix-colliding bindings.
1664    #[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                        // A context-specific override is the intended use.
1672                        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/// What the dispatcher decided for one key event or tick.
1714#[derive(Debug, Clone, PartialEq, Eq)]
1715pub enum Dispatch<A> {
1716    /// A binding fired.
1717    Action {
1718        action: A,
1719        binding: BindingId,
1720        chord: Chord,
1721    },
1722    /// The key extended a chord prefix; waiting for more keys or the timeout.
1723    Pending { prefix: Chord },
1724    /// The key matched nothing (and could not extend a chord).
1725    Unbound(KeyEvent),
1726    /// A pending prefix was abandoned (timeout or a non-extending key).
1727    Expired { prefix: Chord },
1728    /// Esc sequence detector output for an unbound Esc / Esc Esc.
1729    Esc(SequenceOutput),
1730}
1731
1732/// Counters for evidence rows and hint-usage feedback.
1733#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1734pub struct DispatchStats {
1735    /// Bindings fired.
1736    pub dispatched: u64,
1737    /// Keys that entered a chord prefix.
1738    pub pending: u64,
1739    /// Prefixes abandoned.
1740    pub expired: u64,
1741    /// Keys that matched nothing.
1742    pub unbound: u64,
1743    /// Esc / Esc Esc verdicts handed back unbound (see [`Dispatch::Esc`]).
1744    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/// Chord-aware dispatcher over a [`KeyMap`].
1756///
1757/// Feed every key event through [`feed`](Self::feed) and call
1758/// [`tick`](Self::tick) once per frame so pending chords and the Esc timer
1759/// expire; every call returns the decisions to act on. See the module
1760/// section header for the resolution rules.
1761#[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    /// A dispatcher over `map` with no active contexts.
1773    #[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    /// The underlying map.
1787    #[must_use]
1788    pub fn map(&self) -> &KeyMap<A> {
1789        &self.map
1790    }
1791
1792    /// Mutable access to the map (rebinding at runtime).
1793    pub fn map_mut(&mut self) -> &mut KeyMap<A> {
1794        &mut self.map
1795    }
1796
1797    /// Replace the set of active contexts (focused widget, mode, ...).
1798    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    /// Currently active contexts.
1804    #[must_use]
1805    pub fn active_contexts(&self) -> &[ContextId] {
1806        &self.active_contexts
1807    }
1808
1809    /// The chord prefix currently waiting for more keys.
1810    #[must_use]
1811    pub fn pending_prefix(&self) -> Option<Chord> {
1812        Chord::new(self.pending.clone()).ok()
1813    }
1814
1815    /// Counters so far.
1816    #[must_use]
1817    pub fn stats(&self) -> DispatchStats {
1818        self.stats
1819    }
1820
1821    /// Drop any pending prefix and Esc state.
1822    pub fn reset(&mut self) {
1823        self.pending.clear();
1824        self.pending_since = None;
1825        self.esc.reset();
1826    }
1827
1828    /// Process one key event.
1829    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                // Repeat / release of Esc: nothing sequence-related to do.
1838                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            // A key that interrupts a lone Esc resolves it now, so the Esc
1846            // takes effect before the key rather than at a later tick.
1847            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                // A held key re-fires its own single-key binding, never a chord.
1859                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        // The key cannot extend the prefix: flush it, then start over with the
1895        // key on its own so it can fire or begin a new chord.
1896        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    /// Expire a pending prefix past the chord timeout and drive the Esc timer.
1909    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    /// Try to treat `combo` as the next key of the pending prefix. Returns
1923    /// `false` when the extended chord matches nothing (nothing is emitted).
1924    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    /// Fire the pending prefix if it is bound, otherwise report it expired;
1953    /// on a timeout the expiry is reported first so the delay is visible.
1954    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    /// Route a detector verdict: a bound `Esc` / `Esc Esc` fires its binding,
1982    /// anything else is handed back as [`Dispatch::Esc`].
1983    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// ---------------------------------------------------------------------------
2010// Serialization (feature `serde`): human-editable keymap files
2011// ---------------------------------------------------------------------------
2012
2013/// On-disk shape of a [`KeyMap`] (feature `serde`): chords as text, contexts
2014/// by name, the chord timeout in milliseconds. Esc timing is not part of the
2015/// file; it follows [`SequenceConfig`] (defaults and `FTUI_DISABLE_ESC_SEQ`).
2016///
2017/// ```toml
2018/// chord_timeout_ms = 750
2019///
2020/// [[bindings]]
2021/// chord = "Ctrl+x Ctrl+s"
2022/// action = "Save"
2023/// priority = "Mode"
2024/// label = "save"
2025///
2026/// [[bindings]]
2027/// chord = "Enter"
2028/// action = "Newline"
2029/// priority = "Widget"
2030/// context = "editor"
2031/// ```
2032#[cfg(feature = "serde")]
2033#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
2034#[serde(deny_unknown_fields)]
2035pub struct KeyMapFile<A> {
2036    /// Chord timeout in milliseconds (clamped to `200..=5000` on load).
2037    #[serde(default = "default_chord_timeout_ms")]
2038    pub chord_timeout_ms: u64,
2039    /// Bindings in bind order.
2040    #[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/// One binding in a [`KeyMapFile`].
2050#[cfg(feature = "serde")]
2051#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
2052#[serde(deny_unknown_fields)]
2053pub struct BindingFile<A> {
2054    /// Chord text, e.g. `"g g"` or `"Ctrl+x Ctrl+s"`.
2055    pub chord: String,
2056    /// The action (any serde type; usually a unit-variant enum).
2057    pub action: A,
2058    /// Priority level (default `Global`).
2059    #[serde(default)]
2060    pub priority: Priority,
2061    /// Context name (default: none).
2062    #[serde(default, skip_serializing_if = "Option::is_none")]
2063    pub context: Option<String>,
2064    /// Help label (default: none).
2065    #[serde(default, skip_serializing_if = "Option::is_none")]
2066    pub label: Option<String>,
2067}
2068
2069/// Why a [`KeyMapFile`] could not become a [`KeyMap`].
2070#[cfg(feature = "serde")]
2071#[derive(Debug, Clone, PartialEq, Eq)]
2072pub enum KeyMapFileError {
2073    /// A binding's chord text did not parse.
2074    Chord {
2075        /// Index of the binding in the file.
2076        index: usize,
2077        /// The offending chord text.
2078        chord: String,
2079        /// Parse error.
2080        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    /// The file representation (contexts by name, chords as text).
2103    #[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    /// Build a map from its file representation, interning context names and
2125    /// parsing chords; a bad chord names the offending binding.
2126    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    /// `Display` folds SHIFT into an uppercase letter, which only works when
2208    /// uppercasing is a faithful single-character inverse. Three classes of
2209    /// letter are not, and `is_alphabetic()` admitted all three.
2210    #[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        // Caseless: `中` uppercases to itself, so the SHIFT used to vanish
2215        // and `Shift+中` printed as plain `中`.
2216        assert_eq!(shifted('中').to_string(), "Shift+中");
2217        // Several characters: `ß` uppercases to `SS`, which printed as `SS`
2218        // and then failed to parse at all.
2219        assert_eq!(shifted('ß').to_string(), "Shift+ß");
2220        // Does not lowercase back: `ı` uppercases to `I`, whose lowercase is
2221        // `i`, so the round trip would have landed on the wrong letter.
2222        assert_eq!(shifted('ı').to_string(), "Shift+ı");
2223        // The ordinary case is unchanged.
2224        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    /// `trim()` takes Unicode whitespace, which ate the key when the key was
2234    /// one. macOS sends U+00A0 for Option+Space.
2235    #[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        // Used to trim to "Alt+" and come back as Alt plus the *plus* key.
2241        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        // A bare one used to trim away to nothing and fail as an empty key.
2248        assert_eq!(
2249            "\u{a0}".parse::<KeyCombo>().unwrap(),
2250            KeyCombo::new(nbsp, Modifiers::NONE)
2251        );
2252        // ASCII padding around a binding is still ignored.
2253        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        // Shift+a, A and a terminal reporting Char('A')+SHIFT are one combo.
2266        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        // The plus key itself.
2285        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        // Prefix that is itself bound: expiry fires it.
2350        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        // Prefix that is not bound: expiry only.
2366        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        // Same with a bound prefix: it fires first, then the single key.
2394        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        // A non-extending key that starts another chord goes pending itself.
2404        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        // `g` is bound both on its own and as the prefix of `g g`. A following
2422        // key that cannot extend the prefix flushes it. Because this is not a
2423        // timeout, the prefix's own binding fires with no `Expired`, and the
2424        // non-extending key is then reported unbound.
2425        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        // Removing the winner promotes the next.
2492        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        // The later duplicate wins at dispatch.
2565        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        // A lone Esc waits for the detector window, then fires its binding.
2609        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        // Esc Esc inside the window fires the double binding.
2616        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        // Esc cancels a pending chord prefix first.
2624        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        // Unbound Esc surfaces the detector verdict.
2631        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    /// A key typed inside the Esc window resolves the lone Esc first, in the
2640    /// same call: modal input (leave insert mode, then move) must not see the
2641    /// key before the Esc, and no Esc may fire later at a tick.
2642    #[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        // Unbound, the Esc verdict still comes first and the key still fires.
2659        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    /// A map round-trips through TOML and JSON with chords as text, contexts
2669    /// by name and the timeout in milliseconds; a bad hand-written chord is
2670    /// reported with its binding index.
2671    #[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    /// Unknown keys in a keymap file are rejected (the typo names itself), and
2738    /// a bad chord names its binding index.
2739    #[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    /// The keymap example embedded in the keybinding policy doc (and shipped as
2772    /// a fixture) parses into exactly the map it describes, so the docs and the
2773    /// parser cannot silently drift apart.
2774    #[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                // Letters where uppercasing is not a faithful inverse of the
2840                // lowercasing `KeyCombo::new` applies, and a space that is
2841                // not the ASCII one. Every one of these broke the round trip
2842                // while the sample above was all ASCII.
2843                'ß',  // uppercases to two characters, `SS`
2844                'ı',  // uppercases to `I`, which lowercases to `i`
2845                '中', // caseless: uppercases to itself
2846                'é', 'İ', '\u{a0}', // Option+Space on macOS
2847            ])
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        /// No key is ever swallowed: every feed yields at least one dispatch,
2927        /// and draining the timers afterwards never panics or leaks a prefix.
2928        #[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        /// `Display` and `FromStr` are inverse over the normalized combo
2955        /// domain: parsing a combo's own text yields the same combo back.
2956        #[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        /// An unambiguous lookup never depends on the order bindings were
2967        /// inserted; only reported conflicts may change a winner.
2968        #[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            // Keep only the first occurrence of each chord: a duplicate is a
2974            // reported conflict, not something lookup must resolve by order.
2975            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    // --- Basic sequence tests ---
3034
3035    #[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        // Exactly at 250ms boundary
3064        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        // Past 250ms timeout (251ms)
3076        let output = detector.feed(&esc_press(), t + Duration::from_millis(251));
3077
3078        // First Esc timed out, second Esc starts new sequence
3079        assert_eq!(output, SequenceOutput::Esc);
3080        assert!(detector.is_pending()); // New sequence started
3081    }
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        // Before timeout
3091        assert!(detector.check_timeout(t + MS_200).is_none());
3092        assert!(detector.is_pending());
3093
3094        // After timeout (251ms)
3095        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        // Pending Esc is emitted
3109        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        // Release is ignored; still pending
3141        assert_eq!(output, SequenceOutput::PassThrough);
3142        assert!(detector.is_pending());
3143    }
3144
3145    // --- Config tests ---
3146
3147    #[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        // 150ms is past 100ms timeout
3155        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        // First Esc immediately emits Esc
3167        let output = detector.feed(&esc_press(), t);
3168        assert_eq!(output, SequenceOutput::Esc);
3169        assert!(!detector.is_pending());
3170
3171        // Second Esc also immediately emits Esc
3172        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    // --- Reset tests ---
3207
3208    #[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        // After reset, new Esc starts fresh
3220        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        // Timeout check should not emit anything
3233        assert!(detector.check_timeout(t + MS_300).is_none());
3234    }
3235
3236    // --- Edge cases ---
3237
3238    #[test]
3239    fn rapid_triple_esc() {
3240        let mut detector = SequenceDetector::with_defaults();
3241        let t = now();
3242
3243        // First Esc
3244        let out1 = detector.feed(&esc_press(), t);
3245        assert_eq!(out1, SequenceOutput::Pending);
3246
3247        // Second Esc -> EscEsc
3248        let out2 = detector.feed(&esc_press(), t + MS_50);
3249        assert_eq!(out2, SequenceOutput::EscEsc);
3250
3251        // Third Esc -> starts new sequence
3252        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        // Esc -> pending
3262        detector.feed(&esc_press(), t);
3263
3264        // 'a' -> emits Esc
3265        let out1 = detector.feed(&key_press(KeyCode::Char('a')), t + MS_50);
3266        assert_eq!(out1, SequenceOutput::Esc);
3267
3268        // Esc -> pending again
3269        let out2 = detector.feed(&esc_press(), t + MS_100);
3270        assert_eq!(out2, SequenceOutput::Pending);
3271
3272        // 'b' -> emits Esc
3273        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        // Change config while pending
3336        detector.set_config(SequenceConfig::default().with_timeout(Duration::from_millis(500)));
3337
3338        // Still pending
3339        assert!(detector.is_pending());
3340
3341        // New timeout applies
3342        let output = detector.feed(&esc_press(), t + MS_300);
3343        assert_eq!(output, SequenceOutput::EscEsc); // Within new 500ms timeout
3344    }
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    // --- Stress / property-like tests ---
3373
3374    #[test]
3375    fn no_stuck_state() {
3376        let mut detector = SequenceDetector::with_defaults();
3377        let t = now();
3378
3379        // Many operations should always return to Idle eventually
3380        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        // Force timeout check - must be well past the last event (990ms) + timeout (250ms)
3390        detector.check_timeout(t + Duration::from_secs(2));
3391
3392        // Should be idle
3393        assert!(!detector.is_pending());
3394    }
3395
3396    #[test]
3397    fn deterministic_output() {
3398        // Same inputs should produce same outputs
3399        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    // =========================================================================
3420    // ActionMapper Tests
3421    // =========================================================================
3422
3423    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        // --- Ctrl+C tests (policy priorities 2-5) ---
3460
3461        #[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            // Both modal and input are set
3503            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        // --- Ctrl+D and Ctrl+Q tests (policy priorities 10-11) ---
3539
3540        #[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            // Ctrl+D always does SoftQuit regardless of state
3555            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            // Ctrl+Q always does HardQuit regardless of state
3577            let action = mapper.map(&ctrl_q(), &modal_state(), t);
3578            assert_eq!(action, [Action::HardQuit]);
3579        }
3580
3581        // --- Esc tests (policy priorities 1, 6-8) ---
3582
3583        #[test]
3584        fn test_esc_dismisses_modal() {
3585            let mut mapper = ActionMapper::with_defaults();
3586            let t = now();
3587
3588            // First Esc: pending
3589            let action1 = mapper.map(&esc_press(), &modal_state(), t);
3590            assert!(action1.is_empty(), "a lone Esc waits: {action1:?}");
3591
3592            // Timeout: emit Esc action
3593            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        // --- Esc Esc tests (policy priority 9) ---
3649
3650        #[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            // Esc Esc always toggles tree view regardless of state
3666            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            // Past 250ms timeout
3678            let action = mapper.map(&esc_press(), &input_state(), t + MS_300);
3679
3680            // First Esc timed out -> ClearInput, second starts new pending
3681            assert_eq!(action, [Action::ClearInput]);
3682            assert!(mapper.is_pending_esc());
3683        }
3684
3685        // --- Esc then other key ---
3686
3687        #[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            // The pending Esc takes effect first, then the key itself.
3696            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            // An idle Esc has no action (as on timeout); PassThrough is the key's.
3709            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            // Nothing is left to fire on a later tick.
3722            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        // --- Other keys passthrough ---
3737
3738        #[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        // --- State helper tests ---
3758
3759        #[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            // view_overlay doesn't affect is_idle
3781            assert!(AppState::new().with_overlay(true).is_idle());
3782        }
3783
3784        // --- Action enum tests ---
3785
3786        #[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        // --- Config tests ---
3804
3805        #[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        // --- Reset tests ---
3856
3857        #[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        // --- Determinism / property tests ---
3870
3871        #[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            // Ctrl+C with uppercase 'C' should also work
3897            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        // --- Validation tests ---
3903
3904        #[test]
3905        fn test_sequence_config_validation_clamps_high_timeout() {
3906            let config = SequenceConfig::default()
3907                .with_timeout(Duration::from_millis(1000)) // Too high
3908                .validated();
3909
3910            // Should clamp to MAX_ESC_SEQ_TIMEOUT_MS (400ms)
3911            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)) // Too low
3918                .validated();
3919
3920            // Should clamp to MIN_ESC_SEQ_TIMEOUT_MS (150ms)
3921            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)) // Too high
3928                .validated();
3929
3930            // Should clamp to MAX_ESC_DEBOUNCE_MS (100ms)
3931            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)) // Higher than timeout
3939                .validated();
3940
3941            // Debounce should be clamped to min(100, 150) = 100,
3942            // but also can't exceed timeout (150)
3943            // Since debounce max is 100 and timeout is 150, debounce = 100
3944            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            // Invalid: timeout too high
3952            let invalid = SequenceConfig::default().with_timeout(Duration::from_millis(500));
3953            assert!(!invalid.is_valid());
3954
3955            // Valid after validation
3956            assert!(invalid.validated().is_valid());
3957        }
3958
3959        #[test]
3960        fn test_sequence_config_constants() {
3961            // Verify constants match spec
3962            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            // Sequence config should be validated
3979            assert_eq!(config.sequence_config.esc_seq_timeout.as_millis(), 400);
3980        }
3981    }
3982}