Skip to main content

hyprstream_core/tui/
vte_parser.rs

1//! VTE parser for ANSI pane ingestion.
2//!
3//! Implements `vte::Perform` to translate ANSI escape sequences into
4//! cell writes, cursor movement, scroll region operations, and screen
5//! mode switches on a `TuiPane`.
6
7use ratatui::buffer::Cell;
8use ratatui::style::{Color, Modifier, Style};
9
10use super::state::{CursorState, ScrollOp, TuiPane};
11
12// ============================================================================
13// SGR state
14// ============================================================================
15
16/// Tracked SGR (Select Graphic Rendition) state.
17#[derive(Debug, Clone)]
18struct SgrState {
19    fg: Color,
20    bg: Color,
21    modifiers: Modifier,
22}
23
24impl Default for SgrState {
25    fn default() -> Self {
26        Self {
27            fg: Color::Reset,
28            bg: Color::Reset,
29            modifiers: Modifier::empty(),
30        }
31    }
32}
33
34// ============================================================================
35// PanePerformer
36// ============================================================================
37
38/// VTE performer that writes into a `TuiPane`.
39///
40/// Handles: print, execute (CR/LF/BS/HT), CSI dispatch (SGR, CUP, ED, EL,
41/// SU, SD, DECSTBM, cursor movement, DECTCEM, DECSET 1049), OSC (title),
42/// ESC (RIS, DECSC, DECRC).
43pub struct PanePerformer<'a> {
44    pane: &'a mut TuiPane,
45    sgr: SgrState,
46    /// Saved cursor position (DECSC/DECRC).
47    saved_cursor: CursorState,
48    /// Scroll region top (0-indexed, inclusive).
49    scroll_top: u16,
50    /// Scroll region bottom (0-indexed, inclusive).
51    scroll_bottom: u16,
52    /// DEC auto-wrap pending: set when a character is written at the last column.
53    /// The actual wrap (and potential scroll) fires on the next printed character,
54    /// not immediately — this prevents spurious scrolls when a ratatui draw
55    /// writes the very last cell of the screen.
56    pending_wrap: bool,
57}
58
59impl<'a> PanePerformer<'a> {
60    /// Create a new performer for the given pane.
61    pub fn new(pane: &'a mut TuiPane) -> Self {
62        let (_, rows) = pane.size();
63        Self {
64            pane,
65            sgr: SgrState::default(),
66            saved_cursor: CursorState::default(),
67            scroll_top: 0,
68            scroll_bottom: rows.saturating_sub(1),
69            pending_wrap: false,
70        }
71    }
72
73    /// Feed raw bytes through the VTE parser into this pane.
74    pub fn feed(&mut self, data: &[u8]) {
75        let mut parser = vte::Parser::new();
76        for &byte in data {
77            parser.advance(self, byte);
78        }
79    }
80
81    fn cols(&self) -> u16 {
82        self.pane.active_buffer().buffer.area().width
83    }
84
85    fn rows(&self) -> u16 {
86        self.pane.active_buffer().buffer.area().height
87    }
88
89    fn set_cell(&mut self, x: u16, y: u16, symbol: &str) {
90        let buf = self.pane.active_buffer_mut();
91        let area = buf.buffer.area();
92        if x < area.width && y < area.height {
93            buf.buffer[(x, y)].set_symbol(symbol);
94            buf.buffer[(x, y)].set_style(
95                Style::default()
96                    .fg(self.sgr.fg)
97                    .bg(self.sgr.bg)
98                    .add_modifier(self.sgr.modifiers),
99            );
100            buf.mark_dirty(y);
101        }
102    }
103
104    /// Scroll the region up by `n` lines.
105    fn scroll_up(&mut self, n: u16) {
106        let cols = self.cols();
107        let top = self.scroll_top;
108        let bottom = self.scroll_bottom;
109        let blank = self.blank_cell();
110
111        if n == 0 || top >= bottom {
112            return;
113        }
114
115        // Save top lines to scrollback before overwriting
116        if !self.pane.using_alternate && top == 0 {
117            for row in 0..n.min(bottom - top + 1) {
118                let mut line = Vec::with_capacity(cols as usize);
119                let buf = self.pane.active_buffer();
120                for x in 0..cols {
121                    line.push(buf.buffer[(x, row)].clone());
122                }
123                self.pane.push_scrollback(line);
124            }
125        }
126
127        // Move lines up within the scroll region
128        let buf = self.pane.active_buffer_mut();
129        for y in top..=bottom {
130            let src_y = y + n;
131            if src_y <= bottom {
132                for x in 0..cols {
133                    let cell = buf.buffer[(x, src_y)].clone();
134                    buf.buffer[(x, y)] = cell;
135                }
136            } else {
137                for x in 0..cols {
138                    buf.buffer[(x, y)] = blank.clone();
139                }
140            }
141            buf.mark_dirty(y);
142        }
143
144        buf.record_scroll(ScrollOp {
145            top,
146            bottom,
147            amount: n as i16,
148        });
149    }
150
151    /// Scroll the region down by `n` lines.
152    fn scroll_down(&mut self, n: u16) {
153        let cols = self.cols();
154        let top = self.scroll_top;
155        let bottom = self.scroll_bottom;
156        let blank = self.blank_cell();
157
158        if n == 0 || top >= bottom {
159            return;
160        }
161
162        let buf = self.pane.active_buffer_mut();
163
164        // Move lines down within the scroll region (iterate in reverse)
165        for y in (top..=bottom).rev() {
166            if y >= top + n {
167                let src_y = y - n;
168                for x in 0..cols {
169                    let cell = buf.buffer[(x, src_y)].clone();
170                    buf.buffer[(x, y)] = cell;
171                }
172            } else {
173                // Clear new lines at top
174                for x in 0..cols {
175                    buf.buffer[(x, y)] = blank.clone();
176                }
177            }
178            buf.mark_dirty(y);
179        }
180
181        buf.record_scroll(ScrollOp {
182            top,
183            bottom,
184            amount: -(n as i16),
185        });
186    }
187
188    /// Return a blank Cell using the current SGR background colour.
189    ///
190    /// Per the VT specification, erase operations (ED, EL, ECH, ICH clear,
191    /// DCH clear, and scroll-cleared rows) fill cells with a space character
192    /// styled with the current background colour rather than the terminal
193    /// default.  Foreground and modifiers are reset to default.
194    fn blank_cell(&self) -> Cell {
195        let mut cell = Cell::default();
196        cell.set_style(Style::default().fg(Color::Reset).bg(self.sgr.bg));
197        cell
198    }
199
200    /// Erase cells in a region, filling them with the current background color.
201    fn erase_region(&mut self, x1: u16, y1: u16, x2: u16, y2: u16) {
202        let blank = self.blank_cell();
203        let buf = self.pane.active_buffer_mut();
204        let width = buf.buffer.area().width;
205        let height = buf.buffer.area().height;
206        for y in y1..=y2.min(height.saturating_sub(1)) {
207            let start_x = if y == y1 { x1 } else { 0 };
208            let end_x = if y == y2 { x2 } else { width.saturating_sub(1) };
209            for x in start_x..=end_x.min(width.saturating_sub(1)) {
210                buf.buffer[(x, y)] = blank.clone();
211            }
212            buf.mark_dirty(y);
213        }
214    }
215
216    /// Parse SGR parameters and update state.
217    fn process_sgr(&mut self, params: &vte::Params) {
218        let mut iter = params.iter();
219
220        while let Some(param) = iter.next() {
221            let code = param[0];
222
223            match code {
224                0 => self.sgr = SgrState::default(),
225                1 => self.sgr.modifiers |= Modifier::BOLD,
226                2 => self.sgr.modifiers |= Modifier::DIM,
227                3 => self.sgr.modifiers |= Modifier::ITALIC,
228                4 => self.sgr.modifiers |= Modifier::UNDERLINED,
229                5 => self.sgr.modifiers |= Modifier::SLOW_BLINK,
230                7 => self.sgr.modifiers |= Modifier::REVERSED,
231                8 => self.sgr.modifiers |= Modifier::HIDDEN,
232                9 => self.sgr.modifiers |= Modifier::CROSSED_OUT,
233                22 => self.sgr.modifiers -= Modifier::BOLD | Modifier::DIM,
234                23 => self.sgr.modifiers -= Modifier::ITALIC,
235                24 => self.sgr.modifiers -= Modifier::UNDERLINED,
236                25 => self.sgr.modifiers -= Modifier::SLOW_BLINK,
237                27 => self.sgr.modifiers -= Modifier::REVERSED,
238                28 => self.sgr.modifiers -= Modifier::HIDDEN,
239                29 => self.sgr.modifiers -= Modifier::CROSSED_OUT,
240                // Foreground colors
241                30 => self.sgr.fg = Color::Black,
242                31 => self.sgr.fg = Color::Red,
243                32 => self.sgr.fg = Color::Green,
244                33 => self.sgr.fg = Color::Yellow,
245                34 => self.sgr.fg = Color::Blue,
246                35 => self.sgr.fg = Color::Magenta,
247                36 => self.sgr.fg = Color::Cyan,
248                37 => self.sgr.fg = Color::Gray,
249                38 => {
250                    self.sgr.fg = self.parse_extended_color(&mut iter);
251                }
252                39 => self.sgr.fg = Color::Reset,
253                // Background colors
254                40 => self.sgr.bg = Color::Black,
255                41 => self.sgr.bg = Color::Red,
256                42 => self.sgr.bg = Color::Green,
257                43 => self.sgr.bg = Color::Yellow,
258                44 => self.sgr.bg = Color::Blue,
259                45 => self.sgr.bg = Color::Magenta,
260                46 => self.sgr.bg = Color::Cyan,
261                47 => self.sgr.bg = Color::Gray,
262                48 => {
263                    self.sgr.bg = self.parse_extended_color(&mut iter);
264                }
265                49 => self.sgr.bg = Color::Reset,
266                // Bright foreground
267                90 => self.sgr.fg = Color::DarkGray,
268                91 => self.sgr.fg = Color::LightRed,
269                92 => self.sgr.fg = Color::LightGreen,
270                93 => self.sgr.fg = Color::LightYellow,
271                94 => self.sgr.fg = Color::LightBlue,
272                95 => self.sgr.fg = Color::LightMagenta,
273                96 => self.sgr.fg = Color::LightCyan,
274                97 => self.sgr.fg = Color::White,
275                // Bright background
276                100 => self.sgr.bg = Color::DarkGray,
277                101 => self.sgr.bg = Color::LightRed,
278                102 => self.sgr.bg = Color::LightGreen,
279                103 => self.sgr.bg = Color::LightYellow,
280                104 => self.sgr.bg = Color::LightBlue,
281                105 => self.sgr.bg = Color::LightMagenta,
282                106 => self.sgr.bg = Color::LightCyan,
283                107 => self.sgr.bg = Color::White,
284                _ => {} // Ignore unknown
285            }
286        }
287    }
288
289    /// Parse extended color (256-color or RGB) from SGR params.
290    fn parse_extended_color<'b>(&self, iter: &mut impl Iterator<Item = &'b [u16]>) -> Color {
291        match iter.next().map(|p| p[0]) {
292            Some(5) => {
293                // 256-color: ESC[38;5;Nm
294                if let Some(idx) = iter.next().map(|p| p[0] as u8) {
295                    Color::Indexed(idx)
296                } else {
297                    Color::Reset
298                }
299            }
300            Some(2) => {
301                // RGB: ESC[38;2;R;G;Bm
302                let r = iter.next().map(|p| p[0] as u8).unwrap_or(0);
303                let g = iter.next().map(|p| p[0] as u8).unwrap_or(0);
304                let b = iter.next().map(|p| p[0] as u8).unwrap_or(0);
305                Color::Rgb(r, g, b)
306            }
307            _ => Color::Reset,
308        }
309    }
310}
311
312impl<'a> vte::Perform for PanePerformer<'a> {
313    fn print(&mut self, c: char) {
314        // If a wrap was pending from the previous character at EOL, do it now.
315        if self.pending_wrap {
316            self.pending_wrap = false;
317            self.pane.cursor.x = 0;
318            self.pane.cursor.y += 1;
319            if self.pane.cursor.y > self.scroll_bottom {
320                self.pane.cursor.y = self.scroll_bottom;
321                self.scroll_up(1);
322            }
323        }
324
325        let x = self.pane.cursor.x;
326        let y = self.pane.cursor.y;
327        let cols = self.cols();
328
329        let mut buf = [0u8; 4];
330        let s = c.encode_utf8(&mut buf);
331        self.set_cell(x, y, s);
332
333        // Advance cursor (wide char detection).
334        let width = if c.is_ascii() {
335            1
336        } else {
337            let cp = c as u32;
338            if (0x1100..=0x115F).contains(&cp)
339                || (0x2E80..=0x303E).contains(&cp)
340                || (0x3040..=0x9FFF).contains(&cp)
341                || (0xAC00..=0xD7AF).contains(&cp)
342                || (0xF900..=0xFAFF).contains(&cp)
343                || (0x20000..=0x2FA1F).contains(&cp)
344            {
345                2
346            } else {
347                1
348            }
349        };
350
351        let new_x = x + width;
352        if new_x >= cols {
353            // Defer the wrap: real wrap fires on the NEXT printed character.
354            // This prevents a spurious scroll when the last cell of the screen
355            // is written (e.g. by a ratatui full-redraw).
356            self.pending_wrap = true;
357            self.pane.cursor.x = cols - 1;
358        } else {
359            self.pane.cursor.x = new_x;
360        }
361    }
362
363    fn execute(&mut self, byte: u8) {
364        match byte {
365            // BS (backspace)
366            0x08 => {
367                self.pending_wrap = false;
368                self.pane.cursor.x = self.pane.cursor.x.saturating_sub(1);
369            }
370            // HT (horizontal tab)
371            0x09 => {
372                self.pending_wrap = false;
373                let next_tab = ((self.pane.cursor.x / 8) + 1) * 8;
374                self.pane.cursor.x = next_tab.min(self.cols().saturating_sub(1));
375            }
376            // LF (line feed) / VT / FF
377            0x0A..=0x0C => {
378                self.pending_wrap = false;
379                self.pane.cursor.y += 1;
380                if self.pane.cursor.y > self.scroll_bottom {
381                    self.pane.cursor.y = self.scroll_bottom;
382                    self.scroll_up(1);
383                }
384            }
385            // CR (carriage return)
386            0x0D => {
387                self.pending_wrap = false;
388                self.pane.cursor.x = 0;
389            }
390            _ => {}
391        }
392    }
393
394    fn csi_dispatch(
395        &mut self,
396        params: &vte::Params,
397        _intermediates: &[u8],
398        _ignore: bool,
399        action: char,
400    ) {
401        // Any cursor-movement or screen-operation sequence cancels a pending wrap.
402        self.pending_wrap = false;
403
404        let p: Vec<u16> = params.iter().map(|s| s[0]).collect();
405        let p0 = p.first().copied().unwrap_or(0);
406        let p1 = p.get(1).copied().unwrap_or(0);
407
408        match action {
409            // CUP - Cursor Position
410            'H' | 'f' => {
411                let row = if p0 == 0 { 1 } else { p0 };
412                let col = if p1 == 0 { 1 } else { p1 };
413                self.pane.cursor.y = (row - 1).min(self.rows().saturating_sub(1));
414                self.pane.cursor.x = (col - 1).min(self.cols().saturating_sub(1));
415            }
416
417            // CUU - Cursor Up
418            'A' => {
419                let n = if p0 == 0 { 1 } else { p0 };
420                self.pane.cursor.y = self.pane.cursor.y.saturating_sub(n);
421            }
422
423            // CUD - Cursor Down
424            'B' => {
425                let n = if p0 == 0 { 1 } else { p0 };
426                self.pane.cursor.y = (self.pane.cursor.y + n).min(self.rows().saturating_sub(1));
427            }
428
429            // CUF - Cursor Forward
430            'C' => {
431                let n = if p0 == 0 { 1 } else { p0 };
432                self.pane.cursor.x = (self.pane.cursor.x + n).min(self.cols().saturating_sub(1));
433            }
434
435            // CUB - Cursor Backward
436            'D' => {
437                let n = if p0 == 0 { 1 } else { p0 };
438                self.pane.cursor.x = self.pane.cursor.x.saturating_sub(n);
439            }
440
441            // CNL - Cursor Next Line
442            'E' => {
443                let n = if p0 == 0 { 1 } else { p0 };
444                self.pane.cursor.x = 0;
445                self.pane.cursor.y = (self.pane.cursor.y + n).min(self.rows().saturating_sub(1));
446            }
447
448            // CPL - Cursor Previous Line
449            'F' => {
450                let n = if p0 == 0 { 1 } else { p0 };
451                self.pane.cursor.x = 0;
452                self.pane.cursor.y = self.pane.cursor.y.saturating_sub(n);
453            }
454
455            // CHA - Cursor Horizontal Absolute
456            'G' => {
457                let col = if p0 == 0 { 1 } else { p0 };
458                self.pane.cursor.x = (col - 1).min(self.cols().saturating_sub(1));
459            }
460
461            // ED - Erase in Display
462            'J' => {
463                let cx = self.pane.cursor.x;
464                let cy = self.pane.cursor.y;
465                let cols = self.cols();
466                let rows = self.rows();
467                match p0 {
468                    0 => {
469                        // Erase from cursor to end
470                        self.erase_region(cx, cy, cols - 1, rows - 1);
471                    }
472                    1 => {
473                        // Erase from start to cursor
474                        self.erase_region(0, 0, cx, cy);
475                    }
476                    2 | 3 => {
477                        // Erase entire display
478                        self.erase_region(0, 0, cols - 1, rows - 1);
479                    }
480                    _ => {}
481                }
482            }
483
484            // EL - Erase in Line
485            'K' => {
486                let cx = self.pane.cursor.x;
487                let cy = self.pane.cursor.y;
488                let cols = self.cols();
489                match p0 {
490                    0 => self.erase_region(cx, cy, cols - 1, cy),
491                    1 => self.erase_region(0, cy, cx, cy),
492                    2 => self.erase_region(0, cy, cols - 1, cy),
493                    _ => {}
494                }
495            }
496
497            // SU - Scroll Up
498            'S' => {
499                let n = if p0 == 0 { 1 } else { p0 };
500                self.scroll_up(n);
501            }
502
503            // SD - Scroll Down
504            'T' => {
505                let n = if p0 == 0 { 1 } else { p0 };
506                self.scroll_down(n);
507            }
508
509            // SGR - Select Graphic Rendition
510            'm' => {
511                self.process_sgr(params);
512            }
513
514            // DECSTBM - Set Top and Bottom Margins (scroll region)
515            'r' => {
516                let rows = self.rows();
517                let top = if p0 == 0 { 1 } else { p0 };
518                let bottom = if p1 == 0 { rows } else { p1 };
519                self.scroll_top = (top - 1).min(rows.saturating_sub(1));
520                self.scroll_bottom = (bottom - 1).min(rows.saturating_sub(1));
521                // CUP to home on DECSTBM
522                self.pane.cursor.x = 0;
523                self.pane.cursor.y = 0;
524            }
525
526            // ICH - Insert Characters
527            '@' => {
528                let n = if p0 == 0 { 1 } else { p0 };
529                let cols = self.cols();
530                let cx = self.pane.cursor.x;
531                let cy = self.pane.cursor.y;
532                let blank = self.blank_cell();
533                let buf = self.pane.active_buffer_mut();
534                // Shift cells right
535                for x in (cx..cols).rev() {
536                    if x + n < cols {
537                        let cell = buf.buffer[(x, cy)].clone();
538                        buf.buffer[(x + n, cy)] = cell;
539                    }
540                }
541                // Clear inserted cells with current background
542                for x in cx..cx.saturating_add(n).min(cols) {
543                    buf.buffer[(x, cy)] = blank.clone();
544                }
545                buf.mark_dirty(cy);
546            }
547
548            // DCH - Delete Characters
549            'P' => {
550                let n = if p0 == 0 { 1 } else { p0 };
551                let cols = self.cols();
552                let cx = self.pane.cursor.x;
553                let cy = self.pane.cursor.y;
554                let blank = self.blank_cell();
555                let buf = self.pane.active_buffer_mut();
556                // Shift cells left
557                for x in cx..cols {
558                    if x + n < cols {
559                        let cell = buf.buffer[(x + n, cy)].clone();
560                        buf.buffer[(x, cy)] = cell;
561                    } else {
562                        buf.buffer[(x, cy)] = blank.clone();
563                    }
564                }
565                buf.mark_dirty(cy);
566            }
567
568            // ECH - Erase Characters
569            'X' => {
570                let n = if p0 == 0 { 1 } else { p0 };
571                let cx = self.pane.cursor.x;
572                let cy = self.pane.cursor.y;
573                let cols = self.cols();
574                self.erase_region(cx, cy, (cx + n - 1).min(cols - 1), cy);
575            }
576
577            // IL - Insert Lines
578            'L' => {
579                let n = if p0 == 0 { 1 } else { p0 };
580                let cy = self.pane.cursor.y;
581                let saved_top = self.scroll_top;
582                self.scroll_top = cy;
583                self.scroll_down(n);
584                self.scroll_top = saved_top;
585            }
586
587            // DL - Delete Lines
588            'M' => {
589                let n = if p0 == 0 { 1 } else { p0 };
590                let cy = self.pane.cursor.y;
591                let saved_top = self.scroll_top;
592                self.scroll_top = cy;
593                self.scroll_up(n);
594                self.scroll_top = saved_top;
595            }
596
597            // DECSET/DECRST (via intermediates '?')
598            'h' | 'l' => {
599                let enable = action == 'h';
600                // Check if this is a DEC private mode (? prefix)
601                if _intermediates.first() == Some(&b'?') {
602                    for &code in &p {
603                        match code {
604                            // DECTCEM - cursor visibility
605                            25 => {
606                                self.pane.cursor.visible = enable;
607                            }
608                            // DECSET 1049 - alternate screen
609                            1049 => {
610                                if enable {
611                                    self.pane.enter_alternate_screen();
612                                } else {
613                                    self.pane.leave_alternate_screen();
614                                }
615                                // Reset scroll region
616                                self.scroll_top = 0;
617                                self.scroll_bottom = self.rows().saturating_sub(1);
618                            }
619                            _ => {}
620                        }
621                    }
622                }
623            }
624
625            // VPA - Vertical Line Position Absolute
626            'd' => {
627                let row = if p0 == 0 { 1 } else { p0 };
628                self.pane.cursor.y = (row - 1).min(self.rows().saturating_sub(1));
629            }
630
631            // DECSC - Save Cursor (CSI s)
632            's' => {
633                self.saved_cursor = self.pane.cursor;
634            }
635
636            // DECRC - Restore Cursor (CSI u)
637            'u' => {
638                self.pane.cursor = self.saved_cursor;
639            }
640
641            _ => {} // Ignore unhandled CSI
642        }
643    }
644
645    fn esc_dispatch(&mut self, _intermediates: &[u8], _ignore: bool, byte: u8) {
646        match byte {
647            // RIS - Full Reset
648            b'c' => {
649                self.sgr = SgrState::default();
650                self.pane.cursor = CursorState::default();
651                self.scroll_top = 0;
652                self.scroll_bottom = self.rows().saturating_sub(1);
653                let cols = self.cols();
654                let rows = self.rows();
655                self.erase_region(0, 0, cols - 1, rows - 1);
656            }
657            // DECSC - Save Cursor
658            b'7' => {
659                self.saved_cursor = self.pane.cursor;
660            }
661            // DECRC - Restore Cursor
662            b'8' => {
663                self.pane.cursor = self.saved_cursor;
664            }
665            _ => {}
666        }
667    }
668
669    fn osc_dispatch(&mut self, params: &[&[u8]], _bell_terminated: bool) {
670        if params.is_empty() {
671            return;
672        }
673        // OSC 0 or 2: set title
674        match params[0] {
675            b"0" | b"2" if params.len() > 1 => {
676                if let Ok(title) = std::str::from_utf8(params[1]) {
677                    self.pane.title = title.to_owned();
678                }
679            }
680            _ => {}
681        }
682    }
683
684    fn hook(&mut self, _params: &vte::Params, _intermediates: &[u8], _ignore: bool, _action: char) {
685    }
686    fn put(&mut self, _byte: u8) {}
687    fn unhook(&mut self) {}
688}
689
690// ============================================================================
691// Tests
692// ============================================================================
693
694#[cfg(test)]
695mod tests {
696    use super::*;
697
698    fn make_pane() -> TuiPane {
699        TuiPane::new(1, 20, 10, 100)
700    }
701
702    #[test]
703    fn test_print_basic() {
704        let mut pane = make_pane();
705        {
706            let mut perf = PanePerformer::new(&mut pane);
707            perf.feed(b"Hello");
708        }
709        assert_eq!(pane.cursor.x, 5);
710        assert_eq!(pane.cursor.y, 0);
711        assert_eq!(pane.primary.buffer[(0, 0)].symbol(), "H");
712        assert_eq!(pane.primary.buffer[(4, 0)].symbol(), "o");
713    }
714
715    #[test]
716    fn test_sgr_colors() {
717        let mut pane = make_pane();
718        {
719            let mut perf = PanePerformer::new(&mut pane);
720            // Red foreground, green background
721            perf.feed(b"\x1b[31;42mX");
722        }
723        let cell = &pane.primary.buffer[(0, 0)];
724        assert_eq!(cell.symbol(), "X");
725        assert_eq!(cell.fg, Color::Red);
726        assert_eq!(cell.bg, Color::Green);
727    }
728
729    #[test]
730    fn test_sgr_256_color() {
731        let mut pane = make_pane();
732        {
733            let mut perf = PanePerformer::new(&mut pane);
734            perf.feed(b"\x1b[38;5;42mA");
735        }
736        assert_eq!(pane.primary.buffer[(0, 0)].fg, Color::Indexed(42));
737    }
738
739    #[test]
740    fn test_sgr_rgb() {
741        let mut pane = make_pane();
742        {
743            let mut perf = PanePerformer::new(&mut pane);
744            perf.feed(b"\x1b[38;2;255;128;0mB");
745        }
746        assert_eq!(pane.primary.buffer[(0, 0)].fg, Color::Rgb(255, 128, 0));
747    }
748
749    #[test]
750    fn test_cup_positioning() {
751        let mut pane = make_pane();
752        {
753            let mut perf = PanePerformer::new(&mut pane);
754            // Move to row 3, col 5 (1-based)
755            perf.feed(b"\x1b[3;5HX");
756        }
757        assert_eq!(pane.primary.buffer[(4, 2)].symbol(), "X");
758        assert_eq!(pane.cursor.x, 5);
759        assert_eq!(pane.cursor.y, 2);
760    }
761
762    #[test]
763    fn test_cursor_movement() {
764        let mut pane = make_pane();
765        {
766            let mut perf = PanePerformer::new(&mut pane);
767            perf.feed(b"\x1b[5;5H"); // row 5, col 5
768            perf.feed(b"\x1b[2A"); // up 2
769            perf.feed(b"\x1b[3C"); // right 3
770        }
771        assert_eq!(pane.cursor.y, 2); // 5-1-2 = 2
772        assert_eq!(pane.cursor.x, 7); // 5-1+3 = 7
773    }
774
775    #[test]
776    fn test_ed_erase_display() {
777        let mut pane = make_pane();
778        {
779            let mut perf = PanePerformer::new(&mut pane);
780            perf.feed(b"ABCDE");
781            perf.feed(b"\x1b[2J"); // Clear entire display
782        }
783        assert_eq!(pane.primary.buffer[(0, 0)].symbol(), " ");
784        assert_eq!(pane.primary.buffer[(4, 0)].symbol(), " ");
785    }
786
787    #[test]
788    fn test_el_erase_line() {
789        let mut pane = make_pane();
790        {
791            let mut perf = PanePerformer::new(&mut pane);
792            perf.feed(b"Hello World");
793            perf.feed(b"\x1b[1;6H"); // Move to col 6
794            perf.feed(b"\x1b[K"); // Erase to end of line
795        }
796        assert_eq!(pane.primary.buffer[(0, 0)].symbol(), "H");
797        assert_eq!(pane.primary.buffer[(4, 0)].symbol(), "o");
798        assert_eq!(pane.primary.buffer[(5, 0)].symbol(), " "); // Erased
799    }
800
801    #[test]
802    fn test_scroll_region() {
803        let mut pane = make_pane();
804        {
805            let mut perf = PanePerformer::new(&mut pane);
806            // Set scroll region rows 2-5 (1-based)
807            perf.feed(b"\x1b[2;5r");
808            assert_eq!(perf.scroll_top, 1);
809            assert_eq!(perf.scroll_bottom, 4);
810        }
811        // DECSTBM homes the cursor
812        assert_eq!(pane.cursor.x, 0);
813        assert_eq!(pane.cursor.y, 0);
814    }
815
816    #[test]
817    fn test_alt_screen() {
818        let mut pane = make_pane();
819        assert!(!pane.using_alternate);
820        {
821            let mut perf = PanePerformer::new(&mut pane);
822            // Enter alternate screen
823            perf.feed(b"\x1b[?1049h");
824        }
825        assert!(pane.using_alternate);
826        assert!(pane.alternate.is_some());
827        {
828            let mut perf = PanePerformer::new(&mut pane);
829            perf.feed(b"\x1b[?1049l");
830        }
831        assert!(!pane.using_alternate);
832    }
833
834    #[test]
835    fn test_cursor_visibility() {
836        let mut pane = make_pane();
837        {
838            let mut perf = PanePerformer::new(&mut pane);
839            perf.feed(b"\x1b[?25l"); // Hide
840        }
841        assert!(!pane.cursor.visible);
842        {
843            let mut perf = PanePerformer::new(&mut pane);
844            perf.feed(b"\x1b[?25h"); // Show
845        }
846        assert!(pane.cursor.visible);
847    }
848
849    #[test]
850    fn test_cr_lf() {
851        let mut pane = make_pane();
852        {
853            let mut perf = PanePerformer::new(&mut pane);
854            perf.feed(b"AB\r\nCD");
855        }
856        assert_eq!(pane.primary.buffer[(0, 0)].symbol(), "A");
857        assert_eq!(pane.primary.buffer[(1, 0)].symbol(), "B");
858        assert_eq!(pane.primary.buffer[(0, 1)].symbol(), "C");
859        assert_eq!(pane.primary.buffer[(1, 1)].symbol(), "D");
860    }
861
862    #[test]
863    fn test_line_wrap_and_scroll() {
864        let mut pane = TuiPane::new(1, 10, 3, 100); // 10 cols, 3 rows
865        {
866            let mut perf = PanePerformer::new(&mut pane);
867            perf.feed(b"\x1b[1;1HAAAAA"); // Row 1
868            perf.feed(b"\x1b[2;1HBBBBB"); // Row 2
869            perf.feed(b"\x1b[3;1HCCCCC"); // Row 3
870                                          // Now at row 3, col 5. LF should scroll.
871            perf.feed(b"\r\nDDDDD");
872        }
873        // After scroll: row 0=B, row 1=C, row 2=D
874        assert_eq!(pane.primary.buffer[(0, 0)].symbol(), "B");
875        assert_eq!(pane.primary.buffer[(0, 1)].symbol(), "C");
876        assert_eq!(pane.primary.buffer[(0, 2)].symbol(), "D");
877    }
878
879    /// Verifies that writing to the last column of the last row does NOT
880    /// immediately scroll (pending_wrap deferred until next printed char).
881    /// This prevents spurious scrolling when a ratatui full-redraw writes
882    /// cell (cols-1, rows-1) as its final update.
883    #[test]
884    fn test_no_spurious_scroll_on_last_cell() {
885        let mut pane = TuiPane::new(1, 5, 3, 100); // 5 cols, 3 rows
886        {
887            let mut perf = PanePerformer::new(&mut pane);
888            // Fill all three rows (each CUP cancels pending_wrap).
889            perf.feed(b"\x1b[1;1HAAAAA"); // Row 0: 5 chars → pending_wrap=true
890            perf.feed(b"\x1b[2;1HBBBBB"); // Row 1: CUP cancels pending_wrap
891            perf.feed(b"\x1b[3;1HCCCCC"); // Row 2: 5 chars → pending_wrap=true
892                                          // No further input: wrap never fires, NO scroll happens.
893        }
894        // All three rows must retain their content.
895        assert_eq!(pane.primary.buffer[(0, 0)].symbol(), "A");
896        assert_eq!(pane.primary.buffer[(0, 1)].symbol(), "B");
897        assert_eq!(pane.primary.buffer[(0, 2)].symbol(), "C");
898    }
899
900    /// Verifies that pending_wrap DOES fire when the next char arrives without
901    /// a cursor-movement command in between.
902    #[test]
903    fn test_pending_wrap_fires_on_next_char() {
904        let mut pane = TuiPane::new(1, 5, 3, 100); // 5 cols, 3 rows
905        {
906            let mut perf = PanePerformer::new(&mut pane);
907            perf.feed(b"\x1b[1;1HAAAAA"); // Row 0
908            perf.feed(b"\x1b[2;1HBBBBB"); // Row 1
909            perf.feed(b"\x1b[3;1HCCCCC"); // Row 2: pending_wrap=true
910                                          // Next char fires pending_wrap → wrap → scroll.
911            perf.feed(b"D");
912        }
913        // After scroll: row0=B, row1=C, row2 starts with D.
914        assert_eq!(pane.primary.buffer[(0, 0)].symbol(), "B");
915        assert_eq!(pane.primary.buffer[(0, 1)].symbol(), "C");
916        assert_eq!(pane.primary.buffer[(0, 2)].symbol(), "D");
917    }
918
919    #[test]
920    fn test_damage_tracking() {
921        let mut pane = make_pane();
922        pane.primary.clear_damage();
923        {
924            let mut perf = PanePerformer::new(&mut pane);
925            perf.feed(b"\x1b[3;1HX"); // Write at row 3
926        }
927        assert!(pane.primary.is_row_dirty(2));
928        assert!(!pane.primary.is_row_dirty(0));
929    }
930
931    #[test]
932    fn test_osc_title() {
933        let mut pane = make_pane();
934        {
935            let mut perf = PanePerformer::new(&mut pane);
936            perf.feed(b"\x1b]0;My Title\x07");
937        }
938        assert_eq!(pane.title, "My Title");
939    }
940
941    #[test]
942    fn test_save_restore_cursor() {
943        let mut pane = make_pane();
944        {
945            let mut perf = PanePerformer::new(&mut pane);
946            perf.feed(b"\x1b[5;10H"); // row 5, col 10
947            perf.feed(b"\x1b7"); // DECSC
948            perf.feed(b"\x1b[1;1H"); // Home
949            perf.feed(b"\x1b8"); // DECRC
950        }
951        assert_eq!(pane.cursor.y, 4);
952        assert_eq!(pane.cursor.x, 9);
953    }
954
955    #[test]
956    fn test_sgr_bold_italic() {
957        let mut pane = make_pane();
958        {
959            let mut perf = PanePerformer::new(&mut pane);
960            perf.feed(b"\x1b[1;3mX"); // Bold + Italic
961        }
962        let cell = &pane.primary.buffer[(0, 0)];
963        assert!(cell.modifier.contains(Modifier::BOLD));
964        assert!(cell.modifier.contains(Modifier::ITALIC));
965    }
966
967    #[test]
968    fn test_sgr_reset() {
969        let mut pane = make_pane();
970        {
971            let mut perf = PanePerformer::new(&mut pane);
972            perf.feed(b"\x1b[31mR\x1b[0mN"); // Red then reset
973        }
974        assert_eq!(pane.primary.buffer[(0, 0)].fg, Color::Red);
975        assert_eq!(pane.primary.buffer[(1, 0)].fg, Color::Reset);
976    }
977
978    #[test]
979    fn test_erase_preserves_background_color() {
980        // VT spec: EL (erase line) and ED (erase display) fill cells with
981        // the current SGR background color, not the terminal default.
982        let mut pane = make_pane();
983        {
984            let mut perf = PanePerformer::new(&mut pane);
985            // Set dark-blue background (like btop header bars), write some text,
986            // then erase to end of line — erased cells should keep the dark-blue bg.
987            perf.feed(b"\x1b[48;2;20;20;40m"); // dark-blue bg
988            perf.feed(b"ABC");
989            perf.feed(b"\x1b[1;4H"); // cursor to col 4
990            perf.feed(b"\x1b[K"); // EL: erase to EOL
991        }
992        // Cols 3..cols should have dark-blue bg (not Reset)
993        for x in 3..10u16 {
994            let cell = &pane.primary.buffer[(x, 0)];
995            assert_eq!(
996                cell.bg,
997                Color::Rgb(20, 20, 40),
998                "col {x} erase should preserve bg color, got {:?}",
999                cell.bg
1000            );
1001        }
1002        // Written cells should also have the dark-blue bg
1003        assert_eq!(pane.primary.buffer[(0, 0)].bg, Color::Rgb(20, 20, 40));
1004    }
1005
1006    #[test]
1007    fn test_scroll_up_preserves_background_color() {
1008        // When lines scroll up, newly cleared rows at the bottom should
1009        // use the current background color.  The pane is 20×10 so we need
1010        // 11+ LF characters to actually scroll past the bottom margin.
1011        let mut pane = make_pane();
1012        {
1013            let mut perf = PanePerformer::new(&mut pane);
1014            perf.feed(b"\x1b[48;2;10;10;20m"); // set bg
1015                                               // Move to last row then issue one more LF to trigger scroll
1016            perf.feed(b"\x1b[10;1H"); // cursor to row 10 (bottom)
1017            perf.feed(b"\n"); // one LF → scroll up 1
1018        }
1019        // Bottom row (row 9, 0-indexed) should have been cleared with the
1020        // current background color, not Color::Reset.
1021        let last_row = pane.primary.buffer.area().height - 1;
1022        let cell = &pane.primary.buffer[(0, last_row)];
1023        assert_eq!(
1024            cell.bg,
1025            Color::Rgb(10, 10, 20),
1026            "scroll-cleared row should preserve bg, got {:?}",
1027            cell.bg
1028        );
1029    }
1030}