Skip to main content

ftui_render/
terminal_model.rs

1#![forbid(unsafe_code)]
2
3//! Terminal model for presenter validation.
4//!
5//! This module provides a minimal terminal emulator that understands
6//! the subset of ANSI sequences we emit, enabling deterministic testing
7//! of the presenter without requiring actual terminal I/O.
8//!
9//! # Scope
10//!
11//! This is NOT a full VT emulator. It supports only:
12//! - Cursor positioning (CUP, relative moves)
13//! - SGR (style attributes)
14//! - Erase operations (EL, ED)
15//! - OSC 8 hyperlinks
16//! - DEC 2026 synchronized output (tracked but visual effects ignored)
17//!
18//! # Usage
19//!
20//! ```ignore
21//! let mut model = TerminalModel::new(80, 24);
22//! model.process(b"\x1b[1;1H"); // Move cursor to (0, 0)
23//! model.process(b"\x1b[1mHello\x1b[0m"); // Write "Hello" in bold
24//! assert_eq!(model.cursor(), (5, 0)); // Cursor advanced
25//! assert_eq!(model.cell(0, 0).text, "H");
26//! ```
27
28use crate::{
29    cell::{CellAttrs, PackedRgba, StyleFlags},
30    char_width,
31};
32
33/// A single cell in the terminal model grid.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct ModelCell {
36    // ... (existing code matches, just updating imports implies I need context for replace)
37    /// Text content (grapheme cluster). Default is space.
38    pub text: String,
39    /// Foreground color.
40    pub fg: PackedRgba,
41    /// Background color.
42    pub bg: PackedRgba,
43    /// Style flags (bold, italic, etc.).
44    pub attrs: CellAttrs,
45    /// Hyperlink ID (0 = no link).
46    pub link_id: u32,
47}
48
49impl Default for ModelCell {
50    fn default() -> Self {
51        Self {
52            text: " ".to_string(),
53            fg: PackedRgba::WHITE,
54            bg: PackedRgba::TRANSPARENT,
55            attrs: CellAttrs::NONE,
56            link_id: 0,
57        }
58    }
59}
60
61impl ModelCell {
62    /// Create a cell with the given character and default style.
63    pub fn with_char(ch: char) -> Self {
64        Self {
65            text: ch.to_string(),
66            ..Default::default()
67        }
68    }
69}
70
71/// Current SGR (style) state for the terminal model.
72#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct SgrState {
74    /// Current foreground color.
75    pub fg: PackedRgba,
76    /// Current background color.
77    pub bg: PackedRgba,
78    /// Current text attribute flags.
79    pub flags: StyleFlags,
80}
81
82impl Default for SgrState {
83    fn default() -> Self {
84        Self {
85            fg: PackedRgba::WHITE,
86            bg: PackedRgba::TRANSPARENT,
87            flags: StyleFlags::empty(),
88        }
89    }
90}
91
92impl SgrState {
93    /// Reset all fields to defaults (white fg, transparent bg, no flags).
94    pub fn reset(&mut self) {
95        *self = Self::default();
96    }
97}
98
99/// Mode flags tracked by the terminal model.
100#[derive(Debug, Clone, Default, PartialEq, Eq)]
101pub struct ModeFlags {
102    /// Cursor visibility.
103    pub cursor_visible: bool,
104    /// Alternate screen buffer active.
105    pub alt_screen: bool,
106    /// DEC 2026 synchronized output nesting level.
107    pub sync_output_level: u32,
108}
109
110impl ModeFlags {
111    /// Create default mode flags (cursor visible, main screen, sync=0).
112    pub fn new() -> Self {
113        Self {
114            cursor_visible: true,
115            alt_screen: false,
116            sync_output_level: 0,
117        }
118    }
119}
120
121/// Parser state for ANSI escape sequences.
122#[derive(Debug, Clone, PartialEq, Eq)]
123enum ParseState {
124    Ground,
125    Escape,
126    CsiEntry,
127    CsiParam,
128    OscEntry,
129    OscString,
130}
131
132/// A minimal terminal model for testing presenter output.
133///
134/// Tracks grid state, cursor position, SGR state, and hyperlinks.
135/// Processes a subset of ANSI sequences that we emit.
136#[derive(Debug)]
137pub struct TerminalModel {
138    width: usize,
139    height: usize,
140    cells: Vec<ModelCell>,
141    cursor_x: usize,
142    cursor_y: usize,
143    sgr: SgrState,
144    modes: ModeFlags,
145    current_link_id: u32,
146    /// Hyperlink URL registry (link_id -> URL).
147    links: Vec<String>,
148    /// Parser state.
149    parse_state: ParseState,
150    /// CSI parameter buffer.
151    csi_params: Vec<u32>,
152    /// CSI intermediate accumulator.
153    csi_intermediate: Vec<u8>,
154    /// OSC accumulator.
155    osc_buffer: Vec<u8>,
156    /// Pending UTF-8 bytes for multibyte characters.
157    utf8_pending: Vec<u8>,
158    /// Expected UTF-8 sequence length (None if not in a sequence).
159    utf8_expected: Option<usize>,
160    /// Bytes processed (for debugging).
161    bytes_processed: usize,
162    /// The cell the last printed character went to, and the cursor right
163    /// after it: a zero-width character that follows directly belongs there.
164    last_print: Option<(usize, usize, usize)>,
165}
166
167impl TerminalModel {
168    /// Create a new terminal model with the given dimensions.
169    ///
170    /// Dimensions are clamped to a minimum of 1×1 to prevent arithmetic
171    /// underflows in cursor-positioning and diff helpers.
172    pub fn new(width: usize, height: usize) -> Self {
173        let width = width.max(1);
174        let height = height.max(1);
175        let cells = vec![ModelCell::default(); width * height];
176        Self {
177            width,
178            height,
179            cells,
180            cursor_x: 0,
181            cursor_y: 0,
182            sgr: SgrState::default(),
183            modes: ModeFlags::new(),
184            current_link_id: 0,
185            links: vec![String::new()], // Index 0 is "no link"
186            parse_state: ParseState::Ground,
187            csi_params: Vec::with_capacity(16),
188            csi_intermediate: Vec::with_capacity(4),
189            osc_buffer: Vec::with_capacity(256),
190            utf8_pending: Vec::with_capacity(4),
191            utf8_expected: None,
192            bytes_processed: 0,
193            last_print: None,
194        }
195    }
196
197    /// Get the terminal width.
198    #[must_use]
199    pub fn width(&self) -> usize {
200        self.width
201    }
202
203    /// Get the terminal height.
204    #[must_use]
205    pub fn height(&self) -> usize {
206        self.height
207    }
208
209    /// Get the cursor position as (x, y).
210    #[must_use]
211    pub fn cursor(&self) -> (usize, usize) {
212        (self.cursor_x, self.cursor_y)
213    }
214
215    /// Get the current SGR state.
216    #[must_use]
217    pub fn sgr_state(&self) -> &SgrState {
218        &self.sgr
219    }
220
221    /// Get the current mode flags.
222    #[must_use]
223    pub fn modes(&self) -> &ModeFlags {
224        &self.modes
225    }
226
227    /// Get the cell at (x, y). Returns None if out of bounds.
228    #[must_use]
229    pub fn cell(&self, x: usize, y: usize) -> Option<&ModelCell> {
230        if x < self.width && y < self.height {
231            Some(&self.cells[y * self.width + x])
232        } else {
233            None
234        }
235    }
236
237    /// Get a mutable reference to the cell at (x, y).
238    fn cell_mut(&mut self, x: usize, y: usize) -> Option<&mut ModelCell> {
239        if x < self.width && y < self.height {
240            Some(&mut self.cells[y * self.width + x])
241        } else {
242            None
243        }
244    }
245
246    /// Get the current cell under the cursor.
247    #[must_use]
248    pub fn current_cell(&self) -> Option<&ModelCell> {
249        self.cell(self.cursor_x, self.cursor_y)
250    }
251
252    /// Get all cells as a slice.
253    pub fn cells(&self) -> &[ModelCell] {
254        &self.cells
255    }
256
257    /// Get a row of cells.
258    #[must_use]
259    pub fn row(&self, y: usize) -> Option<&[ModelCell]> {
260        if y < self.height {
261            let start = y * self.width;
262            Some(&self.cells[start..start + self.width])
263        } else {
264            None
265        }
266    }
267
268    /// Extract the text content of a row as a string (trimmed of trailing spaces).
269    #[must_use]
270    pub fn row_text(&self, y: usize) -> Option<String> {
271        self.row(y).map(|cells| {
272            let s: String = cells.iter().map(|c| c.text.as_str()).collect();
273            s.trim_end_matches(' ').to_string()
274        })
275    }
276
277    /// Get the URL for a link ID.
278    #[must_use]
279    pub fn link_url(&self, link_id: u32) -> Option<&str> {
280        self.links.get(link_id as usize).map(|s| s.as_str())
281    }
282
283    /// Check if the terminal has a dangling hyperlink (active link after processing).
284    pub fn has_dangling_link(&self) -> bool {
285        self.current_link_id != 0
286    }
287
288    /// Check if synchronized output is properly balanced.
289    pub fn sync_output_balanced(&self) -> bool {
290        self.modes.sync_output_level == 0
291    }
292
293    /// Reset the terminal model to initial state.
294    pub fn reset(&mut self) {
295        self.cells.fill(ModelCell::default());
296        self.cursor_x = 0;
297        self.cursor_y = 0;
298        self.sgr = SgrState::default();
299        self.modes = ModeFlags::new();
300        self.current_link_id = 0;
301        // Restore hyperlink registry to initial state (index 0 = empty sentinel)
302        self.links.clear();
303        self.links.push(String::new());
304        self.parse_state = ParseState::Ground;
305        self.csi_params.clear();
306        self.csi_intermediate.clear();
307        self.osc_buffer.clear();
308        self.utf8_pending.clear();
309        self.utf8_expected = None;
310        self.last_print = None;
311    }
312
313    /// Process a byte sequence, updating the terminal state.
314    pub fn process(&mut self, bytes: &[u8]) {
315        for &b in bytes {
316            self.process_byte(b);
317            self.bytes_processed += 1;
318        }
319    }
320
321    /// Process a single byte.
322    fn process_byte(&mut self, b: u8) {
323        match self.parse_state {
324            ParseState::Ground => self.ground_state(b),
325            ParseState::Escape => self.escape_state(b),
326            ParseState::CsiEntry => self.csi_entry_state(b),
327            ParseState::CsiParam => self.csi_param_state(b),
328            ParseState::OscEntry => self.osc_entry_state(b),
329            ParseState::OscString => self.osc_string_state(b),
330        }
331    }
332
333    fn ground_state(&mut self, b: u8) {
334        match b {
335            0x1B => {
336                // ESC
337                self.flush_pending_utf8_invalid();
338                self.parse_state = ParseState::Escape;
339            }
340            0x00..=0x1A | 0x1C..=0x1F => {
341                // C0 controls (mostly ignored)
342                self.flush_pending_utf8_invalid();
343                self.handle_c0(b);
344            }
345            _ => {
346                // Printable character (UTF-8 aware)
347                self.handle_printable(b);
348            }
349        }
350    }
351
352    fn escape_state(&mut self, b: u8) {
353        match b {
354            b'[' => {
355                // CSI
356                self.csi_params.clear();
357                self.csi_intermediate.clear();
358                self.parse_state = ParseState::CsiEntry;
359            }
360            b']' => {
361                // OSC
362                self.osc_buffer.clear();
363                self.parse_state = ParseState::OscEntry;
364            }
365            b'7' => {
366                // DECSC - save cursor (we track but don't implement save/restore stack)
367                self.parse_state = ParseState::Ground;
368            }
369            b'8' => {
370                // DECRC - restore cursor
371                self.parse_state = ParseState::Ground;
372            }
373            b'=' | b'>' => {
374                // Application/Normal keypad mode (ignored)
375                self.parse_state = ParseState::Ground;
376            }
377            0x1B => {
378                // ESC ESC - stay in escape (malformed, but handle gracefully)
379            }
380            _ => {
381                // Unknown escape, return to ground
382                self.parse_state = ParseState::Ground;
383            }
384        }
385    }
386
387    fn csi_entry_state(&mut self, b: u8) {
388        match b {
389            b'0'..=b'9' => {
390                self.csi_params.push((b - b'0') as u32);
391                self.parse_state = ParseState::CsiParam;
392            }
393            b';' => {
394                // Semicolon at entry means "default first param, start second param".
395                // Push 0 for first param (default) AND 0 for the start of the second.
396                self.csi_params.push(0);
397                self.csi_params.push(0);
398                self.parse_state = ParseState::CsiParam;
399            }
400            b'?' | b'>' | b'!' => {
401                self.csi_intermediate.push(b);
402                self.parse_state = ParseState::CsiParam;
403            }
404            0x40..=0x7E => {
405                // Final byte with no params
406                self.execute_csi(b);
407                self.parse_state = ParseState::Ground;
408            }
409            _ => {
410                self.parse_state = ParseState::Ground;
411            }
412        }
413    }
414
415    fn csi_param_state(&mut self, b: u8) {
416        match b {
417            b'0'..=b'9' => {
418                if self.csi_params.is_empty() {
419                    self.csi_params.push(0);
420                }
421                if let Some(last) = self.csi_params.last_mut() {
422                    *last = last.saturating_mul(10).saturating_add((b - b'0') as u32);
423                }
424            }
425            b';' => {
426                self.csi_params.push(0);
427            }
428            b':' => {
429                // Subparameter (e.g., for 256/RGB colors) - we handle in SGR
430                self.csi_params.push(0);
431            }
432            0x20..=0x2F => {
433                self.csi_intermediate.push(b);
434            }
435            0x40..=0x7E => {
436                // Final byte
437                self.execute_csi(b);
438                self.parse_state = ParseState::Ground;
439            }
440            _ => {
441                self.parse_state = ParseState::Ground;
442            }
443        }
444    }
445
446    fn osc_entry_state(&mut self, b: u8) {
447        match b {
448            0x07 => {
449                // BEL - OSC terminator
450                self.execute_osc();
451                self.parse_state = ParseState::Ground;
452            }
453            0x1B => {
454                // Might be ST (ESC \)
455                self.parse_state = ParseState::OscString;
456            }
457            _ => {
458                self.osc_buffer.push(b);
459            }
460        }
461    }
462
463    fn osc_string_state(&mut self, b: u8) {
464        match b {
465            b'\\' => {
466                // ST (ESC \)
467                self.execute_osc();
468                self.parse_state = ParseState::Ground;
469            }
470            _ => {
471                // Not ST, put ESC back and continue
472                self.osc_buffer.push(0x1B);
473                self.osc_buffer.push(b);
474                self.parse_state = ParseState::OscEntry;
475            }
476        }
477    }
478
479    fn handle_c0(&mut self, b: u8) {
480        match b {
481            0x07 => {} // BEL - ignored
482            0x08 if self.cursor_x > 0 => {
483                // BS - backspace
484                self.cursor_x -= 1;
485            }
486            0x09 => {
487                // HT - tab (move to next 8-column stop)
488                self.cursor_x = (self.cursor_x / 8 + 1) * 8;
489                if self.cursor_x >= self.width {
490                    self.cursor_x = self.width - 1;
491                }
492            }
493            0x0A if self.cursor_y + 1 < self.height => {
494                // LF - line feed
495                self.cursor_y += 1;
496            }
497            0x0D => {
498                // CR - carriage return
499                self.cursor_x = 0;
500            }
501            _ => {} // Other C0 controls ignored
502        }
503    }
504
505    fn handle_printable(&mut self, b: u8) {
506        if self.utf8_expected.is_none() {
507            if b < 0x80 {
508                self.put_char(b as char);
509                return;
510            }
511            if let Some(expected) = Self::utf8_expected_len(b) {
512                self.utf8_pending.clear();
513                self.utf8_pending.push(b);
514                self.utf8_expected = Some(expected);
515                if expected == 1 {
516                    self.flush_utf8_sequence();
517                }
518            } else {
519                self.put_char('\u{FFFD}');
520            }
521            return;
522        }
523
524        if !Self::is_utf8_continuation(b) {
525            self.flush_pending_utf8_invalid();
526            self.handle_printable(b);
527            return;
528        }
529
530        self.utf8_pending.push(b);
531        if let Some(expected) = self.utf8_expected {
532            if self.utf8_pending.len() == expected {
533                self.flush_utf8_sequence();
534            } else if self.utf8_pending.len() > expected {
535                self.flush_pending_utf8_invalid();
536            }
537        }
538    }
539
540    fn flush_utf8_sequence(&mut self) {
541        // Collect chars first to avoid borrow conflict with put_char.
542        // UTF-8 sequences are at most 4 bytes, so this is small.
543        let chars: Vec<char> = std::str::from_utf8(&self.utf8_pending)
544            .map(|text| text.chars().collect())
545            .unwrap_or_else(|_| vec!['\u{FFFD}']);
546        self.utf8_pending.clear();
547        self.utf8_expected = None;
548        for ch in chars {
549            self.put_char(ch);
550        }
551    }
552
553    fn flush_pending_utf8_invalid(&mut self) {
554        if self.utf8_expected.is_some() {
555            self.put_char('\u{FFFD}');
556            self.utf8_pending.clear();
557            self.utf8_expected = None;
558        }
559    }
560
561    fn utf8_expected_len(first: u8) -> Option<usize> {
562        if first < 0x80 {
563            Some(1)
564        } else if (0xC2..=0xDF).contains(&first) {
565            Some(2)
566        } else if (0xE0..=0xEF).contains(&first) {
567            Some(3)
568        } else if (0xF0..=0xF4).contains(&first) {
569            Some(4)
570        } else {
571            None
572        }
573    }
574
575    fn is_utf8_continuation(byte: u8) -> bool {
576        (0x80..=0xBF).contains(&byte)
577    }
578
579    fn put_char(&mut self, ch: char) {
580        let width = char_width(ch);
581
582        // Zero-width (combining) character handling
583        if width == 0 {
584            // It belongs to the character printed just before it, which is
585            // not always the cell left of the cursor: after a wide character
586            // that is the placeholder, and after the last column the cursor
587            // has already wrapped. Both put `中\u{301}` or a mark at the
588            // right edge in the wrong cell.
589            if let Some((idx, x, y)) = self.last_print
590                && (x, y) == (self.cursor_x, self.cursor_y)
591            {
592                if let Some(cell) = self.cells.get_mut(idx) {
593                    cell.text.push(ch);
594                }
595                return;
596            }
597            if self.cursor_x > 0 {
598                // Append to previous cell
599                let idx = self.cursor_y * self.width + self.cursor_x - 1;
600                if let Some(cell) = self.cells.get_mut(idx) {
601                    cell.text.push(ch);
602                }
603            } else if self.cursor_x < self.width && self.cursor_y < self.height {
604                // At start of line, attach to current cell (if empty/space) or append
605                let idx = self.cursor_y * self.width + self.cursor_x;
606                let cell = &mut self.cells[idx];
607                if cell.text == " " {
608                    // Replace default space with space+combining
609                    cell.text = format!(" {}", ch);
610                } else {
611                    cell.text.push(ch);
612                }
613            }
614            return;
615        }
616
617        let mut printed = None;
618        if self.cursor_x < self.width && self.cursor_y < self.height {
619            let idx = self.cursor_y * self.width + self.cursor_x;
620            printed = Some(idx);
621            let cell = &mut self.cells[idx];
622            cell.text = ch.to_string();
623            cell.fg = self.sgr.fg;
624            cell.bg = self.sgr.bg;
625            cell.attrs = CellAttrs::new(self.sgr.flags, self.current_link_id);
626            cell.link_id = self.current_link_id;
627
628            // Handle wide characters (clear the next cell if it exists)
629            if width == 2 && self.cursor_x + 1 < self.width {
630                let next_cell = &mut self.cells[self.cursor_y * self.width + self.cursor_x + 1];
631                next_cell.text = String::new(); // Clear content (placeholder)
632                next_cell.fg = self.sgr.fg; // Extend background color
633                next_cell.bg = self.sgr.bg;
634                next_cell.attrs = CellAttrs::NONE; // Clear attributes
635                next_cell.link_id = 0; // Clear link
636            }
637        }
638
639        self.cursor_x += width;
640
641        // Handle line wrap if at edge
642        if self.cursor_x >= self.width {
643            self.cursor_x = 0;
644            if self.cursor_y + 1 < self.height {
645                self.cursor_y += 1;
646            }
647            // Note: If we are at the bottom line, we wrap to the start of the *same* line.
648            // This model does not implement scrolling because it is intended to validate
649            // Frame-based rendering where absolute positioning (CUP) is used, and
650            // wrapping/scrolling behavior should not be triggered by the Presenter.
651        }
652        self.last_print = printed.map(|idx| (idx, self.cursor_x, self.cursor_y));
653    }
654
655    fn execute_csi(&mut self, final_byte: u8) {
656        let has_question = self.csi_intermediate.contains(&b'?');
657
658        match final_byte {
659            b'H' | b'f' => self.csi_cup(),             // CUP - cursor position
660            b'A' => self.csi_cuu(),                    // CUU - cursor up
661            b'B' => self.csi_cud(),                    // CUD - cursor down
662            b'C' => self.csi_cuf(),                    // CUF - cursor forward
663            b'D' => self.csi_cub(),                    // CUB - cursor back
664            b'G' => self.csi_cha(),                    // CHA - cursor horizontal absolute
665            b'd' => self.csi_vpa(),                    // VPA - vertical position absolute
666            b'J' => self.csi_ed(),                     // ED - erase in display
667            b'K' => self.csi_el(),                     // EL - erase in line
668            b'm' => self.csi_sgr(),                    // SGR - select graphic rendition
669            b'h' if has_question => self.csi_decset(), // DECSET
670            b'l' if has_question => self.csi_decrst(), // DECRST
671            b's' => {
672                // Save cursor position (ANSI)
673            }
674            b'u' => {
675                // Restore cursor position (ANSI)
676            }
677            _ => {} // Unknown CSI - ignored
678        }
679    }
680
681    fn csi_cup(&mut self) {
682        // CSI row ; col H
683        let row = self.csi_params.first().copied().unwrap_or(1).max(1) as usize;
684        let col = self.csi_params.get(1).copied().unwrap_or(1).max(1) as usize;
685        self.cursor_y = (row - 1).min(self.height - 1);
686        self.cursor_x = (col - 1).min(self.width - 1);
687    }
688
689    fn csi_cuu(&mut self) {
690        let n = self.csi_params.first().copied().unwrap_or(1).max(1) as usize;
691        self.cursor_y = self.cursor_y.saturating_sub(n);
692    }
693
694    fn csi_cud(&mut self) {
695        let n = self.csi_params.first().copied().unwrap_or(1).max(1) as usize;
696        self.cursor_y = (self.cursor_y + n).min(self.height - 1);
697    }
698
699    fn csi_cuf(&mut self) {
700        let n = self.csi_params.first().copied().unwrap_or(1).max(1) as usize;
701        self.cursor_x = (self.cursor_x + n).min(self.width - 1);
702    }
703
704    fn csi_cub(&mut self) {
705        let n = self.csi_params.first().copied().unwrap_or(1).max(1) as usize;
706        self.cursor_x = self.cursor_x.saturating_sub(n);
707    }
708
709    fn csi_cha(&mut self) {
710        let col = self.csi_params.first().copied().unwrap_or(1).max(1) as usize;
711        self.cursor_x = (col - 1).min(self.width - 1);
712    }
713
714    fn csi_vpa(&mut self) {
715        let row = self.csi_params.first().copied().unwrap_or(1).max(1) as usize;
716        self.cursor_y = (row - 1).min(self.height - 1);
717    }
718
719    fn csi_ed(&mut self) {
720        let mode = self.csi_params.first().copied().unwrap_or(0);
721        match mode {
722            0 => {
723                // Erase from cursor to end of screen
724                for x in self.cursor_x..self.width {
725                    self.erase_cell(x, self.cursor_y);
726                }
727                for y in (self.cursor_y + 1)..self.height {
728                    for x in 0..self.width {
729                        self.erase_cell(x, y);
730                    }
731                }
732            }
733            1 => {
734                // Erase from start of screen to cursor
735                for y in 0..self.cursor_y {
736                    for x in 0..self.width {
737                        self.erase_cell(x, y);
738                    }
739                }
740                for x in 0..=self.cursor_x {
741                    self.erase_cell(x, self.cursor_y);
742                }
743            }
744            2 | 3 => {
745                // Erase entire screen
746                self.cells.fill(ModelCell::default());
747            }
748            _ => {}
749        }
750    }
751
752    fn csi_el(&mut self) {
753        let mode = self.csi_params.first().copied().unwrap_or(0);
754        match mode {
755            0 => {
756                // Erase from cursor to end of line
757                for x in self.cursor_x..self.width {
758                    self.erase_cell(x, self.cursor_y);
759                }
760            }
761            1 => {
762                // Erase from start of line to cursor
763                for x in 0..=self.cursor_x {
764                    self.erase_cell(x, self.cursor_y);
765                }
766            }
767            2 => {
768                // Erase entire line
769                for x in 0..self.width {
770                    self.erase_cell(x, self.cursor_y);
771                }
772            }
773            _ => {}
774        }
775    }
776
777    fn erase_cell(&mut self, x: usize, y: usize) {
778        // Copy background color before borrowing self mutably
779        let bg = self.sgr.bg;
780        if let Some(cell) = self.cell_mut(x, y) {
781            cell.text = " ".to_string();
782            // Erase uses current background color
783            cell.fg = PackedRgba::WHITE;
784            cell.bg = bg;
785            cell.attrs = CellAttrs::NONE;
786            cell.link_id = 0;
787        }
788    }
789
790    fn csi_sgr(&mut self) {
791        if self.csi_params.is_empty() {
792            self.sgr.reset();
793            return;
794        }
795
796        let mut i = 0;
797        while i < self.csi_params.len() {
798            let code = self.csi_params[i];
799            match code {
800                0 => self.sgr.reset(),
801                1 => self.sgr.flags.insert(StyleFlags::BOLD),
802                2 => self.sgr.flags.insert(StyleFlags::DIM),
803                3 => self.sgr.flags.insert(StyleFlags::ITALIC),
804                4 => self.sgr.flags.insert(StyleFlags::UNDERLINE),
805                5 => self.sgr.flags.insert(StyleFlags::BLINK),
806                7 => self.sgr.flags.insert(StyleFlags::REVERSE),
807                8 => self.sgr.flags.insert(StyleFlags::HIDDEN),
808                9 => self.sgr.flags.insert(StyleFlags::STRIKETHROUGH),
809                21 | 22 => self.sgr.flags.remove(StyleFlags::BOLD | StyleFlags::DIM),
810                23 => self.sgr.flags.remove(StyleFlags::ITALIC),
811                24 => self.sgr.flags.remove(StyleFlags::UNDERLINE),
812                25 => self.sgr.flags.remove(StyleFlags::BLINK),
813                27 => self.sgr.flags.remove(StyleFlags::REVERSE),
814                28 => self.sgr.flags.remove(StyleFlags::HIDDEN),
815                29 => self.sgr.flags.remove(StyleFlags::STRIKETHROUGH),
816                // Basic foreground colors (30-37)
817                30..=37 => {
818                    self.sgr.fg = Self::basic_color(code - 30);
819                }
820                // Default foreground
821                39 => {
822                    self.sgr.fg = PackedRgba::WHITE;
823                }
824                // Basic background colors (40-47)
825                40..=47 => {
826                    self.sgr.bg = Self::basic_color(code - 40);
827                }
828                // Default background
829                49 => {
830                    self.sgr.bg = PackedRgba::TRANSPARENT;
831                }
832                // Bright foreground colors (90-97)
833                90..=97 => {
834                    self.sgr.fg = Self::bright_color(code - 90);
835                }
836                // Bright background colors (100-107)
837                100..=107 => {
838                    self.sgr.bg = Self::bright_color(code - 100);
839                }
840                // Extended colors (38/48)
841                38 => {
842                    if let Some(color) = self.parse_extended_color(&mut i) {
843                        self.sgr.fg = color;
844                    }
845                }
846                48 => {
847                    if let Some(color) = self.parse_extended_color(&mut i) {
848                        self.sgr.bg = color;
849                    }
850                }
851                _ => {} // Unknown SGR code
852            }
853            i += 1;
854        }
855    }
856
857    fn parse_extended_color(&self, i: &mut usize) -> Option<PackedRgba> {
858        let mode = self.csi_params.get(*i + 1)?;
859        match *mode {
860            5 => {
861                // 256-color mode: 38;5;n
862                let idx = self.csi_params.get(*i + 2)?;
863                *i += 2;
864                Some(Self::color_256(*idx as u8))
865            }
866            2 => {
867                // RGB mode: 38;2;r;g;b
868                let r = *self.csi_params.get(*i + 2)? as u8;
869                let g = *self.csi_params.get(*i + 3)? as u8;
870                let b = *self.csi_params.get(*i + 4)? as u8;
871                *i += 4;
872                Some(PackedRgba::rgb(r, g, b))
873            }
874            _ => None,
875        }
876    }
877
878    fn basic_color(idx: u32) -> PackedRgba {
879        match idx {
880            0 => PackedRgba::rgb(0, 0, 0),       // Black
881            1 => PackedRgba::rgb(128, 0, 0),     // Red
882            2 => PackedRgba::rgb(0, 128, 0),     // Green
883            3 => PackedRgba::rgb(128, 128, 0),   // Yellow
884            4 => PackedRgba::rgb(0, 0, 128),     // Blue
885            5 => PackedRgba::rgb(128, 0, 128),   // Magenta
886            6 => PackedRgba::rgb(0, 128, 128),   // Cyan
887            7 => PackedRgba::rgb(192, 192, 192), // White
888            _ => PackedRgba::WHITE,
889        }
890    }
891
892    fn bright_color(idx: u32) -> PackedRgba {
893        match idx {
894            0 => PackedRgba::rgb(128, 128, 128), // Bright Black
895            1 => PackedRgba::rgb(255, 0, 0),     // Bright Red
896            2 => PackedRgba::rgb(0, 255, 0),     // Bright Green
897            3 => PackedRgba::rgb(255, 255, 0),   // Bright Yellow
898            4 => PackedRgba::rgb(0, 0, 255),     // Bright Blue
899            5 => PackedRgba::rgb(255, 0, 255),   // Bright Magenta
900            6 => PackedRgba::rgb(0, 255, 255),   // Bright Cyan
901            7 => PackedRgba::rgb(255, 255, 255), // Bright White
902            _ => PackedRgba::WHITE,
903        }
904    }
905
906    fn color_256(idx: u8) -> PackedRgba {
907        match idx {
908            0..=7 => Self::basic_color(idx as u32),
909            8..=15 => Self::bright_color((idx - 8) as u32),
910            16..=231 => {
911                // 6x6x6 color cube
912                let idx = idx - 16;
913                let r = (idx / 36) % 6;
914                let g = (idx / 6) % 6;
915                let b = idx % 6;
916                let to_channel = |v| if v == 0 { 0 } else { 55 + v * 40 };
917                PackedRgba::rgb(to_channel(r), to_channel(g), to_channel(b))
918            }
919            232..=255 => {
920                // Grayscale ramp
921                let gray = 8 + (idx - 232) * 10;
922                PackedRgba::rgb(gray, gray, gray)
923            }
924        }
925    }
926
927    fn csi_decset(&mut self) {
928        for &code in &self.csi_params {
929            match code {
930                25 => self.modes.cursor_visible = true, // DECTCEM - cursor visible
931                1049 => self.modes.alt_screen = true,   // Alt screen buffer
932                2026 => self.modes.sync_output_level += 1, // Synchronized output begin
933                _ => {}
934            }
935        }
936    }
937
938    fn csi_decrst(&mut self) {
939        for &code in &self.csi_params {
940            match code {
941                25 => self.modes.cursor_visible = false, // DECTCEM - cursor hidden
942                1049 => self.modes.alt_screen = false,   // Alt screen buffer off
943                2026 => {
944                    // Synchronized output end
945                    self.modes.sync_output_level = self.modes.sync_output_level.saturating_sub(1);
946                }
947                _ => {}
948            }
949        }
950    }
951
952    fn execute_osc(&mut self) {
953        // Parse OSC: code ; data
954        // Clone buffer to avoid borrow issues when calling handle_osc8
955        let data = String::from_utf8_lossy(&self.osc_buffer).to_string();
956        let mut parts = data.splitn(2, ';');
957        let code: u32 = parts.next().and_then(|s| s.parse().ok()).unwrap_or(0);
958
959        // OSC 8 - hyperlink (other OSC codes ignored)
960        if code == 8
961            && let Some(rest) = parts.next()
962        {
963            let rest = rest.to_string();
964            self.handle_osc8(&rest);
965        }
966    }
967
968    fn handle_osc8(&mut self, data: &str) {
969        // Format: OSC 8 ; params ; uri ST
970        // We support: OSC 8 ; ; uri ST (start link) and OSC 8 ; ; ST (end link)
971        let mut parts = data.splitn(2, ';');
972        let _params = parts.next().unwrap_or("");
973        let uri = parts.next().unwrap_or("");
974
975        if uri.is_empty() {
976            // End hyperlink
977            self.current_link_id = 0;
978        } else {
979            // Start hyperlink
980            self.links.push(uri.to_string());
981            self.current_link_id = (self.links.len() - 1) as u32;
982        }
983    }
984
985    /// Compare two grids and return a diff description for debugging.
986    #[must_use]
987    pub fn diff_grid(&self, expected: &[ModelCell]) -> Option<String> {
988        if self.cells.len() != expected.len() {
989            return Some(format!(
990                "Grid size mismatch: got {} cells, expected {}",
991                self.cells.len(),
992                expected.len()
993            ));
994        }
995
996        let mut diffs = Vec::new();
997        for (i, (actual, exp)) in self.cells.iter().zip(expected.iter()).enumerate() {
998            if actual != exp {
999                let x = i % self.width;
1000                let y = i / self.width;
1001                diffs.push(format!(
1002                    "  ({}, {}): got {:?}, expected {:?}",
1003                    x, y, actual.text, exp.text
1004                ));
1005            }
1006        }
1007
1008        if diffs.is_empty() {
1009            None
1010        } else {
1011            Some(format!("Grid differences:\n{}", diffs.join("\n")))
1012        }
1013    }
1014
1015    /// Dump the escape sequences in a human-readable format (for debugging test failures).
1016    pub fn dump_sequences(bytes: &[u8]) -> String {
1017        let mut output = String::new();
1018        let mut i = 0;
1019        while i < bytes.len() {
1020            if bytes[i] == 0x1B {
1021                if i + 1 < bytes.len() {
1022                    match bytes[i + 1] {
1023                        b'[' => {
1024                            // CSI sequence
1025                            output.push_str("\\e[");
1026                            i += 2;
1027                            while i < bytes.len() && !(0x40..=0x7E).contains(&bytes[i]) {
1028                                output.push(bytes[i] as char);
1029                                i += 1;
1030                            }
1031                            if i < bytes.len() {
1032                                output.push(bytes[i] as char);
1033                                i += 1;
1034                            }
1035                        }
1036                        b']' => {
1037                            // OSC sequence
1038                            output.push_str("\\e]");
1039                            i += 2;
1040                            while i < bytes.len() && bytes[i] != 0x07 {
1041                                if bytes[i] == 0x1B && i + 1 < bytes.len() && bytes[i + 1] == b'\\'
1042                                {
1043                                    output.push_str("\\e\\\\");
1044                                    i += 2;
1045                                    break;
1046                                }
1047                                output.push(bytes[i] as char);
1048                                i += 1;
1049                            }
1050                            if i < bytes.len() && bytes[i] == 0x07 {
1051                                output.push_str("\\a");
1052                                i += 1;
1053                            }
1054                        }
1055                        _ => {
1056                            output.push_str(&format!("\\e{}", bytes[i + 1] as char));
1057                            i += 2;
1058                        }
1059                    }
1060                } else {
1061                    output.push_str("\\e");
1062                    i += 1;
1063                }
1064            } else if bytes[i] < 0x20 {
1065                output.push_str(&format!("\\x{:02x}", bytes[i]));
1066                i += 1;
1067            } else {
1068                output.push(bytes[i] as char);
1069                i += 1;
1070            }
1071        }
1072        output
1073    }
1074}
1075
1076#[cfg(test)]
1077mod tests {
1078    use super::*;
1079    use crate::ansi;
1080
1081    #[test]
1082    fn new_creates_empty_grid() {
1083        let model = TerminalModel::new(80, 24);
1084        assert_eq!(model.width(), 80);
1085        assert_eq!(model.height(), 24);
1086        assert_eq!(model.cursor(), (0, 0));
1087        assert_eq!(model.cells().len(), 80 * 24);
1088    }
1089
1090    #[test]
1091    fn printable_text_writes_to_grid() {
1092        let mut model = TerminalModel::new(10, 5);
1093        model.process(b"Hello");
1094        assert_eq!(model.cursor(), (5, 0));
1095        assert_eq!(model.row_text(0), Some("Hello".to_string()));
1096    }
1097
1098    #[test]
1099    fn cup_moves_cursor() {
1100        let mut model = TerminalModel::new(80, 24);
1101        model.process(b"\x1b[5;10H"); // Row 5, Col 10 (1-indexed)
1102        assert_eq!(model.cursor(), (9, 4)); // 0-indexed
1103    }
1104
1105    #[test]
1106    fn cup_with_defaults() {
1107        let mut model = TerminalModel::new(80, 24);
1108        model.process(b"\x1b[H"); // Should default to 1;1
1109        assert_eq!(model.cursor(), (0, 0));
1110    }
1111
1112    #[test]
1113    fn relative_cursor_moves() {
1114        let mut model = TerminalModel::new(80, 24);
1115        model.process(b"\x1b[10;10H"); // Move to (9, 9)
1116        model.process(b"\x1b[2A"); // Up 2
1117        assert_eq!(model.cursor(), (9, 7));
1118        model.process(b"\x1b[3B"); // Down 3
1119        assert_eq!(model.cursor(), (9, 10));
1120        model.process(b"\x1b[5C"); // Forward 5
1121        assert_eq!(model.cursor(), (14, 10));
1122        model.process(b"\x1b[3D"); // Back 3
1123        assert_eq!(model.cursor(), (11, 10));
1124    }
1125
1126    #[test]
1127    fn sgr_sets_style_flags() {
1128        let mut model = TerminalModel::new(20, 5);
1129        model.process(b"\x1b[1mBold\x1b[0m");
1130        assert!(model.cell(0, 0).unwrap().attrs.has_flag(StyleFlags::BOLD));
1131        assert!(!model.cell(4, 0).unwrap().attrs.has_flag(StyleFlags::BOLD)); // After reset
1132    }
1133
1134    #[test]
1135    fn sgr_sets_colors() {
1136        let mut model = TerminalModel::new(20, 5);
1137        model.process(b"\x1b[31mRed\x1b[0m");
1138        assert_eq!(model.cell(0, 0).unwrap().fg, PackedRgba::rgb(128, 0, 0));
1139    }
1140
1141    #[test]
1142    fn sgr_256_colors() {
1143        let mut model = TerminalModel::new(20, 5);
1144        model.process(b"\x1b[38;5;196mX"); // Bright red in 256 palette
1145        let cell = model.cell(0, 0).unwrap();
1146        // 196 = 16 + 180 = 16 + 5*36 + 0*6 + 0 = red=5, g=0, b=0
1147        // r = 55 + 5*40 = 255, g = 0, b = 0
1148        assert_eq!(cell.fg, PackedRgba::rgb(255, 0, 0));
1149    }
1150
1151    #[test]
1152    fn sgr_rgb_colors() {
1153        let mut model = TerminalModel::new(20, 5);
1154        model.process(b"\x1b[38;2;100;150;200mX");
1155        assert_eq!(model.cell(0, 0).unwrap().fg, PackedRgba::rgb(100, 150, 200));
1156    }
1157
1158    #[test]
1159    fn erase_line() {
1160        let mut model = TerminalModel::new(10, 5);
1161        model.process(b"ABCDEFGHIJ");
1162        // After 10 chars in 10-col terminal, cursor wraps to (0, 1)
1163        // Move back to row 1, column 5 explicitly
1164        model.process(b"\x1b[1;5H"); // Row 1, Col 5 (1-indexed) = (4, 0)
1165        model.process(b"\x1b[K"); // Erase to end of line
1166        assert_eq!(model.row_text(0), Some("ABCD".to_string()));
1167    }
1168
1169    #[test]
1170    fn erase_display() {
1171        let mut model = TerminalModel::new(10, 5);
1172        model.process(b"Line1\n");
1173        model.process(b"Line2\n");
1174        model.process(b"\x1b[2J"); // Erase entire screen
1175        for y in 0..5 {
1176            assert_eq!(model.row_text(y), Some(String::new()));
1177        }
1178    }
1179
1180    #[test]
1181    fn osc8_hyperlinks() {
1182        let mut model = TerminalModel::new(20, 5);
1183        model.process(b"\x1b]8;;https://example.com\x07Link\x1b]8;;\x07");
1184
1185        let cell = model.cell(0, 0).unwrap();
1186        assert!(cell.link_id > 0);
1187        assert_eq!(model.link_url(cell.link_id), Some("https://example.com"));
1188
1189        // After link ends, link_id should be 0
1190        let cell_after = model.cell(4, 0).unwrap();
1191        assert_eq!(cell_after.link_id, 0);
1192    }
1193
1194    #[test]
1195    fn dangling_link_detection() {
1196        let mut model = TerminalModel::new(20, 5);
1197        model.process(b"\x1b]8;;https://example.com\x07Link");
1198        assert!(model.has_dangling_link());
1199
1200        model.process(b"\x1b]8;;\x07");
1201        assert!(!model.has_dangling_link());
1202    }
1203
1204    #[test]
1205    fn sync_output_tracking() {
1206        let mut model = TerminalModel::new(20, 5);
1207        assert!(model.sync_output_balanced());
1208
1209        model.process(b"\x1b[?2026h"); // Begin sync
1210        assert!(!model.sync_output_balanced());
1211        assert_eq!(model.modes().sync_output_level, 1);
1212
1213        model.process(b"\x1b[?2026l"); // End sync
1214        assert!(model.sync_output_balanced());
1215    }
1216
1217    #[test]
1218    fn utf8_multibyte_stream_is_decoded() {
1219        let mut model = TerminalModel::new(10, 1);
1220        let text = "a\u{00E9}\u{4E2D}\u{1F600}";
1221        model.process(text.as_bytes());
1222
1223        assert_eq!(model.row_text(0).as_deref(), Some(text));
1224        assert_eq!(model.cursor(), (6, 0));
1225    }
1226
1227    #[test]
1228    fn utf8_sequence_can_span_process_calls() {
1229        let mut model = TerminalModel::new(10, 1);
1230        let text = "\u{00E9}";
1231        let bytes = text.as_bytes();
1232
1233        model.process(&bytes[..1]);
1234        assert_eq!(model.row_text(0).as_deref(), Some(""));
1235
1236        model.process(&bytes[1..]);
1237        assert_eq!(model.row_text(0).as_deref(), Some(text));
1238    }
1239
1240    #[test]
1241    fn line_wrap() {
1242        let mut model = TerminalModel::new(5, 3);
1243        model.process(b"ABCDEFGH");
1244        assert_eq!(model.row_text(0), Some("ABCDE".to_string()));
1245        assert_eq!(model.row_text(1), Some("FGH".to_string()));
1246        assert_eq!(model.cursor(), (3, 1));
1247    }
1248
1249    #[test]
1250    fn cr_lf_handling() {
1251        let mut model = TerminalModel::new(20, 5);
1252        model.process(b"Hello\r\n");
1253        assert_eq!(model.cursor(), (0, 1));
1254        model.process(b"World");
1255        assert_eq!(model.row_text(0), Some("Hello".to_string()));
1256        assert_eq!(model.row_text(1), Some("World".to_string()));
1257    }
1258
1259    #[test]
1260    fn cursor_visibility() {
1261        let mut model = TerminalModel::new(20, 5);
1262        assert!(model.modes().cursor_visible);
1263
1264        model.process(b"\x1b[?25l"); // Hide cursor
1265        assert!(!model.modes().cursor_visible);
1266
1267        model.process(b"\x1b[?25h"); // Show cursor
1268        assert!(model.modes().cursor_visible);
1269    }
1270
1271    #[test]
1272    fn alt_screen_toggle_is_tracked() {
1273        let mut model = TerminalModel::new(20, 5);
1274        assert!(!model.modes().alt_screen);
1275
1276        model.process(b"\x1b[?1049h");
1277        assert!(model.modes().alt_screen);
1278
1279        model.process(b"\x1b[?1049l");
1280        assert!(!model.modes().alt_screen);
1281    }
1282
1283    #[test]
1284    fn dump_sequences_readable() {
1285        let bytes = b"\x1b[1;1H\x1b[1mHello\x1b[0m";
1286        let dump = TerminalModel::dump_sequences(bytes);
1287        assert!(dump.contains("\\e[1;1H"));
1288        assert!(dump.contains("\\e[1m"));
1289        assert!(dump.contains("Hello"));
1290        assert!(dump.contains("\\e[0m"));
1291    }
1292
1293    #[test]
1294    fn reset_clears_state() {
1295        let mut model = TerminalModel::new(20, 5);
1296        model.process(b"\x1b[10;10HTest\x1b[1m");
1297        model.reset();
1298
1299        assert_eq!(model.cursor(), (0, 0));
1300        assert!(model.sgr_state().flags.is_empty());
1301        for y in 0..5 {
1302            assert_eq!(model.row_text(y), Some(String::new()));
1303        }
1304    }
1305
1306    #[test]
1307    fn erase_scrollback_mode_clears_screen() {
1308        let mut model = TerminalModel::new(10, 3);
1309        model.process(b"Line1\nLine2\nLine3");
1310        model.process(b"\x1b[3J"); // ED scrollback mode
1311
1312        for y in 0..3 {
1313            assert_eq!(model.row_text(y), Some(String::new()));
1314        }
1315    }
1316
1317    #[test]
1318    fn scroll_region_sequences_are_ignored_but_safe() {
1319        let mut model = TerminalModel::new(12, 3);
1320        model.process(b"ABCD");
1321        let cursor_before = model.cursor();
1322
1323        let mut buf = Vec::new();
1324        ansi::set_scroll_region(&mut buf, 1, 2).expect("scroll region sequence");
1325        model.process(&buf);
1326        model.process(ansi::RESET_SCROLL_REGION);
1327
1328        assert_eq!(model.cursor(), cursor_before);
1329        model.process(b"EF");
1330        assert_eq!(model.row_text(0).as_deref(), Some("ABCDEF"));
1331    }
1332
1333    #[test]
1334    fn scroll_region_invalid_params_do_not_corrupt_state() {
1335        let mut model = TerminalModel::new(8, 2);
1336        model.process(b"Hi");
1337        let cursor_before = model.cursor();
1338
1339        model.process(b"\x1b[5;2r"); // bottom < top
1340        model.process(b"\x1b[0;0r"); // zero params
1341        model.process(b"\x1b[999;999r"); // out of bounds
1342
1343        assert_eq!(model.cursor(), cursor_before);
1344        model.process(b"!");
1345        assert_eq!(model.row_text(0).as_deref(), Some("Hi!"));
1346    }
1347
1348    // --- ModelCell ---
1349
1350    #[test]
1351    fn model_cell_default_is_space() {
1352        let cell = ModelCell::default();
1353        assert_eq!(cell.text, " ");
1354        assert_eq!(cell.fg, PackedRgba::WHITE);
1355        assert_eq!(cell.bg, PackedRgba::TRANSPARENT);
1356        assert_eq!(cell.attrs, CellAttrs::NONE);
1357        assert_eq!(cell.link_id, 0);
1358    }
1359
1360    #[test]
1361    fn model_cell_with_char() {
1362        let cell = ModelCell::with_char('X');
1363        assert_eq!(cell.text, "X");
1364        assert_eq!(cell.fg, PackedRgba::WHITE);
1365        assert_eq!(cell.link_id, 0);
1366    }
1367
1368    #[test]
1369    fn model_cell_eq() {
1370        let a = ModelCell::default();
1371        let b = ModelCell::default();
1372        assert_eq!(a, b);
1373        let c = ModelCell::with_char('X');
1374        assert_ne!(a, c);
1375    }
1376
1377    #[test]
1378    fn model_cell_clone() {
1379        let a = ModelCell::with_char('Z');
1380        let b = a.clone();
1381        assert_eq!(b.text, "Z");
1382    }
1383
1384    // --- SgrState ---
1385
1386    #[test]
1387    fn sgr_state_default_fields() {
1388        let s = SgrState::default();
1389        assert_eq!(s.fg, PackedRgba::WHITE);
1390        assert_eq!(s.bg, PackedRgba::TRANSPARENT);
1391        assert!(s.flags.is_empty());
1392    }
1393
1394    #[test]
1395    fn sgr_state_reset() {
1396        let mut s = SgrState {
1397            fg: PackedRgba::rgb(255, 0, 0),
1398            bg: PackedRgba::rgb(0, 0, 255),
1399            flags: StyleFlags::BOLD | StyleFlags::ITALIC,
1400        };
1401        s.reset();
1402        assert_eq!(s.fg, PackedRgba::WHITE);
1403        assert_eq!(s.bg, PackedRgba::TRANSPARENT);
1404        assert!(s.flags.is_empty());
1405    }
1406
1407    // --- ModeFlags ---
1408
1409    #[test]
1410    fn mode_flags_new_defaults() {
1411        let m = ModeFlags::new();
1412        assert!(m.cursor_visible);
1413        assert!(!m.alt_screen);
1414        assert_eq!(m.sync_output_level, 0);
1415    }
1416
1417    #[test]
1418    fn mode_flags_default_vs_new() {
1419        // Default trait gives false for bools, 0 for u32.
1420        let d = ModeFlags::default();
1421        assert!(!d.cursor_visible);
1422        // new() gives cursor_visible=true.
1423        let n = ModeFlags::new();
1424        assert!(n.cursor_visible);
1425    }
1426
1427    // --- Construction edge cases ---
1428
1429    #[test]
1430    fn new_zero_dimensions_clamped() {
1431        let model = TerminalModel::new(0, 0);
1432        assert_eq!(model.width(), 1);
1433        assert_eq!(model.height(), 1);
1434        assert_eq!(model.cells().len(), 1);
1435    }
1436
1437    #[test]
1438    fn new_1x1() {
1439        let model = TerminalModel::new(1, 1);
1440        assert_eq!(model.width(), 1);
1441        assert_eq!(model.height(), 1);
1442        assert_eq!(model.cursor(), (0, 0));
1443    }
1444
1445    // --- Cell access ---
1446
1447    #[test]
1448    fn cell_out_of_bounds_returns_none() {
1449        let model = TerminalModel::new(5, 3);
1450        assert!(model.cell(5, 0).is_none());
1451        assert!(model.cell(0, 3).is_none());
1452        assert!(model.cell(100, 100).is_none());
1453    }
1454
1455    #[test]
1456    fn cell_in_bounds_returns_some() {
1457        let model = TerminalModel::new(5, 3);
1458        assert!(model.cell(0, 0).is_some());
1459        assert!(model.cell(4, 2).is_some());
1460    }
1461
1462    #[test]
1463    fn current_cell_at_cursor() {
1464        let mut model = TerminalModel::new(10, 5);
1465        model.process(b"AB");
1466        // Cursor at (2,0), current_cell should be the cell under it.
1467        let cc = model.current_cell().unwrap();
1468        assert_eq!(cc.text, " "); // Cursor is past "AB", on empty cell.
1469    }
1470
1471    #[test]
1472    fn row_out_of_bounds_returns_none() {
1473        let model = TerminalModel::new(5, 3);
1474        assert!(model.row(3).is_none());
1475        assert!(model.row(100).is_none());
1476    }
1477
1478    #[test]
1479    fn row_text_trims_trailing_spaces() {
1480        let mut model = TerminalModel::new(10, 1);
1481        model.process(b"Hi");
1482        assert_eq!(model.row_text(0), Some("Hi".to_string()));
1483    }
1484
1485    #[test]
1486    fn row_text_preserves_trailing_non_padding_whitespace() {
1487        let mut model = TerminalModel::new(10, 1);
1488        let text = "Hi\u{00A0}";
1489        model.process(text.as_bytes());
1490        assert_eq!(model.row_text(0).as_deref(), Some(text));
1491    }
1492
1493    #[test]
1494    fn link_url_invalid_id_returns_none() {
1495        let model = TerminalModel::new(5, 1);
1496        assert!(model.link_url(999).is_none());
1497    }
1498
1499    #[test]
1500    fn link_url_zero_is_empty() {
1501        let model = TerminalModel::new(5, 1);
1502        assert_eq!(model.link_url(0), Some(""));
1503    }
1504
1505    #[test]
1506    fn has_dangling_link_initially_false() {
1507        let model = TerminalModel::new(5, 1);
1508        assert!(!model.has_dangling_link());
1509    }
1510
1511    // --- CHA (cursor horizontal absolute) ---
1512
1513    #[test]
1514    fn cha_moves_to_column() {
1515        let mut model = TerminalModel::new(80, 24);
1516        model.process(b"\x1b[1;1H"); // (0,0)
1517        model.process(b"\x1b[20G"); // CHA col 20
1518        assert_eq!(model.cursor(), (19, 0));
1519    }
1520
1521    #[test]
1522    fn cha_clamps_to_width() {
1523        let mut model = TerminalModel::new(10, 1);
1524        model.process(b"\x1b[999G");
1525        assert_eq!(model.cursor().0, 9);
1526    }
1527
1528    // --- VPA (vertical position absolute) ---
1529
1530    #[test]
1531    fn vpa_moves_to_row() {
1532        let mut model = TerminalModel::new(80, 24);
1533        model.process(b"\x1b[10d"); // VPA row 10
1534        assert_eq!(model.cursor(), (0, 9));
1535    }
1536
1537    #[test]
1538    fn vpa_clamps_to_height() {
1539        let mut model = TerminalModel::new(10, 5);
1540        model.process(b"\x1b[999d");
1541        assert_eq!(model.cursor().1, 4);
1542    }
1543
1544    // --- Backspace ---
1545
1546    #[test]
1547    fn backspace_moves_cursor_back() {
1548        let mut model = TerminalModel::new(10, 1);
1549        model.process(b"ABC");
1550        assert_eq!(model.cursor(), (3, 0));
1551        model.process(b"\x08"); // BS
1552        assert_eq!(model.cursor(), (2, 0));
1553    }
1554
1555    #[test]
1556    fn backspace_at_column_zero_no_move() {
1557        let mut model = TerminalModel::new(10, 1);
1558        model.process(b"\x08");
1559        assert_eq!(model.cursor(), (0, 0));
1560    }
1561
1562    // --- Tab ---
1563
1564    #[test]
1565    fn tab_moves_to_next_tab_stop() {
1566        let mut model = TerminalModel::new(80, 1);
1567        model.process(b"\t");
1568        assert_eq!(model.cursor(), (8, 0));
1569        model.process(b"A\t");
1570        assert_eq!(model.cursor(), (16, 0));
1571    }
1572
1573    #[test]
1574    fn tab_clamps_at_right_edge() {
1575        let mut model = TerminalModel::new(10, 1);
1576        model.process(b"\t"); // -> 8
1577        model.process(b"\t"); // -> would be 16, but clamped to 9
1578        assert_eq!(model.cursor(), (9, 0));
1579    }
1580
1581    // --- Escape sequences ---
1582
1583    #[test]
1584    fn esc_7_8_do_not_panic() {
1585        let mut model = TerminalModel::new(10, 1);
1586        model.process(b"\x1b7"); // DECSC
1587        model.process(b"\x1b8"); // DECRC
1588        assert_eq!(model.cursor(), (0, 0));
1589    }
1590
1591    #[test]
1592    fn esc_equals_greater_ignored() {
1593        let mut model = TerminalModel::new(10, 1);
1594        model.process(b"\x1b="); // App keypad
1595        model.process(b"\x1b>"); // Normal keypad
1596        assert_eq!(model.cursor(), (0, 0));
1597    }
1598
1599    #[test]
1600    fn esc_esc_double_escape_handled() {
1601        let mut model = TerminalModel::new(10, 1);
1602        model.process(b"\x1b\x1b"); // Double ESC — stays in escape state
1603        // 'A' is consumed as unknown escape sequence, returning to ground.
1604        model.process(b"AB");
1605        // Only 'B' reaches ground as printable.
1606        assert_eq!(model.row_text(0).as_deref(), Some("B"));
1607    }
1608
1609    #[test]
1610    fn unknown_escape_returns_to_ground() {
1611        let mut model = TerminalModel::new(10, 1);
1612        model.process(b"\x1bQ"); // Unknown
1613        model.process(b"Hi");
1614        assert_eq!(model.row_text(0).as_deref(), Some("Hi"));
1615    }
1616
1617    // --- EL modes ---
1618
1619    #[test]
1620    fn el_mode_1_erases_from_start_to_cursor() {
1621        let mut model = TerminalModel::new(10, 1);
1622        model.process(b"ABCDEFGHIJ");
1623        model.process(b"\x1b[1;5H"); // (4, 0)
1624        model.process(b"\x1b[1K"); // Erase from start to cursor
1625        // Columns 0..=4 erased.
1626        let row = model.row_text(0).unwrap();
1627        assert!(row.starts_with("     ") || row.trim_start().starts_with("FGHIJ"));
1628    }
1629
1630    #[test]
1631    fn el_mode_2_erases_entire_line() {
1632        let mut model = TerminalModel::new(10, 1);
1633        model.process(b"ABCDEFGHIJ");
1634        model.process(b"\x1b[1;5H");
1635        model.process(b"\x1b[2K"); // Erase entire line
1636        assert_eq!(model.row_text(0), Some(String::new()));
1637    }
1638
1639    // --- ED modes ---
1640
1641    #[test]
1642    fn ed_mode_0_erases_from_cursor_to_end() {
1643        let mut model = TerminalModel::new(10, 3);
1644        model.process(b"Line1\nLine2\nLine3");
1645        model.process(b"\x1b[2;1H"); // Row 2, Col 1 (line index 1)
1646        model.process(b"\x1b[0J"); // Erase from cursor to end
1647        assert_eq!(model.row_text(0), Some("Line1".to_string()));
1648        assert_eq!(model.row_text(1), Some(String::new()));
1649        assert_eq!(model.row_text(2), Some(String::new()));
1650    }
1651
1652    #[test]
1653    fn ed_mode_1_erases_from_start_to_cursor() {
1654        let mut model = TerminalModel::new(10, 3);
1655        model.process(b"Line1\nLine2\nLine3");
1656        model.process(b"\x1b[2;3H"); // Row 2, Col 3 (0-indexed: y=1, x=2)
1657        model.process(b"\x1b[1J"); // Erase from start to cursor
1658        assert_eq!(model.row_text(0), Some(String::new()));
1659        // Row 1 erased up to and including cursor position (x=2).
1660        let row1 = model.row_text(1).unwrap();
1661        assert!(row1.starts_with("   ") || row1.len() <= 10);
1662    }
1663
1664    // --- SGR attribute flags ---
1665
1666    #[test]
1667    fn sgr_italic() {
1668        let mut model = TerminalModel::new(10, 1);
1669        model.process(b"\x1b[3mI\x1b[0m");
1670        assert!(model.cell(0, 0).unwrap().attrs.has_flag(StyleFlags::ITALIC));
1671    }
1672
1673    #[test]
1674    fn sgr_underline() {
1675        let mut model = TerminalModel::new(10, 1);
1676        model.process(b"\x1b[4mU\x1b[0m");
1677        assert!(
1678            model
1679                .cell(0, 0)
1680                .unwrap()
1681                .attrs
1682                .has_flag(StyleFlags::UNDERLINE)
1683        );
1684    }
1685
1686    #[test]
1687    fn sgr_dim() {
1688        let mut model = TerminalModel::new(10, 1);
1689        model.process(b"\x1b[2mD\x1b[0m");
1690        assert!(model.cell(0, 0).unwrap().attrs.has_flag(StyleFlags::DIM));
1691    }
1692
1693    #[test]
1694    fn sgr_strikethrough() {
1695        let mut model = TerminalModel::new(10, 1);
1696        model.process(b"\x1b[9mS\x1b[0m");
1697        assert!(
1698            model
1699                .cell(0, 0)
1700                .unwrap()
1701                .attrs
1702                .has_flag(StyleFlags::STRIKETHROUGH)
1703        );
1704    }
1705
1706    #[test]
1707    fn sgr_reverse() {
1708        let mut model = TerminalModel::new(10, 1);
1709        model.process(b"\x1b[7mR\x1b[0m");
1710        assert!(
1711            model
1712                .cell(0, 0)
1713                .unwrap()
1714                .attrs
1715                .has_flag(StyleFlags::REVERSE)
1716        );
1717    }
1718
1719    #[test]
1720    fn sgr_remove_bold() {
1721        let mut model = TerminalModel::new(10, 1);
1722        model.process(b"\x1b[1mB\x1b[22mX");
1723        assert!(model.cell(0, 0).unwrap().attrs.has_flag(StyleFlags::BOLD));
1724        assert!(!model.cell(1, 0).unwrap().attrs.has_flag(StyleFlags::BOLD));
1725    }
1726
1727    #[test]
1728    fn sgr_remove_italic() {
1729        let mut model = TerminalModel::new(10, 1);
1730        model.process(b"\x1b[3mI\x1b[23mX");
1731        assert!(!model.cell(1, 0).unwrap().attrs.has_flag(StyleFlags::ITALIC));
1732    }
1733
1734    // --- SGR colors ---
1735
1736    #[test]
1737    fn sgr_basic_background() {
1738        let mut model = TerminalModel::new(10, 1);
1739        model.process(b"\x1b[42mG"); // Green bg
1740        assert_eq!(model.cell(0, 0).unwrap().bg, PackedRgba::rgb(0, 128, 0));
1741    }
1742
1743    #[test]
1744    fn sgr_default_fg_39() {
1745        let mut model = TerminalModel::new(10, 1);
1746        model.process(b"\x1b[31m\x1b[39mX");
1747        assert_eq!(model.cell(0, 0).unwrap().fg, PackedRgba::WHITE);
1748    }
1749
1750    #[test]
1751    fn sgr_default_bg_49() {
1752        let mut model = TerminalModel::new(10, 1);
1753        model.process(b"\x1b[41m\x1b[49mX");
1754        assert_eq!(model.cell(0, 0).unwrap().bg, PackedRgba::TRANSPARENT);
1755    }
1756
1757    #[test]
1758    fn sgr_bright_fg() {
1759        let mut model = TerminalModel::new(10, 1);
1760        model.process(b"\x1b[91mX"); // Bright red fg
1761        assert_eq!(model.cell(0, 0).unwrap().fg, PackedRgba::rgb(255, 0, 0));
1762    }
1763
1764    #[test]
1765    fn sgr_bright_bg() {
1766        let mut model = TerminalModel::new(10, 1);
1767        model.process(b"\x1b[104mX"); // Bright blue bg
1768        assert_eq!(model.cell(0, 0).unwrap().bg, PackedRgba::rgb(0, 0, 255));
1769    }
1770
1771    #[test]
1772    fn sgr_256_grayscale() {
1773        let mut model = TerminalModel::new(10, 1);
1774        model.process(b"\x1b[38;5;232mX"); // Grayscale idx 232 → gray=8
1775        assert_eq!(model.cell(0, 0).unwrap().fg, PackedRgba::rgb(8, 8, 8));
1776    }
1777
1778    #[test]
1779    fn sgr_256_basic_range() {
1780        let mut model = TerminalModel::new(10, 1);
1781        model.process(b"\x1b[38;5;1mX"); // Index 1 = basic red
1782        assert_eq!(model.cell(0, 0).unwrap().fg, PackedRgba::rgb(128, 0, 0));
1783    }
1784
1785    #[test]
1786    fn sgr_256_bright_range() {
1787        let mut model = TerminalModel::new(10, 1);
1788        model.process(b"\x1b[38;5;9mX"); // Index 9 = bright red
1789        assert_eq!(model.cell(0, 0).unwrap().fg, PackedRgba::rgb(255, 0, 0));
1790    }
1791
1792    #[test]
1793    fn sgr_empty_params_resets() {
1794        let mut model = TerminalModel::new(10, 1);
1795        model.process(b"\x1b[1m\x1b[mX"); // SGR with no params = reset
1796        assert!(!model.cell(0, 0).unwrap().attrs.has_flag(StyleFlags::BOLD));
1797    }
1798
1799    // --- Sync output ---
1800
1801    #[test]
1802    fn sync_output_extra_end_saturates() {
1803        let mut model = TerminalModel::new(10, 1);
1804        model.process(b"\x1b[?2026l"); // End without begin
1805        assert_eq!(model.modes().sync_output_level, 0);
1806        assert!(model.sync_output_balanced());
1807    }
1808
1809    #[test]
1810    fn sync_output_nested() {
1811        let mut model = TerminalModel::new(10, 1);
1812        model.process(b"\x1b[?2026h");
1813        model.process(b"\x1b[?2026h");
1814        assert_eq!(model.modes().sync_output_level, 2);
1815        model.process(b"\x1b[?2026l");
1816        assert_eq!(model.modes().sync_output_level, 1);
1817        assert!(!model.sync_output_balanced());
1818    }
1819
1820    // --- diff_grid ---
1821
1822    #[test]
1823    fn diff_grid_identical_returns_none() {
1824        let model = TerminalModel::new(3, 2);
1825        let expected = vec![ModelCell::default(); 6];
1826        assert!(model.diff_grid(&expected).is_none());
1827    }
1828
1829    #[test]
1830    fn diff_grid_different_returns_some() {
1831        let mut model = TerminalModel::new(3, 1);
1832        model.process(b"ABC");
1833        let expected = vec![ModelCell::default(); 3];
1834        let diff = model.diff_grid(&expected);
1835        assert!(diff.is_some());
1836        let diff_str = diff.unwrap();
1837        assert!(diff_str.contains("Grid differences"));
1838    }
1839
1840    #[test]
1841    fn diff_grid_size_mismatch() {
1842        let model = TerminalModel::new(3, 2);
1843        let expected = vec![ModelCell::default(); 5]; // Wrong size
1844        let diff = model.diff_grid(&expected);
1845        assert!(diff.is_some());
1846        assert!(diff.unwrap().contains("Grid size mismatch"));
1847    }
1848
1849    // --- dump_sequences ---
1850
1851    #[test]
1852    fn dump_sequences_osc() {
1853        let bytes = b"\x1b]8;;https://example.com\x07text\x1b]8;;\x07";
1854        let dump = TerminalModel::dump_sequences(bytes);
1855        assert!(dump.contains("\\e]8;;https://example.com\\a"));
1856    }
1857
1858    #[test]
1859    fn dump_sequences_osc_st() {
1860        let bytes = b"\x1b]0;title\x1b\\";
1861        let dump = TerminalModel::dump_sequences(bytes);
1862        assert!(dump.contains("\\e]"));
1863        assert!(dump.contains("\\e\\\\"));
1864    }
1865
1866    #[test]
1867    fn dump_sequences_c0_controls() {
1868        let bytes = b"\x08\x09\x0A";
1869        let dump = TerminalModel::dump_sequences(bytes);
1870        assert!(dump.contains("\\x08"));
1871        assert!(dump.contains("\\x09"));
1872        assert!(dump.contains("\\x0a"));
1873    }
1874
1875    #[test]
1876    fn dump_sequences_trailing_esc() {
1877        let bytes = b"text\x1b";
1878        let dump = TerminalModel::dump_sequences(bytes);
1879        assert!(dump.contains("text"));
1880        assert!(dump.contains("\\e"));
1881    }
1882
1883    #[test]
1884    fn dump_sequences_unknown_escape() {
1885        let bytes = b"\x1bQ";
1886        let dump = TerminalModel::dump_sequences(bytes);
1887        assert!(dump.contains("\\eQ"));
1888    }
1889
1890    // --- Erase uses current bg color ---
1891
1892    #[test]
1893    fn erase_line_uses_current_bg() {
1894        let mut model = TerminalModel::new(5, 1);
1895        model.process(b"Hello");
1896        model.process(b"\x1b[1;1H"); // Move to (0,0)
1897        model.process(b"\x1b[41m"); // Red bg
1898        model.process(b"\x1b[K"); // Erase to end
1899        let cell = model.cell(0, 0).unwrap();
1900        assert_eq!(cell.text, " ");
1901        assert_eq!(cell.bg, PackedRgba::rgb(128, 0, 0));
1902    }
1903
1904    // --- Multiple hyperlinks ---
1905
1906    #[test]
1907    fn multiple_hyperlinks_get_different_ids() {
1908        let mut model = TerminalModel::new(30, 1);
1909        model.process(b"\x1b]8;;https://a.com\x07A\x1b]8;;\x07");
1910        model.process(b"\x1b]8;;https://b.com\x07B\x1b]8;;\x07");
1911        let id_a = model.cell(0, 0).unwrap().link_id;
1912        let id_b = model.cell(1, 0).unwrap().link_id;
1913        assert_ne!(id_a, id_b);
1914        assert_eq!(model.link_url(id_a), Some("https://a.com"));
1915        assert_eq!(model.link_url(id_b), Some("https://b.com"));
1916    }
1917
1918    // --- OSC with ST terminator ---
1919
1920    #[test]
1921    fn osc8_with_st_terminator() {
1922        let mut model = TerminalModel::new(20, 1);
1923        model.process(b"\x1b]8;;https://st.com\x1b\\Link\x1b]8;;\x1b\\");
1924        let cell = model.cell(0, 0).unwrap();
1925        assert!(cell.link_id > 0);
1926        assert_eq!(model.link_url(cell.link_id), Some("https://st.com"));
1927        assert!(!model.has_dangling_link());
1928    }
1929
1930    // --- TerminalModel Debug ---
1931
1932    #[test]
1933    fn terminal_model_debug() {
1934        let model = TerminalModel::new(5, 3);
1935        let dbg = format!("{model:?}");
1936        assert!(dbg.contains("TerminalModel"));
1937    }
1938
1939    // --- Wide character ---
1940
1941    #[test]
1942    fn wide_char_occupies_two_cells() {
1943        let mut model = TerminalModel::new(10, 1);
1944        // CJK character takes 2 columns
1945        model.process("中".as_bytes());
1946        assert_eq!(model.cell(0, 0).unwrap().text, "中");
1947        // Next cell should be cleared (placeholder)
1948        assert_eq!(model.cell(1, 0).unwrap().text, "");
1949        assert_eq!(model.cursor(), (2, 0));
1950    }
1951
1952    #[test]
1953    fn combining_mark_joins_the_character_it_follows() {
1954        // After a wide character the cell left of the cursor is its
1955        // placeholder, and the mark landed there.
1956        let mut model = TerminalModel::new(10, 2);
1957        model.process("中\u{301}x".as_bytes());
1958        assert_eq!(model.cell(0, 0).unwrap().text, "中\u{301}");
1959        assert_eq!(model.cell(1, 0).unwrap().text, "");
1960        assert_eq!(model.cell(2, 0).unwrap().text, "x");
1961
1962        // After the last column the cursor has wrapped, and the mark landed
1963        // on the next line's first cell.
1964        let mut model = TerminalModel::new(3, 2);
1965        model.process("\x1b[1;3He\u{301}".as_bytes());
1966        assert_eq!(model.cell(2, 0).unwrap().text, "e\u{301}");
1967        assert_eq!(model.cell(0, 1).unwrap().text, " ");
1968
1969        // A mark after a cursor move still takes the old rule.
1970        let mut model = TerminalModel::new(5, 1);
1971        model.process("ab\x1b[1;2H\u{301}".as_bytes());
1972        assert_eq!(model.cell(0, 0).unwrap().text, "a\u{301}");
1973    }
1974
1975    // --- Cursor CUP with f final byte ---
1976
1977    #[test]
1978    fn cup_with_f_final_byte() {
1979        let mut model = TerminalModel::new(80, 24);
1980        model.process(b"\x1b[3;7f"); // Same as H
1981        assert_eq!(model.cursor(), (6, 2));
1982    }
1983
1984    // --- CSI unknown final byte ---
1985
1986    #[test]
1987    fn csi_unknown_final_byte_ignored() {
1988        let mut model = TerminalModel::new(10, 1);
1989        model.process(b"A");
1990        model.process(b"\x1b[99X"); // Unknown CSI
1991        model.process(b"B");
1992        assert_eq!(model.row_text(0).as_deref(), Some("AB"));
1993    }
1994
1995    // --- CSI save/restore cursor (s/u) ---
1996
1997    #[test]
1998    fn csi_save_restore_cursor_no_panic() {
1999        let mut model = TerminalModel::new(10, 5);
2000        model.process(b"\x1b[5;5H");
2001        model.process(b"\x1b[s"); // Save
2002        model.process(b"\x1b[1;1H");
2003        model.process(b"\x1b[u"); // Restore (not fully implemented, but shouldn't panic)
2004        // Just verify no crash.
2005        let (x, y) = model.cursor();
2006        assert!(x < model.width());
2007        assert!(y < model.height());
2008    }
2009
2010    // --- BEL in ground state ---
2011
2012    #[test]
2013    fn bel_in_ground_is_ignored() {
2014        let mut model = TerminalModel::new(10, 1);
2015        model.process(b"\x07Hi");
2016        assert_eq!(model.row_text(0).as_deref(), Some("Hi"));
2017    }
2018
2019    // --- CUP clamps out-of-range values ---
2020
2021    #[test]
2022    fn cup_clamps_large_row_col() {
2023        let mut model = TerminalModel::new(10, 5);
2024        model.process(b"\x1b[999;999H");
2025        assert_eq!(model.cursor(), (9, 4));
2026    }
2027
2028    // --- Relative moves at boundaries ---
2029
2030    #[test]
2031    fn cuu_at_top_stays() {
2032        let mut model = TerminalModel::new(10, 5);
2033        model.process(b"\x1b[1;1H");
2034        model.process(b"\x1b[50A"); // Up 50 from top
2035        assert_eq!(model.cursor(), (0, 0));
2036    }
2037
2038    #[test]
2039    fn cud_at_bottom_stays() {
2040        let mut model = TerminalModel::new(10, 5);
2041        model.process(b"\x1b[5;1H");
2042        model.process(b"\x1b[50B"); // Down 50 from bottom
2043        assert_eq!(model.cursor(), (0, 4));
2044    }
2045
2046    #[test]
2047    fn cuf_at_right_stays() {
2048        let mut model = TerminalModel::new(10, 1);
2049        model.process(b"\x1b[1;10H");
2050        model.process(b"\x1b[50C"); // Forward 50 from right edge
2051        assert_eq!(model.cursor().0, 9);
2052    }
2053
2054    #[test]
2055    fn cub_at_left_stays() {
2056        let mut model = TerminalModel::new(10, 1);
2057        model.process(b"\x1b[50D"); // Back 50 from column 0
2058        assert_eq!(model.cursor().0, 0);
2059    }
2060
2061    // --- CSI with intermediate bytes ---
2062
2063    #[test]
2064    fn csi_with_intermediate_no_crash() {
2065        let mut model = TerminalModel::new(10, 1);
2066        // Space (0x20) in CSI entry falls to default → Ground.
2067        // Then 'q' is printed as regular char.
2068        model.process(b"\x1b[ q");
2069        model.process(b"OK");
2070        // 'q' + "OK" are all printed.
2071        assert_eq!(model.row_text(0).as_deref(), Some("qOK"));
2072    }
2073
2074    // --- Reset preserves dimensions ---
2075
2076    #[test]
2077    fn reset_preserves_dimensions() {
2078        let mut model = TerminalModel::new(40, 20);
2079        model.process(b"SomeText");
2080        model.reset();
2081        assert_eq!(model.width(), 40);
2082        assert_eq!(model.height(), 20);
2083        assert_eq!(model.cursor(), (0, 0));
2084    }
2085
2086    // --- LF at bottom does not crash ---
2087
2088    #[test]
2089    fn lf_at_bottom_row_stays() {
2090        let mut model = TerminalModel::new(10, 3);
2091        model.process(b"\x1b[3;1H"); // Row 3 (bottom)
2092        model.process(b"\n"); // LF at bottom
2093        assert_eq!(model.cursor().1, 2); // Stays at bottom
2094    }
2095}
2096
2097/// Property tests for terminal model correctness.
2098#[cfg(test)]
2099mod proptests {
2100    use super::*;
2101    use proptest::prelude::*;
2102
2103    /// Generate a valid CSI sequence for cursor positioning.
2104    fn cup_sequence(row: u8, col: u8) -> Vec<u8> {
2105        format!("\x1b[{};{}H", row.max(1), col.max(1)).into_bytes()
2106    }
2107
2108    /// Generate a valid SGR sequence.
2109    fn sgr_sequence(codes: &[u8]) -> Vec<u8> {
2110        let codes_str: Vec<String> = codes.iter().map(|c| c.to_string()).collect();
2111        format!("\x1b[{}m", codes_str.join(";")).into_bytes()
2112    }
2113
2114    proptest! {
2115        /// Any sequence of printable ASCII doesn't crash.
2116        #[test]
2117        fn printable_ascii_no_crash(s in "[A-Za-z0-9 ]{0,100}") {
2118            let mut model = TerminalModel::new(80, 24);
2119            model.process(s.as_bytes());
2120            // Model should be in a valid state
2121            let (x, y) = model.cursor();
2122            prop_assert!(x < model.width());
2123            prop_assert!(y < model.height());
2124        }
2125
2126        /// CUP sequences always leave cursor in bounds.
2127        #[test]
2128        fn cup_cursor_in_bounds(row in 0u8..100, col in 0u8..200) {
2129            let mut model = TerminalModel::new(80, 24);
2130            let seq = cup_sequence(row, col);
2131            model.process(&seq);
2132
2133            let (x, y) = model.cursor();
2134            prop_assert!(x < model.width(), "cursor_x {} >= width {}", x, model.width());
2135            prop_assert!(y < model.height(), "cursor_y {} >= height {}", y, model.height());
2136        }
2137
2138        /// Relative cursor moves never go out of bounds.
2139        #[test]
2140        fn relative_moves_in_bounds(
2141            start_row in 1u8..24,
2142            start_col in 1u8..80,
2143            up in 0u8..50,
2144            down in 0u8..50,
2145            left in 0u8..100,
2146            right in 0u8..100,
2147        ) {
2148            let mut model = TerminalModel::new(80, 24);
2149
2150            // Position cursor
2151            model.process(&cup_sequence(start_row, start_col));
2152
2153            // Apply relative moves
2154            model.process(format!("\x1b[{}A", up).as_bytes());
2155            model.process(format!("\x1b[{}B", down).as_bytes());
2156            model.process(format!("\x1b[{}D", left).as_bytes());
2157            model.process(format!("\x1b[{}C", right).as_bytes());
2158
2159            let (x, y) = model.cursor();
2160            prop_assert!(x < model.width());
2161            prop_assert!(y < model.height());
2162        }
2163
2164        /// SGR reset always clears all flags.
2165        #[test]
2166        fn sgr_reset_clears_flags(attrs in proptest::collection::vec(1u8..9, 0..5)) {
2167            let mut model = TerminalModel::new(80, 24);
2168
2169            // Set some attributes
2170            if !attrs.is_empty() {
2171                model.process(&sgr_sequence(&attrs));
2172            }
2173
2174            // Reset
2175            model.process(b"\x1b[0m");
2176
2177            prop_assert!(model.sgr_state().flags.is_empty());
2178        }
2179
2180        /// Hyperlinks always balance (no dangling after close).
2181        #[test]
2182        fn hyperlinks_balance(text in "[a-z]{1,20}") {
2183            let mut model = TerminalModel::new(80, 24);
2184
2185            // Start link
2186            model.process(b"\x1b]8;;https://example.com\x07");
2187            prop_assert!(model.has_dangling_link());
2188
2189            // Write some text
2190            model.process(text.as_bytes());
2191
2192            // End link
2193            model.process(b"\x1b]8;;\x07");
2194            prop_assert!(!model.has_dangling_link());
2195        }
2196
2197        /// Sync output always balances with nested begin/end.
2198        #[test]
2199        fn sync_output_balances(nesting in 1usize..5) {
2200            let mut model = TerminalModel::new(80, 24);
2201
2202            // Begin sync N times
2203            for _ in 0..nesting {
2204                model.process(b"\x1b[?2026h");
2205            }
2206            prop_assert_eq!(model.modes().sync_output_level, nesting as u32);
2207
2208            // End sync N times
2209            for _ in 0..nesting {
2210                model.process(b"\x1b[?2026l");
2211            }
2212            prop_assert!(model.sync_output_balanced());
2213        }
2214
2215        /// Erase operations don't crash and leave cursor in bounds.
2216        #[test]
2217        fn erase_operations_safe(
2218            row in 1u8..24,
2219            col in 1u8..80,
2220            ed_mode in 0u8..4,
2221            el_mode in 0u8..3,
2222        ) {
2223            let mut model = TerminalModel::new(80, 24);
2224
2225            // Position cursor
2226            model.process(&cup_sequence(row, col));
2227
2228            // Erase display
2229            model.process(format!("\x1b[{}J", ed_mode).as_bytes());
2230
2231            // Position again and erase line
2232            model.process(&cup_sequence(row, col));
2233            model.process(format!("\x1b[{}K", el_mode).as_bytes());
2234
2235            let (x, y) = model.cursor();
2236            prop_assert!(x < model.width());
2237            prop_assert!(y < model.height());
2238        }
2239
2240        /// Random bytes never cause a panic (fuzz-like test).
2241        #[test]
2242        fn random_bytes_no_panic(bytes in proptest::collection::vec(any::<u8>(), 0..200)) {
2243            let mut model = TerminalModel::new(80, 24);
2244            model.process(&bytes);
2245
2246            // Just check it didn't panic and cursor is valid
2247            let (x, y) = model.cursor();
2248            prop_assert!(x < model.width());
2249            prop_assert!(y < model.height());
2250        }
2251    }
2252}