Skip to main content

ftui_core/
input_parser.rs

1#![forbid(unsafe_code)]
2
3//! Input parser state machine.
4//!
5//! Decodes terminal input bytes into [`crate::event::Event`] values with DoS protection.
6//!
7//! # Design
8//!
9//! The parser is a state machine that handles:
10//! - ASCII characters and control codes
11//! - UTF-8 multi-byte sequences
12//! - CSI (Control Sequence Introducer) sequences
13//! - SS3 (Single Shift 3) sequences
14//! - OSC (Operating System Command) sequences
15//! - Bracketed paste mode
16//! - Mouse events (SGR protocol)
17//! - Focus events
18//!
19//! # DoS Protection
20//!
21//! The parser enforces length limits on all sequence types to prevent memory exhaustion:
22//! - CSI sequences: 256 bytes max
23//! - OSC sequences: 100KB max (large enough for OSC 52 clipboard payloads)
24//! - Paste content: 1MB max
25
26use crate::event::{
27    ClipboardEvent, ClipboardSource, Event, KeyCode, KeyEvent, KeyEventKind, Modifiers,
28    MouseButton, MouseEvent, MouseEventKind, PasteEvent, TerminalResponse,
29};
30
31// Import tracing macros (no-op when tracing feature is disabled).
32#[cfg(feature = "tracing")]
33use crate::logging::{debug, debug_span, trace};
34#[cfg(not(feature = "tracing"))]
35use crate::{debug, debug_span, trace};
36
37/// DoS protection: maximum CSI sequence length.
38const MAX_CSI_LEN: usize = 256;
39
40/// DoS protection: maximum OSC sequence length.
41const MAX_OSC_LEN: usize = 102_400;
42
43/// DoS protection: maximum DCS / APC payload length (8 KiB).
44pub const MAX_DCS_LEN: usize = 8 * 1024;
45
46/// DoS protection: maximum paste content length.
47const MAX_PASTE_LEN: usize = 1024 * 1024; // 1MB
48/// Upper bound for event vector preallocation hints.
49///
50/// Keep this bounded so callers passing very large slices do not cause
51/// disproportionate reserve spikes.
52const MAX_EVENT_RESERVE_HINT: usize = 8 * 1024 + 1;
53
54/// Parser state machine states.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
56enum ParserState {
57    /// Normal character input.
58    #[default]
59    Ground,
60    /// After ESC (0x1B).
61    Escape,
62    /// After ESC [ (CSI introducer).
63    Csi,
64    /// Collecting CSI parameters.
65    CsiParam,
66    /// Ignoring oversized CSI sequence.
67    CsiIgnore,
68    /// After ESC O (SS3 introducer).
69    Ss3,
70    /// After ESC ] (OSC introducer).
71    Osc,
72    /// Collecting OSC content.
73    OscContent,
74    /// After ESC inside OSC (for ESC \ terminator).
75    OscEscape,
76    /// Ignoring oversized OSC sequence.
77    OscIgnore,
78    /// Inside a DCS (`ESC P …`) control string, capturing up to [`MAX_DCS_LEN`]
79    /// bytes until its String Terminator (`ESC \`). DCS carries terminal query
80    /// *responses* (XTGETTCAP capability reports, DECRQSS status strings), not
81    /// key input; bytes beyond the cap are discarded while waiting for ST.
82    DcsBody,
83    /// After an ESC inside a DCS string — checking for the `ESC \` (ST)
84    /// terminator.
85    DcsEscape,
86    /// Inside an APC (`ESC _ …`) control string when `capture_apc` is enabled,
87    /// capturing up to [`MAX_DCS_LEN`] bytes until its String Terminator (`ESC \`).
88    ApcBody,
89    /// After an ESC inside an APC string — checking for the `ESC \` (ST)
90    /// terminator.
91    ApcEscape,
92    /// Collecting UTF-8 multi-byte sequence.
93    Utf8 {
94        /// Bytes collected so far.
95        collected: u8,
96        /// Total bytes expected.
97        expected: u8,
98        /// Whether the sequence was Alt-prefixed (ESC + UTF-8 lead byte,
99        /// i.e. Alt+non-ASCII under metaSendsEscape).
100        alt: bool,
101    },
102    /// Collecting X10 mouse coordinates (3 bytes).
103    MouseX10 { collected: u8, buffer: [u8; 3] },
104}
105
106/// Terminal input parser with DoS protection.
107///
108/// Parse terminal input bytes into events:
109///
110/// ```ignore
111/// let mut parser = InputParser::new();
112/// let events = parser.parse(b"\x1b[A"); // Up arrow
113/// assert_eq!(events.len(), 1);
114/// ```
115#[derive(Debug)]
116pub struct InputParser {
117    /// Current parser state.
118    state: ParserState,
119    /// Buffer for accumulating sequence bytes.
120    buffer: Vec<u8>,
121    /// Buffer for collecting paste content.
122    paste_buffer: Vec<u8>,
123    /// Buffer for collecting bounded DCS or APC control-string payloads.
124    dcs_buffer: Vec<u8>,
125    /// Whether the active DCS or APC payload exceeded [`MAX_DCS_LEN`].
126    dcs_truncated: bool,
127    /// UTF-8 bytes collected so far.
128    utf8_buffer: [u8; 4],
129    /// Whether we're in bracketed paste mode.
130    in_paste: bool,
131    /// Event queued for the next iteration (allows emitting 2 events per byte).
132    pending_event: Option<Event>,
133    /// Whether to expect X10-encoded mouse events (`CSI M cb cx cy`).
134    ///
135    /// In practice some terminals/muxes can fall back to raw X10 packets even
136    /// after SGR negotiation. This flag should track whether mouse capture is
137    /// active for the current session.
138    ///
139    /// Defaults to `false`. When false, bare `CSI M` is treated as an unknown
140    /// CSI sequence (silently ignored) rather than entering X10 decode mode.
141    expect_x10_mouse: bool,
142    /// Whether to accept legacy xterm/rxvt mouse packets (`CSI Cb;Cx;Cy M`).
143    ///
144    /// Some terminals/muxes may ignore SGR mode requests and continue emitting
145    /// legacy numeric mouse packets. This flag enables that fallback parser
146    /// while keeping raw X10 byte-triplet decoding separately gated by
147    /// `expect_x10_mouse`.
148    allow_legacy_mouse: bool,
149    /// Whether SGR mouse packets (`CSI < Cb;Cx;Cy M|m`) carry pixel coordinates
150    /// (`?1016h` mode) rather than 1-based cell coordinates (`?1006h` mode).
151    pixel_mouse: bool,
152    /// Cell dimensions in pixels `(width, height)` for SGR-Pixels (`?1016h`)
153    /// coordinate conversion, populated via [`Self::set_cell_size_px`] or an
154    /// XTWINOPS `CSI 6 ; height ; width t` reply.
155    cell_size_px: Option<(u16, u16)>,
156    /// Whether `ESC _ ... ST` (APC) should be captured as a
157    /// [`TerminalResponse::Apc`] event instead of decoded as `Alt+_`.
158    capture_apc: bool,
159}
160
161impl Default for InputParser {
162    fn default() -> Self {
163        Self::new()
164    }
165}
166
167impl InputParser {
168    #[inline]
169    fn event_reserve_hint(input_len: usize) -> usize {
170        input_len.saturating_add(1).min(MAX_EVENT_RESERVE_HINT)
171    }
172
173    /// Create a new input parser.
174    #[must_use]
175    pub fn new() -> Self {
176        Self {
177            state: ParserState::Ground,
178            buffer: Vec::with_capacity(64),
179            paste_buffer: Vec::new(),
180            dcs_buffer: Vec::new(),
181            dcs_truncated: false,
182            utf8_buffer: [0; 4],
183            in_paste: false,
184            pending_event: None,
185            expect_x10_mouse: false,
186            allow_legacy_mouse: false,
187            pixel_mouse: false,
188            cell_size_px: None,
189            capture_apc: false,
190        }
191    }
192
193    /// Enable or disable X10 mouse event parsing.
194    ///
195    /// When enabled, bare `CSI M` triggers X10 coordinate collection
196    /// (3 raw bytes). This should generally follow mouse-capture state.
197    pub fn set_expect_x10_mouse(&mut self, enabled: bool) {
198        self.expect_x10_mouse = enabled;
199    }
200
201    /// Enable or disable legacy numeric mouse fallback parsing.
202    ///
203    /// When enabled, parse `CSI Cb;Cx;Cy M` as mouse input. This is useful when
204    /// mouse capture is active but the terminal does not honor SGR 1006 mode.
205    ///
206    /// Default: `false`.
207    pub fn set_allow_legacy_mouse(&mut self, enabled: bool) {
208        self.allow_legacy_mouse = enabled;
209    }
210
211    /// Enable or disable SGR-Pixels (`?1016h`) mouse coordinate conversion.
212    ///
213    /// When enabled, `CSI < Cb ; Px ; Py M|m` coordinates are treated as
214    /// pixel coordinates, stored in [`MouseEvent::pixel`], and converted to
215    /// 0-indexed cell coordinates using [`Self::cell_size_px`] (or `(0, 0)`
216    /// if the cell size is not yet known).
217    pub fn set_pixel_mouse(&mut self, enabled: bool) {
218        self.pixel_mouse = enabled;
219    }
220
221    /// Builder variant of [`Self::set_pixel_mouse`].
222    #[must_use]
223    pub const fn with_pixel_mouse(mut self, enabled: bool) -> Self {
224        self.pixel_mouse = enabled;
225        self
226    }
227
228    /// Whether SGR-Pixels (`?1016h`) mouse mode is enabled.
229    #[must_use]
230    pub const fn pixel_mouse(&self) -> bool {
231        self.pixel_mouse
232    }
233
234    /// Set the cell dimensions in pixels `(width, height)` used to convert
235    /// SGR-Pixels (`?1016h`) coordinates into cell coordinates.
236    ///
237    /// Passing a zero width or height clears the stored cell size.
238    pub fn set_cell_size_px(&mut self, width: u16, height: u16) {
239        if width > 0 && height > 0 {
240            self.cell_size_px = Some((width, height));
241        } else {
242            self.cell_size_px = None;
243        }
244    }
245
246    /// Current cell size in pixels `(width, height)`, if known.
247    #[must_use]
248    pub const fn cell_size_px(&self) -> Option<(u16, u16)> {
249        self.cell_size_px
250    }
251
252    /// Enable or disable APC (`ESC _ ... ST`) control-string capture.
253    ///
254    /// Defaults to `false` so `ESC _` continues to decode as `Alt+_`.
255    /// When `true`, `ESC _ ... ST` is captured up to [`MAX_DCS_LEN`] bytes
256    /// and emitted as `Event::TerminalResponse(TerminalResponse::Apc { .. })`.
257    pub fn set_capture_apc(&mut self, enabled: bool) {
258        self.capture_apc = enabled;
259    }
260
261    /// Builder variant of [`Self::set_capture_apc`].
262    #[must_use]
263    pub const fn with_capture_apc(mut self, enabled: bool) -> Self {
264        self.capture_apc = enabled;
265        self
266    }
267
268    /// Whether APC (`ESC _ ... ST`) capture is enabled.
269    #[must_use]
270    pub const fn capture_apc(&self) -> bool {
271        self.capture_apc
272    }
273
274    /// Current length of the internal DCS/APC accumulation buffer (for fuzzing/tests).
275    #[must_use]
276    pub fn dcs_buffer_len(&self) -> usize {
277        self.dcs_buffer.len()
278    }
279
280    /// Whether the parser is currently waiting on additional bytes for a
281    /// timeout-resolved sequence (bare ESC or partial UTF-8).
282    #[must_use]
283    pub const fn has_pending_timeout_state(&self) -> bool {
284        matches!(self.state, ParserState::Escape | ParserState::Utf8 { .. })
285    }
286
287    /// Handle a timeout in the input stream.
288    ///
289    /// If the parser is waiting for more bytes to complete an ambiguous sequence
290    /// (specifically a bare ESC), a timeout indicates the sequence has ended.
291    pub fn timeout(&mut self) -> Option<Event> {
292        match self.state {
293            ParserState::Escape => {
294                self.state = ParserState::Ground;
295                Some(Event::Key(KeyEvent::new(KeyCode::Escape)))
296            }
297            ParserState::Utf8 { alt, .. } => {
298                // Incomplete UTF-8 sequence at timeout -> replacement char
299                // (Alt-flagged if the sequence was ESC-prefixed).
300                self.state = ParserState::Ground;
301                self.utf8_buffer = [0; 4];
302                let mods = if alt { Modifiers::ALT } else { Modifiers::NONE };
303                Some(Event::Key(
304                    KeyEvent::new(KeyCode::Char(std::char::REPLACEMENT_CHARACTER))
305                        .with_modifiers(mods),
306                ))
307            }
308            ParserState::DcsBody
309            | ParserState::DcsEscape
310            | ParserState::ApcBody
311            | ParserState::ApcEscape => {
312                self.dcs_buffer.clear();
313                self.dcs_truncated = false;
314                self.state = ParserState::Ground;
315                None
316            }
317            _ => None,
318        }
319    }
320
321    /// Parse input bytes and return any completed events.
322    pub fn parse(&mut self, input: &[u8]) -> Vec<Event> {
323        let mut events = Vec::with_capacity(Self::event_reserve_hint(input.len()));
324        self.parse_with(input, |event| events.push(event));
325        events
326    }
327
328    /// Parse input bytes and emit each completed event through `emit`.
329    pub fn parse_with<F>(&mut self, input: &[u8], mut emit: F)
330    where
331        F: FnMut(Event),
332    {
333        let span = debug_span!("event.normalize", raw_byte_count = input.len());
334        let _guard = span.enter();
335        trace!("raw input bytes: {} bytes", input.len());
336
337        for &byte in input {
338            if let Some(event) = self.process_byte(byte) {
339                debug!(event_type = event.event_type_label(), "normalized event");
340                emit(event);
341            }
342            if let Some(pending) = self.pending_event.take() {
343                debug!(event_type = pending.event_type_label(), "normalized event");
344                emit(pending);
345            }
346        }
347    }
348
349    /// Parse input bytes and append completed events to `events`.
350    ///
351    /// This variant lets callers reuse a scratch buffer across parses to avoid
352    /// repeated allocations on hot input paths.
353    pub fn parse_into(&mut self, input: &[u8], events: &mut Vec<Event>) {
354        let needed = Self::event_reserve_hint(input.len());
355        let available = events.capacity().saturating_sub(events.len());
356        if available < needed {
357            events.reserve(needed - available);
358        }
359        self.parse_with(input, |event| events.push(event));
360    }
361
362    /// Process a single byte and optionally return an event.
363    fn process_byte(&mut self, byte: u8) -> Option<Event> {
364        // In paste mode, collect bytes until end sequence
365        if self.in_paste {
366            return self.process_paste_byte(byte);
367        }
368
369        match self.state {
370            ParserState::Ground => self.process_ground(byte),
371            ParserState::Escape => self.process_escape(byte),
372            ParserState::Csi => self.process_csi(byte),
373            ParserState::CsiParam => self.process_csi_param(byte),
374            ParserState::CsiIgnore => self.process_csi_ignore(byte),
375            ParserState::Ss3 => self.process_ss3(byte),
376            ParserState::Osc => self.process_osc(byte),
377            ParserState::OscContent => self.process_osc_content(byte),
378            ParserState::OscEscape => self.process_osc_escape(byte),
379            ParserState::OscIgnore => self.process_osc_ignore(byte),
380            ParserState::DcsBody => self.process_dcs_body(byte),
381            ParserState::DcsEscape => self.process_dcs_escape(byte),
382            ParserState::ApcBody => self.process_apc_body(byte),
383            ParserState::ApcEscape => self.process_apc_escape(byte),
384            ParserState::Utf8 {
385                collected,
386                expected,
387                alt,
388            } => self.process_utf8(byte, collected, expected, alt),
389            ParserState::MouseX10 { .. } => self.process_mouse_x10(byte),
390        }
391    }
392
393    /// Process byte in ground state.
394    fn process_ground(&mut self, byte: u8) -> Option<Event> {
395        match byte {
396            // ESC - start escape sequence
397            0x1B => {
398                self.state = ParserState::Escape;
399                None
400            }
401            // C1 CSI (S8C1T): start CSI sequence without ESC prefix.
402            0x9B => {
403                self.state = ParserState::Csi;
404                self.buffer.clear();
405                None
406            }
407            // C1 SS3: start SS3 sequence without ESC prefix.
408            0x8F => {
409                self.state = ParserState::Ss3;
410                None
411            }
412            // C1 OSC: start OSC sequence without ESC prefix.
413            0x9D => {
414                self.state = ParserState::Osc;
415                self.buffer.clear();
416                None
417            }
418            // NUL - Ctrl+Space or Ctrl+@
419            0x00 => Some(Event::Key(KeyEvent::new(KeyCode::Null))),
420            // Backspace alternate (Ctrl+H)
421            0x08 => Some(Event::Key(KeyEvent::new(KeyCode::Backspace))),
422            // Tab (Ctrl+I) - check before generic Ctrl range
423            0x09 => Some(Event::Key(KeyEvent::new(KeyCode::Tab))),
424            // Enter (Ctrl+M) - check before generic Ctrl range
425            0x0D => Some(Event::Key(KeyEvent::new(KeyCode::Enter))),
426            // Other Ctrl+A through Ctrl+Z (0x01-0x1A excluding Tab and Enter)
427            0x01..=0x07 | 0x0A..=0x0C | 0x0E..=0x1A => {
428                let c = (byte + b'a' - 1) as char;
429                Some(Event::Key(
430                    KeyEvent::new(KeyCode::Char(c)).with_modifiers(Modifiers::CTRL),
431                ))
432            }
433            // Ctrl+\, Ctrl+], Ctrl+^, Ctrl+_ (0x1C-0x1F)
434            0x1C => Some(Event::Key(
435                KeyEvent::new(KeyCode::Char('\\')).with_modifiers(Modifiers::CTRL),
436            )),
437            0x1D => Some(Event::Key(
438                KeyEvent::new(KeyCode::Char(']')).with_modifiers(Modifiers::CTRL),
439            )),
440            0x1E => Some(Event::Key(
441                KeyEvent::new(KeyCode::Char('^')).with_modifiers(Modifiers::CTRL),
442            )),
443            0x1F => Some(Event::Key(
444                KeyEvent::new(KeyCode::Char('_')).with_modifiers(Modifiers::CTRL),
445            )),
446            // Backspace (DEL)
447            0x7F => Some(Event::Key(KeyEvent::new(KeyCode::Backspace))),
448            // Printable ASCII
449            0x20..=0x7E => Some(Event::Key(KeyEvent::new(KeyCode::Char(byte as char)))),
450            // UTF-8 lead bytes (valid ranges only)
451            0xC2..=0xDF => {
452                self.utf8_buffer[0] = byte;
453                self.state = ParserState::Utf8 {
454                    collected: 1,
455                    expected: 2,
456                    alt: false,
457                };
458                None
459            }
460            0xE0..=0xEF => {
461                self.utf8_buffer[0] = byte;
462                self.state = ParserState::Utf8 {
463                    collected: 1,
464                    expected: 3,
465                    alt: false,
466                };
467                None
468            }
469            0xF0..=0xF4 => {
470                self.utf8_buffer[0] = byte;
471                self.state = ParserState::Utf8 {
472                    collected: 1,
473                    expected: 4,
474                    alt: false,
475                };
476                None
477            }
478            // Invalid UTF-8 lead bytes (overlong or out of range)
479            0xC0..=0xC1 | 0xF5..=0xFF => Some(Event::Key(KeyEvent::new(KeyCode::Char(
480                std::char::REPLACEMENT_CHARACTER,
481            )))),
482            // Invalid or ignored bytes
483            _ => None,
484        }
485    }
486
487    /// Process byte after ESC.
488    fn process_escape(&mut self, byte: u8) -> Option<Event> {
489        match byte {
490            // CSI introducer
491            b'[' => {
492                self.state = ParserState::Csi;
493                self.buffer.clear();
494                None
495            }
496            // SS3 introducer
497            b'O' => {
498                self.state = ParserState::Ss3;
499                None
500            }
501            // OSC introducer
502            b']' => {
503                self.state = ParserState::Osc;
504                self.buffer.clear();
505                None
506            }
507            // DCS introducer (ESC P). DCS is how terminals return string-valued
508            // query responses — XTGETTCAP capability reports and DECRQSS status
509            // strings — so we capture up to MAX_DCS_LEN bytes of the `ESC P … ST`
510            // string into `Event::TerminalResponse(TerminalResponse::Dcs { .. })`
511            // rather than decoding it as keys. Without this, a leaked XTGETTCAP
512            // reply (`ESC P 1+r524742=8/8/8 ESC \`) would decode as `Alt+P`
513            // followed by its payload as literal keystrokes
514            // (`1 + r 5 2 4 7 4 2 = 8 / 8 / 8`, `Alt+\`).
515            //
516            // This shadows the legacy `Alt+Shift+P` encoding (which also sends
517            // `ESC P` under metaSendsEscape) — an unavoidable, standard ambiguity
518            // (DCS wins, exactly as `ESC [`/`ESC ]`/`ESC O` already shadow
519            // `Alt+[`/`Alt+]`/`Alt+Shift+O`). We deliberately do NOT intercept
520            // the sibling C1 string introducers SOS (`ESC X`), PM (`ESC ^`) or,
521            // by default, APC (`ESC _`): terminals essentially never send those as
522            // responses, so shadowing them would needlessly swallow `Alt+Shift+X`/
523            // `Alt+^`/`Alt+_` keypresses for no benefit. Callers that need APC
524            // responses can opt in via `set_capture_apc(true)`. (8-bit C1 DCS
525            // `0x90` is likewise not handled — modern UTF-8 terminals use the
526            // 7-bit form above.)
527            b'P' => {
528                self.state = ParserState::DcsBody;
529                self.buffer.clear();
530                self.dcs_buffer.clear();
531                self.dcs_truncated = false;
532                None
533            }
534            // APC introducer (ESC _) when explicitly opted in via `set_capture_apc(true)`.
535            b'_' if self.capture_apc => {
536                self.state = ParserState::ApcBody;
537                self.buffer.clear();
538                self.dcs_buffer.clear();
539                self.dcs_truncated = false;
540                None
541            }
542            // Another ESC - emit Alt+Escape and reset to ground
543            // (or treat as start of new sequence - but ESC ESC is usually Alt+ESC)
544            0x1B => {
545                self.state = ParserState::Ground;
546                Some(Event::Key(
547                    KeyEvent::new(KeyCode::Escape).with_modifiers(Modifiers::ALT),
548                ))
549            }
550            // Control characters (Ctrl+Key) -> Alt+Ctrl+Key
551            0x00..=0x1F => {
552                self.state = ParserState::Ground;
553                // Delegate to process_ground to decode the control key (e.g. 0x01 -> Ctrl+A)
554                // then add the ALT modifier.
555                if let Some(mut event) = self.process_ground(byte) {
556                    if let Event::Key(ref mut key) = event {
557                        key.modifiers |= Modifiers::ALT;
558                    }
559                    Some(event)
560                } else {
561                    None
562                }
563            }
564            // Alt+letter or Alt+char
565            0x20..=0x7E => {
566                self.state = ParserState::Ground;
567                Some(Event::Key(
568                    KeyEvent::new(KeyCode::Char(byte as char)).with_modifiers(Modifiers::ALT),
569                ))
570            }
571            // Alt+Backspace (DEL)
572            0x7F => {
573                self.state = ParserState::Ground;
574                Some(Event::Key(
575                    KeyEvent::new(KeyCode::Backspace).with_modifiers(Modifiers::ALT),
576                ))
577            }
578            // Alt + non-ASCII (metaSendsEscape in a UTF-8 terminal sends
579            // ESC + the UTF-8 encoding of the character). Collect the
580            // sequence with the alt flag so it decodes as Alt+char instead
581            // of being dropped.
582            0xC2..=0xDF => {
583                self.utf8_buffer[0] = byte;
584                self.state = ParserState::Utf8 {
585                    collected: 1,
586                    expected: 2,
587                    alt: true,
588                };
589                None
590            }
591            0xE0..=0xEF => {
592                self.utf8_buffer[0] = byte;
593                self.state = ParserState::Utf8 {
594                    collected: 1,
595                    expected: 3,
596                    alt: true,
597                };
598                None
599            }
600            0xF0..=0xF4 => {
601                self.utf8_buffer[0] = byte;
602                self.state = ParserState::Utf8 {
603                    collected: 1,
604                    expected: 4,
605                    alt: true,
606                };
607                None
608            }
609            // Invalid UTF-8 lead bytes after ESC: emit Alt+replacement (the
610            // ground path emits a bare replacement char for these).
611            0xC0..=0xC1 | 0xF5..=0xFF => {
612                self.state = ParserState::Ground;
613                Some(Event::Key(
614                    KeyEvent::new(KeyCode::Char(std::char::REPLACEMENT_CHARACTER))
615                        .with_modifiers(Modifiers::ALT),
616                ))
617            }
618            // Invalid (bare UTF-8 continuation bytes 0x80-0xBF) - return to
619            // ground; ground ignores these bytes too.
620            _ => {
621                self.state = ParserState::Ground;
622                None
623            }
624        }
625    }
626
627    /// Process byte at start of CSI sequence.
628    fn process_csi(&mut self, byte: u8) -> Option<Event> {
629        // Robustness: ESC restarts sequence
630        if byte == 0x1B {
631            self.state = ParserState::Escape;
632            self.buffer.clear();
633            return None;
634        }
635
636        self.buffer.push(byte);
637
638        match byte {
639            // Parameter bytes (0x30-0x3F) and Intermediate bytes (0x20-0x2F)
640            0x20..=0x3F => {
641                self.state = ParserState::CsiParam;
642                None
643            }
644            // Final byte (0x40-0x7E) - parse and return
645            0x40..=0x7E => {
646                // X10 mouse trigger: bare `CSI M` enters raw X10 coordinate
647                // collection only when the runtime currently expects possible
648                // X10 fallback traffic.
649                if self.expect_x10_mouse && byte == b'M' && self.buffer.len() == 1 {
650                    self.state = ParserState::MouseX10 {
651                        collected: 0,
652                        buffer: [0; 3],
653                    };
654                    self.buffer.clear();
655                    return None;
656                }
657
658                self.state = ParserState::Ground;
659                self.parse_csi_sequence()
660            }
661            // Invalid (0x00-0x1F, 0x7F-0xFF): abort the sequence and reprocess
662            // the byte, matching process_csi_param/process_csi_ignore so that
663            // e.g. `ESC [ CR` still delivers Enter (anti-swallow contract,
664            // tests/repro/parser_swallow.rs).
665            _ => {
666                self.state = ParserState::Ground;
667                self.buffer.clear();
668                self.process_ground(byte)
669            }
670        }
671    }
672
673    /// Process byte while collecting CSI parameters.
674    fn process_csi_param(&mut self, byte: u8) -> Option<Event> {
675        // Robustness: ESC restarts sequence
676        if byte == 0x1B {
677            self.state = ParserState::Escape;
678            self.buffer.clear();
679            return None;
680        }
681
682        // DoS protection. Only parameter/intermediate accumulation is capped:
683        // a final byte (0x40-0x7E) arriving exactly at the cap must still
684        // terminate the sequence, otherwise it is swallowed here and the
685        // parser enters CsiIgnore, which then eats the next legitimate
686        // keystroke as a bogus ignore-terminator.
687        if self.buffer.len() >= MAX_CSI_LEN && !(0x40..=0x7E).contains(&byte) {
688            self.state = ParserState::CsiIgnore;
689            self.buffer.clear();
690            return None;
691        }
692
693        self.buffer.push(byte);
694
695        match byte {
696            // Continue collecting parameters/intermediates
697            0x20..=0x3F => None,
698            // Final byte - parse and return
699            0x40..=0x7E => {
700                self.state = ParserState::Ground;
701                self.parse_csi_sequence()
702            }
703            // Invalid
704            _ => {
705                self.state = ParserState::Ground;
706                self.buffer.clear();
707                self.process_ground(byte)
708            }
709        }
710    }
711
712    /// Ignore bytes until end of CSI sequence.
713    fn process_csi_ignore(&mut self, byte: u8) -> Option<Event> {
714        // Robustness: ESC restarts sequence
715        if byte == 0x1B {
716            self.state = ParserState::Escape;
717            return None;
718        }
719
720        // Final byte (0x40-0x7E) - return to ground
721        if (0x40..=0x7E).contains(&byte) {
722            self.state = ParserState::Ground;
723            None
724        } else if (0x20..=0x3F).contains(&byte) {
725            // Parameter/Intermediate bytes - continue ignoring
726            None
727        } else {
728            // Invalid character (e.g. newline) - abort sequence and reprocess
729            self.state = ParserState::Ground;
730            self.process_ground(byte)
731        }
732    }
733
734    /// Parse a complete CSI sequence from the buffer.
735    fn parse_csi_sequence(&mut self) -> Option<Event> {
736        let seq = std::mem::take(&mut self.buffer);
737        if seq.is_empty() {
738            return None;
739        }
740
741        let final_byte = *seq.last()?;
742        let params = &seq[..seq.len() - 1];
743
744        // Check for special sequences first
745        match (params, final_byte) {
746            // Focus events
747            ([], b'I') => return Some(Event::Focus(true)),
748            ([], b'O') => return Some(Event::Focus(false)),
749
750            // Bracketed paste
751            (b"200", b'~') => {
752                self.in_paste = true;
753                self.paste_buffer.clear();
754                self.buffer.clear(); // Ensure tail buffer is clean
755                return None;
756            }
757            (b"201", b'~') => {
758                // Stray end-paste with no matching start: the in-paste path
759                // consumes its own terminator in `process_paste_byte`, so this
760                // arm is only reachable when `in_paste` is already false (e.g.
761                // the start marker was corrupted or eaten upstream). Discard it
762                // instead of emitting a spurious empty Paste event.
763                debug_assert!(!self.in_paste);
764                self.paste_buffer.clear();
765                return None;
766            }
767
768            // SGR mouse protocol
769            _ if params.starts_with(b"<") && (final_byte == b'M' || final_byte == b'm') => {
770                return self.parse_sgr_mouse(params, final_byte);
771            }
772            // Legacy mouse protocol fallback (xterm/rxvt 1015):
773            // CSI Cb ; Cx ; Cy M
774            //
775            // Gate this behind explicit mouse fallback toggles so we don't
776            // reinterpret generic CSI ... M sequences as mouse input when
777            // mouse capture is off.
778            _ if (self.allow_legacy_mouse || self.expect_x10_mouse) && final_byte == b'M' => {
779                if let Some(event) = self.parse_legacy_mouse(params) {
780                    return Some(event);
781                }
782            }
783
784            _ => {}
785        }
786
787        // Arrow keys and other CSI sequences
788        match final_byte {
789            b'A' => Some(Event::Key(self.key_with_modifiers(KeyCode::Up, params))),
790            b'B' => Some(Event::Key(self.key_with_modifiers(KeyCode::Down, params))),
791            b'C' => Some(Event::Key(self.key_with_modifiers(KeyCode::Right, params))),
792            b'D' => Some(Event::Key(self.key_with_modifiers(KeyCode::Left, params))),
793            b'H' => Some(Event::Key(self.key_with_modifiers(KeyCode::Home, params))),
794            b'F' => Some(Event::Key(self.key_with_modifiers(KeyCode::End, params))),
795            b'P' => Some(Event::Key(self.key_with_modifiers(KeyCode::F(1), params))),
796            b'Q' => Some(Event::Key(self.key_with_modifiers(KeyCode::F(2), params))),
797            b'R' => Some(Event::Key(self.key_with_modifiers(KeyCode::F(3), params))),
798            b'S' => Some(Event::Key(self.key_with_modifiers(KeyCode::F(4), params))),
799            b'Z' => Some(Event::Key(
800                self.key_with_modifiers(KeyCode::BackTab, params),
801            )),
802            b'~' => self.parse_csi_tilde(params),
803            b'u' => self.parse_kitty_keyboard(params),
804            b't' => self.parse_xtwinops(params),
805            _ => None,
806        }
807    }
808
809    /// Parse XTWINOPS replies ending in `t` (`CSI 6 ; height ; width t` cell size in pixels).
810    fn parse_xtwinops(&mut self, params: &[u8]) -> Option<Event> {
811        let s = std::str::from_utf8(params).ok()?;
812        let mut parts = s.split(';');
813        let op: u16 = parts.next()?.parse().ok()?;
814        if op != 6 {
815            return None;
816        }
817        let height: u16 = parts.next()?.parse().ok()?;
818        let width: u16 = parts.next()?.parse().ok()?;
819        if parts.next().is_some() || width == 0 || height == 0 {
820            return None;
821        }
822        self.set_cell_size_px(width, height);
823        debug!(
824            target: crate::TARGET_INPUT_PARSER,
825            kind = "cell_size",
826            width,
827            height,
828            "parsed XTWINOPS cell size"
829        );
830        Some(Event::TerminalResponse(TerminalResponse::CellSize {
831            width,
832            height,
833        }))
834    }
835
836    /// Parse CSI sequences ending in ~.
837    fn parse_csi_tilde(&self, params: &[u8]) -> Option<Event> {
838        let num = self.parse_first_param(params)?;
839        let (mods, kind) = self.parse_modifier_param(params);
840
841        let code = match num {
842            1 => KeyCode::Home,
843            2 => KeyCode::Insert,
844            3 => KeyCode::Delete,
845            4 => KeyCode::End,
846            5 => KeyCode::PageUp,
847            6 => KeyCode::PageDown,
848            15 => KeyCode::F(5),
849            17 => KeyCode::F(6),
850            18 => KeyCode::F(7),
851            19 => KeyCode::F(8),
852            20 => KeyCode::F(9),
853            21 => KeyCode::F(10),
854            23 => KeyCode::F(11),
855            24 => KeyCode::F(12),
856            _ => return None,
857        };
858
859        Some(Event::Key(
860            KeyEvent::new(code).with_modifiers(mods).with_kind(kind),
861        ))
862    }
863
864    /// Parse the first numeric parameter from CSI params.
865    fn parse_first_param(&self, params: &[u8]) -> Option<u32> {
866        let s = std::str::from_utf8(params).ok()?;
867        let first = s.split(';').next()?;
868        first.parse().ok()
869    }
870
871    /// Parse the modifier parameter (second param in CSI sequences) plus the
872    /// optional kitty event-type sub-parameter.
873    ///
874    /// With the kitty keyboard enhancement "report event types" enabled, the
875    /// legacy functional-key encodings also carry `modifiers:event_type`
876    /// (e.g. `CSI 1;1:3 A` = Up release, `CSI 3;5:3 ~` = Ctrl+Delete
877    /// release). Parsing only `mods` here would fail on the colon form and
878    /// silently fall back to `Modifiers::NONE`, turning every key release
879    /// into a duplicate unmodified press.
880    fn parse_modifier_param(&self, params: &[u8]) -> (Modifiers, KeyEventKind) {
881        let s = match std::str::from_utf8(params) {
882            Ok(s) => s,
883            Err(_) => return (Modifiers::NONE, KeyEventKind::Press),
884        };
885
886        let mod_part = s.split(';').nth(1).unwrap_or("");
887        Self::kitty_modifiers_and_kind(mod_part)
888    }
889
890    /// Parse Kitty keyboard protocol CSI u sequences.
891    ///
892    /// Format: `CSI unicode-key-code:alt-keys ; modifiers:event-type ; text-as-codepoints u`
893    fn parse_kitty_keyboard(&self, params: &[u8]) -> Option<Event> {
894        let s = std::str::from_utf8(params).ok()?;
895        if s.is_empty() {
896            return None;
897        }
898
899        let mut parts = s.split(';');
900        let key_part = parts.next().unwrap_or("");
901        let mut key_codes = key_part.split(':');
902        let key_code: u32 = key_codes.next().unwrap_or("").parse().ok()?;
903        // With "report alternate keys" the second field is the shifted key.
904        let shifted = key_codes
905            .next()
906            .and_then(|field| field.parse().ok())
907            .and_then(char::from_u32);
908
909        let mod_part = parts.next().unwrap_or("");
910        let (modifiers, kind) = Self::kitty_modifiers_and_kind(mod_part);
911
912        let mut code = Self::kitty_keycode_to_keycode(key_code)?;
913        if let KeyCode::Char(base) = code
914            && !(57_344..=63_743).contains(&key_code)
915        {
916            let caps_lock = mod_part
917                .split(':')
918                .next()
919                .and_then(|value| value.parse::<u32>().ok())
920                .is_some_and(|value| value.saturating_sub(1) & 64 != 0);
921            code = KeyCode::Char(Self::kitty_typed_char(
922                base,
923                shifted,
924                modifiers.contains(Modifiers::SHIFT),
925                caps_lock,
926            ));
927        }
928        Some(Event::Key(
929            KeyEvent::new(code)
930                .with_modifiers(modifiers)
931                .with_kind(kind),
932        ))
933    }
934
935    /// The character a kitty key event types.
936    ///
937    /// The key code is always the unshifted key, and the runtime asks for
938    /// every key as an escape code without the text. Shift+a arrived as
939    /// `Char('a')` and Caps Lock was ignored, so text fields typed lower case.
940    /// The shifted key from "report alternate keys" is used when Shift is
941    /// held, the upper case of a letter when the terminal omits it, and Caps
942    /// Lock inverts the case of letters. Shift stays in the modifiers, as the
943    /// web backend and [`KeyCombo`](crate::keybinding::KeyCombo) expect.
944    fn kitty_typed_char(base: char, shifted: Option<char>, shift: bool, caps_lock: bool) -> char {
945        // Case mappings that expand (`ß` to `SS`) leave the character as is.
946        let upper = |c: char| {
947            let mut chars = c.to_uppercase();
948            match (chars.next(), chars.next()) {
949                (Some(u), None) => u,
950                _ => c,
951            }
952        };
953        let lower = |c: char| {
954            let mut chars = c.to_lowercase();
955            match (chars.next(), chars.next()) {
956                (Some(l), None) => l,
957                _ => c,
958            }
959        };
960        let typed = if shift {
961            shifted.unwrap_or_else(|| upper(base))
962        } else {
963            base
964        };
965        if caps_lock && typed.is_alphabetic() {
966            if typed.is_lowercase() {
967                upper(typed)
968            } else {
969                lower(typed)
970            }
971        } else {
972            typed
973        }
974    }
975
976    fn kitty_modifiers_and_kind(mod_part: &str) -> (Modifiers, KeyEventKind) {
977        if mod_part.is_empty() {
978            return (Modifiers::NONE, KeyEventKind::Press);
979        }
980
981        let mut parts = mod_part.split(':');
982        let mod_value: u32 = parts.next().and_then(|v| v.parse().ok()).unwrap_or(1);
983        let kind_value: u32 = parts.next().and_then(|v| v.parse().ok()).unwrap_or(1);
984
985        let modifiers = Self::modifiers_from_xterm(mod_value);
986        let kind = match kind_value {
987            2 => KeyEventKind::Repeat,
988            3 => KeyEventKind::Release,
989            _ => KeyEventKind::Press,
990        };
991
992        (modifiers, kind)
993    }
994
995    fn kitty_keycode_to_keycode(key_code: u32) -> Option<KeyCode> {
996        match key_code {
997            // Standard ASCII keys
998            9 => Some(KeyCode::Tab),
999            13 => Some(KeyCode::Enter),
1000            27 => Some(KeyCode::Escape),
1001            8 | 127 => Some(KeyCode::Backspace),
1002            // Kitty keyboard protocol extended keys (CSI u)
1003            57_344 => Some(KeyCode::Escape),
1004            57_345 => Some(KeyCode::Enter),
1005            57_346 => Some(KeyCode::Tab),
1006            57_347 => Some(KeyCode::Backspace),
1007            57_348 => Some(KeyCode::Insert),
1008            57_349 => Some(KeyCode::Delete),
1009            57_350 => Some(KeyCode::Left),
1010            57_351 => Some(KeyCode::Right),
1011            57_352 => Some(KeyCode::Up),
1012            57_353 => Some(KeyCode::Down),
1013            57_354 => Some(KeyCode::PageUp),
1014            57_355 => Some(KeyCode::PageDown),
1015            57_356 => Some(KeyCode::Home),
1016            57_357 => Some(KeyCode::End),
1017            // F1-F24 (57_364-57_387)
1018            57_364..=57_387 => {
1019                // Safety: range is [57_364, 57_387], so (key_code - 57_364 + 1) is [1, 24]
1020                // which fits in u8. We use debug_assert to catch any future range changes.
1021                let f_num = key_code - 57_364 + 1;
1022                debug_assert!(f_num <= 24, "F-key number {f_num} exceeds F24");
1023                Some(KeyCode::F(f_num as u8))
1024            }
1025            // Keypad keys. The disambiguate flag reports them with these
1026            // codes, which used to fall in the unhandled range below, so
1027            // numpad digits, operators, Enter and arrows were dropped.
1028            57_399..=57_408 => char::from_digit(key_code - 57_399, 10).map(KeyCode::Char),
1029            57_409 => Some(KeyCode::Char('.')),
1030            57_410 => Some(KeyCode::Char('/')),
1031            57_411 => Some(KeyCode::Char('*')),
1032            57_412 => Some(KeyCode::Char('-')),
1033            57_413 => Some(KeyCode::Char('+')),
1034            57_414 => Some(KeyCode::Enter),
1035            57_415 => Some(KeyCode::Char('=')),
1036            57_416 => Some(KeyCode::Char(',')),
1037            57_417 => Some(KeyCode::Left),
1038            57_418 => Some(KeyCode::Right),
1039            57_419 => Some(KeyCode::Up),
1040            57_420 => Some(KeyCode::Down),
1041            57_421 => Some(KeyCode::PageUp),
1042            57_422 => Some(KeyCode::PageDown),
1043            57_423 => Some(KeyCode::Home),
1044            57_424 => Some(KeyCode::End),
1045            57_425 => Some(KeyCode::Insert),
1046            57_426 => Some(KeyCode::Delete),
1047            // Media keys with a KeyCode.
1048            57_430 => Some(KeyCode::MediaPlayPause),
1049            57_432 => Some(KeyCode::MediaStop),
1050            57_435 => Some(KeyCode::MediaNextTrack),
1051            57_436 => Some(KeyCode::MediaPrevTrack),
1052            // Reserved/unhandled Kitty keycodes return None
1053            57_358..=57_363 | 57_388..=63_743 => None,
1054            // Unicode codepoints
1055            _ => char::from_u32(key_code).map(KeyCode::Char),
1056        }
1057    }
1058
1059    fn modifiers_from_xterm(value: u32) -> Modifiers {
1060        // xterm modifier encoding: value = 1 + modifier_bits
1061        // Shift=1, Alt=2, Ctrl=4, Super=8
1062        let bits = value.saturating_sub(1);
1063        let mut mods = Modifiers::NONE;
1064        if bits & 1 != 0 {
1065            mods |= Modifiers::SHIFT;
1066        }
1067        if bits & 2 != 0 {
1068            mods |= Modifiers::ALT;
1069        }
1070        if bits & 4 != 0 {
1071            mods |= Modifiers::CTRL;
1072        }
1073        if bits & 8 != 0 {
1074            mods |= Modifiers::SUPER;
1075        }
1076        mods
1077    }
1078
1079    /// Create a key event with modifiers (and kitty event kind) from CSI params.
1080    fn key_with_modifiers(&self, code: KeyCode, params: &[u8]) -> KeyEvent {
1081        let (mods, kind) = self.parse_modifier_param(params);
1082        KeyEvent::new(code).with_modifiers(mods).with_kind(kind)
1083    }
1084
1085    /// Parse SGR mouse protocol events.
1086    fn parse_sgr_mouse(&self, params: &[u8], final_byte: u8) -> Option<Event> {
1087        // Format: CSI < button ; x ; y M|m
1088        // Skip the leading '<'
1089        let params = &params[1..];
1090        let s = std::str::from_utf8(params).ok()?;
1091        let mut parts = s.split(';');
1092
1093        // Accept numeric prefixes in each token so sequences with sub-params
1094        // (e.g. `10:0`) still decode to their base coordinate/button values.
1095        let button_code_u32 = Self::parse_u32_prefix(parts.next()?)?;
1096        let button_code = button_code_u32.min(u16::MAX as u32) as u16;
1097        let x_raw = Self::parse_i32_prefix(parts.next()?)?;
1098        let y_raw = Self::parse_i32_prefix(parts.next()?)?;
1099
1100        // Decode button and modifiers
1101        let (button, mods) = self.decode_mouse_button(button_code);
1102
1103        let kind = if final_byte == b'M' {
1104            if button_code & 64 != 0 {
1105                // Scroll event: bit 6 (64) is set
1106                // bits 0-1 determine direction: 0=up, 1=down, 2=left, 3=right
1107                match button_code & 3 {
1108                    0 => MouseEventKind::ScrollUp,
1109                    1 => MouseEventKind::ScrollDown,
1110                    2 => MouseEventKind::ScrollLeft,
1111                    _ => MouseEventKind::ScrollRight,
1112                }
1113            } else if button_code & 32 != 0 {
1114                // Motion event (bit 5 set)
1115                // bits 0-1: 0=left, 1=middle, 2=right, 3=no button (moved)
1116                if button_code & 3 == 3 {
1117                    MouseEventKind::Moved
1118                } else {
1119                    MouseEventKind::Drag(button)
1120                }
1121            } else if (button_code & 3) == 3 {
1122                // Compatibility: some terminals emit release as uppercase 'M'
1123                // with button code 3 instead of lowercase 'm'.
1124                MouseEventKind::Up(MouseButton::Left)
1125            } else {
1126                MouseEventKind::Down(button)
1127            }
1128        } else {
1129            MouseEventKind::Up(button)
1130        };
1131
1132        if self.pixel_mouse {
1133            let px = x_raw.max(0) as u32;
1134            let py = y_raw.max(0) as u32;
1135            let (x, y) = if let Some((cell_w, cell_h)) = self.cell_size_px {
1136                let cx = (px / u32::from(cell_w)).min(u32::from(u16::MAX)) as u16;
1137                let cy = (py / u32::from(cell_h)).min(u32::from(u16::MAX)) as u16;
1138                (cx, cy)
1139            } else {
1140                (0, 0)
1141            };
1142            debug!(
1143                target: crate::TARGET_INPUT_PARSER,
1144                kind = "mouse_pixel",
1145                px,
1146                py,
1147                cell_x = x,
1148                cell_y = y,
1149                "parsed SGR-Pixels mouse event"
1150            );
1151            Some(Event::Mouse(MouseEvent {
1152                kind,
1153                x,
1154                y,
1155                modifiers: mods,
1156                pixel: Some((px, py)),
1157            }))
1158        } else {
1159            Some(Event::Mouse(MouseEvent {
1160                kind,
1161                x: Self::normalize_sgr_coord(x_raw),
1162                y: Self::normalize_sgr_coord(y_raw),
1163                modifiers: mods,
1164                pixel: None,
1165            }))
1166        }
1167    }
1168
1169    #[inline]
1170    fn parse_u32_prefix(token: &str) -> Option<u32> {
1171        let bytes = token.as_bytes();
1172        let digits = bytes.iter().take_while(|b| b.is_ascii_digit()).count();
1173        if digits == 0 {
1174            return None;
1175        }
1176        token[..digits].parse().ok()
1177    }
1178
1179    #[inline]
1180    fn parse_i32_prefix(token: &str) -> Option<i32> {
1181        let bytes = token.as_bytes();
1182        if bytes.is_empty() {
1183            return None;
1184        }
1185        let start = if bytes[0] == b'-' || bytes[0] == b'+' {
1186            1
1187        } else {
1188            0
1189        };
1190        let digits = bytes[start..]
1191            .iter()
1192            .take_while(|b| b.is_ascii_digit())
1193            .count();
1194        if digits == 0 {
1195            return None;
1196        }
1197        token[..start + digits].parse().ok()
1198    }
1199
1200    #[inline]
1201    fn normalize_sgr_coord(raw: i32) -> u16 {
1202        if raw <= 1 {
1203            return 0;
1204        }
1205        let zero_indexed = raw - 1;
1206        zero_indexed.min(i32::from(u16::MAX)) as u16
1207    }
1208
1209    /// Parse legacy xterm/rxvt 1015 mouse events: `CSI Cb;Cx;Cy M`.
1210    ///
1211    /// This acts as a compatibility fallback for terminals that don't emit SGR
1212    /// mouse (`CSI < ... M/m`) despite mouse capture being enabled.
1213    fn parse_legacy_mouse(&self, params: &[u8]) -> Option<Event> {
1214        if params.is_empty() || params.starts_with(b"<") {
1215            return None;
1216        }
1217
1218        let s = std::str::from_utf8(params).ok()?;
1219        let mut parts = s.split(';');
1220        let button_code: u16 = parts.next()?.parse().ok()?;
1221        let x: u16 = parts.next()?.parse().ok()?;
1222        let y: u16 = parts.next()?.parse().ok()?;
1223        // Reject if shape doesn't match exactly Cb;Cx;Cy.
1224        if parts.next().is_some() {
1225            return None;
1226        }
1227
1228        let (button, mods) = self.decode_mouse_button(button_code);
1229        let kind = if button_code & 64 != 0 {
1230            // Scroll: bit 6 set, direction in low bits.
1231            match button_code & 3 {
1232                0 => MouseEventKind::ScrollUp,
1233                1 => MouseEventKind::ScrollDown,
1234                2 => MouseEventKind::ScrollLeft,
1235                _ => MouseEventKind::ScrollRight,
1236            }
1237        } else if button_code & 32 != 0 {
1238            // Motion: bit 5 set.
1239            if button_code & 3 == 3 {
1240                MouseEventKind::Moved
1241            } else {
1242                MouseEventKind::Drag(button)
1243            }
1244        } else if (button_code & 3) == 3 {
1245            // Legacy release doesn't identify which button was released.
1246            MouseEventKind::Up(MouseButton::Left)
1247        } else {
1248            MouseEventKind::Down(button)
1249        };
1250
1251        Some(Event::Mouse(MouseEvent {
1252            kind,
1253            x: x.saturating_sub(1),
1254            y: y.saturating_sub(1),
1255            modifiers: mods,
1256            pixel: None,
1257        }))
1258    }
1259
1260    /// Decode mouse button code to button and modifiers.
1261    fn decode_mouse_button(&self, code: u16) -> (MouseButton, Modifiers) {
1262        let button = match code & 0b11 {
1263            0 => MouseButton::Left,
1264            1 => MouseButton::Middle,
1265            2 => MouseButton::Right,
1266            _ => MouseButton::Left,
1267        };
1268
1269        let mut mods = Modifiers::NONE;
1270        if code & 4 != 0 {
1271            mods |= Modifiers::SHIFT;
1272        }
1273        if code & 8 != 0 {
1274            mods |= Modifiers::ALT;
1275        }
1276        if code & 16 != 0 {
1277            mods |= Modifiers::CTRL;
1278        }
1279
1280        (button, mods)
1281    }
1282
1283    /// Process SS3 (ESC O) sequences.
1284    fn process_ss3(&mut self, byte: u8) -> Option<Event> {
1285        // Robustness: ESC restarts sequence
1286        if byte == 0x1B {
1287            self.state = ParserState::Escape;
1288            return None;
1289        }
1290
1291        self.state = ParserState::Ground;
1292
1293        let code = match byte {
1294            b'P' => KeyCode::F(1),
1295            b'Q' => KeyCode::F(2),
1296            b'R' => KeyCode::F(3),
1297            b'S' => KeyCode::F(4),
1298            b'A' => KeyCode::Up,
1299            b'B' => KeyCode::Down,
1300            b'C' => KeyCode::Right,
1301            b'D' => KeyCode::Left,
1302            b'H' => KeyCode::Home,
1303            b'F' => KeyCode::End,
1304            _ => return None,
1305        };
1306
1307        Some(Event::Key(KeyEvent::new(code)))
1308    }
1309
1310    /// Process OSC start.
1311    fn process_osc(&mut self, byte: u8) -> Option<Event> {
1312        // Handle ESC as potential ST terminator (ESC \) - don't add to buffer
1313        if byte == 0x1B {
1314            self.state = ParserState::OscEscape;
1315            return None;
1316        }
1317
1318        self.buffer.push(byte);
1319
1320        match byte {
1321            // BEL terminates immediately
1322            0x07 => {
1323                self.state = ParserState::Ground;
1324                self.parse_osc_sequence()
1325            }
1326            // Continue collecting
1327            _ => {
1328                self.state = ParserState::OscContent;
1329                None
1330            }
1331        }
1332    }
1333
1334    /// Process OSC content.
1335    fn process_osc_content(&mut self, byte: u8) -> Option<Event> {
1336        // Handle ESC (0x1B) as potential terminator or reset
1337        if byte == 0x1B {
1338            self.state = ParserState::OscEscape;
1339            return None;
1340        }
1341
1342        // Robustness: Abort on control characters (except BEL) to prevent swallowing logs
1343        if byte < 0x20 && byte != 0x07 {
1344            self.state = ParserState::Ground;
1345            self.buffer.clear();
1346            return self.process_ground(byte);
1347        }
1348
1349        match byte {
1350            // BEL terminates. Checked before the DoS cap (mirroring the ESC/ST
1351            // path above): a terminator arriving exactly at the cap must still
1352            // end the sequence instead of being dropped into OscIgnore, which
1353            // would swallow all subsequent printable input.
1354            0x07 => {
1355                self.state = ParserState::Ground;
1356                self.parse_osc_sequence()
1357            }
1358            // Continue collecting (content accumulation is capped)
1359            _ => {
1360                if self.buffer.len() >= MAX_OSC_LEN {
1361                    self.state = ParserState::OscIgnore;
1362                    self.buffer.clear();
1363                    return None;
1364                }
1365                self.buffer.push(byte);
1366                None
1367            }
1368        }
1369    }
1370
1371    /// Process ESC inside OSC (checking for ST terminator).
1372    fn process_osc_escape(&mut self, byte: u8) -> Option<Event> {
1373        if byte == b'\\' {
1374            // ST (String Terminator) found
1375            self.state = ParserState::Ground;
1376            self.parse_osc_sequence()
1377        } else if byte == 0x1B {
1378            // ESC ESC - treat second ESC as start of new sequence (restart)
1379            self.state = ParserState::Escape;
1380            self.buffer.clear();
1381            None
1382        } else {
1383            // ESC followed by something else.
1384            // Strict ANSI would say the OSC is cancelled by the ESC.
1385            // We treat this as a restart of parsing at the *current* byte,
1386            // effectively interpreting the previous ESC as a cancel.
1387
1388            self.buffer.clear();
1389            self.state = ParserState::Escape;
1390            self.process_escape(byte)
1391        }
1392    }
1393
1394    /// Ignore bytes until end of OSC sequence.
1395    fn process_osc_ignore(&mut self, byte: u8) -> Option<Event> {
1396        match byte {
1397            // BEL terminates
1398            0x07 => {
1399                self.state = ParserState::Ground;
1400                None
1401            }
1402            // ESC might start terminator or new sequence
1403            0x1B => {
1404                self.state = ParserState::OscEscape;
1405                None
1406            }
1407            // Abort on control characters to prevent swallowing logs (except DEL 0x7F)
1408            _ if byte < 0x20 => {
1409                self.state = ParserState::Ground;
1410                self.process_ground(byte)
1411            }
1412            // Continue ignoring
1413            _ => None,
1414        }
1415    }
1416
1417    /// Accumulate bytes inside a DCS (`ESC P …`) string until its `ESC \` (ST)
1418    /// terminator, capped at [`MAX_DCS_LEN`].
1419    ///
1420    /// Per ECMA-48, BEL (`0x07`) is body data inside a DCS string (not a
1421    /// terminator); only `ESC \` terminates and emits [`TerminalResponse::Dcs`].
1422    /// Other C0 control characters (`< 0x20`) abort the string and are
1423    /// reprocessed in Ground so a truncated/never-terminated string cannot
1424    /// permanently swallow real input.
1425    fn process_dcs_body(&mut self, byte: u8) -> Option<Event> {
1426        match byte {
1427            // ESC may begin the ST (ESC \) terminator.
1428            0x1B => {
1429                self.state = ParserState::DcsEscape;
1430                None
1431            }
1432            // Abort on C0 control characters (except BEL 0x07 which is treated
1433            // as body data per ECMA-48) so a malformed string can't swallow
1434            // subsequent legitimate input.
1435            _ if byte < 0x20 && byte != 0x07 => {
1436                self.dcs_buffer.clear();
1437                self.dcs_truncated = false;
1438                self.state = ParserState::Ground;
1439                self.process_ground(byte)
1440            }
1441            // Accumulate DCS payload up to MAX_DCS_LEN.
1442            _ => {
1443                if self.dcs_buffer.len() < MAX_DCS_LEN {
1444                    self.dcs_buffer.push(byte);
1445                } else {
1446                    self.dcs_truncated = true;
1447                }
1448                None
1449            }
1450        }
1451    }
1452
1453    /// After an ESC inside a DCS string: emit [`TerminalResponse::Dcs`] on `\` (ST)
1454    /// or cancel and recover.
1455    fn process_dcs_escape(&mut self, byte: u8) -> Option<Event> {
1456        if byte == b'\\' {
1457            // ST found — emit bounded DCS response.
1458            self.state = ParserState::Ground;
1459            let payload = std::mem::take(&mut self.dcs_buffer);
1460            let truncated = std::mem::replace(&mut self.dcs_truncated, false);
1461            let len = payload.len();
1462            debug!(
1463                target: crate::TARGET_INPUT_PARSER,
1464                kind = "dcs",
1465                len,
1466                truncated,
1467                "captured DCS terminal response"
1468            );
1469            let _ = len;
1470            Some(Event::TerminalResponse(TerminalResponse::Dcs {
1471                payload,
1472                truncated,
1473            }))
1474        } else if byte == 0x1B {
1475            // ESC ESC — cancel the string and treat the second ESC as the start of a new sequence.
1476            self.dcs_buffer.clear();
1477            self.dcs_truncated = false;
1478            self.state = ParserState::Escape;
1479            None
1480        } else {
1481            // ESC followed by something else cancels the string; reprocess the
1482            // byte as a fresh escape sequence (matches OSC-escape recovery).
1483            self.dcs_buffer.clear();
1484            self.dcs_truncated = false;
1485            self.state = ParserState::Escape;
1486            self.process_escape(byte)
1487        }
1488    }
1489
1490    /// Accumulate bytes inside an APC (`ESC _ …`) string until its `ESC \` (ST)
1491    /// terminator when `capture_apc` is enabled, capped at [`MAX_DCS_LEN`].
1492    fn process_apc_body(&mut self, byte: u8) -> Option<Event> {
1493        match byte {
1494            0x1B => {
1495                self.state = ParserState::ApcEscape;
1496                None
1497            }
1498            _ if byte < 0x20 && byte != 0x07 => {
1499                self.dcs_buffer.clear();
1500                self.dcs_truncated = false;
1501                self.state = ParserState::Ground;
1502                self.process_ground(byte)
1503            }
1504            _ => {
1505                if self.dcs_buffer.len() < MAX_DCS_LEN {
1506                    self.dcs_buffer.push(byte);
1507                } else {
1508                    self.dcs_truncated = true;
1509                }
1510                None
1511            }
1512        }
1513    }
1514
1515    /// After an ESC inside an APC string: emit [`TerminalResponse::Apc`] on `\` (ST)
1516    /// or cancel and recover.
1517    fn process_apc_escape(&mut self, byte: u8) -> Option<Event> {
1518        if byte == b'\\' {
1519            self.state = ParserState::Ground;
1520            let payload = std::mem::take(&mut self.dcs_buffer);
1521            let truncated = std::mem::replace(&mut self.dcs_truncated, false);
1522            let len = payload.len();
1523            debug!(
1524                target: crate::TARGET_INPUT_PARSER,
1525                kind = "apc",
1526                len,
1527                truncated,
1528                "captured APC terminal response"
1529            );
1530            let _ = len;
1531            Some(Event::TerminalResponse(TerminalResponse::Apc {
1532                payload,
1533                truncated,
1534            }))
1535        } else if byte == 0x1B {
1536            self.dcs_buffer.clear();
1537            self.dcs_truncated = false;
1538            self.state = ParserState::Escape;
1539            None
1540        } else {
1541            self.dcs_buffer.clear();
1542            self.dcs_truncated = false;
1543            self.state = ParserState::Escape;
1544            self.process_escape(byte)
1545        }
1546    }
1547
1548    /// Parse a complete OSC sequence.
1549    fn parse_osc_sequence(&mut self) -> Option<Event> {
1550        let seq = std::mem::take(&mut self.buffer);
1551
1552        // OSC 52 clipboard response: OSC 52 ; c ; <base64> BEL/ST
1553        if seq.starts_with(b"52;") {
1554            return self.parse_osc52_clipboard(&seq);
1555        }
1556
1557        // Other OSC sequences (e.g., OSC 8 hyperlinks) are not parsed as events
1558        None
1559    }
1560
1561    /// Parse OSC 52 clipboard response.
1562    fn parse_osc52_clipboard(&self, seq: &[u8]) -> Option<Event> {
1563        // Format: 52;c;<base64> or 52;p;<base64>
1564        let content = &seq[3..]; // Skip "52;"
1565        if content.is_empty() {
1566            return None;
1567        }
1568
1569        // OSC 52 uses clipboard selectors: c=clipboard, p=primary, s=secondary
1570        // We map all to Osc52 source type since that's how we received it
1571        let source = ClipboardSource::Osc52;
1572
1573        // Skip "c;" prefix
1574        let base64_start = content.iter().position(|&b| b == b';').map(|i| i + 1)?;
1575        let base64_data = &content[base64_start..];
1576
1577        // Decode base64 (simple implementation)
1578        let decoded = self.decode_base64(base64_data)?;
1579
1580        Some(Event::Clipboard(ClipboardEvent::new(
1581            String::from_utf8_lossy(&decoded).into_owned(),
1582            source,
1583        )))
1584    }
1585
1586    /// Simple base64 decoder.
1587    fn decode_base64(&self, input: &[u8]) -> Option<Vec<u8>> {
1588        const DECODE_TABLE: [i8; 256] = {
1589            let mut table = [-1i8; 256];
1590            let mut i = 0u8;
1591            while i < 26 {
1592                table[(b'A' + i) as usize] = i as i8;
1593                table[(b'a' + i) as usize] = (i + 26) as i8;
1594                i += 1;
1595            }
1596            let mut i = 0u8;
1597            while i < 10 {
1598                table[(b'0' + i) as usize] = (i + 52) as i8;
1599                i += 1;
1600            }
1601            table[b'+' as usize] = 62;
1602            table[b'/' as usize] = 63;
1603            table
1604        };
1605
1606        let mut output = Vec::with_capacity(input.len() * 3 / 4);
1607        let mut buffer = 0u32;
1608        let mut bits = 0u8;
1609
1610        for &byte in input {
1611            if byte == b'=' {
1612                break;
1613            }
1614            let value = DECODE_TABLE[byte as usize];
1615            if value < 0 {
1616                continue; // Skip whitespace/invalid
1617            }
1618            buffer = (buffer << 6) | (value as u32);
1619            bits += 6;
1620            if bits >= 8 {
1621                bits -= 8;
1622                output.push((buffer >> bits) as u8);
1623                buffer &= (1 << bits) - 1;
1624            }
1625        }
1626
1627        Some(output)
1628    }
1629
1630    /// Process UTF-8 continuation bytes.
1631    fn process_utf8(&mut self, byte: u8, collected: u8, expected: u8, alt: bool) -> Option<Event> {
1632        let alt_mods = if alt { Modifiers::ALT } else { Modifiers::NONE };
1633
1634        // Check for valid continuation byte
1635        if (byte & 0xC0) != 0x80 {
1636            // Invalid - return to ground and re-process the unexpected byte.
1637            // Also emit a replacement character for the invalid sequence we just aborted.
1638            self.state = ParserState::Ground;
1639
1640            // Queue the replacement event for the next iteration of the parse loop
1641            self.pending_event = self.process_ground(byte);
1642
1643            return Some(Event::Key(
1644                KeyEvent::new(KeyCode::Char(std::char::REPLACEMENT_CHARACTER))
1645                    .with_modifiers(alt_mods),
1646            ));
1647        }
1648
1649        self.utf8_buffer[collected as usize] = byte;
1650        let new_collected = collected + 1;
1651
1652        if new_collected == expected {
1653            // Complete - decode and emit
1654            self.state = ParserState::Ground;
1655            match std::str::from_utf8(&self.utf8_buffer[..expected as usize]) {
1656                Ok(s) => {
1657                    let c = s.chars().next()?;
1658                    Some(Event::Key(
1659                        KeyEvent::new(KeyCode::Char(c)).with_modifiers(alt_mods),
1660                    ))
1661                }
1662                Err(_) => Some(Event::Key(
1663                    KeyEvent::new(KeyCode::Char(std::char::REPLACEMENT_CHARACTER))
1664                        .with_modifiers(alt_mods),
1665                )),
1666            }
1667        } else {
1668            // Need more bytes
1669            self.state = ParserState::Utf8 {
1670                collected: new_collected,
1671                expected,
1672                alt,
1673            };
1674            None
1675        }
1676    }
1677
1678    /// Process bytes while in X10 mouse mode.
1679    fn process_mouse_x10(&mut self, byte: u8) -> Option<Event> {
1680        if let ParserState::MouseX10 {
1681            ref mut collected,
1682            ref mut buffer,
1683        } = self.state
1684        {
1685            buffer[*collected as usize] = byte;
1686            *collected += 1;
1687
1688            if *collected == 3 {
1689                // Copy buffer before reassigning state (borrow of self.state).
1690                let buf = *buffer;
1691                self.state = ParserState::Ground;
1692
1693                // X10 encoding: byte = value + 32.
1694                // Reject malformed packets so noise bytes do not become bogus
1695                // pointer events.
1696                if buf[0] < 32 || buf[1] < 33 || buf[2] < 33 {
1697                    return None;
1698                }
1699                let cb = buf[0].saturating_sub(32) as u16;
1700                let cx = buf[1].saturating_sub(33) as u16; // 1-based -> 0-based
1701                let cy = buf[2].saturating_sub(33) as u16;
1702
1703                let (button, mods) = self.decode_mouse_button(cb);
1704
1705                // Decode order matches the SGR path: the scroll bit (64) must
1706                // be tested BEFORE the release bits, because scroll codes 66
1707                // (left) and 67 (right) also have (cb & 3) == 2/3 and would
1708                // otherwise decode as button events.
1709                // Low 2 bits when not scrolling: 0=Btn1, 1=Btn2, 2=Btn3,
1710                // 3=Release (X10 release doesn't say which button; Left).
1711                let kind = if cb & 64 != 0 {
1712                    // Scroll event (bit 6 set); direction in bits 0-1.
1713                    match cb & 3 {
1714                        0 => MouseEventKind::ScrollUp,
1715                        1 => MouseEventKind::ScrollDown,
1716                        2 => MouseEventKind::ScrollLeft,
1717                        _ => MouseEventKind::ScrollRight,
1718                    }
1719                } else if (cb & 3) == 3 {
1720                    // Release event
1721                    MouseEventKind::Up(MouseButton::Left)
1722                } else {
1723                    // Press event
1724                    MouseEventKind::Down(button)
1725                };
1726
1727                return Some(Event::Mouse(MouseEvent {
1728                    kind,
1729                    x: cx,
1730                    y: cy,
1731                    modifiers: mods,
1732                    pixel: None,
1733                }));
1734            }
1735        }
1736        None
1737    }
1738
1739    /// Process bytes while in paste mode.
1740    fn process_paste_byte(&mut self, byte: u8) -> Option<Event> {
1741        const END_SEQ: &[u8] = b"\x1b[201~";
1742
1743        // Logic:
1744        // 1. If we have room in paste_buffer, push it.
1745        // 2. If we are full, push to self.buffer (used as a tail tracker) to detect END_SEQ.
1746        // 3. Always check if the effective stream ends with END_SEQ.
1747
1748        if self.paste_buffer.len() < MAX_PASTE_LEN {
1749            self.paste_buffer.push(byte);
1750
1751            // Check for end sequence in paste_buffer
1752            if self.paste_buffer.ends_with(END_SEQ) {
1753                self.in_paste = false;
1754                // Remove the end sequence from content
1755                let content_len = self.paste_buffer.len() - END_SEQ.len();
1756                let content =
1757                    String::from_utf8_lossy(&self.paste_buffer[..content_len]).into_owned();
1758                self.paste_buffer.clear();
1759                return Some(Event::Paste(PasteEvent::bracketed(content)));
1760            }
1761        } else {
1762            // Buffer is full. DoS protection active.
1763            // We stop collecting content, but we MUST track the end sequence.
1764            // Use self.buffer as a sliding window for the tail.
1765
1766            self.buffer.push(byte);
1767            if self.buffer.len() > END_SEQ.len() {
1768                self.buffer.remove(0);
1769            }
1770
1771            // Check if we found the end sequence.
1772            // The sequence might be split between paste_buffer and buffer.
1773            // We only need to check the last 6 bytes.
1774            // Since `buffer` contains the most recent bytes (up to 6), and `paste_buffer` is full...
1775
1776            // Construct a view of the last 6 bytes
1777            let mut last_bytes = [0u8; 6];
1778            let tail_len = self.buffer.len();
1779            let paste_len = self.paste_buffer.len();
1780
1781            // Only proceed if we have enough total bytes to form the end sequence
1782            if tail_len + paste_len >= 6 {
1783                // Fill from buffer (reverse order)
1784                for i in 0..tail_len {
1785                    last_bytes[6 - tail_len + i] = self.buffer[i];
1786                }
1787                // Fill remaining from paste_buffer
1788                let remaining = 6 - tail_len;
1789                if remaining > 0 {
1790                    let start = paste_len - remaining;
1791                    last_bytes[..remaining]
1792                        .copy_from_slice(&self.paste_buffer[start..(remaining + start)]);
1793                }
1794
1795                if last_bytes == END_SEQ {
1796                    self.in_paste = false;
1797
1798                    // We found the end sequence.
1799                    // The content is `paste_buffer` MINUS the part of END_SEQ that was in it.
1800                    // `remaining` bytes of END_SEQ were in paste_buffer.
1801
1802                    let content_len = paste_len - remaining;
1803                    let content =
1804                        String::from_utf8_lossy(&self.paste_buffer[..content_len]).into_owned();
1805
1806                    self.paste_buffer.clear();
1807                    self.buffer.clear();
1808
1809                    return Some(Event::Paste(PasteEvent::bracketed(content)));
1810                }
1811            }
1812        }
1813
1814        None
1815    }
1816}
1817
1818#[cfg(test)]
1819mod tests {
1820    use super::*;
1821
1822    #[test]
1823    fn csi_ignore_handles_final_bytes() {
1824        let mut parser = InputParser::new();
1825
1826        // Create a very long CSI sequence terminated by '@' (0x40)
1827        // 0x40 is a valid Final Byte (ECMA-48), but our parser currently only checks A-Za-z~
1828        let mut seq = vec![0x1B, b'['];
1829        seq.extend(std::iter::repeat_n(b'0', MAX_CSI_LEN + 100)); // Trigger CsiIgnore
1830        seq.push(b'@'); // Final byte
1831
1832        let events = parser.parse(&seq);
1833        assert_eq!(events.len(), 0);
1834
1835        // Feed 'a'. If '@' was correctly treated as final byte, 'a' should be parsed as 'a'.
1836        // If '@' was ignored (stayed in CsiIgnore), 'a' terminates the sequence and is swallowed.
1837        let events = parser.parse(b"a");
1838        assert_eq!(events.len(), 1, "Subsequent char 'a' was swallowed");
1839        assert!(matches!(events[0], Event::Key(k) if k.code == KeyCode::Char('a')));
1840    }
1841
1842    #[test]
1843    fn legacy_key_with_kitty_event_type_subparam_decodes_release_and_mods() {
1844        // With kitty "report event types" active, legacy functional keys carry
1845        // `modifiers:event_type`. CSI 1;1:3 A = Up RELEASE (no modifiers).
1846        let mut parser = InputParser::new();
1847        let events = parser.parse(b"\x1b[1;1:3A");
1848        assert_eq!(events.len(), 1);
1849        assert!(matches!(
1850            events[0],
1851            Event::Key(k) if k.code == KeyCode::Up
1852                && k.modifiers == Modifiers::NONE
1853                && k.kind == KeyEventKind::Release
1854        ));
1855
1856        // CSI 3;5:3 ~ = Ctrl+Delete RELEASE: Ctrl must survive the sub-param.
1857        let events = parser.parse(b"\x1b[3;5:3~");
1858        assert_eq!(events.len(), 1);
1859        assert!(matches!(
1860            events[0],
1861            Event::Key(k) if k.code == KeyCode::Delete
1862                && k.modifiers == Modifiers::CTRL
1863                && k.kind == KeyEventKind::Release
1864        ));
1865
1866        // Plain legacy form is unchanged: CSI 1;5 A = Ctrl+Up press.
1867        let events = parser.parse(b"\x1b[1;5A");
1868        assert_eq!(events.len(), 1);
1869        assert!(matches!(
1870            events[0],
1871            Event::Key(k) if k.code == KeyCode::Up
1872                && k.modifiers == Modifiers::CTRL
1873                && k.kind == KeyEventKind::Press
1874        ));
1875    }
1876
1877    #[test]
1878    fn csi_final_byte_at_exact_dos_boundary_terminates() {
1879        // The real final byte arriving when the buffer holds exactly
1880        // MAX_CSI_LEN params must terminate the sequence, not be dropped
1881        // into CsiIgnore (which would then eat the next keystroke).
1882        let mut parser = InputParser::new();
1883        let mut seq = vec![0x1B, b'['];
1884        seq.extend(std::iter::repeat_n(b'0', MAX_CSI_LEN));
1885        seq.push(b'A'); // final byte exactly at the cap
1886
1887        let events = parser.parse(&seq);
1888        // The oversized sequence itself yields at most a garbage-param event;
1889        // the crucial part is the parser is back in Ground.
1890        drop(events);
1891        let events = parser.parse(b"a");
1892        assert_eq!(events.len(), 1, "keystroke after boundary CSI swallowed");
1893        assert!(matches!(events[0], Event::Key(k) if k.code == KeyCode::Char('a')));
1894    }
1895
1896    #[test]
1897    fn osc_bel_terminator_at_exact_dos_boundary_terminates() {
1898        // BEL arriving when the OSC buffer is exactly at the cap must end the
1899        // sequence; entering OscIgnore here would swallow all later printables.
1900        let mut parser = InputParser::new();
1901        let mut seq = vec![0x1B, b']'];
1902        seq.extend(std::iter::repeat_n(b'x', MAX_OSC_LEN));
1903        seq.push(0x07); // BEL exactly at the cap
1904
1905        let events = parser.parse(&seq);
1906        drop(events);
1907        let events = parser.parse(b"a");
1908        assert_eq!(events.len(), 1, "keystroke after boundary OSC swallowed");
1909        assert!(matches!(events[0], Event::Key(k) if k.code == KeyCode::Char('a')));
1910    }
1911
1912    #[test]
1913    fn stray_paste_terminator_is_ignored() {
1914        // CSI 201~ without a preceding CSI 200~ must not emit an empty Paste.
1915        let mut parser = InputParser::new();
1916        let events = parser.parse(b"\x1b[201~");
1917        assert_eq!(events.len(), 0, "stray end-paste produced {events:?}");
1918
1919        // Parser still works normally afterwards.
1920        let events = parser.parse(b"\x1b[200~hi\x1b[201~");
1921        assert_eq!(events.len(), 1);
1922        assert!(matches!(&events[0], Event::Paste(p) if p.text == "hi"));
1923    }
1924
1925    #[test]
1926    fn x10_mouse_scroll_codes_not_misread_as_button_events() {
1927        // X10 cb 64+3 = 67 (scroll-right in SGR terms) has (cb & 3) == 3 and
1928        // must decode as a scroll event, not Up(Left). Encoded byte = cb + 32.
1929        let mut parser = InputParser::new();
1930        parser.set_expect_x10_mouse(true);
1931
1932        // ESC [ M (67+32) (0+33) (0+33)
1933        let events = parser.parse(&[0x1B, b'[', b'M', 67 + 32, 33, 33]);
1934        assert_eq!(events.len(), 1);
1935        assert!(matches!(
1936            events[0],
1937            Event::Mouse(m) if m.kind == MouseEventKind::ScrollRight && m.x == 0 && m.y == 0
1938        ));
1939
1940        // Scroll-up (64) still decodes as scroll.
1941        let events = parser.parse(&[0x1B, b'[', b'M', 64 + 32, 33, 33]);
1942        assert_eq!(events.len(), 1);
1943        assert!(matches!(
1944            events[0],
1945            Event::Mouse(m) if m.kind == MouseEventKind::ScrollUp
1946        ));
1947
1948        // Plain release (3) still decodes as Up(Left).
1949        let events = parser.parse(&[0x1B, b'[', b'M', 3 + 32, 33, 33]);
1950        assert_eq!(events.len(), 1);
1951        assert!(matches!(
1952            events[0],
1953            Event::Mouse(m) if m.kind == MouseEventKind::Up(MouseButton::Left)
1954        ));
1955    }
1956
1957    #[test]
1958    fn csi_first_byte_control_char_is_reprocessed_not_swallowed() {
1959        // ESC [ CR: the CR aborts the CSI and must still deliver Enter,
1960        // matching the CsiParam/CsiIgnore anti-swallow behavior.
1961        let mut parser = InputParser::new();
1962        let events = parser.parse(b"\x1b[\r");
1963        assert_eq!(events.len(), 1);
1964        assert!(matches!(events[0], Event::Key(k) if k.code == KeyCode::Enter));
1965    }
1966
1967    #[test]
1968    fn alt_non_ascii_decodes_as_alt_char() {
1969        // metaSendsEscape + UTF-8: Alt+é arrives as ESC 0xC3 0xA9.
1970        let mut parser = InputParser::new();
1971        let events = parser.parse(b"\x1b\xc3\xa9");
1972        assert_eq!(events.len(), 1, "Alt+\u{e9} dropped: {events:?}");
1973        assert!(matches!(
1974            events[0],
1975            Event::Key(k) if k.code == KeyCode::Char('\u{e9}')
1976                && k.modifiers == Modifiers::ALT
1977        ));
1978
1979        // Split across feeds: state must persist.
1980        let events1 = parser.parse(b"\x1b\xc3");
1981        assert_eq!(events1.len(), 0);
1982        let events2 = parser.parse(b"\xa9");
1983        assert_eq!(events2.len(), 1);
1984        assert!(matches!(
1985            events2[0],
1986            Event::Key(k) if k.code == KeyCode::Char('\u{e9}')
1987                && k.modifiers == Modifiers::ALT
1988        ));
1989
1990        // Plain UTF-8 (no ESC) stays unmodified.
1991        let events = parser.parse(b"\xc3\xa9");
1992        assert_eq!(events.len(), 1);
1993        assert!(matches!(
1994            events[0],
1995            Event::Key(k) if k.code == KeyCode::Char('\u{e9}')
1996                && k.modifiers == Modifiers::NONE
1997        ));
1998    }
1999
2000    #[test]
2001    fn ascii_characters_parsed() {
2002        let mut parser = InputParser::new();
2003
2004        let events = parser.parse(b"abc");
2005        assert_eq!(events.len(), 3);
2006        assert!(matches!(events[0], Event::Key(k) if k.code == KeyCode::Char('a')));
2007        assert!(matches!(events[1], Event::Key(k) if k.code == KeyCode::Char('b')));
2008        assert!(matches!(events[2], Event::Key(k) if k.code == KeyCode::Char('c')));
2009    }
2010
2011    #[test]
2012    fn control_characters() {
2013        let mut parser = InputParser::new();
2014
2015        // Ctrl+A
2016        let events = parser.parse(&[0x01]);
2017        assert_eq!(events.len(), 1);
2018        assert!(matches!(
2019            events[0],
2020            Event::Key(k) if k.code == KeyCode::Char('a') && k.modifiers.contains(Modifiers::CTRL)
2021        ));
2022
2023        // Backspace
2024        let events = parser.parse(&[0x7F]);
2025        assert!(matches!(events[0], Event::Key(k) if k.code == KeyCode::Backspace));
2026    }
2027
2028    #[test]
2029    fn arrow_keys() {
2030        let mut parser = InputParser::new();
2031
2032        assert!(matches!(
2033            parser.parse(b"\x1b[A").first(),
2034            Some(Event::Key(k)) if k.code == KeyCode::Up
2035        ));
2036        assert!(matches!(
2037            parser.parse(b"\x1b[B").first(),
2038            Some(Event::Key(k)) if k.code == KeyCode::Down
2039        ));
2040        assert!(matches!(
2041            parser.parse(b"\x1b[C").first(),
2042            Some(Event::Key(k)) if k.code == KeyCode::Right
2043        ));
2044        assert!(matches!(
2045            parser.parse(b"\x1b[D").first(),
2046            Some(Event::Key(k)) if k.code == KeyCode::Left
2047        ));
2048    }
2049
2050    #[test]
2051    fn c1_csi_arrow_keys() {
2052        let mut parser = InputParser::new();
2053
2054        assert!(matches!(
2055            parser.parse(&[0x9B, b'A']).first(),
2056            Some(Event::Key(k)) if k.code == KeyCode::Up
2057        ));
2058        assert!(matches!(
2059            parser.parse(&[0x9B, b'B']).first(),
2060            Some(Event::Key(k)) if k.code == KeyCode::Down
2061        ));
2062    }
2063
2064    #[test]
2065    fn c1_csi_mouse_sgr_protocol() {
2066        let mut parser = InputParser::new();
2067
2068        let events = parser.parse(&[0x9B, b'<', b'0', b';', b'1', b'0', b';', b'2', b'0', b'M']);
2069        assert!(matches!(
2070            events.first(),
2071            Some(Event::Mouse(m)) if m.x == 9 && m.y == 19
2072        ));
2073    }
2074
2075    #[test]
2076    fn function_keys_ss3() {
2077        let mut parser = InputParser::new();
2078
2079        assert!(matches!(
2080            parser.parse(b"\x1bOP").first(),
2081            Some(Event::Key(k)) if k.code == KeyCode::F(1)
2082        ));
2083        assert!(matches!(
2084            parser.parse(b"\x1bOQ").first(),
2085            Some(Event::Key(k)) if k.code == KeyCode::F(2)
2086        ));
2087        assert!(matches!(
2088            parser.parse(b"\x1bOR").first(),
2089            Some(Event::Key(k)) if k.code == KeyCode::F(3)
2090        ));
2091        assert!(matches!(
2092            parser.parse(b"\x1bOS").first(),
2093            Some(Event::Key(k)) if k.code == KeyCode::F(4)
2094        ));
2095    }
2096
2097    #[test]
2098    fn function_keys_csi() {
2099        let mut parser = InputParser::new();
2100
2101        assert!(matches!(
2102            parser.parse(b"\x1b[15~").first(),
2103            Some(Event::Key(k)) if k.code == KeyCode::F(5)
2104        ));
2105        assert!(matches!(
2106            parser.parse(b"\x1b[17~").first(),
2107            Some(Event::Key(k)) if k.code == KeyCode::F(6)
2108        ));
2109    }
2110
2111    #[test]
2112    fn modifiers_in_csi() {
2113        let mut parser = InputParser::new();
2114
2115        // Shift+Up: CSI 1;2 A
2116        let events = parser.parse(b"\x1b[1;2A");
2117        assert!(matches!(
2118            events.first(),
2119            Some(Event::Key(k)) if k.code == KeyCode::Up && k.modifiers.contains(Modifiers::SHIFT)
2120        ));
2121
2122        // Ctrl+Up: CSI 1;5 A
2123        let events = parser.parse(b"\x1b[1;5A");
2124        assert!(matches!(
2125            events.first(),
2126            Some(Event::Key(k)) if k.code == KeyCode::Up && k.modifiers.contains(Modifiers::CTRL)
2127        ));
2128    }
2129
2130    #[test]
2131    fn modifiers_in_csi_alt_ctrl() {
2132        let mut parser = InputParser::new();
2133
2134        // Alt+Ctrl+Up: CSI 1;7 A (1 + ALT(2) + CTRL(4) = 7)
2135        let events = parser.parse(b"\x1b[1;7A");
2136        assert!(matches!(
2137            events.first(),
2138            Some(Event::Key(k))
2139                if k.code == KeyCode::Up
2140                    && k.modifiers.contains(Modifiers::ALT)
2141                    && k.modifiers.contains(Modifiers::CTRL)
2142        ));
2143    }
2144
2145    #[test]
2146    fn kitty_keyboard_basic_char() {
2147        let mut parser = InputParser::new();
2148
2149        let events = parser.parse(b"\x1b[97u");
2150        assert!(matches!(
2151            events.first(),
2152            Some(Event::Key(k))
2153                if k.code == KeyCode::Char('a')
2154                    && k.modifiers == Modifiers::NONE
2155                    && k.kind == KeyEventKind::Press
2156        ));
2157    }
2158
2159    #[test]
2160    fn kitty_keyboard_with_modifiers_and_kind() {
2161        let mut parser = InputParser::new();
2162
2163        // Ctrl+repeat for 'a' (modifiers=5, event_type=2)
2164        let events = parser.parse(b"\x1b[97;5:2u");
2165        assert!(matches!(
2166            events.first(),
2167            Some(Event::Key(k))
2168                if k.code == KeyCode::Char('a')
2169                    && k.modifiers.contains(Modifiers::CTRL)
2170                    && k.kind == KeyEventKind::Repeat
2171        ));
2172    }
2173
2174    #[test]
2175    fn kitty_keyboard_function_key() {
2176        let mut parser = InputParser::new();
2177
2178        let events = parser.parse(b"\x1b[57364;1u");
2179        assert!(matches!(
2180            events.first(),
2181            Some(Event::Key(k)) if k.code == KeyCode::F(1)
2182        ));
2183    }
2184
2185    #[test]
2186    fn kitty_keyboard_types_the_shifted_character() {
2187        let key = |input: &[u8]| match InputParser::new().parse(input).first() {
2188            Some(Event::Key(k)) => (k.code, k.modifiers),
2189            other => panic!("{input:?}: {other:?}"),
2190        };
2191        let shift = Modifiers::SHIFT;
2192
2193        // Shift+a with the shifted key, and without it.
2194        assert_eq!(key(b"\x1b[97:65;2u"), (KeyCode::Char('A'), shift));
2195        assert_eq!(key(b"\x1b[97;2u"), (KeyCode::Char('A'), shift));
2196        // The shifted key decides for symbols: Shift+1 on a US layout.
2197        assert_eq!(key(b"\x1b[49:33;2u"), (KeyCode::Char('!'), shift));
2198        // An empty shifted field falls back like a missing one.
2199        assert_eq!(key(b"\x1b[97::97;2u"), (KeyCode::Char('A'), shift));
2200        // Caps Lock (64) inverts letter case; with Shift it gives lower case.
2201        assert_eq!(key(b"\x1b[97;65u"), (KeyCode::Char('A'), Modifiers::NONE));
2202        assert_eq!(key(b"\x1b[97:65;66u"), (KeyCode::Char('a'), shift));
2203        assert_eq!(key(b"\x1b[49;65u"), (KeyCode::Char('1'), Modifiers::NONE));
2204        // Unshifted keys are unchanged.
2205        assert_eq!(key(b"\x1b[97u"), (KeyCode::Char('a'), Modifiers::NONE));
2206        assert_eq!(key(b"\x1b[97;5u"), (KeyCode::Char('a'), Modifiers::CTRL));
2207        assert_eq!(
2208            key(b"\x1b[97:65;6u"),
2209            (KeyCode::Char('A'), Modifiers::CTRL | shift)
2210        );
2211    }
2212
2213    #[test]
2214    fn kitty_keyboard_keypad_and_media_keys() {
2215        let key = |input: &[u8]| match InputParser::new().parse(input).first() {
2216            Some(Event::Key(k)) => (k.code, k.modifiers, k.kind),
2217            other => panic!("{input:?}: {other:?}"),
2218        };
2219        let press = KeyEventKind::Press;
2220
2221        assert_eq!(key(b"\x1b[57399u").0, KeyCode::Char('0'));
2222        assert_eq!(key(b"\x1b[57404u").0, KeyCode::Char('5'));
2223        assert_eq!(key(b"\x1b[57408u").0, KeyCode::Char('9'));
2224        assert_eq!(key(b"\x1b[57409u").0, KeyCode::Char('.'));
2225        assert_eq!(key(b"\x1b[57413u").0, KeyCode::Char('+'));
2226        assert_eq!(key(b"\x1b[57414u").0, KeyCode::Enter);
2227        assert_eq!(key(b"\x1b[57426u").0, KeyCode::Delete);
2228        assert_eq!(
2229            key(b"\x1b[57419;1:3u"),
2230            (KeyCode::Up, Modifiers::NONE, KeyEventKind::Release)
2231        );
2232        // Shift on a keypad key does not change the character.
2233        assert_eq!(
2234            key(b"\x1b[57400;2u"),
2235            (KeyCode::Char('1'), Modifiers::SHIFT, press)
2236        );
2237        assert_eq!(key(b"\x1b[57430u").0, KeyCode::MediaPlayPause);
2238        assert_eq!(key(b"\x1b[57436u").0, KeyCode::MediaPrevTrack);
2239        // Modifier keys on their own still report nothing.
2240        assert!(InputParser::new().parse(b"\x1b[57441u").is_empty());
2241    }
2242
2243    #[test]
2244    fn alt_key_escapes() {
2245        let mut parser = InputParser::new();
2246
2247        let events = parser.parse(b"\x1ba");
2248        assert!(matches!(
2249            events.first(),
2250            Some(Event::Key(k)) if k.code == KeyCode::Char('a') && k.modifiers.contains(Modifiers::ALT)
2251        ));
2252    }
2253
2254    #[test]
2255    fn alt_backspace() {
2256        let mut parser = InputParser::new();
2257
2258        let events = parser.parse(b"\x1b\x7f");
2259        assert!(matches!(
2260            events.first(),
2261            Some(Event::Key(k))
2262                if k.code == KeyCode::Backspace && k.modifiers.contains(Modifiers::ALT)
2263        ));
2264    }
2265
2266    #[test]
2267    fn escape_escape_resets_state() {
2268        let mut parser = InputParser::new();
2269
2270        let events = parser.parse(b"\x1b\x1b");
2271        assert!(matches!(
2272            events.first(),
2273            Some(Event::Key(k)) if k.code == KeyCode::Escape && k.modifiers.contains(Modifiers::ALT)
2274        ));
2275
2276        let events = parser.parse(b"a");
2277        assert!(matches!(
2278            events.first(),
2279            Some(Event::Key(k)) if k.code == KeyCode::Char('a') && k.modifiers == Modifiers::NONE
2280        ));
2281    }
2282
2283    #[test]
2284    fn focus_events() {
2285        let mut parser = InputParser::new();
2286
2287        assert!(matches!(
2288            parser.parse(b"\x1b[I").first(),
2289            Some(Event::Focus(true))
2290        ));
2291        assert!(matches!(
2292            parser.parse(b"\x1b[O").first(),
2293            Some(Event::Focus(false))
2294        ));
2295    }
2296
2297    #[test]
2298    fn bracketed_paste() {
2299        let mut parser = InputParser::new();
2300
2301        // Start paste mode, paste content, end paste mode
2302        let events = parser.parse(b"\x1b[200~hello world\x1b[201~");
2303        assert_eq!(events.len(), 1);
2304        assert!(matches!(
2305            &events[0],
2306            Event::Paste(p) if p.text == "hello world"
2307        ));
2308    }
2309
2310    #[test]
2311    fn mouse_sgr_protocol() {
2312        let mut parser = InputParser::new();
2313
2314        // Left click at (10, 20)
2315        let events = parser.parse(b"\x1b[<0;10;20M");
2316        assert!(matches!(
2317            events.first(),
2318            Some(Event::Mouse(m)) if m.x == 9 && m.y == 19 // 0-indexed
2319        ));
2320    }
2321
2322    #[test]
2323    fn mouse_sgr_protocol_with_subparams() {
2324        let mut parser = InputParser::new();
2325
2326        // Accept numeric prefixes when terminals include sub-params.
2327        let events = parser.parse(b"\x1b[<0:0;10:0;20:0M");
2328        assert!(matches!(
2329            events.first(),
2330            Some(Event::Mouse(m))
2331                if matches!(m.kind, MouseEventKind::Down(MouseButton::Left))
2332                    && m.x == 9
2333                    && m.y == 19
2334        ));
2335    }
2336
2337    #[test]
2338    fn mouse_sgr_protocol_large_coords_clamped() {
2339        let mut parser = InputParser::new();
2340
2341        // Coordinates beyond u16 range should be clamped instead of dropped.
2342        let events = parser.parse(b"\x1b[<0;70000;80000M");
2343        assert!(matches!(
2344            events.first(),
2345            Some(Event::Mouse(m))
2346                if matches!(m.kind, MouseEventKind::Down(MouseButton::Left))
2347                    && m.x == u16::MAX
2348                    && m.y == u16::MAX
2349        ));
2350    }
2351
2352    #[test]
2353    fn mouse_sgr_protocol_negative_coords_clamped() {
2354        let mut parser = InputParser::new();
2355
2356        // Some pixel-mouse emitters can report negative coords near edges.
2357        // Clamp to origin rather than dropping the event.
2358        let events = parser.parse(b"\x1b[<0;-12;-3M");
2359        assert!(matches!(
2360            events.first(),
2361            Some(Event::Mouse(m))
2362                if matches!(m.kind, MouseEventKind::Down(MouseButton::Left))
2363                    && m.x == 0
2364                    && m.y == 0
2365        ));
2366    }
2367
2368    #[test]
2369    fn mouse_sgr_modifiers() {
2370        let mut parser = InputParser::new();
2371
2372        // Shift+Alt+Ctrl + left button (0 + 4 + 8 + 16 = 28)
2373        let events = parser.parse(b"\x1b[<28;3;4M");
2374        assert!(matches!(
2375            events.first(),
2376            Some(Event::Mouse(m))
2377                if m.modifiers.contains(Modifiers::SHIFT)
2378                    && m.modifiers.contains(Modifiers::ALT)
2379                    && m.modifiers.contains(Modifiers::CTRL)
2380        ));
2381    }
2382
2383    #[test]
2384    fn mouse_sgr_scroll_up() {
2385        let mut parser = InputParser::new();
2386
2387        // Scroll up: button code 64
2388        let events = parser.parse(b"\x1b[<64;5;5M");
2389        assert!(matches!(
2390            events.first(),
2391            Some(Event::Mouse(m)) if matches!(m.kind, MouseEventKind::ScrollUp)
2392        ));
2393    }
2394
2395    #[test]
2396    fn mouse_sgr_scroll_down() {
2397        let mut parser = InputParser::new();
2398
2399        // Scroll down: button code 65
2400        let events = parser.parse(b"\x1b[<65;5;5M");
2401        assert!(matches!(
2402            events.first(),
2403            Some(Event::Mouse(m)) if matches!(m.kind, MouseEventKind::ScrollDown)
2404        ));
2405    }
2406
2407    #[test]
2408    fn mouse_sgr_scroll_left() {
2409        let mut parser = InputParser::new();
2410
2411        // Scroll left: button code 66
2412        let events = parser.parse(b"\x1b[<66;5;5M");
2413        assert!(matches!(
2414            events.first(),
2415            Some(Event::Mouse(m)) if matches!(m.kind, MouseEventKind::ScrollLeft)
2416        ));
2417    }
2418
2419    #[test]
2420    fn mouse_sgr_scroll_right() {
2421        let mut parser = InputParser::new();
2422
2423        // Scroll right: button code 67
2424        let events = parser.parse(b"\x1b[<67;5;5M");
2425        assert!(matches!(
2426            events.first(),
2427            Some(Event::Mouse(m)) if matches!(m.kind, MouseEventKind::ScrollRight)
2428        ));
2429    }
2430
2431    #[test]
2432    fn mouse_sgr_drag_left() {
2433        let mut parser = InputParser::new();
2434
2435        // Drag with left button: button code 32
2436        let events = parser.parse(b"\x1b[<32;10;20M");
2437        assert!(matches!(
2438            events.first(),
2439            Some(Event::Mouse(m)) if matches!(m.kind, MouseEventKind::Drag(MouseButton::Left))
2440        ));
2441    }
2442
2443    #[test]
2444    fn utf8_characters() {
2445        let mut parser = InputParser::new();
2446
2447        // é (U+00E9) = 0xC3 0xA9
2448        let events = parser.parse(&[0xC3, 0xA9]);
2449        assert!(matches!(
2450            events.first(),
2451            Some(Event::Key(k)) if k.code == KeyCode::Char('é')
2452        ));
2453    }
2454
2455    #[test]
2456    fn invalid_utf8_emits_replacement_then_reprocesses_byte() {
2457        let mut parser = InputParser::new();
2458
2459        // 0xE2 expects a 3-byte sequence, 0x28 is invalid continuation.
2460        let events = parser.parse(&[0xE2, 0x28]);
2461        assert_eq!(events.len(), 2);
2462        assert!(matches!(
2463            events[0],
2464            Event::Key(k) if k.code == KeyCode::Char(std::char::REPLACEMENT_CHARACTER)
2465        ));
2466        assert!(matches!(
2467            events[1],
2468            Event::Key(k) if k.code == KeyCode::Char('(')
2469        ));
2470    }
2471
2472    #[test]
2473    fn dos_protection_csi() {
2474        let mut parser = InputParser::new();
2475
2476        // Create a very long CSI sequence
2477        let mut seq = vec![0x1B, b'['];
2478        seq.extend(std::iter::repeat_n(b'0', MAX_CSI_LEN + 100));
2479        seq.push(b'A');
2480
2481        // DoS protection kicks in and switches to CsiIgnore
2482        // Excess bytes should be ignored, NOT leaked as characters
2483        let events = parser.parse(&seq);
2484        assert_eq!(
2485            events.len(),
2486            0,
2487            "Oversized CSI sequence should produce no events"
2488        );
2489
2490        // The key invariant: parser should be back in ground state and functional
2491        // Verify by parsing a normal sequence after the attack
2492        let events = parser.parse(b"\x1b[A");
2493        assert!(matches!(
2494            events.first(),
2495            Some(Event::Key(k)) if k.code == KeyCode::Up
2496        ));
2497    }
2498
2499    #[test]
2500    fn incomplete_csi_sequence_emits_no_event() {
2501        let mut parser = InputParser::new();
2502        let events = parser.parse(b"\x1b[");
2503        assert!(events.is_empty());
2504    }
2505
2506    #[test]
2507    fn dos_protection_paste() {
2508        let mut parser = InputParser::new();
2509
2510        // Start paste mode
2511        parser.parse(b"\x1b[200~");
2512
2513        // Paste content up to the limit
2514        let content = vec![b'x'; MAX_PASTE_LEN - 100]; // Leave room for end sequence
2515        parser.parse(&content);
2516
2517        // End paste mode
2518        let events = parser.parse(b"\x1b[201~");
2519
2520        // Should have collected content up to limit
2521        assert!(matches!(
2522            events.first(),
2523            Some(Event::Paste(p)) if p.text.len() <= MAX_PASTE_LEN
2524        ));
2525    }
2526
2527    #[test]
2528    fn dos_protection_paste_overflow_terminator() {
2529        let mut parser = InputParser::new();
2530
2531        // Start paste mode
2532        parser.parse(b"\x1b[200~");
2533
2534        // Overflow the buffer by pushing more than MAX_PASTE_LEN bytes.
2535        // DoS protection stops collecting content once buffer is full,
2536        // but continues tracking the end sequence to properly exit paste mode.
2537        let overflow = 100;
2538        let content = vec![b'a'; MAX_PASTE_LEN + overflow];
2539        parser.parse(&content);
2540
2541        // Send terminator - parser MUST detect it and exit paste mode.
2542        // Even though the buffer overflowed, the terminator detection still works.
2543        let events = parser.parse(b"\x1b[201~");
2544
2545        assert_eq!(events.len(), 1, "Should emit paste event");
2546        match &events[0] {
2547            Event::Paste(p) => {
2548                // Content is capped at MAX_PASTE_LEN due to DoS protection.
2549                // Overflow bytes are discarded but terminator is still detected.
2550                assert_eq!(
2551                    p.text.len(),
2552                    MAX_PASTE_LEN,
2553                    "Paste should be capped at MAX_PASTE_LEN bytes"
2554                );
2555                // The content should be all 'a' since we filled with 'a'
2556                assert!(p.text.chars().all(|c| c == 'a'));
2557            }
2558            _ => unreachable!("Expected Paste event"),
2559        }
2560
2561        // Verify we are back in ground state by parsing a key
2562        let events = parser.parse(b"b");
2563        assert_eq!(events.len(), 1);
2564        assert!(matches!(events[0], Event::Key(k) if k.code == KeyCode::Char('b')));
2565    }
2566
2567    #[test]
2568    fn no_panic_on_invalid_input() {
2569        let mut parser = InputParser::new();
2570
2571        // Random bytes that might trip up the parser
2572        let garbage = [0xFF, 0xFE, 0x00, 0x1B, 0x1B, 0x1B, b'[', 0xFF, b']', 0x00];
2573
2574        // Should not panic
2575        let _ = parser.parse(&garbage);
2576    }
2577
2578    #[test]
2579    fn dos_protection_paste_boundary() {
2580        let mut parser = InputParser::new();
2581        // Start paste mode
2582        parser.parse(b"\x1b[200~");
2583
2584        // Fill buffer exactly to limit
2585        let content = vec![b'x'; MAX_PASTE_LEN];
2586        parser.parse(&content);
2587
2588        // Send end sequence
2589        // This will be processed by the DoS protection fallback logic
2590        let events = parser.parse(b"\x1b[201~");
2591
2592        assert!(
2593            !events.is_empty(),
2594            "Parser trapped in paste mode after hitting limit"
2595        );
2596        assert!(matches!(events[0], Event::Paste(_)));
2597    }
2598
2599    // ── Navigation keys via CSI ~ sequences ──────────────────────────
2600
2601    #[test]
2602    fn csi_tilde_home() {
2603        let mut parser = InputParser::new();
2604        let events = parser.parse(b"\x1b[1~");
2605        assert!(matches!(
2606            events.first(),
2607            Some(Event::Key(k)) if k.code == KeyCode::Home
2608        ));
2609    }
2610
2611    #[test]
2612    fn csi_tilde_insert() {
2613        let mut parser = InputParser::new();
2614        let events = parser.parse(b"\x1b[2~");
2615        assert!(matches!(
2616            events.first(),
2617            Some(Event::Key(k)) if k.code == KeyCode::Insert
2618        ));
2619    }
2620
2621    #[test]
2622    fn csi_tilde_delete() {
2623        let mut parser = InputParser::new();
2624        let events = parser.parse(b"\x1b[3~");
2625        assert!(matches!(
2626            events.first(),
2627            Some(Event::Key(k)) if k.code == KeyCode::Delete
2628        ));
2629    }
2630
2631    #[test]
2632    fn csi_tilde_end() {
2633        let mut parser = InputParser::new();
2634        let events = parser.parse(b"\x1b[4~");
2635        assert!(matches!(
2636            events.first(),
2637            Some(Event::Key(k)) if k.code == KeyCode::End
2638        ));
2639    }
2640
2641    #[test]
2642    fn csi_tilde_page_up() {
2643        let mut parser = InputParser::new();
2644        let events = parser.parse(b"\x1b[5~");
2645        assert!(matches!(
2646            events.first(),
2647            Some(Event::Key(k)) if k.code == KeyCode::PageUp
2648        ));
2649    }
2650
2651    #[test]
2652    fn csi_tilde_page_down() {
2653        let mut parser = InputParser::new();
2654        let events = parser.parse(b"\x1b[6~");
2655        assert!(matches!(
2656            events.first(),
2657            Some(Event::Key(k)) if k.code == KeyCode::PageDown
2658        ));
2659    }
2660
2661    // ── Navigation keys via CSI H/F (xterm-style) ───────────────────
2662
2663    #[test]
2664    fn csi_home_and_end() {
2665        let mut parser = InputParser::new();
2666        assert!(matches!(
2667            parser.parse(b"\x1b[H").first(),
2668            Some(Event::Key(k)) if k.code == KeyCode::Home
2669        ));
2670        assert!(matches!(
2671            parser.parse(b"\x1b[F").first(),
2672            Some(Event::Key(k)) if k.code == KeyCode::End
2673        ));
2674    }
2675
2676    // ── SS3 Home/End ─────────────────────────────────────────────────
2677
2678    #[test]
2679    fn ss3_home_and_end() {
2680        let mut parser = InputParser::new();
2681        assert!(matches!(
2682            parser.parse(b"\x1bOH").first(),
2683            Some(Event::Key(k)) if k.code == KeyCode::Home
2684        ));
2685        assert!(matches!(
2686            parser.parse(b"\x1bOF").first(),
2687            Some(Event::Key(k)) if k.code == KeyCode::End
2688        ));
2689    }
2690
2691    // ── BackTab (Shift+Tab via CSI Z) ────────────────────────────────
2692
2693    #[test]
2694    fn backtab_csi_z() {
2695        let mut parser = InputParser::new();
2696        let events = parser.parse(b"\x1b[Z");
2697        assert!(matches!(
2698            events.first(),
2699            Some(Event::Key(k)) if k.code == KeyCode::BackTab
2700        ));
2701    }
2702
2703    // ── F7-F12 keys via CSI tilde ────────────────────────────────────
2704
2705    #[test]
2706    fn function_keys_f7_to_f12() {
2707        let mut parser = InputParser::new();
2708        assert!(matches!(
2709            parser.parse(b"\x1b[18~").first(),
2710            Some(Event::Key(k)) if k.code == KeyCode::F(7)
2711        ));
2712        assert!(matches!(
2713            parser.parse(b"\x1b[19~").first(),
2714            Some(Event::Key(k)) if k.code == KeyCode::F(8)
2715        ));
2716        assert!(matches!(
2717            parser.parse(b"\x1b[20~").first(),
2718            Some(Event::Key(k)) if k.code == KeyCode::F(9)
2719        ));
2720        assert!(matches!(
2721            parser.parse(b"\x1b[21~").first(),
2722            Some(Event::Key(k)) if k.code == KeyCode::F(10)
2723        ));
2724        assert!(matches!(
2725            parser.parse(b"\x1b[23~").first(),
2726            Some(Event::Key(k)) if k.code == KeyCode::F(11)
2727        ));
2728        assert!(matches!(
2729            parser.parse(b"\x1b[24~").first(),
2730            Some(Event::Key(k)) if k.code == KeyCode::F(12)
2731        ));
2732    }
2733
2734    // ── Modifier combinations on navigation keys ─────────────────────
2735
2736    #[test]
2737    fn ctrl_home_and_alt_end() {
2738        let mut parser = InputParser::new();
2739
2740        // Ctrl+Home: CSI 1;5 H
2741        let events = parser.parse(b"\x1b[1;5H");
2742        assert!(matches!(
2743            events.first(),
2744            Some(Event::Key(k)) if k.code == KeyCode::Home && k.modifiers.contains(Modifiers::CTRL)
2745        ));
2746
2747        // Alt+End: CSI 1;3 F
2748        let events = parser.parse(b"\x1b[1;3F");
2749        assert!(matches!(
2750            events.first(),
2751            Some(Event::Key(k)) if k.code == KeyCode::End && k.modifiers.contains(Modifiers::ALT)
2752        ));
2753    }
2754
2755    #[test]
2756    fn shift_ctrl_arrow() {
2757        let mut parser = InputParser::new();
2758
2759        // Shift+Ctrl+Right: CSI 1;6 C (modifier value 6 = 1 + Shift|Ctrl = 1 + 5)
2760        let events = parser.parse(b"\x1b[1;6C");
2761        assert!(matches!(
2762            events.first(),
2763            Some(Event::Key(k)) if k.code == KeyCode::Right
2764                && k.modifiers.contains(Modifiers::SHIFT)
2765                && k.modifiers.contains(Modifiers::CTRL)
2766        ));
2767    }
2768
2769    #[test]
2770    fn modifiers_on_tilde_keys() {
2771        let mut parser = InputParser::new();
2772
2773        // Ctrl+Delete: CSI 3;5 ~
2774        let events = parser.parse(b"\x1b[3;5~");
2775        assert!(matches!(
2776            events.first(),
2777            Some(Event::Key(k)) if k.code == KeyCode::Delete && k.modifiers.contains(Modifiers::CTRL)
2778        ));
2779
2780        // Shift+PageUp: CSI 5;2 ~
2781        let events = parser.parse(b"\x1b[5;2~");
2782        assert!(matches!(
2783            events.first(),
2784            Some(Event::Key(k)) if k.code == KeyCode::PageUp && k.modifiers.contains(Modifiers::SHIFT)
2785        ));
2786    }
2787
2788    // ── Mouse right/middle click and release ─────────────────────────
2789
2790    #[test]
2791    fn mouse_sgr_right_click() {
2792        let mut parser = InputParser::new();
2793        // Right click: button code 2
2794        let events = parser.parse(b"\x1b[<2;15;10M");
2795        assert!(matches!(
2796            events.first(),
2797            Some(Event::Mouse(m)) if matches!(m.kind, MouseEventKind::Down(MouseButton::Right))
2798                && m.x == 14 && m.y == 9
2799        ));
2800    }
2801
2802    #[test]
2803    fn mouse_sgr_middle_click() {
2804        let mut parser = InputParser::new();
2805        // Middle click: button code 1
2806        let events = parser.parse(b"\x1b[<1;5;5M");
2807        assert!(matches!(
2808            events.first(),
2809            Some(Event::Mouse(m)) if matches!(m.kind, MouseEventKind::Down(MouseButton::Middle))
2810        ));
2811    }
2812
2813    #[test]
2814    fn mouse_sgr_button_release() {
2815        let mut parser = InputParser::new();
2816        // Left button release: final byte 'm'
2817        let events = parser.parse(b"\x1b[<0;10;20m");
2818        assert!(matches!(
2819            events.first(),
2820            Some(Event::Mouse(m)) if matches!(m.kind, MouseEventKind::Up(MouseButton::Left))
2821        ));
2822    }
2823
2824    #[test]
2825    fn mouse_sgr_button_release_uppercase_m_compat() {
2826        let mut parser = InputParser::new();
2827        // Compatibility release encoding used by some terminals:
2828        // final byte 'M' with low bits == 3.
2829        let events = parser.parse(b"\x1b[<3;10;20M");
2830        assert!(matches!(
2831            events.first(),
2832            Some(Event::Mouse(m))
2833                if matches!(m.kind, MouseEventKind::Up(MouseButton::Left))
2834                    && m.x == 9
2835                    && m.y == 19
2836        ));
2837    }
2838
2839    #[test]
2840    fn mouse_sgr_moved() {
2841        let mut parser = InputParser::new();
2842        // Mouse move (no button): button code 35 (32 | 3, bit 5 set + bits 0-1 = 3)
2843        let events = parser.parse(b"\x1b[<35;10;20M");
2844        assert!(matches!(
2845            events.first(),
2846            Some(Event::Mouse(m)) if matches!(m.kind, MouseEventKind::Moved)
2847        ));
2848    }
2849
2850    #[test]
2851    fn mouse_sgr_with_modifiers() {
2852        let mut parser = InputParser::new();
2853        // Shift+Left click: button_code bit 2 set (shift) = 4
2854        let events = parser.parse(b"\x1b[<4;5;5M");
2855        assert!(matches!(
2856            events.first(),
2857            Some(Event::Mouse(m)) if matches!(m.kind, MouseEventKind::Down(MouseButton::Left))
2858                && m.modifiers.contains(Modifiers::SHIFT)
2859        ));
2860
2861        // Ctrl+Left click: button_code bit 4 set (ctrl) = 16
2862        let events = parser.parse(b"\x1b[<16;5;5M");
2863        assert!(matches!(
2864            events.first(),
2865            Some(Event::Mouse(m)) if matches!(m.kind, MouseEventKind::Down(MouseButton::Left))
2866                && m.modifiers.contains(Modifiers::CTRL)
2867        ));
2868
2869        // Alt+Left click: button_code bit 3 set (alt) = 8
2870        let events = parser.parse(b"\x1b[<8;5;5M");
2871        assert!(matches!(
2872            events.first(),
2873            Some(Event::Mouse(m)) if matches!(m.kind, MouseEventKind::Down(MouseButton::Left))
2874                && m.modifiers.contains(Modifiers::ALT)
2875        ));
2876    }
2877
2878    #[test]
2879    fn mouse_legacy_1015_when_enabled() {
2880        let mut parser = InputParser::new();
2881        parser.set_expect_x10_mouse(true);
2882
2883        let events = parser.parse(b"\x1b[0;10;20M");
2884        assert!(matches!(
2885            events.first(),
2886            Some(Event::Mouse(m)) if matches!(m.kind, MouseEventKind::Down(MouseButton::Left))
2887                && m.x == 9 && m.y == 19
2888        ));
2889    }
2890
2891    #[test]
2892    fn mouse_legacy_1015_with_fallback_enabled() {
2893        let mut parser = InputParser::new();
2894        parser.set_allow_legacy_mouse(true);
2895
2896        let events = parser.parse(b"\x1b[0;10;20M");
2897        assert!(matches!(
2898            events.first(),
2899            Some(Event::Mouse(m)) if matches!(m.kind, MouseEventKind::Down(MouseButton::Left))
2900                && m.x == 9 && m.y == 19
2901        ));
2902    }
2903
2904    #[test]
2905    fn mouse_legacy_1015_ignored_when_disabled() {
2906        let mut parser = InputParser::new();
2907        let events = parser.parse(b"\x1b[0;10;20M");
2908        assert!(
2909            events.is_empty(),
2910            "legacy mouse should require explicit opt-in"
2911        );
2912    }
2913
2914    #[test]
2915    fn mouse_x10_when_enabled() {
2916        let mut parser = InputParser::new();
2917        parser.set_expect_x10_mouse(true);
2918
2919        let events = parser.parse(&[0x1B, b'[', b'M', 32, 42, 52]);
2920        assert!(matches!(
2921            events.first(),
2922            Some(Event::Mouse(m)) if matches!(m.kind, MouseEventKind::Down(MouseButton::Left))
2923                && m.x == 9 && m.y == 19
2924        ));
2925    }
2926
2927    #[test]
2928    fn mouse_x10_malformed_packet_ignored() {
2929        let mut parser = InputParser::new();
2930        parser.set_expect_x10_mouse(true);
2931
2932        // Invalid X10 payload bytes (<32 / <33) should be dropped.
2933        let events = parser.parse(&[0x1B, b'[', b'M', 31, 0, 10]);
2934        assert!(
2935            events.iter().all(|event| !matches!(event, Event::Mouse(_))),
2936            "malformed X10 payload must not emit mouse events"
2937        );
2938    }
2939
2940    // ── Kitty keyboard release events and special keys ───────────────
2941
2942    #[test]
2943    fn kitty_keyboard_release_event() {
2944        let mut parser = InputParser::new();
2945        // Release event: kind=3
2946        let events = parser.parse(b"\x1b[97;1:3u");
2947        assert!(matches!(
2948            events.first(),
2949            Some(Event::Key(k)) if k.code == KeyCode::Char('a') && k.kind == KeyEventKind::Release
2950        ));
2951
2952        // Ctrl+release for 'A' (modifiers=5, event_type=3)
2953        let events = parser.parse(b"\x1b[65;5:3u");
2954        assert!(matches!(
2955            events.first(),
2956            Some(Event::Key(k))
2957                if k.code == KeyCode::Char('A')
2958                    && k.modifiers.contains(Modifiers::CTRL)
2959                    && k.kind == KeyEventKind::Release
2960        ));
2961    }
2962
2963    #[test]
2964    fn kitty_keyboard_special_keys() {
2965        let mut parser = InputParser::new();
2966
2967        // Escape: 57344
2968        assert!(matches!(
2969            parser.parse(b"\x1b[57344u").first(),
2970            Some(Event::Key(k)) if k.code == KeyCode::Escape
2971        ));
2972
2973        // Enter: 57345
2974        assert!(matches!(
2975            parser.parse(b"\x1b[57345u").first(),
2976            Some(Event::Key(k)) if k.code == KeyCode::Enter
2977        ));
2978
2979        // Tab: 57346
2980        assert!(matches!(
2981            parser.parse(b"\x1b[57346u").first(),
2982            Some(Event::Key(k)) if k.code == KeyCode::Tab
2983        ));
2984
2985        // Backspace: 57347
2986        assert!(matches!(
2987            parser.parse(b"\x1b[57347u").first(),
2988            Some(Event::Key(k)) if k.code == KeyCode::Backspace
2989        ));
2990
2991        // Insert: 57348
2992        assert!(matches!(
2993            parser.parse(b"\x1b[57348u").first(),
2994            Some(Event::Key(k)) if k.code == KeyCode::Insert
2995        ));
2996
2997        // Delete: 57349
2998        assert!(matches!(
2999            parser.parse(b"\x1b[57349u").first(),
3000            Some(Event::Key(k)) if k.code == KeyCode::Delete
3001        ));
3002    }
3003
3004    #[test]
3005    fn kitty_keyboard_navigation_keys() {
3006        let mut parser = InputParser::new();
3007
3008        // Left: 57350
3009        assert!(matches!(
3010            parser.parse(b"\x1b[57350u").first(),
3011            Some(Event::Key(k)) if k.code == KeyCode::Left
3012        ));
3013        // Right: 57351
3014        assert!(matches!(
3015            parser.parse(b"\x1b[57351u").first(),
3016            Some(Event::Key(k)) if k.code == KeyCode::Right
3017        ));
3018        // Up: 57352
3019        assert!(matches!(
3020            parser.parse(b"\x1b[57352u").first(),
3021            Some(Event::Key(k)) if k.code == KeyCode::Up
3022        ));
3023        // Down: 57353
3024        assert!(matches!(
3025            parser.parse(b"\x1b[57353u").first(),
3026            Some(Event::Key(k)) if k.code == KeyCode::Down
3027        ));
3028        // PageUp: 57354
3029        assert!(matches!(
3030            parser.parse(b"\x1b[57354u").first(),
3031            Some(Event::Key(k)) if k.code == KeyCode::PageUp
3032        ));
3033        // PageDown: 57355
3034        assert!(matches!(
3035            parser.parse(b"\x1b[57355u").first(),
3036            Some(Event::Key(k)) if k.code == KeyCode::PageDown
3037        ));
3038        // Home: 57356
3039        assert!(matches!(
3040            parser.parse(b"\x1b[57356u").first(),
3041            Some(Event::Key(k)) if k.code == KeyCode::Home
3042        ));
3043        // End: 57357
3044        assert!(matches!(
3045            parser.parse(b"\x1b[57357u").first(),
3046            Some(Event::Key(k)) if k.code == KeyCode::End
3047        ));
3048    }
3049
3050    #[test]
3051    fn kitty_keyboard_f_keys() {
3052        let mut parser = InputParser::new();
3053        // F1: 57364
3054        assert!(matches!(
3055            parser.parse(b"\x1b[57364u").first(),
3056            Some(Event::Key(k)) if k.code == KeyCode::F(1)
3057        ));
3058        // F12: 57375
3059        assert!(matches!(
3060            parser.parse(b"\x1b[57375u").first(),
3061            Some(Event::Key(k)) if k.code == KeyCode::F(12)
3062        ));
3063        // F24: 57387
3064        assert!(matches!(
3065            parser.parse(b"\x1b[57387u").first(),
3066            Some(Event::Key(k)) if k.code == KeyCode::F(24)
3067        ));
3068    }
3069
3070    #[test]
3071    fn kitty_keyboard_ascii_as_standard() {
3072        let mut parser = InputParser::new();
3073        // Tab (9), Enter (13), Escape (27), Backspace (127)
3074        assert!(matches!(
3075            parser.parse(b"\x1b[9u").first(),
3076            Some(Event::Key(k)) if k.code == KeyCode::Tab
3077        ));
3078        assert!(matches!(
3079            parser.parse(b"\x1b[13u").first(),
3080            Some(Event::Key(k)) if k.code == KeyCode::Enter
3081        ));
3082        assert!(matches!(
3083            parser.parse(b"\x1b[27u").first(),
3084            Some(Event::Key(k)) if k.code == KeyCode::Escape
3085        ));
3086        assert!(matches!(
3087            parser.parse(b"\x1b[127u").first(),
3088            Some(Event::Key(k)) if k.code == KeyCode::Backspace
3089        ));
3090        // Backspace alternate: 8
3091        assert!(matches!(
3092            parser.parse(b"\x1b[8u").first(),
3093            Some(Event::Key(k)) if k.code == KeyCode::Backspace
3094        ));
3095    }
3096
3097    // ── OSC 52 clipboard ─────────────────────────────────────────────
3098
3099    #[test]
3100    fn osc52_clipboard_bel_terminated() {
3101        let mut parser = InputParser::new();
3102        // OSC 52;c;<base64 "hello"> BEL
3103        // "hello" in base64 is "aGVsbG8="
3104        let events = parser.parse(b"\x1b]52;c;aGVsbG8=\x07");
3105        assert!(matches!(
3106            events.first(),
3107            Some(Event::Clipboard(c)) if c.content == "hello" && c.source == ClipboardSource::Osc52
3108        ));
3109    }
3110
3111    #[test]
3112    fn osc52_clipboard_st_terminated() {
3113        let mut parser = InputParser::new();
3114        // OSC 52;c;<base64 "hello"> ESC \
3115        let events = parser.parse(b"\x1b]52;c;aGVsbG8=\x1b\\");
3116        assert!(matches!(
3117            events.first(),
3118            Some(Event::Clipboard(c)) if c.content == "hello"
3119        ));
3120    }
3121
3122    // --- DCS / control-string handling (XTGETTCAP-reply capture & leak guard) ---
3123
3124    #[test]
3125    fn dcs_xtgettcap_reply_produces_no_events() {
3126        let mut parser = InputParser::new();
3127        // A leaked XTGETTCAP `RGB` reply MUST be captured as a structured
3128        // `TerminalResponse::Dcs` event — never decoded as `Alt+P` then the
3129        // payload as literal keys.
3130        let events = parser.parse(b"\x1bP1+r524742=8/8/8\x1b\\");
3131        assert!(
3132            !events.iter().any(|e| matches!(e, Event::Key(_))),
3133            "a DCS reply must produce no key events, got: {events:?}"
3134        );
3135        assert_eq!(
3136            events,
3137            vec![Event::TerminalResponse(TerminalResponse::Dcs {
3138                payload: b"1+r524742=8/8/8".to_vec(),
3139                truncated: false,
3140            })],
3141        );
3142    }
3143
3144    #[test]
3145    fn dcs_then_real_key_recovers_to_ground() {
3146        let mut parser = InputParser::new();
3147        // After an ST-terminated DCS the parser must be back in Ground so the
3148        // following real keypress parses normally.
3149        let events = parser.parse(b"\x1bP1+r524742=8/8/8\x1b\\a");
3150        assert!(
3151            matches!(
3152                events.as_slice(),
3153                [
3154                    Event::TerminalResponse(TerminalResponse::Dcs { payload, truncated: false }),
3155                    Event::Key(k),
3156                ] if payload == b"1+r524742=8/8/8" && k.code == KeyCode::Char('a')
3157            ),
3158            "parser must emit DCS then recover to Ground for the key, got: {events:?}"
3159        );
3160    }
3161
3162    #[test]
3163    fn dcs_bel_terminated_is_ignored() {
3164        let mut parser = InputParser::new();
3165        // Per ECMA-48, BEL (0x07) inside a DCS string is body data, not a
3166        // terminator; ST (ESC \) terminates the DCS and the following key parses.
3167        let events = parser.parse(b"\x1bPsome-payload\x07\x1b\\b");
3168        assert!(
3169            matches!(
3170                events.as_slice(),
3171                [
3172                    Event::TerminalResponse(TerminalResponse::Dcs { payload, truncated: false }),
3173                    Event::Key(k),
3174                ] if payload == b"some-payload\x07" && k.code == KeyCode::Char('b')
3175            ),
3176            "BEL inside DCS is body data until ST, then key parses, got: {events:?}"
3177        );
3178    }
3179
3180    #[test]
3181    fn dcs_payload_captured_up_to_cap() {
3182        let mut parser = InputParser::new();
3183        let events = parser.parse(b"\x1bP1+r524742=8/8/8\x1b\\");
3184        assert_eq!(
3185            events,
3186            vec![Event::TerminalResponse(TerminalResponse::Dcs {
3187                payload: b"1+r524742=8/8/8".to_vec(),
3188                truncated: false,
3189            })]
3190        );
3191    }
3192
3193    #[test]
3194    fn dcs_split_across_reads() {
3195        let mut parser = InputParser::new();
3196        assert!(parser.parse(b"\x1bP1+r").is_empty());
3197        assert!(parser.parse(b"524742=").is_empty());
3198        let events = parser.parse(b"8/8/8\x1b\\");
3199        assert_eq!(
3200            events,
3201            vec![Event::TerminalResponse(TerminalResponse::Dcs {
3202                payload: b"1+r524742=8/8/8".to_vec(),
3203                truncated: false,
3204            })]
3205        );
3206    }
3207
3208    #[test]
3209    fn dcs_overlong_truncated_not_dropped_keys_after_st() {
3210        let mut parser = InputParser::new();
3211        let mut input = b"\x1bP".to_vec();
3212        input.extend(std::iter::repeat_n(b'A', 10_000));
3213        input.extend_from_slice(b"\x1b\\x");
3214        let events = parser.parse(&input);
3215        assert_eq!(events.len(), 2, "expected DCS + key 'x', got {events:?}");
3216        match &events[0] {
3217            Event::TerminalResponse(TerminalResponse::Dcs { payload, truncated }) => {
3218                assert_eq!(payload.len(), MAX_DCS_LEN);
3219                assert!(payload.iter().all(|&b| b == b'A'));
3220                assert!(*truncated);
3221            }
3222            other => panic!("expected TerminalResponse::Dcs, got {other:?}"),
3223        }
3224        assert!(matches!(
3225            events[1],
3226            Event::Key(k) if k.code == KeyCode::Char('x') && k.modifiers == Modifiers::NONE
3227        ));
3228    }
3229
3230    #[test]
3231    fn dcs_bel_is_not_a_terminator() {
3232        let mut parser = InputParser::new();
3233        let events = parser.parse(b"\x1bPa\x07b\x1b\\c");
3234        assert_eq!(events.len(), 2, "expected DCS + key 'c', got {events:?}");
3235        assert_eq!(
3236            events[0],
3237            Event::TerminalResponse(TerminalResponse::Dcs {
3238                payload: b"a\x07b".to_vec(),
3239                truncated: false,
3240            })
3241        );
3242        assert!(matches!(
3243            events[1],
3244            Event::Key(k) if k.code == KeyCode::Char('c') && k.modifiers == Modifiers::NONE
3245        ));
3246    }
3247
3248    #[test]
3249    fn apc_default_stays_alt_key() {
3250        let mut parser = InputParser::new();
3251        let events = parser.parse(b"\x1b_");
3252        assert!(matches!(
3253            events.as_slice(),
3254            [Event::Key(k)] if k.code == KeyCode::Char('_') && k.modifiers.contains(Modifiers::ALT)
3255        ));
3256    }
3257
3258    #[test]
3259    fn apc_capture_opt_in() {
3260        let mut parser = InputParser::new();
3261        parser.set_capture_apc(true);
3262        let events = parser.parse(b"\x1b_Gi=31;OK\x1b\\z");
3263        assert_eq!(events.len(), 2, "expected APC + key 'z', got {events:?}");
3264        assert_eq!(
3265            events[0],
3266            Event::TerminalResponse(TerminalResponse::Apc {
3267                payload: b"Gi=31;OK".to_vec(),
3268                truncated: false,
3269            })
3270        );
3271        assert!(matches!(
3272            events[1],
3273            Event::Key(k) if k.code == KeyCode::Char('z') && k.modifiers == Modifiers::NONE
3274        ));
3275    }
3276
3277    #[test]
3278    fn sos_pm_unchanged_with_apc_capture() {
3279        let mut parser = InputParser::new();
3280        parser.set_capture_apc(true);
3281        for &introducer in b"X^" {
3282            let events = parser.parse(&[0x1b, introducer]);
3283            assert!(
3284                matches!(
3285                    events.as_slice(),
3286                    [Event::Key(k)]
3287                        if k.code == KeyCode::Char(introducer as char)
3288                            && k.modifiers.contains(Modifiers::ALT)
3289                ),
3290                "ESC {} must stay an Alt key even with capture_apc=true, got: {events:?}",
3291                introducer as char
3292            );
3293        }
3294    }
3295
3296    #[test]
3297    fn sgr_pixel_mouse_converts_to_cells() {
3298        let mut parser = InputParser::new();
3299        parser.set_pixel_mouse(true);
3300        parser.set_cell_size_px(10, 20);
3301        let events = parser.parse(b"\x1b[<0;25;45M");
3302        assert_eq!(
3303            events,
3304            vec![Event::Mouse(MouseEvent {
3305                kind: MouseEventKind::Down(MouseButton::Left),
3306                x: 2,
3307                y: 2,
3308                modifiers: Modifiers::NONE,
3309                pixel: Some((25, 45)),
3310            })]
3311        );
3312    }
3313
3314    #[test]
3315    fn sgr_pixel_mouse_release_and_motion() {
3316        let mut parser = InputParser::new();
3317        parser.set_pixel_mouse(true);
3318        parser.set_cell_size_px(8, 16);
3319
3320        let release = parser.parse(b"\x1b[<0;80;160m");
3321        assert_eq!(
3322            release,
3323            vec![Event::Mouse(MouseEvent {
3324                kind: MouseEventKind::Up(MouseButton::Left),
3325                x: 10,
3326                y: 10,
3327                modifiers: Modifiers::NONE,
3328                pixel: Some((80, 160)),
3329            })]
3330        );
3331
3332        let drag = parser.parse(b"\x1b[<32;15;31M");
3333        assert_eq!(
3334            drag,
3335            vec![Event::Mouse(MouseEvent {
3336                kind: MouseEventKind::Drag(MouseButton::Left),
3337                x: 1,
3338                y: 1,
3339                modifiers: Modifiers::NONE,
3340                pixel: Some((15, 31)),
3341            })]
3342        );
3343    }
3344
3345    #[test]
3346    fn sgr_pixel_mouse_without_cell_size_keeps_pixels_and_zero_cells() {
3347        let mut parser = InputParser::new();
3348        parser.set_pixel_mouse(true);
3349        let events = parser.parse(b"\x1b[<0;123;456M");
3350        assert_eq!(
3351            events,
3352            vec![Event::Mouse(MouseEvent {
3353                kind: MouseEventKind::Down(MouseButton::Left),
3354                x: 0,
3355                y: 0,
3356                modifiers: Modifiers::NONE,
3357                pixel: Some((123, 456)),
3358            })]
3359        );
3360    }
3361
3362    #[test]
3363    fn sgr_pixel_mouse_off_ignores_cell_size() {
3364        let mut parser = InputParser::new();
3365        parser.set_pixel_mouse(false);
3366        parser.set_cell_size_px(10, 20);
3367        let events = parser.parse(b"\x1b[<0;5;3M");
3368        assert_eq!(
3369            events,
3370            vec![Event::Mouse(MouseEvent {
3371                kind: MouseEventKind::Down(MouseButton::Left),
3372                x: 4,
3373                y: 2,
3374                modifiers: Modifiers::NONE,
3375                pixel: None,
3376            })]
3377        );
3378    }
3379
3380    #[test]
3381    fn sgr_pixel_mouse_negative_coords_clamp() {
3382        let mut parser = InputParser::new();
3383        parser.set_pixel_mouse(true);
3384        parser.set_cell_size_px(10, 20);
3385        let events = parser.parse(b"\x1b[<32;-5;-10M");
3386        assert_eq!(
3387            events,
3388            vec![Event::Mouse(MouseEvent {
3389                kind: MouseEventKind::Drag(MouseButton::Left),
3390                x: 0,
3391                y: 0,
3392                modifiers: Modifiers::NONE,
3393                pixel: Some((0, 0)),
3394            })]
3395        );
3396    }
3397
3398    #[test]
3399    fn xtwinops_cell_size_reply_parsed() {
3400        let mut parser = InputParser::new();
3401        parser.set_pixel_mouse(true);
3402        let events = parser.parse(b"\x1b[6;18;9t\x1b[<0;27;36M");
3403        assert_eq!(
3404            events,
3405            vec![
3406                Event::TerminalResponse(TerminalResponse::CellSize {
3407                    width: 9,
3408                    height: 18,
3409                }),
3410                Event::Mouse(MouseEvent {
3411                    kind: MouseEventKind::Down(MouseButton::Left),
3412                    x: 3,
3413                    y: 2,
3414                    modifiers: Modifiers::NONE,
3415                    pixel: Some((27, 36)),
3416                }),
3417            ]
3418        );
3419    }
3420
3421    #[test]
3422    fn sos_pm_apc_introducers_stay_alt_keys() {
3423        // We deliberately intercept ONLY DCS (ESC P), not the sibling C1 string
3424        // introducers SOS/PM/APC — terminals never send those as responses, so
3425        // they remain `Alt+Shift+X` / `Alt+^` / `Alt+_` keypresses.
3426        for &introducer in b"X^_" {
3427            let mut parser = InputParser::new();
3428            let events = parser.parse(&[0x1b, introducer]);
3429            assert!(
3430                matches!(
3431                    events.as_slice(),
3432                    [Event::Key(k)]
3433                        if k.code == KeyCode::Char(introducer as char)
3434                            && k.modifiers.contains(Modifiers::ALT)
3435                ),
3436                "ESC {} must stay an Alt key, got: {events:?}",
3437                introducer as char
3438            );
3439        }
3440    }
3441
3442    #[test]
3443    fn dcs_esc_then_csi_recovers_to_arrow_key() {
3444        let mut parser = InputParser::new();
3445        // ESC inside the DCS payload, followed not by `\` (ST) but by a CSI
3446        // (`[A` = Up): the string is cancelled and the CSI parses cleanly.
3447        let events = parser.parse(b"\x1bP payload \x1b[A");
3448        assert!(
3449            matches!(events.as_slice(), [Event::Key(k)] if k.code == KeyCode::Up),
3450            "ESC-mid-DCS then a CSI must recover and parse the arrow, got: {events:?}"
3451        );
3452    }
3453
3454    #[test]
3455    fn dcs_aborts_on_control_char_so_input_is_not_swallowed() {
3456        let mut parser = InputParser::new();
3457        // A never-terminated DCS followed by Enter (CR, a control byte): the
3458        // control char must abort the string and be reprocessed, so a malformed
3459        // string cannot swallow subsequent real input forever.
3460        let events = parser.parse(b"\x1bPunterminated\r");
3461        assert!(
3462            !events.is_empty(),
3463            "a control char must abort a stuck DCS and emit the key, got: {events:?}"
3464        );
3465    }
3466
3467    #[test]
3468    fn osc52_clipboard_primary_selection() {
3469        let mut parser = InputParser::new();
3470        // Primary selection: p instead of c
3471        // "abc" in base64 is "YWJj"
3472        let events = parser.parse(b"\x1b]52;p;YWJj\x07");
3473        assert!(matches!(
3474            events.first(),
3475            Some(Event::Clipboard(c)) if c.content == "abc"
3476        ));
3477    }
3478
3479    // ── Control keys ─────────────────────────────────────────────────
3480
3481    #[test]
3482    fn ctrl_space_is_null() {
3483        let mut parser = InputParser::new();
3484        let events = parser.parse(&[0x00]);
3485        assert!(matches!(
3486            events.first(),
3487            Some(Event::Key(k)) if k.code == KeyCode::Null
3488        ));
3489    }
3490
3491    #[test]
3492    fn all_ctrl_letter_keys() {
3493        let mut parser = InputParser::new();
3494        // Ctrl+A (0x01) through Ctrl+Z (0x1A), skipping Backspace (0x08), Tab (0x09), and Enter (0x0D)
3495        for byte in 0x01..=0x1Au8 {
3496            let events = parser.parse(&[byte]);
3497            assert_eq!(
3498                events.len(),
3499                1,
3500                "Ctrl+{} should produce one event",
3501                (byte + b'a' - 1) as char
3502            );
3503            match byte {
3504                0x08 => assert!(matches!(events[0], Event::Key(k) if k.code == KeyCode::Backspace)),
3505                0x09 => assert!(matches!(events[0], Event::Key(k) if k.code == KeyCode::Tab)),
3506                0x0D => assert!(matches!(events[0], Event::Key(k) if k.code == KeyCode::Enter)),
3507                _ => {
3508                    let expected_char = (byte + b'a' - 1) as char;
3509                    match &events[0] {
3510                        Event::Key(k) => {
3511                            assert_eq!(
3512                                k.code,
3513                                KeyCode::Char(expected_char),
3514                                "Byte 0x{byte:02X} should produce Ctrl+{expected_char}"
3515                            );
3516                            assert!(
3517                                k.modifiers.contains(Modifiers::CTRL),
3518                                "Byte 0x{byte:02X} should have Ctrl modifier"
3519                            );
3520                        }
3521                        other => {
3522                            panic!("Byte 0x{byte:02X}: expected Key event, got {other:?}");
3523                        }
3524                    }
3525                }
3526            }
3527        }
3528    }
3529
3530    // ── UTF-8 multi-byte: 3-byte and 4-byte ─────────────────────────
3531
3532    #[test]
3533    fn utf8_3byte_cjk() {
3534        let mut parser = InputParser::new();
3535        // 中 (U+4E2D) = 0xE4 0xB8 0xAD
3536        let events = parser.parse(&[0xE4, 0xB8, 0xAD]);
3537        assert!(matches!(
3538            events.first(),
3539            Some(Event::Key(k)) if k.code == KeyCode::Char('中')
3540        ));
3541    }
3542
3543    #[test]
3544    fn utf8_4byte_emoji() {
3545        let mut parser = InputParser::new();
3546        // 🦀 (U+1F980) = 0xF0 0x9F 0xA6 0x80
3547        let events = parser.parse(&[0xF0, 0x9F, 0xA6, 0x80]);
3548        assert!(matches!(
3549            events.first(),
3550            Some(Event::Key(k)) if k.code == KeyCode::Char('🦀')
3551        ));
3552    }
3553
3554    // ── Empty input ──────────────────────────────────────────────────
3555
3556    #[test]
3557    fn empty_input_returns_no_events() {
3558        let mut parser = InputParser::new();
3559        let events = parser.parse(b"");
3560        assert!(events.is_empty());
3561    }
3562
3563    // ── Unknown CSI tilde values ─────────────────────────────────────
3564
3565    #[test]
3566    fn unknown_csi_tilde_ignored() {
3567        let mut parser = InputParser::new();
3568        // Code 99 is not a known tilde key
3569        let events = parser.parse(b"\x1b[99~");
3570        assert!(events.is_empty());
3571
3572        // Parser should still work
3573        let events = parser.parse(b"a");
3574        assert!(matches!(events.first(), Some(Event::Key(k)) if k.code == KeyCode::Char('a')));
3575    }
3576
3577    // ── Alt+various characters ───────────────────────────────────────
3578
3579    #[test]
3580    fn alt_special_chars() {
3581        let mut parser = InputParser::new();
3582
3583        // Alt+space
3584        let events = parser.parse(b"\x1b ");
3585        assert!(matches!(
3586            events.first(),
3587            Some(Event::Key(k)) if k.code == KeyCode::Char(' ') && k.modifiers.contains(Modifiers::ALT)
3588        ));
3589
3590        // Alt+digit
3591        let events = parser.parse(b"\x1b5");
3592        assert!(matches!(
3593            events.first(),
3594            Some(Event::Key(k)) if k.code == KeyCode::Char('5') && k.modifiers.contains(Modifiers::ALT)
3595        ));
3596
3597        // Alt+bracket
3598        let events = parser.parse(b"\x1b}");
3599        assert!(matches!(
3600            events.first(),
3601            Some(Event::Key(k)) if k.code == KeyCode::Char('}') && k.modifiers.contains(Modifiers::ALT)
3602        ));
3603    }
3604
3605    #[test]
3606    fn alt_ctrl_key_combinations() {
3607        let mut parser = InputParser::new();
3608
3609        // ESC + Ctrl+A (0x01) -> Alt+Ctrl+A
3610        let events = parser.parse(&[0x1B, 0x01]);
3611        assert_eq!(events.len(), 1);
3612        match &events[0] {
3613            Event::Key(k) => {
3614                assert_eq!(k.code, KeyCode::Char('a'));
3615                assert!(k.modifiers.contains(Modifiers::ALT));
3616                assert!(k.modifiers.contains(Modifiers::CTRL));
3617            }
3618            _ => panic!("Expected Key event"),
3619        }
3620
3621        // ESC + Backspace (0x08) -> Alt+Backspace (Ctrl+H is Backspace)
3622        // Note: 0x08 is Backspace in process_ground.
3623        // So ESC + 0x08 should be Alt+Backspace.
3624        let events = parser.parse(&[0x1B, 0x08]);
3625        assert_eq!(events.len(), 1);
3626        match &events[0] {
3627            Event::Key(k) => {
3628                assert_eq!(k.code, KeyCode::Backspace);
3629                assert!(k.modifiers.contains(Modifiers::ALT));
3630            }
3631            _ => panic!("Expected Key event"),
3632        }
3633    }
3634
3635    // ── SS3 arrow keys ───────────────────────────────────────────────
3636
3637    #[test]
3638    fn ss3_arrow_keys() {
3639        let mut parser = InputParser::new();
3640        assert!(matches!(
3641            parser.parse(b"\x1bOA").first(),
3642            Some(Event::Key(k)) if k.code == KeyCode::Up
3643        ));
3644        assert!(matches!(
3645            parser.parse(b"\x1bOB").first(),
3646            Some(Event::Key(k)) if k.code == KeyCode::Down
3647        ));
3648        assert!(matches!(
3649            parser.parse(b"\x1bOC").first(),
3650            Some(Event::Key(k)) if k.code == KeyCode::Right
3651        ));
3652        assert!(matches!(
3653            parser.parse(b"\x1bOD").first(),
3654            Some(Event::Key(k)) if k.code == KeyCode::Left
3655        ));
3656    }
3657
3658    // ── Xterm modifier encoding ──────────────────────────────────────
3659
3660    #[test]
3661    fn xterm_modifier_encoding() {
3662        // Verify modifiers_from_xterm decoding (value = 1 + modifier_bits)
3663        assert_eq!(InputParser::modifiers_from_xterm(1), Modifiers::NONE);
3664        assert_eq!(InputParser::modifiers_from_xterm(2), Modifiers::SHIFT);
3665        assert_eq!(InputParser::modifiers_from_xterm(3), Modifiers::ALT);
3666        assert_eq!(
3667            InputParser::modifiers_from_xterm(4),
3668            Modifiers::SHIFT | Modifiers::ALT
3669        );
3670        assert_eq!(InputParser::modifiers_from_xterm(5), Modifiers::CTRL);
3671        assert_eq!(
3672            InputParser::modifiers_from_xterm(6),
3673            Modifiers::SHIFT | Modifiers::CTRL
3674        );
3675        assert_eq!(InputParser::modifiers_from_xterm(9), Modifiers::SUPER);
3676    }
3677
3678    // ── SS3 interrupted by ESC ───────────────────────────────────────
3679
3680    #[test]
3681    fn ss3_interrupted_by_esc() {
3682        let mut parser = InputParser::new();
3683        // ESC O ESC should restart into Escape state
3684        let events = parser.parse(b"\x1bO\x1b[A");
3685        // Should get Up arrow from the new ESC [ A sequence
3686        assert!(matches!(
3687            events.first(),
3688            Some(Event::Key(k)) if k.code == KeyCode::Up
3689        ));
3690    }
3691
3692    // ── Kitty keyboard: unhandled keycodes ───────────────────────────
3693
3694    #[test]
3695    fn kitty_keyboard_reserved_keycode_ignored() {
3696        let mut parser = InputParser::new();
3697        // Reserved range 57358..=57363 returns None
3698        let events = parser.parse(b"\x1b[57360u");
3699        assert!(events.is_empty());
3700
3701        // Parser still works
3702        let events = parser.parse(b"x");
3703        assert!(matches!(events.first(), Some(Event::Key(k)) if k.code == KeyCode::Char('x')));
3704    }
3705    #[test]
3706    fn utf8_invalid_sequence_emits_replacement() {
3707        let mut parser = InputParser::new();
3708
3709        // 0xE0 is a start of 3-byte sequence.
3710        // 0x41 ('A') is not a valid continuation byte.
3711        // Should emit Replacement Character then 'A'.
3712        let events = parser.parse(&[0xE0, 0x41]);
3713        assert_eq!(events.len(), 2);
3714
3715        match &events[0] {
3716            Event::Key(k) => assert_eq!(k.code, KeyCode::Char(std::char::REPLACEMENT_CHARACTER)),
3717            _ => panic!("Expected replacement character"),
3718        }
3719
3720        match &events[1] {
3721            Event::Key(k) => assert_eq!(k.code, KeyCode::Char('A')),
3722            _ => panic!("Expected character 'A'"),
3723        }
3724    }
3725
3726    #[test]
3727    fn utf8_invalid_lead_emits_replacement() {
3728        let mut parser = InputParser::new();
3729
3730        // 0xC0 is an invalid UTF-8 lead byte (overlong sequence).
3731        let events = parser.parse(&[0xC0, b'a']);
3732        assert!(
3733            matches!(events.first(), Some(Event::Key(k)) if k.code == KeyCode::Char(std::char::REPLACEMENT_CHARACTER)),
3734            "Expected replacement for invalid lead"
3735        );
3736        assert!(
3737            events
3738                .iter()
3739                .any(|e| matches!(e, Event::Key(k) if k.code == KeyCode::Char('a'))),
3740            "Expected subsequent ASCII to be preserved"
3741        );
3742
3743        // 0xF5 is an out-of-range UTF-8 lead byte.
3744        let events = parser.parse(&[0xF5, b'b']);
3745        assert!(
3746            matches!(events.first(), Some(Event::Key(k)) if k.code == KeyCode::Char(std::char::REPLACEMENT_CHARACTER)),
3747            "Expected replacement for out-of-range lead"
3748        );
3749        assert!(
3750            events
3751                .iter()
3752                .any(|e| matches!(e, Event::Key(k) if k.code == KeyCode::Char('b'))),
3753            "Expected subsequent ASCII to be preserved"
3754        );
3755    }
3756}
3757
3758#[cfg(test)]
3759mod proptest_fuzz {
3760    use super::*;
3761    use proptest::prelude::*;
3762
3763    // ── Strategy helpers ────────────────────────────────────────────────
3764    // Avoid turbofish inside proptest! macro (Rust 2024 edition compat).
3765
3766    fn arb_byte() -> impl Strategy<Value = u8> {
3767        any::<u8>()
3768    }
3769
3770    fn arb_byte_vec(max_len: usize) -> impl Strategy<Value = Vec<u8>> {
3771        prop::collection::vec(arb_byte(), 0..=max_len)
3772    }
3773
3774    /// Generate a well-formed CSI sequence: ESC [ <params> <final byte>.
3775    fn csi_sequence() -> impl Strategy<Value = Vec<u8>> {
3776        let params = prop::collection::vec(0x30u8..=0x3F, 0..=20);
3777        let final_byte = 0x40u8..=0x7E;
3778        (params, final_byte).prop_map(|(p, f)| {
3779            let mut buf = vec![0x1B, b'['];
3780            buf.extend_from_slice(&p);
3781            buf.push(f);
3782            buf
3783        })
3784    }
3785
3786    /// Generate an OSC sequence: ESC ] <content> ST.
3787    fn osc_sequence() -> impl Strategy<Value = Vec<u8>> {
3788        let content = prop::collection::vec(0x20u8..=0x7E, 0..=64);
3789        let terminator = prop_oneof![
3790            Just(vec![0x1B, b'\\']), // ESC backslash
3791            Just(vec![0x07]),        // BEL
3792        ];
3793        (content, terminator).prop_map(|(c, t)| {
3794            let mut buf = vec![0x1B, b']'];
3795            buf.extend_from_slice(&c);
3796            buf.extend_from_slice(&t);
3797            buf
3798        })
3799    }
3800
3801    /// Generate an SS3 sequence: ESC O <final byte>.
3802    fn ss3_sequence() -> impl Strategy<Value = Vec<u8>> {
3803        (0x40u8..=0x7E).prop_map(|f| vec![0x1B, b'O', f])
3804    }
3805
3806    /// Generate a bracketed paste: ESC[200~ <content> ESC[201~.
3807    fn paste_sequence() -> impl Strategy<Value = Vec<u8>> {
3808        prop::collection::vec(0x20u8..=0x7E, 0..=128).prop_map(|content| {
3809            let mut buf = vec![0x1B, b'[', b'2', b'0', b'0', b'~'];
3810            buf.extend_from_slice(&content);
3811            buf.extend_from_slice(b"\x1b[201~");
3812            buf
3813        })
3814    }
3815
3816    /// Generate structured adversarial input: mix of valid sequences and random bytes.
3817    fn mixed_adversarial() -> impl Strategy<Value = Vec<u8>> {
3818        let fragment = prop_oneof![
3819            csi_sequence(),
3820            osc_sequence(),
3821            ss3_sequence(),
3822            paste_sequence(),
3823            arb_byte_vec(16),                            // random bytes
3824            Just(vec![0x1B]),                            // bare ESC
3825            Just(vec![0x1B, b'[']),                      // unterminated CSI
3826            Just(vec![0x1B, b']']),                      // unterminated OSC
3827            prop::collection::vec(0x80u8..=0xFF, 1..=4), // high bytes
3828        ];
3829        prop::collection::vec(fragment, 1..=8)
3830            .prop_map(|frags| frags.into_iter().flatten().collect())
3831    }
3832
3833    // ── Property tests ─────────────────────────────────────────────────
3834
3835    proptest! {
3836        /// Random bytes must never panic.
3837        #[test]
3838        fn random_bytes_never_panic(input in arb_byte_vec(512)) {
3839            let mut parser = InputParser::new();
3840            let _ = parser.parse(&input);
3841        }
3842
3843        /// After parsing any input, the parser must be reusable for normal keys.
3844        #[test]
3845        fn parser_recovers_after_garbage(input in arb_byte_vec(256)) {
3846            let mut parser = InputParser::new();
3847            let _ = parser.parse(&input);
3848
3849            // Feed a clean known sequence (letter 'z') after the garbage.
3850            let events = parser.parse(b"z");
3851            // Parser must not panic. We can't assert exact events because
3852            // the parser may still be mid-sequence, but it must not panic.
3853            let _ = events;
3854        }
3855
3856        /// Structured mixed input (valid sequences + garbage) must never panic.
3857        #[test]
3858        fn mixed_sequences_never_panic(input in mixed_adversarial()) {
3859            let mut parser = InputParser::new();
3860            let _ = parser.parse(&input);
3861        }
3862
3863        /// All generated events must be valid (non-panicking Debug).
3864        #[test]
3865        fn events_are_well_formed(input in arb_byte_vec(256)) {
3866            let mut parser = InputParser::new();
3867            let events = parser.parse(&input);
3868            for event in &events {
3869                // Exercise Debug impl — catches inconsistent internal state.
3870                let _ = format!("{event:?}");
3871            }
3872        }
3873
3874        /// CSI sequences never produce more events than bytes fed.
3875        #[test]
3876        fn csi_event_count_bounded(seq in csi_sequence()) {
3877            let mut parser = InputParser::new();
3878            let events = parser.parse(&seq);
3879            prop_assert!(events.len() <= seq.len(),
3880                "Got {} events from {} bytes", events.len(), seq.len());
3881        }
3882
3883        /// OSC sequences never produce more events than bytes fed.
3884        #[test]
3885        fn osc_event_count_bounded(seq in osc_sequence()) {
3886            let mut parser = InputParser::new();
3887            let events = parser.parse(&seq);
3888            prop_assert!(events.len() <= seq.len(),
3889                "Got {} events from {} bytes", events.len(), seq.len());
3890        }
3891
3892        /// Paste content is always bounded by MAX_PASTE_LEN.
3893        #[test]
3894        fn paste_content_bounded(content in prop::collection::vec(arb_byte(), 0..=2048)) {
3895            let mut parser = InputParser::new();
3896            let mut input = vec![0x1B, b'[', b'2', b'0', b'0', b'~'];
3897            input.extend_from_slice(&content);
3898            input.extend_from_slice(b"\x1b[201~");
3899
3900            let events = parser.parse(&input);
3901            for event in &events {
3902                if let Event::Paste(p) = event {
3903                    prop_assert!(p.text.len() <= MAX_PASTE_LEN,
3904                        "Paste text {} exceeds limit {}", p.text.len(), MAX_PASTE_LEN);
3905                }
3906            }
3907        }
3908
3909        /// Feeding input byte-by-byte yields same events as feeding all at once.
3910        #[test]
3911        fn incremental_matches_bulk(input in arb_byte_vec(128)) {
3912            let mut bulk_parser = InputParser::new();
3913            let bulk_events = bulk_parser.parse(&input);
3914
3915            let mut incr_parser = InputParser::new();
3916            let mut incr_events = Vec::new();
3917            for byte in &input {
3918                incr_events.extend(incr_parser.parse(std::slice::from_ref(byte)));
3919            }
3920
3921            let bulk_dbg: Vec<String> = bulk_events.iter().map(|e| format!("{e:?}")).collect();
3922            let incr_dbg: Vec<String> = incr_events.iter().map(|e| format!("{e:?}")).collect();
3923            prop_assert_eq!(bulk_dbg, incr_dbg,
3924                "Bulk vs incremental mismatch for input {:?}", input);
3925        }
3926
3927        /// Repeated parsing of the same input must always produce the same result
3928        /// (parser is deterministic after reset).
3929        #[test]
3930        fn deterministic_output(input in arb_byte_vec(128)) {
3931            let mut parser1 = InputParser::new();
3932            let events1 = parser1.parse(&input);
3933
3934            let mut parser2 = InputParser::new();
3935            let events2 = parser2.parse(&input);
3936
3937            let dbg1: Vec<String> = events1.iter().map(|e| format!("{e:?}")).collect();
3938            let dbg2: Vec<String> = events2.iter().map(|e| format!("{e:?}")).collect();
3939            prop_assert_eq!(dbg1, dbg2);
3940        }
3941    }
3942
3943    // ── Targeted invariant tests (outside proptest! macro) ─────────────
3944
3945    /// After a long garbage run, parser handles a simple key within bounded time.
3946    #[test]
3947    fn no_quadratic_blowup() {
3948        let mut parser = InputParser::new();
3949
3950        // 64KB of random-ish bytes (repeating pattern).
3951        let garbage: Vec<u8> = (0..65536).map(|i| (i % 256) as u8).collect();
3952        let _ = parser.parse(&garbage);
3953
3954        // Follow with a clean key — must not take pathological time.
3955        let events = parser.parse(b"a");
3956        let _ = events; // primarily asserting no hang/panic
3957    }
3958
3959    /// Oversized CSI sequence triggers DoS protection without panic.
3960    #[test]
3961    fn oversized_csi_transitions_to_ignore() {
3962        let mut parser = InputParser::new();
3963
3964        // CSI followed by MAX_CSI_LEN+100 parameter bytes then a final byte.
3965        let mut input = vec![0x1B, b'['];
3966        input.extend(std::iter::repeat_n(b'0', MAX_CSI_LEN + 100));
3967        input.push(b'm');
3968
3969        let _ = parser.parse(&input);
3970
3971        // Parser must still be usable.
3972        let events = parser.parse(b"x");
3973        assert_eq!(events.len(), 1);
3974        assert!(matches!(events[0], Event::Key(k) if k.code == KeyCode::Char('x')));
3975    }
3976
3977    /// Oversized OSC sequence triggers DoS protection without panic.
3978    #[test]
3979    fn oversized_osc_transitions_to_ignore() {
3980        let mut parser = InputParser::new();
3981
3982        // OSC followed by MAX_OSC_LEN+100 content bytes then ST.
3983        let mut input = vec![0x1B, b']'];
3984        input.extend(std::iter::repeat_n(b'a', MAX_OSC_LEN + 100));
3985        input.push(0x07); // BEL terminator
3986
3987        let _ = parser.parse(&input);
3988
3989        // Parser must still be usable.
3990        let events = parser.parse(b"y");
3991        assert_eq!(events.len(), 1);
3992        assert!(matches!(events[0], Event::Key(k) if k.code == KeyCode::Char('y')));
3993    }
3994
3995    /// Rapid ESC toggling doesn't corrupt state.
3996    #[test]
3997    fn rapid_esc_toggle() {
3998        let mut parser = InputParser::new();
3999
4000        // 1000 bare ESCs in a row.
4001        let input: Vec<u8> = vec![0x1B; 1000];
4002        let _ = parser.parse(&input);
4003
4004        // Must recover for a normal key.
4005        let events = parser.parse(b"k");
4006        assert!(!events.is_empty());
4007    }
4008
4009    /// Interleaved paste start sequences without end.
4010    #[test]
4011    fn unterminated_paste_recovery() {
4012        let mut parser = InputParser::new();
4013
4014        // Start paste, but never end it — feed lots of data.
4015        let mut input = b"\x1b[200~".to_vec();
4016        input.extend(std::iter::repeat_n(b'x', 2048));
4017
4018        let _ = parser.parse(&input);
4019
4020        // Now end the paste.
4021        let events = parser.parse(b"\x1b[201~");
4022        assert!(
4023            !events.is_empty(),
4024            "Parser should emit paste event on terminator"
4025        );
4026    }
4027
4028    /// UTF-8 boundary: all possible lead bytes followed by truncation.
4029    #[test]
4030    fn truncated_utf8_lead_bytes() {
4031        let mut parser = InputParser::new();
4032
4033        // Two-byte lead (0xC0..0xDF), three-byte (0xE0..0xEF), four-byte (0xF0..0xF7)
4034        for lead in [0xC2, 0xE0, 0xF0] {
4035            let _ = parser.parse(&[lead]);
4036            // Feed a normal ASCII after the truncated lead.
4037            let events = parser.parse(b"a");
4038            // Must not panic; 'a' should eventually appear.
4039            let _ = events;
4040        }
4041    }
4042
4043    /// Null bytes mixed with valid input.
4044    #[test]
4045    fn null_bytes_interleaved() {
4046        let mut parser = InputParser::new();
4047
4048        let input = b"\x00A\x00\x1b[A\x00B\x00";
4049        let events = parser.parse(input);
4050        // Should get events for 'A', Up arrow, and 'B' (nulls handled gracefully).
4051        assert!(
4052            events.len() >= 2,
4053            "Expected at least 2 events, got {}",
4054            events.len()
4055        );
4056    }
4057
4058    // ── Additional fuzz invariant tests (bd-10i.11.3) ─────────────────
4059
4060    /// Generate an OSC 52 clipboard sequence with arbitrary base64 payload.
4061    fn osc52_sequence() -> impl Strategy<Value = Vec<u8>> {
4062        let selector = prop_oneof![Just(b'c'), Just(b'p'), Just(b's')];
4063        // Generate valid base64 characters with occasional invalid ones
4064        let payload = prop::collection::vec(
4065            prop_oneof![
4066                0x41u8..=0x5A, // A-Z
4067                0x61u8..=0x7A, // a-z
4068                0x30u8..=0x39, // 0-9
4069                Just(b'+'),
4070                Just(b'/'),
4071                Just(b'='),
4072            ],
4073            0..=128,
4074        );
4075        let terminator = prop_oneof![
4076            Just(vec![0x1B, b'\\']), // ESC backslash (ST)
4077            Just(vec![0x07]),        // BEL
4078        ];
4079        (selector, payload, terminator).prop_map(|(sel, pay, term)| {
4080            let mut buf = vec![0x1B, b']', b'5', b'2', b';', sel, b';'];
4081            buf.extend_from_slice(&pay);
4082            buf.extend_from_slice(&term);
4083            buf
4084        })
4085    }
4086
4087    /// Generate an SGR mouse sequence.
4088    fn sgr_mouse_sequence() -> impl Strategy<Value = Vec<u8>> {
4089        let button_code = 0u16..128;
4090        let x = 1u16..300;
4091        let y = 1u16..100;
4092        let final_byte = prop_oneof![Just(b'M'), Just(b'm')];
4093        (button_code, x, y, final_byte)
4094            .prop_map(|(btn, x, y, fb)| format!("\x1b[<{btn};{x};{y}{}", fb as char).into_bytes())
4095    }
4096
4097    /// Generate Kitty keyboard protocol sequences.
4098    fn kitty_keyboard_sequence() -> impl Strategy<Value = Vec<u8>> {
4099        let keycode = prop_oneof![
4100            0x20u32..0x7F,       // ASCII range
4101            0x57344u32..0x57400, // Kitty special keys
4102            0x100u32..0x200,     // Extended range
4103        ];
4104        let modifier = 1u32..16;
4105        let kind = prop_oneof![Just(1u32), Just(2u32), Just(3u32)]; // press/repeat/release
4106        (keycode, prop::option::of(modifier), prop::option::of(kind)).prop_map(
4107            |(kc, mods, kind)| match (mods, kind) {
4108                (Some(m), Some(k)) => format!("\x1b[{kc};{m}:{k}u").into_bytes(),
4109                (Some(m), None) => format!("\x1b[{kc};{m}u").into_bytes(),
4110                _ => format!("\x1b[{kc}u").into_bytes(),
4111            },
4112        )
4113    }
4114
4115    proptest! {
4116        // --- OSC 52 clipboard tests ---
4117
4118        /// OSC 52 clipboard sequences never panic.
4119        #[test]
4120        fn osc52_never_panics(seq in osc52_sequence()) {
4121            let mut parser = InputParser::new();
4122            let events = parser.parse(&seq);
4123            // If parsed, should be a Clipboard event
4124            for event in &events {
4125                if let Event::Clipboard(c) = event {
4126                    prop_assert!(!c.content.is_empty() || c.content.is_empty(),
4127                        "Clipboard event must have a content field");
4128                }
4129            }
4130        }
4131
4132        /// OSC 52 with corrupt base64 doesn't panic.
4133        #[test]
4134        fn osc52_corrupt_base64_safe(payload in arb_byte_vec(128)) {
4135            let mut parser = InputParser::new();
4136            let mut input = b"\x1b]52;c;".to_vec();
4137            input.extend_from_slice(&payload);
4138            input.push(0x07); // BEL terminator
4139            let _ = parser.parse(&input);
4140        }
4141
4142        // --- SGR mouse tests ---
4143
4144        /// All SGR mouse sequences parse without panicking.
4145        #[test]
4146        fn sgr_mouse_never_panics(seq in sgr_mouse_sequence()) {
4147            let mut parser = InputParser::new();
4148            let events = parser.parse(&seq);
4149            for event in &events {
4150                // Verify events are well-formed (exercises Debug impl)
4151                let _ = format!("{event:?}");
4152            }
4153        }
4154
4155        /// SGR mouse with extreme coordinates doesn't overflow.
4156        #[test]
4157        fn sgr_mouse_extreme_coords(
4158            btn in 0u16..128,
4159            x in 0u16..=65535,
4160            y in 0u16..=65535,
4161        ) {
4162            let mut parser = InputParser::new();
4163            let input = format!("\x1b[<{btn};{x};{y}M").into_bytes();
4164            let events = parser.parse(&input);
4165            for event in &events {
4166                if let Event::Mouse(m) = event {
4167                    prop_assert!(m.x <= x, "Mouse x {} > input x {}", m.x, x);
4168                    prop_assert!(m.y <= y, "Mouse y {} > input y {}", m.y, y);
4169                }
4170            }
4171        }
4172
4173        /// SGR-Pixels coordinate conversion is monotone in pixel coordinates.
4174        #[test]
4175        fn pixel_to_cell_is_monotone(
4176            px1 in 0u32..=100_000,
4177            px2 in 0u32..=100_000,
4178            py1 in 0u32..=100_000,
4179            py2 in 0u32..=100_000,
4180            cw in 1u16..=64,
4181            ch in 1u16..=64,
4182        ) {
4183            let (px_lo, px_hi) = if px1 <= px2 { (px1, px2) } else { (px2, px1) };
4184            let (py_lo, py_hi) = if py1 <= py2 { (py1, py2) } else { (py2, py1) };
4185
4186            let mut parser = InputParser::new();
4187            parser.set_pixel_mouse(true);
4188            parser.set_cell_size_px(cw, ch);
4189
4190            let seq1 = format!("\x1b[<0;{px_lo};{py_lo}M");
4191            let seq2 = format!("\x1b[<0;{px_hi};{py_hi}M");
4192
4193            let ev1 = parser.parse(seq1.as_bytes());
4194            let ev2 = parser.parse(seq2.as_bytes());
4195
4196            match (ev1.as_slice(), ev2.as_slice()) {
4197                ([Event::Mouse(m1)], [Event::Mouse(m2)]) => {
4198                    prop_assert!(m1.x <= m2.x, "m1.x={} > m2.x={}", m1.x, m2.x);
4199                    prop_assert!(m1.y <= m2.y, "m1.y={} > m2.y={}", m1.y, m2.y);
4200                    prop_assert_eq!(m1.pixel, Some((px_lo, py_lo)));
4201                    prop_assert_eq!(m2.pixel, Some((px_hi, py_hi)));
4202                }
4203                other => prop_assert!(false, "unexpected events: {other:?}"),
4204            }
4205        }
4206
4207        // --- Kitty keyboard protocol tests ---
4208
4209        /// Kitty keyboard sequences never panic.
4210        #[test]
4211        fn kitty_keyboard_never_panics(seq in kitty_keyboard_sequence()) {
4212            let mut parser = InputParser::new();
4213            let _ = parser.parse(&seq);
4214        }
4215
4216        // --- State boundary tests ---
4217
4218        /// Truncated CSI followed by new valid sequence works correctly.
4219        #[test]
4220        fn truncated_csi_then_valid(
4221            params in prop::collection::vec(0x30u8..=0x3F, 1..=10),
4222            valid_char in 0x20u8..0x7F,
4223        ) {
4224            let mut parser = InputParser::new();
4225
4226            // Send truncated CSI (no final byte)
4227            let mut partial = vec![0x1B, b'['];
4228            partial.extend_from_slice(&params);
4229            let _ = parser.parse(&partial);
4230
4231            // Now send a fresh ESC sequence that should reset state
4232            let events = parser.parse(&[0x1B, b'[', b'A']); // Up arrow
4233            // Parser should eventually emit events (possibly including
4234            // interpretation of partial as complete)
4235            let _ = events;
4236
4237            // Verify recovery with a simple key
4238            let events = parser.parse(&[valid_char]);
4239            let _ = events;
4240        }
4241
4242        /// Truncated OSC followed by new valid sequence works.
4243        #[test]
4244        fn truncated_osc_then_valid(
4245            content in prop::collection::vec(0x20u8..=0x7E, 1..=32),
4246        ) {
4247            let mut parser = InputParser::new();
4248
4249            // Send unterminated OSC
4250            let mut partial = vec![0x1B, b']'];
4251            partial.extend_from_slice(&content);
4252            let _ = parser.parse(&partial);
4253
4254            // Send a new ESC to interrupt, then a valid key
4255            let events = parser.parse(b"\x1bz");
4256            let _ = events;
4257        }
4258
4259        // --- Near-limit tests ---
4260
4261        /// CSI sequence just under MAX_CSI_LEN produces events.
4262        #[test]
4263        fn csi_near_limit_produces_event(
4264            fill_byte in 0x30u8..=0x39, // digit parameter bytes
4265        ) {
4266            let mut parser = InputParser::new();
4267
4268            let mut input = vec![0x1B, b'['];
4269            // Fill to just under limit
4270            input.extend(std::iter::repeat_n(fill_byte, MAX_CSI_LEN - 1));
4271            input.push(b'm'); // final byte (SGR)
4272
4273            let events = parser.parse(&input);
4274            // Should NOT have been ignored (under limit)
4275            // The sequence is valid structurally even if params are nonsensical
4276            let _ = events;
4277
4278            // Parser should still work
4279            let events = parser.parse(b"a");
4280            prop_assert!(!events.is_empty(), "Parser stuck after near-limit CSI");
4281        }
4282
4283        /// OSC sequence just under MAX_OSC_LEN still processes.
4284        #[test]
4285        fn osc_near_limit_processes(
4286            fill_byte in 0x20u8..=0x7E,
4287        ) {
4288            let mut parser = InputParser::new();
4289
4290            let mut input = vec![0x1B, b']'];
4291            input.extend(std::iter::repeat_n(fill_byte, MAX_OSC_LEN - 1));
4292            input.push(0x07); // BEL terminator
4293
4294            let _ = parser.parse(&input);
4295
4296            // Parser should still work
4297            let events = parser.parse(b"b");
4298            prop_assert!(!events.is_empty(), "Parser stuck after near-limit OSC");
4299        }
4300
4301        // --- Consecutive paste tests ---
4302
4303        /// Multiple back-to-back paste sequences all emit events.
4304        #[test]
4305        fn consecutive_pastes_emit_events(count in 2usize..=5) {
4306            let mut parser = InputParser::new();
4307            let mut input = Vec::new();
4308
4309            for i in 0..count {
4310                input.extend_from_slice(b"\x1b[200~");
4311                input.extend_from_slice(format!("paste_{i}").as_bytes());
4312                input.extend_from_slice(b"\x1b[201~");
4313            }
4314
4315            let events = parser.parse(&input);
4316            let paste_events: Vec<_> = events.iter()
4317                .filter(|e| matches!(e, Event::Paste(_)))
4318                .collect();
4319
4320            prop_assert_eq!(paste_events.len(), count,
4321                "Expected {} paste events, got {}", count, paste_events.len());
4322        }
4323
4324        /// Paste with invalid UTF-8 bytes doesn't panic.
4325        #[test]
4326        fn paste_with_invalid_utf8(content in arb_byte_vec(256)) {
4327            let mut parser = InputParser::new();
4328            let mut input = b"\x1b[200~".to_vec();
4329            input.extend_from_slice(&content);
4330            input.extend_from_slice(b"\x1b[201~");
4331
4332            let events = parser.parse(&input);
4333            for event in &events {
4334                if let Event::Paste(p) = event {
4335                    // Text should be valid UTF-8 (lossy conversion happens internally)
4336                    prop_assert!(p.text.is_char_boundary(0), "Paste text is not valid UTF-8");
4337                }
4338            }
4339        }
4340
4341        // --- Recovery invariants ---
4342
4343        /// After any arbitrary input, feeding ESC then a known key recovers.
4344        #[test]
4345        fn recovery_via_esc_reset(garbage in arb_byte_vec(256)) {
4346            let mut parser = InputParser::new();
4347            let _ = parser.parse(&garbage);
4348
4349            // Terminate any pending OSC (BEL works from any OSC sub-state),
4350            // then ESC to flush any other intermediate state.
4351            let _ = parser.parse(b"\x07\x1b\\\x1b");
4352            let _ = parser.parse(b"\x1b");
4353
4354            // Now feed a clean character.
4355            let _ = parser.parse(b"z");
4356
4357            // Feed one more clean character to verify.
4358            let events = parser.parse(b"q");
4359            // After terminating all pending sequences and feeding clean input,
4360            // the parser must produce events.
4361            prop_assert!(!events.is_empty(),
4362                "Parser did not recover after garbage + reset");
4363        }
4364    }
4365}