Skip to main content

boxmux_lib/
ansi_processor.rs

1use vte::{Params, Parser, Perform};
2
3/// F0304: Terminal Message Architecture - Comprehensive terminal operation messages
4#[derive(Debug, Clone, PartialEq)]
5pub enum TerminalMessage {
6    // Core terminal operations
7    ProcessBytes(Vec<u8>),
8    SendInput(String),
9    ResizeTerminal {
10        width: usize,
11        height: usize,
12    },
13
14    // Screen buffer operations
15    SwitchScreenBuffer {
16        to_alternate: bool,
17    },
18    ClearScreen {
19        mode: ClearMode,
20    },
21    ClearLine {
22        line: usize,
23        mode: ClearMode,
24    },
25    ScrollUp {
26        lines: usize,
27    },
28    ScrollDown {
29        lines: usize,
30    },
31
32    // Cursor operations
33    MoveCursor {
34        x: usize,
35        y: usize,
36    },
37    MoveCursorRelative {
38        dx: i32,
39        dy: i32,
40    },
41    SaveCursor,
42    RestoreCursor,
43    SetCursorVisibility {
44        visible: bool,
45    },
46    SetCursorStyle {
47        style: CursorStyle,
48    },
49    SetCursorColumn {
50        col: usize,
51    },
52    SetCursorLine {
53        line: usize,
54    },
55    CursorUp {
56        lines: usize,
57    },
58    CursorDown {
59        lines: usize,
60    },
61    CursorLeft {
62        cols: usize,
63    },
64    CursorRight {
65        cols: usize,
66    },
67    CursorToLineStart,
68    CursorNextLine {
69        lines: usize,
70    },
71    CursorPreviousLine {
72        lines: usize,
73    },
74
75    // Terminal modes
76    SetMode {
77        mode: TerminalModeType,
78        enabled: bool,
79    },
80
81    // Character attributes and formatting
82    SetAttributes {
83        attributes: TerminalAttributes,
84    },
85    ResetAttributes,
86
87    // Scrolling regions
88    SetScrollingRegion {
89        top: usize,
90        bottom: usize,
91    },
92    ResetScrollingRegion,
93    ScrollUpInRegion {
94        lines: usize,
95    }, // F0307: Scroll up within margins
96    ScrollDownInRegion {
97        lines: usize,
98    }, // F0307: Scroll down within margins
99
100    // Tab operations
101    SetTabStop,
102    ClearTabStop,
103    ClearAllTabStops,
104    TabForward {
105        count: usize,
106    },
107    TabBackward {
108        count: usize,
109    },
110
111    // Device control and queries
112    DeviceStatusReport {
113        report_type: DeviceReportType,
114    },
115    DeviceAttributes {
116        primary: bool,
117    },
118    TerminalIdentification,
119
120    // OSC operations
121    SetTerminalTitle {
122        title: String,
123    },
124    SetIconName {
125        name: String,
126    },
127    SetColorPalette {
128        index: u8,
129        color: String,
130    },
131    ClipboardOperation {
132        operation: ClipboardOp,
133    },
134
135    // Content updates with dirty regions
136    ContentUpdate {
137        content: String,
138        dirty_regions: Vec<DirtyRegion>,
139        replace_mode: bool,
140    },
141
142    // Mouse operations
143    MouseEvent {
144        event_type: MouseEventType,
145        x: usize,
146        y: usize,
147        button: Option<MouseButton>,
148        modifiers: MouseModifiers,
149    },
150
151    // Character sets
152    SetCharacterSet {
153        set: CharacterSetType,
154        charset: String,
155    },
156
157    // Terminal state queries
158    QueryTerminalState,
159    QueryCursorPosition,
160    QueryScreenSize,
161}
162
163#[derive(Debug, Clone, PartialEq)]
164pub enum ClearMode {
165    FromCursor,
166    ToCursor,
167    Entire,
168    Scrollback,
169}
170
171#[derive(Debug, Clone, PartialEq)]
172pub enum TerminalModeType {
173    CursorKeys,   // DECCKM
174    Keypad,       // DECPAM
175    AutoWrap,     // DECAWM
176    Origin,       // DECOM
177    Insert,       // IRM
178    LocalEcho,    // LNM
179    ReverseVideo, // DECSCNM
180    MouseX10,     // Mouse reporting modes
181    MouseNormal,
182    MouseButtonEvent,
183    MouseAnyEvent,
184    MouseSgr,
185    BracketedPaste,
186    AlternateScreen, // 1047/1049
187}
188
189#[derive(Debug, Clone, PartialEq, Default)]
190pub struct TerminalAttributes {
191    pub fg_color: Option<TerminalColor>,
192    pub bg_color: Option<TerminalColor>,
193    pub bold: bool,
194    pub italic: bool,
195    pub underline: bool,
196    pub strikethrough: bool,
197    pub reverse: bool,
198    pub blink: bool,
199    pub dim: bool,
200}
201
202#[derive(Debug, Clone, PartialEq)]
203pub enum TerminalColor {
204    Named(u8),                   // 0-15 standard colors
205    Palette(u8),                 // 0-255 palette colors
206    Rgb { r: u8, g: u8, b: u8 }, // 24-bit RGB
207}
208
209#[derive(Debug, Clone, PartialEq)]
210pub enum DeviceReportType {
211    Status,         // DSR 5
212    CursorPosition, // DSR 6
213    PrinterStatus,  // DSR ?15
214    UdkStatus,      // DSR ?25
215    KeyboardStatus, // DSR ?26
216    LocatorStatus,  // DSR ?53
217}
218
219#[derive(Debug, Clone, PartialEq)]
220pub enum ClipboardOp {
221    SetSelection { selection: String },
222    GetSelection,
223    SetClipboard { content: String },
224    GetClipboard,
225}
226
227#[derive(Debug, Clone, PartialEq)]
228pub struct DirtyRegion {
229    pub x: usize,
230    pub y: usize,
231    pub width: usize,
232    pub height: usize,
233}
234
235#[derive(Debug, Clone, PartialEq)]
236pub enum MouseEventType {
237    Press,
238    Release,
239    Motion,
240    Wheel,
241}
242
243#[derive(Debug, Clone, PartialEq)]
244pub enum MouseButton {
245    Left,
246    Middle,
247    Right,
248    WheelUp,
249    WheelDown,
250    WheelLeft,
251    WheelRight,
252}
253
254#[derive(Debug, Clone, PartialEq, Default)]
255pub struct MouseModifiers {
256    pub shift: bool,
257    pub ctrl: bool,
258    pub alt: bool,
259    pub meta: bool,
260}
261
262#[derive(Debug, Clone, PartialEq)]
263pub enum CharacterSetType {
264    G0,
265    G1,
266    G2,
267    G3,
268}
269
270#[derive(Debug, Clone, Default)]
271pub struct TextFormatting {
272    pub fg: Option<u8>,
273    pub bg: Option<u8>,
274    pub bold: bool,
275    pub underline: bool,
276    pub italic: bool,
277    pub reverse: bool,
278    pub strikethrough: bool,
279}
280
281#[derive(Debug, Clone, PartialEq)]
282/// F0306: Extended TerminalCell with comprehensive SGR attribute support
283pub struct TerminalCell {
284    pub character: char,
285    pub fg_color: Option<u8>,
286    pub bg_color: Option<u8>,
287
288    // Basic text attributes
289    pub bold: bool,
290    pub dim: bool, // F0306: Faint/dim text
291    pub italic: bool,
292    pub underline: bool,
293    pub double_underline: bool, // F0306: Double underline
294    pub blink: bool,            // F0306: Blinking text
295    pub reverse: bool,
296    pub hidden: bool, // F0306: Concealed/hidden text
297    pub strikethrough: bool,
298
299    // Extended attributes
300    pub font_id: Option<u8>, // F0306: Alternative font selection (0-9)
301    pub framed: bool,        // F0306: Framed text
302    pub encircled: bool,     // F0306: Encircled text
303    pub overlined: bool,     // F0306: Overlined text
304
305    // Ideogram attributes (rarely used)
306    pub ideogram_underline: bool,        // F0306: Ideogram underline
307    pub ideogram_double_underline: bool, // F0306: Ideogram double underline
308    pub ideogram_overline: bool,         // F0306: Ideogram overline
309    pub ideogram_double_overline: bool,  // F0306: Ideogram double overline
310    pub ideogram_stress: bool,           // F0306: Ideogram stress marking
311}
312
313impl Default for TerminalCell {
314    fn default() -> Self {
315        TerminalCell {
316            character: ' ',
317            fg_color: None,
318            bg_color: None,
319
320            // Basic text attributes
321            bold: false,
322            dim: false,
323            italic: false,
324            underline: false,
325            double_underline: false,
326            blink: false,
327            reverse: false,
328            hidden: false,
329            strikethrough: false,
330
331            // Extended attributes
332            font_id: None,
333            framed: false,
334            encircled: false,
335            overlined: false,
336
337            // Ideogram attributes
338            ideogram_underline: false,
339            ideogram_double_underline: false,
340            ideogram_overline: false,
341            ideogram_double_overline: false,
342            ideogram_stress: false,
343        }
344    }
345}
346
347#[derive(Debug, Clone)]
348pub struct CursorState {
349    pub x: usize,
350    pub y: usize,
351    pub visible: bool,
352    pub style: CursorStyle,
353}
354
355#[derive(Debug, Clone, PartialEq, Default)]
356pub enum CursorStyle {
357    #[default]
358    Block,
359    Underline,
360    Bar,
361    BlinkingBlock,
362    BlinkingUnderline,
363    BlinkingBar,
364}
365
366/// F0314: Line attributes for double-width and double-height lines
367#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
368pub enum LineAttribute {
369    #[default]
370    Normal, // Standard single-width, single-height line
371    DoubleWidth,        // DECDWL - Double-width line
372    DoubleHeightTop,    // DECDHL - Double-height line (top half)
373    DoubleHeightBottom, // DECDHL - Double-height line (bottom half)
374}
375
376/// F0306: SGR sequence state tracking for extended color support
377#[derive(Debug, Clone, PartialEq, Default)]
378pub struct SGRState {
379    pub expecting_extended_fg: bool, // Expecting 38;5;n or 38;2;r;g;b sequence
380    pub expecting_extended_bg: bool, // Expecting 48;5;n or 48;2;r;g;b sequence
381    pub extended_fg_mode: Option<u8>, // 5 for palette, 2 for RGB
382    pub extended_bg_mode: Option<u8>, // 5 for palette, 2 for RGB
383    pub rgb_components: Vec<u8>,     // RGB components being collected
384    pub palette_index: Option<u8>,   // 256-color palette index
385}
386
387#[derive(Debug, Clone)]
388pub struct TerminalMode {
389    pub cursor_key_mode: bool, // DECCKM - Application cursor keys
390    pub keypad_mode: bool,     // DECPAM - Application keypad
391    pub auto_wrap_mode: bool,  // DECAWM - Auto wrap
392    pub origin_mode: bool,     // DECOM - Origin mode
393    pub insert_mode: bool,     // IRM - Insert/Replace mode
394    pub local_echo_mode: bool, // LNM - Linefeed/Newline mode
395    pub reverse_video: bool,   // DECSCNM - Screen mode (reverse)
396    // F0310: Mouse Protocol Support
397    pub mouse_x10_mode: bool,          // 1000 - X10 mouse reporting
398    pub mouse_normal_mode: bool,       // 1002 - Normal mouse reporting
399    pub mouse_button_event_mode: bool, // 1002 - Button event tracking
400    pub mouse_any_event_mode: bool,    // 1003 - Any event tracking
401    pub mouse_sgr_mode: bool,          // 1006 - SGR extended reporting
402    pub bracketed_paste_mode: bool,    // 2004 - Bracketed paste mode
403}
404
405impl Default for TerminalMode {
406    fn default() -> Self {
407        TerminalMode {
408            cursor_key_mode: false,
409            keypad_mode: false,
410            auto_wrap_mode: true,
411            origin_mode: false,
412            insert_mode: false,
413            local_echo_mode: false,
414            reverse_video: false,
415            // F0310: Mouse Protocol Support - all disabled by default
416            mouse_x10_mode: false,
417            mouse_normal_mode: false,
418            mouse_button_event_mode: false,
419            mouse_any_event_mode: false,
420            mouse_sgr_mode: false,
421            bracketed_paste_mode: false,
422        }
423    }
424}
425
426#[derive(Debug, Clone)]
427/// F0307: Scrolling region for DECSTBM (Set Top and Bottom Margins)
428#[derive(Default)]
429pub struct ScrollRegion {
430    pub top: usize,    // Top margin (0-based, inclusive)
431    pub bottom: usize, // Bottom margin (0-based, inclusive)
432}
433
434#[derive(Debug, Clone)]
435pub struct TerminalScreenBuffer {
436    pub content: Vec<Vec<TerminalCell>>,
437    pub scrollback: Vec<Vec<TerminalCell>>,
438    pub cursor: CursorState,
439    pub saved_cursor: Option<CursorState>,
440    pub scroll_position: usize, // 0 = bottom (normal), higher = scrolled up
441    pub max_scrollback: usize,
442    pub width: usize,
443    pub height: usize,
444    // F0314: Line attributes for each line
445    pub line_attributes: Vec<LineAttribute>,
446    pub scrollback_line_attributes: Vec<LineAttribute>,
447}
448
449impl TerminalScreenBuffer {
450    pub fn new(width: usize, height: usize, max_scrollback: usize) -> Self {
451        TerminalScreenBuffer {
452            content: vec![vec![TerminalCell::default(); width]; height],
453            scrollback: Vec::new(),
454            cursor: CursorState {
455                x: 0,
456                y: 0,
457                visible: true,
458                style: CursorStyle::default(),
459            },
460            saved_cursor: None,
461            scroll_position: 0,
462            max_scrollback,
463            width,
464            height,
465            // F0314: Initialize line attributes to normal for all lines
466            line_attributes: vec![LineAttribute::Normal; height],
467            scrollback_line_attributes: Vec::new(),
468        }
469    }
470
471    pub fn scroll_up_one_line(&mut self) {
472        // Move top line to scrollback
473        if let Some(top_line) = self.content.first().cloned() {
474            self.scrollback.push(top_line);
475
476            // F0314: Move top line attribute to scrollback too
477            if !self.line_attributes.is_empty() {
478                let top_attr = self.line_attributes.remove(0);
479                self.scrollback_line_attributes.push(top_attr);
480            }
481
482            // Limit scrollback size
483            if self.scrollback.len() > self.max_scrollback {
484                self.scrollback.remove(0);
485                if !self.scrollback_line_attributes.is_empty() {
486                    self.scrollback_line_attributes.remove(0);
487                }
488            }
489        }
490
491        // Shift all lines up and add empty line at bottom
492        self.content.remove(0);
493        self.content.push(vec![TerminalCell::default(); self.width]);
494
495        // F0314: Add normal line attribute for new bottom line
496        self.line_attributes.push(LineAttribute::Normal);
497    }
498
499    pub fn scroll_down_one_line(&mut self) {
500        // Move bottom line up and get line from scrollback
501        if let Some(line) = self.scrollback.pop() {
502            self.content.remove(self.content.len() - 1);
503            self.content.insert(0, line);
504
505            // F0314: Restore line attribute from scrollback
506            if let Some(attr) = self.scrollback_line_attributes.pop() {
507                self.line_attributes.remove(self.line_attributes.len() - 1);
508                self.line_attributes.insert(0, attr);
509            }
510        }
511    }
512
513    pub fn get_visible_content(&self) -> &Vec<Vec<TerminalCell>> {
514        &self.content
515    }
516
517    pub fn get_line_mut(&mut self, y: usize) -> Option<&mut Vec<TerminalCell>> {
518        self.content.get_mut(y)
519    }
520
521    pub fn clear_screen(&mut self) {
522        for row in &mut self.content {
523            for cell in row {
524                *cell = TerminalCell::default();
525            }
526        }
527        self.cursor.x = 0;
528        self.cursor.y = 0;
529    }
530
531    pub fn clear_from_cursor_to_end(&mut self) {
532        // Clear from cursor position to end of screen
533        for y in self.cursor.y..self.height {
534            let start_x = if y == self.cursor.y { self.cursor.x } else { 0 };
535            if let Some(row) = self.content.get_mut(y) {
536                for cell in row.iter_mut().skip(start_x) {
537                    *cell = TerminalCell::default();
538                }
539            }
540        }
541    }
542
543    pub fn clear_from_beginning_to_cursor(&mut self) {
544        // Clear from beginning of screen to cursor position
545        for y in 0..=self.cursor.y.min(self.height - 1) {
546            let end_x = if y == self.cursor.y {
547                self.cursor.x + 1
548            } else {
549                self.width
550            };
551            if let Some(row) = self.content.get_mut(y) {
552                for x in 0..end_x.min(row.len()) {
553                    row[x] = TerminalCell::default();
554                }
555            }
556        }
557    }
558
559    pub fn insert_lines(&mut self, count: usize) {
560        let y = self.cursor.y;
561        if y < self.height {
562            for _ in 0..count {
563                if self.content.len() > y {
564                    self.content
565                        .insert(y, vec![TerminalCell::default(); self.width]);
566                    if self.content.len() > self.height {
567                        self.content.pop();
568                    }
569                }
570            }
571        }
572    }
573
574    pub fn delete_lines(&mut self, count: usize) {
575        let y = self.cursor.y;
576        if y < self.height {
577            for _ in 0..count.min(self.height - y) {
578                if self.content.len() > y {
579                    self.content.remove(y);
580                    self.content.push(vec![TerminalCell::default(); self.width]);
581                }
582            }
583        }
584    }
585
586    pub fn resize(&mut self, new_width: usize, new_height: usize) {
587        self.width = new_width;
588        self.height = new_height;
589
590        // Resize existing content rows
591        for row in &mut self.content {
592            row.resize(new_width, TerminalCell::default());
593        }
594
595        // Add or remove rows as needed
596        if self.content.len() < new_height {
597            while self.content.len() < new_height {
598                self.content.push(vec![TerminalCell::default(); new_width]);
599            }
600        } else if self.content.len() > new_height {
601            self.content.truncate(new_height);
602        }
603
604        // F0314: Resize line attributes to match new height
605        self.line_attributes
606            .resize(new_height, LineAttribute::Normal);
607
608        // Adjust cursor position if out of bounds
609        self.cursor.x = self.cursor.x.min(new_width.saturating_sub(1));
610        self.cursor.y = self.cursor.y.min(new_height.saturating_sub(1));
611    }
612
613    /// Convert TerminalScreenBuffer to content lines for stream integration
614    /// This feeds PTY content into BoxMux's main differential drawing system
615    pub fn to_content_lines(&self, include_scrollback: bool) -> Vec<String> {
616        let mut lines = Vec::new();
617
618        // Include scrollback if requested
619        if include_scrollback {
620            for row in &self.scrollback {
621                let line = self.terminal_row_to_string(row);
622                lines.push(line);
623            }
624        }
625
626        // Add visible content
627        for row in &self.content {
628            let line = self.terminal_row_to_string(row);
629            lines.push(line);
630        }
631
632        lines
633    }
634
635    /// Convert a single terminal row to string with ANSI color codes
636    /// This preserves formatting for BoxMux's main renderer
637    fn terminal_row_to_string(&self, row: &[TerminalCell]) -> String {
638        let mut result = String::new();
639        let mut current_fg: Option<u8> = None;
640        let mut current_bg: Option<u8> = None;
641        let mut current_bold = false;
642        let mut current_underline = false;
643        let mut current_italic = false;
644        let mut current_reverse = false;
645        let mut current_strikethrough = false;
646
647        for cell in row {
648            // Check if we need to change formatting
649            let mut format_changed = false;
650
651            if cell.fg_color != current_fg {
652                current_fg = cell.fg_color;
653                format_changed = true;
654            }
655            if cell.bg_color != current_bg {
656                current_bg = cell.bg_color;
657                format_changed = true;
658            }
659            if cell.bold != current_bold {
660                current_bold = cell.bold;
661                format_changed = true;
662            }
663            if cell.underline != current_underline {
664                current_underline = cell.underline;
665                format_changed = true;
666            }
667            if cell.italic != current_italic {
668                current_italic = cell.italic;
669                format_changed = true;
670            }
671            if cell.reverse != current_reverse {
672                current_reverse = cell.reverse;
673                format_changed = true;
674            }
675            if cell.strikethrough != current_strikethrough {
676                current_strikethrough = cell.strikethrough;
677                format_changed = true;
678            }
679
680            // Apply formatting changes as ANSI escape codes
681            if format_changed {
682                let formatting = TextFormatting {
683                    fg: current_fg,
684                    bg: current_bg,
685                    bold: current_bold,
686                    underline: current_underline,
687                    italic: current_italic,
688                    reverse: current_reverse,
689                    strikethrough: current_strikethrough,
690                };
691                result.push_str(&self.generate_ansi_formatting(&formatting));
692            }
693
694            // Add the character
695            result.push(cell.character);
696        }
697
698        // Reset formatting at end of line if any was applied
699        if current_fg.is_some()
700            || current_bg.is_some()
701            || current_bold
702            || current_underline
703            || current_italic
704            || current_reverse
705            || current_strikethrough
706        {
707            result.push_str("\x1b[0m"); // Reset all formatting
708        }
709
710        result
711    }
712
713    /// Generate ANSI escape sequence for terminal formatting
714    fn generate_ansi_formatting(&self, formatting: &TextFormatting) -> String {
715        let mut codes = Vec::new();
716
717        // Reset first if any formatting is different
718        codes.push("0".to_string()); // Reset all
719
720        // Text attributes
721        if formatting.bold {
722            codes.push("1".to_string());
723        }
724        if formatting.italic {
725            codes.push("3".to_string());
726        }
727        if formatting.underline {
728            codes.push("4".to_string());
729        }
730        if formatting.reverse {
731            codes.push("7".to_string());
732        }
733        if formatting.strikethrough {
734            codes.push("9".to_string());
735        }
736
737        // Foreground color
738        if let Some(fg_color) = formatting.fg {
739            if fg_color < 8 {
740                codes.push(format!("{}", 30 + fg_color));
741            } else if fg_color < 16 {
742                codes.push(format!("{}", 90 + (fg_color - 8)));
743            } else {
744                codes.push(format!("38;5;{}", fg_color));
745            }
746        }
747
748        // Background color
749        if let Some(bg_color) = formatting.bg {
750            if bg_color < 8 {
751                codes.push(format!("{}", 40 + bg_color));
752            } else if bg_color < 16 {
753                codes.push(format!("{}", 100 + (bg_color - 8)));
754            } else {
755                codes.push(format!("48;5;{}", bg_color));
756            }
757        }
758
759        if codes.is_empty() {
760            String::new()
761        } else {
762            format!("\x1b[{}m", codes.join(";"))
763        }
764    }
765
766    /// Get content as string for stream updates - integrates with BoxMux stream system
767    pub fn get_content_for_stream(&self) -> String {
768        let lines = self.to_content_lines(true); // Include scrollback for PTY
769        lines.join("\n")
770    }
771}
772
773#[derive(Debug, Clone)]
774pub struct TerminalState {
775    // Screen dimensions
776    pub screen_width: usize,
777    pub screen_height: usize,
778
779    // Primary and alternate screen buffers
780    pub primary_buffer: TerminalScreenBuffer,
781    pub alternate_buffer: TerminalScreenBuffer,
782    pub use_alternate_screen: bool,
783
784    // Cursor save stack for DECSC/DECRC
785    pub cursor_save_stack: Vec<CursorState>,
786
787    // Character attributes for new text
788    pub current_attributes: TerminalCell,
789
790    // Terminal modes and settings
791    pub mode: TerminalMode,
792    pub scroll_region: ScrollRegion,
793
794    // Tab stops
795    pub tab_stops: Vec<bool>,
796
797    // Character sets (G0/G1)
798    pub charset_g0: Option<String>,
799    pub charset_g1: Option<String>,
800    pub active_charset: u8, // 0 for G0, 1 for G1
801
802    // Terminal identification
803    pub terminal_title: Option<String>,
804    pub icon_name: Option<String>,
805    pub title_changed: bool, // F0315: Track when title changes for propagation
806
807    // State tracking
808    pub full_screen_program_detected: bool,
809
810    // F0306: SGR state tracking for extended colors
811    pub sgr_state: SGRState,
812
813    // DCS (Device Control String) processing
814    pub dcs_sequence_type: Option<char>,
815    pub dcs_buffer: Option<Vec<u8>>,
816    pub pending_response: Option<String>,
817
818    // OSC (Operating System Command) processing
819    pub osc_buffer: Option<Vec<u8>>,
820}
821
822impl TerminalState {
823    pub fn new(width: usize, height: usize) -> Self {
824        let max_scrollback = 10000; // Same as PTY manager default
825        let mut state = TerminalState {
826            screen_width: width,
827            screen_height: height,
828            primary_buffer: TerminalScreenBuffer::new(width, height, max_scrollback),
829            alternate_buffer: TerminalScreenBuffer::new(width, height, max_scrollback),
830            use_alternate_screen: false,
831            cursor_save_stack: Vec::new(),
832            current_attributes: TerminalCell::default(),
833            mode: TerminalMode::default(),
834            scroll_region: ScrollRegion {
835                top: 0,
836                bottom: height.saturating_sub(1),
837            },
838            tab_stops: vec![false; width],
839            charset_g0: None,
840            charset_g1: None,
841            active_charset: 0,
842            terminal_title: None,
843            icon_name: None,
844            title_changed: false, // F0315: Initialize title change tracking
845            full_screen_program_detected: false,
846            sgr_state: SGRState::default(),
847            dcs_sequence_type: None,
848            dcs_buffer: None,
849            pending_response: None,
850            osc_buffer: None,
851        };
852
853        // Set default tab stops every 8 columns
854        for i in (8..width).step_by(8) {
855            if i < state.tab_stops.len() {
856                state.tab_stops[i] = true;
857            }
858        }
859
860        state
861    }
862
863    pub fn get_active_buffer(&mut self) -> &mut TerminalScreenBuffer {
864        if self.use_alternate_screen {
865            &mut self.alternate_buffer
866        } else {
867            &mut self.primary_buffer
868        }
869    }
870
871    pub fn get_active_buffer_ref(&self) -> &TerminalScreenBuffer {
872        if self.use_alternate_screen {
873            &self.alternate_buffer
874        } else {
875            &self.primary_buffer
876        }
877    }
878
879    pub fn get_active_screen(&mut self) -> &mut Vec<Vec<TerminalCell>> {
880        &mut self.get_active_buffer().content
881    }
882
883    pub fn get_active_screen_ref(&self) -> &Vec<Vec<TerminalCell>> {
884        &self.get_active_buffer_ref().content
885    }
886
887    pub fn get_cursor(&self) -> &CursorState {
888        &self.get_active_buffer_ref().cursor
889    }
890
891    pub fn get_cursor_mut(&mut self) -> &mut CursorState {
892        &mut self.get_active_buffer().cursor
893    }
894
895    /// F0305: Cursor Management System - Save cursor position and attributes
896    pub fn save_cursor(&mut self) {
897        let current_cursor = self.get_cursor().clone();
898        self.cursor_save_stack.push(current_cursor);
899    }
900
901    /// F0305: Cursor Management System - Restore cursor position and attributes
902    pub fn restore_cursor(&mut self) {
903        if let Some(saved_cursor) = self.cursor_save_stack.pop() {
904            let screen_width = self.screen_width;
905            let screen_height = self.screen_height;
906            let cursor = self.get_cursor_mut();
907            cursor.x = saved_cursor.x.min(screen_width.saturating_sub(1));
908            cursor.y = saved_cursor.y.min(screen_height.saturating_sub(1));
909            cursor.visible = saved_cursor.visible;
910            cursor.style = saved_cursor.style;
911        }
912    }
913
914    /// F0305: Set cursor position with bounds checking
915    pub fn set_cursor_position(&mut self, x: usize, y: usize) {
916        let screen_width = self.screen_width;
917        let screen_height = self.screen_height;
918        let origin_mode = self.mode.origin_mode;
919        let region_top = self.scroll_region.top;
920        let region_bottom = self.scroll_region.bottom;
921
922        let cursor = self.get_cursor_mut();
923
924        // F0308: Handle origin mode (DECOM) - coordinates relative to scrolling region
925        if origin_mode {
926            // In origin mode, coordinates are relative to the scrolling region
927            // Clamp Y to scrolling region bounds
928            cursor.y = (region_top + y).min(region_bottom);
929            cursor.x = x.min(screen_width.saturating_sub(1));
930        } else {
931            // Normal mode: coordinates are absolute to screen
932            cursor.x = x.min(screen_width.saturating_sub(1));
933            cursor.y = y.min(screen_height.saturating_sub(1));
934        }
935    }
936
937    /// F0305: Move cursor relatively with bounds checking
938    pub fn move_cursor_relative(&mut self, dx: i32, dy: i32) {
939        let screen_width = self.screen_width;
940        let screen_height = self.screen_height;
941        let cursor = self.get_cursor_mut();
942        let new_x = if dx >= 0 {
943            cursor.x.saturating_add(dx as usize)
944        } else {
945            cursor.x.saturating_sub((-dx) as usize)
946        };
947        let new_y = if dy >= 0 {
948            cursor.y.saturating_add(dy as usize)
949        } else {
950            cursor.y.saturating_sub((-dy) as usize)
951        };
952
953        cursor.x = new_x.min(screen_width.saturating_sub(1));
954        cursor.y = new_y.min(screen_height.saturating_sub(1));
955    }
956
957    /// F0305: Set cursor visibility
958    pub fn set_cursor_visibility(&mut self, visible: bool) {
959        self.get_cursor_mut().visible = visible;
960    }
961
962    /// F0305: Set cursor style
963    pub fn set_cursor_style(&mut self, style: CursorStyle) {
964        self.get_cursor_mut().style = style;
965    }
966
967    /// F0305: Move cursor to column (absolute positioning)
968    pub fn set_cursor_column(&mut self, col: usize) {
969        let screen_width = self.screen_width;
970        let cursor = self.get_cursor_mut();
971        cursor.x = col.min(screen_width.saturating_sub(1));
972    }
973
974    /// F0305: Move cursor to line (absolute positioning)
975    pub fn set_cursor_line(&mut self, line: usize) {
976        let screen_height = self.screen_height;
977        let cursor = self.get_cursor_mut();
978        cursor.y = line.min(screen_height.saturating_sub(1));
979    }
980
981    /// F0305: Move cursor up with bounds checking
982    pub fn cursor_up(&mut self, lines: usize) {
983        let cursor = self.get_cursor_mut();
984        cursor.y = cursor.y.saturating_sub(lines);
985    }
986
987    /// F0305: Move cursor down with bounds checking
988    pub fn cursor_down(&mut self, lines: usize) {
989        let screen_height = self.screen_height;
990        let cursor = self.get_cursor_mut();
991        cursor.y = (cursor.y + lines).min(screen_height.saturating_sub(1));
992    }
993
994    /// F0305: Move cursor left with bounds checking
995    pub fn cursor_left(&mut self, cols: usize) {
996        let cursor = self.get_cursor_mut();
997        cursor.x = cursor.x.saturating_sub(cols);
998    }
999
1000    /// F0305: Move cursor right with bounds checking
1001    pub fn cursor_right(&mut self, cols: usize) {
1002        let screen_width = self.screen_width;
1003        let cursor = self.get_cursor_mut();
1004        cursor.x = (cursor.x + cols).min(screen_width.saturating_sub(1));
1005    }
1006
1007    /// F0305: Move cursor to beginning of line
1008    pub fn cursor_to_line_start(&mut self) {
1009        self.get_cursor_mut().x = 0;
1010    }
1011
1012    /// F0305: Move cursor to next line (carriage return + line feed)
1013    pub fn cursor_next_line(&mut self, lines: usize) {
1014        self.cursor_down(lines);
1015        self.cursor_to_line_start();
1016    }
1017
1018    /// F0305: Move cursor to previous line
1019    pub fn cursor_previous_line(&mut self, lines: usize) {
1020        self.cursor_up(lines);
1021        self.cursor_to_line_start();
1022    }
1023
1024    /// F0313: Tab forward to next tab stop
1025    pub fn tab_forward(&mut self) {
1026        let cursor_x = self.get_cursor().x;
1027        let screen_width = self.screen_width;
1028
1029        // Find next tab stop
1030        for x in (cursor_x + 1)..screen_width {
1031            if x < self.tab_stops.len() && self.tab_stops[x] {
1032                self.get_cursor_mut().x = x;
1033                return;
1034            }
1035        }
1036
1037        // No tab stop found, move to end of line
1038        self.get_cursor_mut().x = screen_width.saturating_sub(1);
1039    }
1040
1041    /// F0313: Tab backward to previous tab stop
1042    pub fn tab_backward(&mut self) {
1043        let cursor_x = self.get_cursor().x;
1044
1045        // Find previous tab stop
1046        if cursor_x > 0 {
1047            for x in (0..cursor_x).rev() {
1048                if x < self.tab_stops.len() && self.tab_stops[x] {
1049                    self.get_cursor_mut().x = x;
1050                    return;
1051                }
1052            }
1053        }
1054
1055        // No tab stop found, move to beginning of line
1056        self.get_cursor_mut().x = 0;
1057    }
1058
1059    /// F0314: Set line attribute for current line
1060    pub fn set_line_attribute(&mut self, attribute: LineAttribute) {
1061        let cursor_y = self.get_cursor().y;
1062        let buffer = if self.use_alternate_screen {
1063            &mut self.alternate_buffer
1064        } else {
1065            &mut self.primary_buffer
1066        };
1067
1068        if cursor_y < buffer.line_attributes.len() {
1069            buffer.line_attributes[cursor_y] = attribute;
1070        }
1071    }
1072
1073    /// F0314: Get line attribute for specific line
1074    pub fn get_line_attribute(&self, line: usize) -> LineAttribute {
1075        let buffer = if self.use_alternate_screen {
1076            &self.alternate_buffer
1077        } else {
1078            &self.primary_buffer
1079        };
1080
1081        buffer
1082            .line_attributes
1083            .get(line)
1084            .copied()
1085            .unwrap_or(LineAttribute::Normal)
1086    }
1087
1088    /// F0314: Set double-width line (DECDWL)
1089    pub fn set_double_width_line(&mut self) {
1090        self.set_line_attribute(LineAttribute::DoubleWidth);
1091    }
1092
1093    /// F0314: Set double-height line top half (DECDHL top)
1094    pub fn set_double_height_line_top(&mut self) {
1095        self.set_line_attribute(LineAttribute::DoubleHeightTop);
1096    }
1097
1098    /// F0314: Set double-height line bottom half (DECDHL bottom)
1099    pub fn set_double_height_line_bottom(&mut self) {
1100        self.set_line_attribute(LineAttribute::DoubleHeightBottom);
1101    }
1102
1103    /// F0314: Reset line to normal (single-width, single-height)
1104    pub fn set_normal_line(&mut self) {
1105        self.set_line_attribute(LineAttribute::Normal);
1106    }
1107
1108    /// F0307: Set scrolling region (DECSTBM - Set Top and Bottom Margins)
1109    pub fn set_scrolling_region(&mut self, top: Option<usize>, bottom: Option<usize>) {
1110        let screen_height = self.screen_height;
1111
1112        // Convert 1-based VT coordinates to 0-based internal coordinates
1113        let new_top = top.map(|t| t.saturating_sub(1)).unwrap_or(0);
1114        let new_bottom = bottom
1115            .map(|b| b.saturating_sub(1))
1116            .unwrap_or(screen_height.saturating_sub(1));
1117
1118        // Validate region bounds
1119        if new_top < screen_height && new_bottom < screen_height && new_top <= new_bottom {
1120            self.scroll_region.top = new_top;
1121            self.scroll_region.bottom = new_bottom;
1122        }
1123        // If invalid bounds, reset to full screen
1124        else {
1125            self.scroll_region.top = 0;
1126            self.scroll_region.bottom = screen_height.saturating_sub(1);
1127        }
1128    }
1129
1130    /// F0307: Reset scrolling region to full screen
1131    pub fn reset_scrolling_region(&mut self) {
1132        self.scroll_region.top = 0;
1133        self.scroll_region.bottom = self.screen_height.saturating_sub(1);
1134    }
1135
1136    /// F0307: Scroll up within the scrolling region
1137    pub fn scroll_up_in_region(&mut self, lines: usize) {
1138        if lines == 0 {
1139            return;
1140        }
1141
1142        let top = self.scroll_region.top;
1143        let bottom = self.scroll_region.bottom;
1144        let screen_width = self.screen_width;
1145
1146        // Move lines up within the region
1147        for _ in 0..lines {
1148            // Get buffer once for each iteration to avoid borrow checker issues
1149            {
1150                let buffer = self.get_active_buffer();
1151                if top <= bottom && top < buffer.content.len() && bottom < buffer.content.len() {
1152                    // Remove the top line of the scrolling region
1153                    let _removed_line = buffer.content.remove(top);
1154
1155                    // Add a blank line at the bottom of the scrolling region
1156                    if bottom < buffer.content.len() {
1157                        let width = if !buffer.content.is_empty() {
1158                            buffer.content[0].len()
1159                        } else {
1160                            screen_width
1161                        };
1162                        let blank_line = vec![TerminalCell::default(); width];
1163                        buffer.content.insert(bottom, blank_line);
1164                    } else {
1165                        // If we're at the end, just push a new line
1166                        let blank_line = vec![TerminalCell::default(); screen_width];
1167                        buffer.content.push(blank_line);
1168                    }
1169                }
1170            }
1171        }
1172    }
1173
1174    /// F0307: Scroll down within the scrolling region
1175    pub fn scroll_down_in_region(&mut self, lines: usize) {
1176        if lines == 0 {
1177            return;
1178        }
1179
1180        let top = self.scroll_region.top;
1181        let bottom = self.scroll_region.bottom;
1182        let screen_width = self.screen_width;
1183
1184        // Move lines down within the region
1185        for _ in 0..lines {
1186            // Get buffer once for each iteration to avoid borrow checker issues
1187            {
1188                let buffer = self.get_active_buffer();
1189                if top <= bottom && top < buffer.content.len() && bottom < buffer.content.len() {
1190                    // Remove the bottom line of the scrolling region
1191                    if bottom < buffer.content.len() {
1192                        let _removed_line = buffer.content.remove(bottom);
1193                    }
1194
1195                    // Add a blank line at the top of the scrolling region
1196                    let blank_line = vec![TerminalCell::default(); screen_width];
1197                    buffer.content.insert(top, blank_line);
1198                }
1199            }
1200        }
1201    }
1202
1203    /// F0307: Check if cursor is within scrolling region
1204    pub fn is_cursor_in_scrolling_region(&self) -> bool {
1205        let cursor_y = self.get_cursor().y;
1206        cursor_y >= self.scroll_region.top && cursor_y <= self.scroll_region.bottom
1207    }
1208
1209    /// F0307: Handle line feed with scrolling region awareness
1210    pub fn line_feed_with_scrolling(&mut self) {
1211        let current_y = self.get_cursor().y;
1212        let bottom = self.scroll_region.bottom;
1213
1214        // If cursor is at the bottom of the scrolling region, scroll up
1215        if current_y >= bottom {
1216            self.scroll_up_in_region(1);
1217            // Keep cursor at bottom of scrolling region
1218            self.get_cursor_mut().y = bottom;
1219        } else {
1220            // Normal line feed within the scrolling region
1221            self.get_cursor_mut().y = (current_y + 1).min(bottom);
1222        }
1223    }
1224
1225    /// F0307: Handle reverse line feed with scrolling region awareness
1226    pub fn reverse_line_feed_with_scrolling(&mut self) {
1227        let current_y = self.get_cursor().y;
1228        let top = self.scroll_region.top;
1229
1230        // If cursor is at the top of the scrolling region, scroll down
1231        if current_y <= top {
1232            self.scroll_down_in_region(1);
1233            // Keep cursor at top of scrolling region
1234            self.get_cursor_mut().y = top;
1235        } else {
1236            // Normal reverse line feed within the scrolling region
1237            self.get_cursor_mut().y = current_y.saturating_sub(1).max(top);
1238        }
1239    }
1240
1241    /// F0308: Insert character at cursor position (IRM - Insert/Replace Mode)
1242    pub fn insert_character_at_cursor(&mut self) {
1243        let cursor_x = self.get_cursor().x;
1244        let cursor_y = self.get_cursor().y;
1245        let screen_width = self.screen_width;
1246
1247        let buffer = self.get_active_buffer();
1248        if cursor_y < buffer.content.len() && cursor_x <= buffer.content[cursor_y].len() {
1249            // Shift all characters to the right from cursor position
1250            let line = &mut buffer.content[cursor_y];
1251            if cursor_x < line.len() {
1252                // Insert a blank character at cursor position, shifting others right
1253                let blank_cell = TerminalCell::default();
1254                line.insert(cursor_x, blank_cell);
1255
1256                // Keep line length within screen width by removing rightmost character if needed
1257                if line.len() > screen_width {
1258                    line.truncate(screen_width);
1259                }
1260            }
1261        }
1262    }
1263
1264    /// F0308: Delete character at cursor position (DCH command support)
1265    pub fn delete_character_at_cursor(&mut self, count: usize) {
1266        let cursor_x = self.get_cursor().x;
1267        let cursor_y = self.get_cursor().y;
1268        let screen_width = self.screen_width;
1269
1270        let buffer = self.get_active_buffer();
1271        if cursor_y < buffer.content.len() {
1272            let line = &mut buffer.content[cursor_y];
1273            for _ in 0..count {
1274                if cursor_x < line.len() {
1275                    line.remove(cursor_x);
1276                }
1277            }
1278
1279            // Fill line with blank characters to maintain screen width
1280            while line.len() < screen_width {
1281                line.push(TerminalCell::default());
1282            }
1283        }
1284    }
1285
1286    /// F0308: Get appropriate escape sequence for cursor key based on cursor key mode
1287    pub fn get_cursor_key_sequence(&self, key: &str) -> String {
1288        if self.mode.cursor_key_mode {
1289            // Application cursor keys (DECCKM enabled)
1290            match key {
1291                "up" => "\x1bOA".to_string(),
1292                "down" => "\x1bOB".to_string(),
1293                "right" => "\x1bOC".to_string(),
1294                "left" => "\x1bOD".to_string(),
1295                "home" => "\x1bOH".to_string(),
1296                "end" => "\x1bOF".to_string(),
1297                _ => format!("\x1b[{}", key), // Fallback to normal mode
1298            }
1299        } else {
1300            // Normal cursor keys (DECCKM disabled)
1301            match key {
1302                "up" => "\x1b[A".to_string(),
1303                "down" => "\x1b[B".to_string(),
1304                "right" => "\x1b[C".to_string(),
1305                "left" => "\x1b[D".to_string(),
1306                "home" => "\x1b[H".to_string(),
1307                "end" => "\x1b[F".to_string(),
1308                _ => format!("\x1b[{}", key),
1309            }
1310        }
1311    }
1312
1313    /// F0308: Get appropriate escape sequence for keypad key based on keypad mode
1314    pub fn get_keypad_sequence(&self, key: &str) -> String {
1315        if self.mode.keypad_mode {
1316            // Application keypad (DECPAM enabled)
1317            match key {
1318                "0" => "\x1bOp".to_string(),
1319                "1" => "\x1bOq".to_string(),
1320                "2" => "\x1bOr".to_string(),
1321                "3" => "\x1bOs".to_string(),
1322                "4" => "\x1bOt".to_string(),
1323                "5" => "\x1bOu".to_string(),
1324                "6" => "\x1bOv".to_string(),
1325                "7" => "\x1bOw".to_string(),
1326                "8" => "\x1bOx".to_string(),
1327                "9" => "\x1bOy".to_string(),
1328                "." => "\x1bOn".to_string(),
1329                "+" => "\x1bOk".to_string(),
1330                "-" => "\x1bOm".to_string(),
1331                "*" => "\x1bOj".to_string(),
1332                "/" => "\x1bOo".to_string(),
1333                "=" => "\x1bOX".to_string(),
1334                "enter" => "\x1bOM".to_string(),
1335                _ => key.to_string(), // Fallback to literal key
1336            }
1337        } else {
1338            // Normal keypad (DECPAM disabled) - just return the key
1339            key.to_string()
1340        }
1341    }
1342
1343    /// F0308: Handle linefeed/newline mode (LNM) - affects how newlines are processed
1344    pub fn process_newline(&mut self) {
1345        if self.mode.local_echo_mode {
1346            // LNM enabled: Newline acts as CR+LF
1347            self.get_cursor_mut().x = 0; // Carriage return
1348            self.line_feed_with_scrolling(); // Line feed
1349        } else {
1350            // LNM disabled: Newline is just LF
1351            self.line_feed_with_scrolling();
1352        }
1353    }
1354
1355    /// F0312: Switch to alternate screen buffer with proper isolation
1356    pub fn switch_to_alternate_screen(&mut self) {
1357        if !self.use_alternate_screen {
1358            self.use_alternate_screen = true;
1359            self.full_screen_program_detected = true;
1360            // Alternate screen starts clean but preserves previous content
1361            // Only clear if explicitly requested (like mode 1047/1049)
1362        }
1363    }
1364
1365    /// F0312: Switch to primary screen buffer maintaining buffer isolation
1366    pub fn switch_to_primary_screen(&mut self) {
1367        if self.use_alternate_screen {
1368            self.use_alternate_screen = false;
1369            // Primary screen content is preserved during alternate screen usage
1370        }
1371    }
1372
1373    /// F0312: Clear alternate screen buffer explicitly
1374    pub fn clear_alternate_screen(&mut self) {
1375        self.alternate_buffer.clear_screen();
1376    }
1377
1378    /// F0312: Verify buffer isolation - ensure buffers don't share content
1379    pub fn verify_buffer_isolation(&self) -> bool {
1380        // Buffers should have independent content structures
1381        !self.primary_buffer.content.is_empty() || !self.alternate_buffer.content.is_empty()
1382    }
1383
1384    pub fn scroll_up(&mut self, lines: usize) {
1385        for _ in 0..lines {
1386            self.get_active_buffer().scroll_up_one_line();
1387        }
1388    }
1389
1390    pub fn scroll_down(&mut self, lines: usize) {
1391        for _ in 0..lines {
1392            self.get_active_buffer().scroll_down_one_line();
1393        }
1394    }
1395
1396    pub fn resize(&mut self, new_width: usize, new_height: usize) {
1397        self.screen_width = new_width;
1398        self.screen_height = new_height;
1399
1400        // Resize both screen buffers
1401        self.primary_buffer.resize(new_width, new_height);
1402        self.alternate_buffer.resize(new_width, new_height);
1403
1404        // Update scroll region
1405        self.scroll_region.bottom = new_height.saturating_sub(1);
1406
1407        // Resize and reset tab stops
1408        self.tab_stops = vec![false; new_width];
1409        for i in (8..new_width).step_by(8) {
1410            if i < self.tab_stops.len() {
1411                self.tab_stops[i] = true;
1412            }
1413        }
1414    }
1415
1416    pub fn clear_screen(&mut self) {
1417        self.get_active_buffer().clear_screen();
1418    }
1419
1420    pub fn clear_line(&mut self, line: usize) {
1421        if line < self.screen_height {
1422            let screen = self.get_active_screen();
1423            for cell in &mut screen[line] {
1424                *cell = TerminalCell::default();
1425            }
1426        }
1427    }
1428
1429    /// Process DCS query sequences
1430    pub fn process_dcs_query(&mut self, data: &str) {
1431        match data {
1432            "1c" => {
1433                // Terminal ID query response
1434                self.pending_response = Some("\x1b[?6c".to_string());
1435            }
1436            "2c" => {
1437                // Secondary device attributes
1438                self.pending_response = Some("\x1b[>0;276;0c".to_string());
1439            }
1440            _ => {
1441                log::debug!("Unknown DCS query: {}", data);
1442            }
1443        }
1444    }
1445
1446    /// Process DCS extended capability sequences
1447    pub fn process_dcs_extended(&mut self, data: &str) {
1448        // Extended capabilities like sixel graphics, ReGIS, etc.
1449        // For now, just log for debugging
1450        log::debug!("DCS extended capability: {}", data);
1451    }
1452
1453    /// F0310: Check if any mouse reporting mode is active
1454    pub fn is_mouse_reporting_enabled(&self) -> bool {
1455        self.mode.mouse_x10_mode
1456            || self.mode.mouse_normal_mode
1457            || self.mode.mouse_button_event_mode
1458            || self.mode.mouse_any_event_mode
1459    }
1460
1461    /// F0310: Get the current active mouse reporting mode
1462    pub fn get_mouse_reporting_mode(&self) -> Option<&str> {
1463        if self.mode.mouse_x10_mode {
1464            Some("X10")
1465        } else if self.mode.mouse_button_event_mode {
1466            Some("ButtonEvent")
1467        } else if self.mode.mouse_any_event_mode {
1468            Some("AnyEvent")
1469        } else if self.mode.mouse_normal_mode {
1470            Some("Normal")
1471        } else {
1472            None
1473        }
1474    }
1475
1476    /// F0310: Generate mouse report sequence for xterm compatibility
1477    pub fn generate_mouse_report(
1478        &self,
1479        event_type: MouseEventType,
1480        x: usize,
1481        y: usize,
1482        button: Option<MouseButton>,
1483        modifiers: MouseModifiers,
1484    ) -> Option<String> {
1485        if !self.is_mouse_reporting_enabled() {
1486            return None;
1487        }
1488
1489        // Convert coordinates to 1-based (xterm convention)
1490        let x = (x + 1).min(255); // Clamp to valid range
1491        let y = (y + 1).min(255); // Clamp to valid range
1492
1493        if self.mode.mouse_sgr_mode {
1494            // SGR (1006) extended reporting - supports coordinates > 223
1495            self.generate_sgr_mouse_report(event_type, x, y, button, modifiers)
1496        } else {
1497            // Standard reporting (X10, Normal, ButtonEvent, AnyEvent)
1498            self.generate_standard_mouse_report(event_type, x, y, button, modifiers)
1499        }
1500    }
1501
1502    /// F0310: Generate standard mouse report (modes 1000, 1002, 1003)
1503    fn generate_standard_mouse_report(
1504        &self,
1505        event_type: MouseEventType,
1506        x: usize,
1507        y: usize,
1508        button: Option<MouseButton>,
1509        modifiers: MouseModifiers,
1510    ) -> Option<String> {
1511        let mut cb = 0u8; // Control byte
1512
1513        // Set button bits
1514        match button {
1515            Some(MouseButton::Left) => cb |= 0,
1516            Some(MouseButton::Middle) => cb |= 1,
1517            Some(MouseButton::Right) => cb |= 2,
1518            Some(MouseButton::WheelUp) => cb |= 64,
1519            Some(MouseButton::WheelDown) => cb |= 65,
1520            Some(MouseButton::WheelLeft) => cb |= 66,
1521            Some(MouseButton::WheelRight) => cb |= 67,
1522            None => {}
1523        }
1524
1525        // Set modifier bits
1526        if modifiers.shift {
1527            cb |= 4;
1528        }
1529        if modifiers.meta {
1530            cb |= 8;
1531        }
1532        if modifiers.ctrl {
1533            cb |= 16;
1534        }
1535
1536        // Set event type bits
1537        match event_type {
1538            MouseEventType::Press => {} // Default - no additional bits
1539            MouseEventType::Release => {
1540                if self.mode.mouse_x10_mode {
1541                    return None; // X10 mode doesn't report releases
1542                }
1543                cb |= 3; // Release marker
1544            }
1545            MouseEventType::Motion => {
1546                if !self.mode.mouse_any_event_mode {
1547                    return None; // Only AnyEvent mode reports motion
1548                }
1549                cb |= 32; // Motion marker
1550            }
1551            MouseEventType::Wheel => {
1552                // Wheel events already handled in button assignment
1553            }
1554        }
1555
1556        // Add base offset
1557        cb += 32;
1558
1559        // Generate escape sequence
1560        Some(format!(
1561            "\x1b[M{}{}{}",
1562            cb as char,
1563            (x + 32) as u8 as char,
1564            (y + 32) as u8 as char
1565        ))
1566    }
1567
1568    /// F0310: Generate SGR mouse report (mode 1006)
1569    fn generate_sgr_mouse_report(
1570        &self,
1571        event_type: MouseEventType,
1572        x: usize,
1573        y: usize,
1574        button: Option<MouseButton>,
1575        modifiers: MouseModifiers,
1576    ) -> Option<String> {
1577        let mut cb = 0u8;
1578
1579        // Set button bits
1580        match button {
1581            Some(MouseButton::Left) => cb |= 0,
1582            Some(MouseButton::Middle) => cb |= 1,
1583            Some(MouseButton::Right) => cb |= 2,
1584            Some(MouseButton::WheelUp) => cb |= 64,
1585            Some(MouseButton::WheelDown) => cb |= 65,
1586            Some(MouseButton::WheelLeft) => cb |= 66,
1587            Some(MouseButton::WheelRight) => cb |= 67,
1588            None => {}
1589        }
1590
1591        // Set modifier bits
1592        if modifiers.shift {
1593            cb |= 4;
1594        }
1595        if modifiers.meta {
1596            cb |= 8;
1597        }
1598        if modifiers.ctrl {
1599            cb |= 16;
1600        }
1601
1602        // Set motion bit for motion events
1603        if event_type == MouseEventType::Motion && self.mode.mouse_any_event_mode {
1604            cb |= 32;
1605        }
1606
1607        // SGR format: ESC[<Cb;Cx;CyM/m (M=press, m=release)
1608        let end_char = match event_type {
1609            MouseEventType::Press | MouseEventType::Motion | MouseEventType::Wheel => 'M',
1610            MouseEventType::Release => 'm',
1611        };
1612
1613        Some(format!("\x1b[<{};{};{}{}", cb, x, y, end_char))
1614    }
1615}
1616
1617/// F0304: Terminal Message Processor - Handles TerminalMessage enum operations
1618pub struct TerminalMessageProcessor {
1619    pub ansi_processor: AnsiProcessor,
1620    pub message_queue: Vec<TerminalMessage>,
1621    pub pending_responses: Vec<String>,
1622}
1623
1624impl Default for TerminalMessageProcessor {
1625    fn default() -> Self {
1626        Self::new()
1627    }
1628}
1629
1630impl TerminalMessageProcessor {
1631    pub fn new() -> Self {
1632        TerminalMessageProcessor {
1633            ansi_processor: AnsiProcessor::new(),
1634            message_queue: Vec::new(),
1635            pending_responses: Vec::new(),
1636        }
1637    }
1638
1639    /// Process a terminal message and update terminal state
1640    pub fn process_message(&mut self, message: TerminalMessage) {
1641        match message {
1642            TerminalMessage::ProcessBytes(bytes) => {
1643                self.ansi_processor.process_bytes(&bytes);
1644            }
1645            TerminalMessage::SendInput(input) => {
1646                // Send input to terminal - would be handled by PTY in real implementation
1647                log::debug!("Terminal input: {}", input);
1648            }
1649            TerminalMessage::ResizeTerminal { width, height } => {
1650                self.ansi_processor.resize_screen(width, height);
1651            }
1652            TerminalMessage::SwitchScreenBuffer { to_alternate } => {
1653                if to_alternate {
1654                    self.ansi_processor
1655                        .terminal_state
1656                        .switch_to_alternate_screen();
1657                } else {
1658                    self.ansi_processor
1659                        .terminal_state
1660                        .switch_to_primary_screen();
1661                }
1662            }
1663            TerminalMessage::ClearScreen { mode } => match mode {
1664                ClearMode::Entire => self.ansi_processor.terminal_state.clear_screen(),
1665                ClearMode::FromCursor => self
1666                    .ansi_processor
1667                    .terminal_state
1668                    .get_active_buffer()
1669                    .clear_from_cursor_to_end(),
1670                ClearMode::ToCursor => self
1671                    .ansi_processor
1672                    .terminal_state
1673                    .get_active_buffer()
1674                    .clear_from_beginning_to_cursor(),
1675                ClearMode::Scrollback => {
1676                    self.ansi_processor
1677                        .terminal_state
1678                        .get_active_buffer()
1679                        .scrollback
1680                        .clear();
1681                }
1682            },
1683            TerminalMessage::MoveCursor { x, y } => {
1684                self.ansi_processor.terminal_state.set_cursor_position(x, y);
1685            }
1686            TerminalMessage::MoveCursorRelative { dx, dy } => {
1687                self.ansi_processor
1688                    .terminal_state
1689                    .move_cursor_relative(dx, dy);
1690            }
1691            TerminalMessage::SaveCursor => {
1692                self.ansi_processor.terminal_state.save_cursor();
1693            }
1694            TerminalMessage::RestoreCursor => {
1695                self.ansi_processor.terminal_state.restore_cursor();
1696            }
1697            TerminalMessage::SetCursorVisibility { visible } => {
1698                self.ansi_processor
1699                    .terminal_state
1700                    .set_cursor_visibility(visible);
1701            }
1702            TerminalMessage::SetCursorStyle { style } => {
1703                self.ansi_processor.terminal_state.set_cursor_style(style);
1704            }
1705            TerminalMessage::SetCursorColumn { col } => {
1706                self.ansi_processor.terminal_state.set_cursor_column(col);
1707            }
1708            TerminalMessage::SetCursorLine { line } => {
1709                self.ansi_processor.terminal_state.set_cursor_line(line);
1710            }
1711            TerminalMessage::CursorUp { lines } => {
1712                self.ansi_processor.terminal_state.cursor_up(lines);
1713            }
1714            TerminalMessage::CursorDown { lines } => {
1715                self.ansi_processor.terminal_state.cursor_down(lines);
1716            }
1717            TerminalMessage::CursorLeft { cols } => {
1718                self.ansi_processor.terminal_state.cursor_left(cols);
1719            }
1720            TerminalMessage::CursorRight { cols } => {
1721                self.ansi_processor.terminal_state.cursor_right(cols);
1722            }
1723            TerminalMessage::CursorToLineStart => {
1724                self.ansi_processor.terminal_state.cursor_to_line_start();
1725            }
1726            TerminalMessage::CursorNextLine { lines } => {
1727                self.ansi_processor.terminal_state.cursor_next_line(lines);
1728            }
1729            TerminalMessage::CursorPreviousLine { lines } => {
1730                self.ansi_processor
1731                    .terminal_state
1732                    .cursor_previous_line(lines);
1733            }
1734            TerminalMessage::SetMode { mode, enabled } => {
1735                self.set_terminal_mode(mode, enabled);
1736            }
1737            TerminalMessage::SetScrollingRegion { top, bottom } => {
1738                // F0307: Use enhanced scrolling region methods
1739                self.ansi_processor
1740                    .terminal_state
1741                    .set_scrolling_region(Some(top + 1), Some(bottom + 1));
1742            }
1743            TerminalMessage::ResetScrollingRegion => {
1744                // F0307: Reset scrolling region to full screen
1745                self.ansi_processor.terminal_state.reset_scrolling_region();
1746            }
1747            TerminalMessage::ScrollUpInRegion { lines } => {
1748                // F0307: Scroll up within the current scrolling region
1749                self.ansi_processor
1750                    .terminal_state
1751                    .scroll_up_in_region(lines);
1752            }
1753            TerminalMessage::ScrollDownInRegion { lines } => {
1754                // F0307: Scroll down within the current scrolling region
1755                self.ansi_processor
1756                    .terminal_state
1757                    .scroll_down_in_region(lines);
1758            }
1759            TerminalMessage::DeviceStatusReport { report_type } => {
1760                let response = self.generate_device_status_report(report_type);
1761                self.pending_responses.push(response);
1762            }
1763            TerminalMessage::SetTerminalTitle { title } => {
1764                self.ansi_processor.terminal_state.terminal_title = Some(title);
1765            }
1766            TerminalMessage::ContentUpdate {
1767                content,
1768                dirty_regions: _,
1769                replace_mode,
1770            } => {
1771                if replace_mode {
1772                    self.ansi_processor.processed_text = content;
1773                } else {
1774                    self.ansi_processor.processed_text.push_str(&content);
1775                }
1776            }
1777            // Add more message handlers as needed
1778            _ => {
1779                log::debug!("Unhandled terminal message: {:?}", message);
1780            }
1781        }
1782    }
1783
1784    fn set_terminal_mode(&mut self, mode: TerminalModeType, enabled: bool) {
1785        match mode {
1786            TerminalModeType::CursorKeys => {
1787                self.ansi_processor.terminal_state.mode.cursor_key_mode = enabled;
1788            }
1789            TerminalModeType::Keypad => {
1790                self.ansi_processor.terminal_state.mode.keypad_mode = enabled;
1791            }
1792            TerminalModeType::AutoWrap => {
1793                self.ansi_processor.terminal_state.mode.auto_wrap_mode = enabled;
1794            }
1795            TerminalModeType::Origin => {
1796                self.ansi_processor.terminal_state.mode.origin_mode = enabled;
1797            }
1798            TerminalModeType::Insert => {
1799                self.ansi_processor.terminal_state.mode.insert_mode = enabled;
1800            }
1801            TerminalModeType::AlternateScreen => {
1802                if enabled {
1803                    self.ansi_processor
1804                        .terminal_state
1805                        .switch_to_alternate_screen();
1806                } else {
1807                    self.ansi_processor
1808                        .terminal_state
1809                        .switch_to_primary_screen();
1810                }
1811            }
1812            // F0310: Mouse Protocol Support - Enable/disable mouse reporting modes
1813            TerminalModeType::MouseX10 => {
1814                self.ansi_processor.terminal_state.mode.mouse_x10_mode = enabled;
1815            }
1816            TerminalModeType::MouseNormal => {
1817                self.ansi_processor.terminal_state.mode.mouse_normal_mode = enabled;
1818            }
1819            TerminalModeType::MouseButtonEvent => {
1820                self.ansi_processor
1821                    .terminal_state
1822                    .mode
1823                    .mouse_button_event_mode = enabled;
1824            }
1825            TerminalModeType::MouseAnyEvent => {
1826                self.ansi_processor.terminal_state.mode.mouse_any_event_mode = enabled;
1827            }
1828            TerminalModeType::MouseSgr => {
1829                self.ansi_processor.terminal_state.mode.mouse_sgr_mode = enabled;
1830            }
1831            _ => {
1832                log::debug!("Unhandled terminal mode: {:?}", mode);
1833            }
1834        }
1835    }
1836
1837    /// F0311: Generate comprehensive device status reports
1838    fn generate_device_status_report(&self, report_type: DeviceReportType) -> String {
1839        match report_type {
1840            DeviceReportType::Status => "\x1b[0n".to_string(), // Terminal OK (always ready)
1841            DeviceReportType::CursorPosition => {
1842                let cursor = self.ansi_processor.terminal_state.get_cursor();
1843                format!("\x1b[{};{}R", cursor.y + 1, cursor.x + 1)
1844            }
1845            DeviceReportType::PrinterStatus => {
1846                // Printer status - report no printer (always ready)
1847                "\x1b[?10n".to_string()
1848            }
1849            DeviceReportType::UdkStatus => {
1850                // User-Defined Keys status - UDK unlocked
1851                "\x1b[?20n".to_string()
1852            }
1853            DeviceReportType::KeyboardStatus => {
1854                // Keyboard status - North American keyboard
1855                "\x1b[?27;1n".to_string()
1856            }
1857            DeviceReportType::LocatorStatus => {
1858                // Locator (mouse) status - not available
1859                "\x1b[?50n".to_string()
1860            }
1861        }
1862    }
1863
1864    /// Get pending terminal responses (for device queries, etc.)
1865    pub fn get_pending_responses(&mut self) -> Vec<String> {
1866        std::mem::take(&mut self.pending_responses)
1867    }
1868
1869    /// Queue a message for processing
1870    pub fn queue_message(&mut self, message: TerminalMessage) {
1871        self.message_queue.push(message);
1872    }
1873
1874    /// Process all queued messages
1875    pub fn process_queued_messages(&mut self) {
1876        let messages = std::mem::take(&mut self.message_queue);
1877        for message in messages {
1878            self.process_message(message);
1879        }
1880    }
1881}
1882
1883pub struct AnsiProcessor {
1884    pub processed_text: String,
1885    pub terminal_state: TerminalState,
1886    pub use_screen_buffer: bool,
1887    pub alternate_screen_mode: bool, // Legacy compatibility
1888    // F0316: Performance Optimization - Dirty region tracking
1889    previous_screen_state: Option<Vec<Vec<TerminalCell>>>,
1890    _dirty_regions_cache: Vec<DirtyRegion>,
1891    baseline_captured: bool,
1892}
1893
1894impl AnsiProcessor {
1895    pub fn new() -> Self {
1896        Self::with_screen_size(80, 24)
1897    }
1898
1899    pub fn with_screen_size(width: usize, height: usize) -> Self {
1900        AnsiProcessor {
1901            processed_text: String::new(),
1902            terminal_state: TerminalState::new(width, height),
1903            use_screen_buffer: false,
1904            alternate_screen_mode: false,
1905            // F0316: Performance Optimization - Initialize dirty region tracking
1906            previous_screen_state: None,
1907            _dirty_regions_cache: Vec::new(),
1908            baseline_captured: false,
1909        }
1910    }
1911
1912    pub fn set_screen_mode(&mut self, use_screen_buffer: bool) {
1913        self.use_screen_buffer = use_screen_buffer;
1914    }
1915
1916    /// Check if we should replace content instead of appending
1917    pub fn should_replace_content(&self) -> bool {
1918        self.terminal_state.full_screen_program_detected
1919            || self.alternate_screen_mode
1920            || self.terminal_state.use_alternate_screen
1921    }
1922
1923    pub fn resize_screen(&mut self, width: usize, height: usize) {
1924        self.terminal_state.resize(width, height);
1925    }
1926
1927    pub fn get_cursor_x(&self) -> usize {
1928        self.terminal_state.get_cursor().x
1929    }
1930
1931    pub fn get_cursor_y(&self) -> usize {
1932        self.terminal_state.get_cursor().y
1933    }
1934
1935    pub fn detect_full_screen_program(&self) -> bool {
1936        self.terminal_state.full_screen_program_detected
1937    }
1938
1939    pub fn is_using_alternate_screen(&self) -> bool {
1940        self.terminal_state.use_alternate_screen
1941    }
1942
1943    /// Get current screen content for stream integration
1944    /// This feeds PTY terminal content into BoxMux's main differential drawing system
1945    pub fn get_screen_content_for_stream(&self) -> String {
1946        if self.use_screen_buffer {
1947            // Use terminal screen buffer content with proper formatting
1948            self.terminal_state
1949                .get_active_buffer_ref()
1950                .get_content_for_stream()
1951        } else {
1952            // Fall back to processed text for non-screen buffer mode
1953            self.get_processed_text()
1954        }
1955    }
1956
1957    /// Get terminal content lines for stream updates
1958    pub fn get_terminal_content_lines(&self, include_scrollback: bool) -> Vec<String> {
1959        if self.use_screen_buffer {
1960            self.terminal_state
1961                .get_active_buffer_ref()
1962                .to_content_lines(include_scrollback)
1963        } else {
1964            // For non-screen buffer mode, return processed text as lines
1965            self.processed_text.lines().map(|s| s.to_string()).collect()
1966        }
1967    }
1968
1969    /// F0304: Convert current terminal state changes to TerminalMessage
1970    pub fn get_state_changes(&self) -> Vec<TerminalMessage> {
1971        let mut messages = Vec::new();
1972
1973        // Check for pending terminal responses
1974        if let Some(response) = &self.terminal_state.pending_response {
1975            messages.push(TerminalMessage::ContentUpdate {
1976                content: response.clone(),
1977                dirty_regions: vec![],
1978                replace_mode: false,
1979            });
1980        }
1981
1982        // Check for terminal title changes
1983        if let Some(title) = &self.terminal_state.terminal_title {
1984            messages.push(TerminalMessage::SetTerminalTitle {
1985                title: title.clone(),
1986            });
1987        }
1988
1989        // Check for screen buffer mode changes
1990        if self.terminal_state.use_alternate_screen {
1991            messages.push(TerminalMessage::SwitchScreenBuffer { to_alternate: true });
1992        }
1993
1994        messages
1995    }
1996
1997    /// F0304: Create TerminalMessage for content updates with dirty regions
1998    pub fn create_content_update_message(&self, replace_mode: bool) -> TerminalMessage {
1999        let content = if self.use_screen_buffer {
2000            self.get_screen_content_for_stream()
2001        } else {
2002            self.processed_text.clone()
2003        };
2004
2005        // Calculate dirty regions based on recent changes
2006        let dirty_regions = self.calculate_dirty_regions();
2007
2008        TerminalMessage::ContentUpdate {
2009            content,
2010            dirty_regions,
2011            replace_mode,
2012        }
2013    }
2014
2015    /// F0316: Capture baseline screen state for differential drawing
2016    pub fn capture_baseline(&mut self) {
2017        if self.use_screen_buffer {
2018            let current_screen = &self.terminal_state.get_active_buffer_ref().content;
2019            self.previous_screen_state = Some(current_screen.clone());
2020            self.baseline_captured = true;
2021        }
2022    }
2023
2024    /// F0316: Update previous screen state after processing changes
2025    pub fn update_screen_state(&mut self) {
2026        if self.use_screen_buffer && self.baseline_captured {
2027            let current_screen = &self.terminal_state.get_active_buffer_ref().content;
2028            self.previous_screen_state = Some(current_screen.clone());
2029        }
2030    }
2031
2032    /// F0316: Check if baseline has been captured for differential drawing
2033    pub fn has_baseline(&self) -> bool {
2034        self.baseline_captured && self.previous_screen_state.is_some()
2035    }
2036
2037    /// F0318: Get terminal state for character set and other state inspection
2038    pub fn get_terminal_state(&self) -> &TerminalState {
2039        &self.terminal_state
2040    }
2041
2042    /// Calculate dirty regions for efficient screen updates
2043    fn calculate_dirty_regions(&self) -> Vec<DirtyRegion> {
2044        // F0316: Performance Optimization - Proper dirty region calculation
2045        if !self.use_screen_buffer {
2046            // For non-screen buffer mode, mark entire screen as dirty
2047            return vec![DirtyRegion {
2048                x: 0,
2049                y: 0,
2050                width: self.terminal_state.screen_width,
2051                height: self.terminal_state.screen_height,
2052            }];
2053        }
2054
2055        // If no previous state exists or baseline not captured, mark entire screen as dirty
2056        let previous_state = match &self.previous_screen_state {
2057            Some(prev) => prev,
2058            None => {
2059                return vec![DirtyRegion {
2060                    x: 0,
2061                    y: 0,
2062                    width: self.terminal_state.screen_width,
2063                    height: self.terminal_state.screen_height,
2064                }];
2065            }
2066        };
2067
2068        let current_screen = &self.terminal_state.get_active_buffer_ref().content;
2069        let mut dirty_regions = Vec::new();
2070        let mut current_region: Option<DirtyRegion> = None;
2071
2072        // Compare line by line to find changed regions
2073        for y in 0..self.terminal_state.screen_height.min(previous_state.len()) {
2074            let mut line_has_changes = false;
2075            let current_line = &current_screen[y];
2076            let previous_line = &previous_state[y];
2077
2078            // Find the range of changed cells in this line
2079            let mut first_changed: Option<usize> = None;
2080            let mut last_changed: Option<usize> = None;
2081
2082            for x in 0..self
2083                .terminal_state
2084                .screen_width
2085                .min(current_line.len().min(previous_line.len()))
2086            {
2087                if current_line[x] != previous_line[x] {
2088                    if first_changed.is_none() {
2089                        first_changed = Some(x);
2090                    }
2091                    last_changed = Some(x);
2092                    line_has_changes = true;
2093                }
2094            }
2095
2096            if line_has_changes {
2097                let first_x = first_changed.unwrap_or(0);
2098                let last_x = last_changed.unwrap_or(0);
2099                let width = (last_x - first_x + 1).max(1);
2100
2101                // Try to merge with existing region or create new one
2102                match &mut current_region {
2103                    Some(region)
2104                        if region.y + region.height == y
2105                            && region.x == first_x
2106                            && region.width == width =>
2107                    {
2108                        // Extend current region vertically
2109                        region.height += 1;
2110                    }
2111                    Some(region) => {
2112                        // Different area, finalize current region and start new one
2113                        dirty_regions.push(region.clone());
2114                        current_region = Some(DirtyRegion {
2115                            x: first_x,
2116                            y,
2117                            width,
2118                            height: 1,
2119                        });
2120                    }
2121                    None => {
2122                        // Start new region
2123                        current_region = Some(DirtyRegion {
2124                            x: first_x,
2125                            y,
2126                            width,
2127                            height: 1,
2128                        });
2129                    }
2130                }
2131            }
2132        }
2133
2134        // Add final region if exists
2135        if let Some(region) = current_region {
2136            dirty_regions.push(region);
2137        }
2138
2139        // If no changes detected, still return empty vec (no dirty regions)
2140        dirty_regions
2141    }
2142
2143    fn put_char_at_cursor(&mut self, c: char) {
2144        if self.use_screen_buffer
2145            && self.terminal_state.get_cursor().y < self.terminal_state.screen_height
2146            && self.terminal_state.get_cursor().x < self.terminal_state.screen_width
2147        {
2148            // Extract needed values first to avoid borrow checker issues
2149            let cursor_y = self.terminal_state.get_cursor().y;
2150            let cursor_x = self.terminal_state.get_cursor().x;
2151            let reverse_video = self.terminal_state.mode.reverse_video;
2152            let mut cell = self.terminal_state.current_attributes.clone();
2153            cell.character = c;
2154
2155            // F0308: Apply reverse video mode (DECSCNM) globally
2156            if reverse_video {
2157                // Swap foreground and background colors for reverse video effect
2158                std::mem::swap(&mut cell.fg_color, &mut cell.bg_color);
2159
2160                // If no explicit colors were set, use default reverse (white on black becomes black on white)
2161                if cell.fg_color.is_none() && cell.bg_color.is_none() {
2162                    cell.fg_color = Some(0); // Black foreground
2163                    cell.bg_color = Some(15); // White background
2164                }
2165            }
2166
2167            let screen = self.terminal_state.get_active_screen();
2168            screen[cursor_y][cursor_x] = cell;
2169        } else {
2170            self.processed_text.push(c);
2171        }
2172    }
2173
2174    pub fn get_screen_content(&self) -> String {
2175        if self.use_screen_buffer {
2176            let mut content = String::new();
2177            let screen = self.terminal_state.get_active_screen_ref();
2178            for row in screen {
2179                let line: String = row.iter().map(|cell| cell.character).collect();
2180                content.push_str(line.trim_end());
2181                content.push('\n');
2182            }
2183            content
2184        } else {
2185            self.processed_text.clone()
2186        }
2187    }
2188
2189    pub fn process_bytes(&mut self, bytes: &[u8]) {
2190        let mut parser = Parser::new();
2191        for &byte in bytes {
2192            parser.advance(self, byte);
2193        }
2194    }
2195
2196    pub fn process_string(&mut self, text: &str) {
2197        self.process_bytes(text.as_bytes());
2198    }
2199
2200    pub fn get_processed_text(&self) -> String {
2201        if self.use_screen_buffer {
2202            let mut content = String::new();
2203            let screen = self.terminal_state.get_active_screen_ref();
2204            for row in screen {
2205                let line: String = row.iter().map(|cell| cell.character).collect();
2206                content.push_str(line.trim_end());
2207                content.push('\n');
2208            }
2209            content.trim_end().to_string() // Remove trailing newline for consistency
2210        } else {
2211            self.processed_text.clone()
2212        }
2213    }
2214
2215    pub fn clear_processed_text(&mut self) {
2216        self.processed_text.clear();
2217        if !self.use_screen_buffer {
2218            self.terminal_state.get_cursor_mut().x = 0;
2219            self.terminal_state.get_cursor_mut().y = 0;
2220        }
2221    }
2222
2223    pub fn clear_screen_buffer(&mut self) {
2224        self.terminal_state.clear_screen();
2225    }
2226
2227    /// F0306: Enhanced SGR parameter handling with comprehensive color and attribute support
2228    fn apply_sgr_param(&mut self, param: u16) {
2229        match param {
2230            0 => {
2231                // Reset all attributes
2232                self.terminal_state.current_attributes = TerminalCell::default();
2233            }
2234            // Text attributes
2235            1 => self.terminal_state.current_attributes.bold = true,
2236            2 => self.terminal_state.current_attributes.dim = true, // Dim/faint
2237            3 => self.terminal_state.current_attributes.italic = true,
2238            4 => self.terminal_state.current_attributes.underline = true,
2239            5 => self.terminal_state.current_attributes.blink = true, // Slow blink
2240            6 => self.terminal_state.current_attributes.blink = true, // Rapid blink (treat as slow blink)
2241            7 => self.terminal_state.current_attributes.reverse = true,
2242            8 => self.terminal_state.current_attributes.hidden = true, // Concealed characters
2243            9 => self.terminal_state.current_attributes.strikethrough = true,
2244
2245            // Double-width/height characters
2246            10 => { /* Primary font - default */ }
2247            11..=19 => {
2248                // Alternative fonts 1-9 - store font selection
2249                self.terminal_state.current_attributes.font_id = Some((param - 10) as u8);
2250            }
2251            20 => { /* Gothic/Fraktur - rarely supported */ }
2252            21 => {
2253                // Double underline or bold off (depending on implementation)
2254                self.terminal_state.current_attributes.double_underline = true;
2255            }
2256
2257            // Reset attributes
2258            22 => {
2259                // Normal intensity - reset bold and dim
2260                self.terminal_state.current_attributes.bold = false;
2261                self.terminal_state.current_attributes.dim = false;
2262            }
2263            23 => {
2264                // Reset italic and gothic
2265                self.terminal_state.current_attributes.italic = false;
2266            }
2267            24 => {
2268                // Reset underline
2269                self.terminal_state.current_attributes.underline = false;
2270                self.terminal_state.current_attributes.double_underline = false;
2271            }
2272            25 => self.terminal_state.current_attributes.blink = false, // Reset blink
2273            26 => { /* Reserved */ }
2274            27 => self.terminal_state.current_attributes.reverse = false,
2275            28 => self.terminal_state.current_attributes.hidden = false, // Reveal
2276            29 => self.terminal_state.current_attributes.strikethrough = false,
2277
2278            // Standard 8-color foreground (30-37)
2279            30..=37 => self.terminal_state.current_attributes.fg_color = Some((param - 30) as u8),
2280            38 => {
2281                // Extended foreground color (handled in apply_sgr_sequence for 38;5;n and 38;2;r;g;b)
2282                self.terminal_state.sgr_state.expecting_extended_fg = true;
2283            }
2284            39 => self.terminal_state.current_attributes.fg_color = None, // Default foreground
2285
2286            // Standard 8-color background (40-47)
2287            40..=47 => self.terminal_state.current_attributes.bg_color = Some((param - 40) as u8),
2288            48 => {
2289                // Extended background color (handled in apply_sgr_sequence for 48;5;n and 48;2;r;g;b)
2290                self.terminal_state.sgr_state.expecting_extended_bg = true;
2291            }
2292            49 => self.terminal_state.current_attributes.bg_color = None, // Default background
2293
2294            // Additional attributes (50-65)
2295            50 => { /* Reserved */ }
2296            51 => self.terminal_state.current_attributes.framed = true, // Framed
2297            52 => self.terminal_state.current_attributes.encircled = true, // Encircled
2298            53 => self.terminal_state.current_attributes.overlined = true, // Overlined
2299            54 => {
2300                // Reset framed and encircled
2301                self.terminal_state.current_attributes.framed = false;
2302                self.terminal_state.current_attributes.encircled = false;
2303            }
2304            55 => self.terminal_state.current_attributes.overlined = false, // Reset overlined
2305
2306            // Ideogram attributes (60-65) - rarely used
2307            60 => self.terminal_state.current_attributes.ideogram_underline = true,
2308            61 => {
2309                self.terminal_state
2310                    .current_attributes
2311                    .ideogram_double_underline = true
2312            }
2313            62 => self.terminal_state.current_attributes.ideogram_overline = true,
2314            63 => {
2315                self.terminal_state
2316                    .current_attributes
2317                    .ideogram_double_overline = true
2318            }
2319            64 => self.terminal_state.current_attributes.ideogram_stress = true,
2320            65 => {
2321                // Reset ideogram attributes
2322                self.terminal_state.current_attributes.ideogram_underline = false;
2323                self.terminal_state
2324                    .current_attributes
2325                    .ideogram_double_underline = false;
2326                self.terminal_state.current_attributes.ideogram_overline = false;
2327                self.terminal_state
2328                    .current_attributes
2329                    .ideogram_double_overline = false;
2330                self.terminal_state.current_attributes.ideogram_stress = false;
2331            }
2332
2333            // Bright/intense colors (90-97 foreground, 100-107 background)
2334            90..=97 => {
2335                self.terminal_state.current_attributes.fg_color = Some((param - 90 + 8) as u8)
2336            }
2337            100..=107 => {
2338                self.terminal_state.current_attributes.bg_color = Some((param - 100 + 8) as u8)
2339            }
2340
2341            _ => {} // Ignore unknown parameters
2342        }
2343    }
2344
2345    /// F0306: Process complete SGR sequence with extended color support (38;5;n, 38;2;r;g;b, etc.)
2346    fn apply_sgr_sequence(&mut self, params: &Params) {
2347        if params.is_empty() {
2348            self.apply_sgr_param(0); // Reset if no params
2349            return;
2350        }
2351
2352        let mut param_iter = params.iter().flat_map(|slice| slice.iter());
2353
2354        while let Some(&param) = param_iter.next() {
2355            match param {
2356                38 => {
2357                    // Extended foreground color: 38;5;n (256-color) or 38;2;r;g;b (24-bit RGB)
2358                    if let Some(&mode) = param_iter.next() {
2359                        match mode {
2360                            5 => {
2361                                // 256-color palette: 38;5;n
2362                                if let Some(&palette_index) = param_iter.next() {
2363                                    self.terminal_state.current_attributes.fg_color =
2364                                        Some(palette_index as u8);
2365                                }
2366                            }
2367                            2 => {
2368                                // 24-bit RGB: 38;2;r;g;b
2369                                if let (Some(&r), Some(&g), Some(&b)) =
2370                                    (param_iter.next(), param_iter.next(), param_iter.next())
2371                                {
2372                                    // Convert RGB to nearest palette color for now
2373                                    let palette_index =
2374                                        Self::rgb_to_palette(r as u8, g as u8, b as u8);
2375                                    self.terminal_state.current_attributes.fg_color =
2376                                        Some(palette_index);
2377                                }
2378                            }
2379                            _ => {} // Unknown extended color mode
2380                        }
2381                    }
2382                }
2383                48 => {
2384                    // Extended background color: 48;5;n (256-color) or 48;2;r;g;b (24-bit RGB)
2385                    if let Some(&mode) = param_iter.next() {
2386                        match mode {
2387                            5 => {
2388                                // 256-color palette: 48;5;n
2389                                if let Some(&palette_index) = param_iter.next() {
2390                                    self.terminal_state.current_attributes.bg_color =
2391                                        Some(palette_index as u8);
2392                                }
2393                            }
2394                            2 => {
2395                                // 24-bit RGB: 48;2;r;g;b
2396                                if let (Some(&r), Some(&g), Some(&b)) =
2397                                    (param_iter.next(), param_iter.next(), param_iter.next())
2398                                {
2399                                    // Convert RGB to nearest palette color for now
2400                                    let palette_index =
2401                                        Self::rgb_to_palette(r as u8, g as u8, b as u8);
2402                                    self.terminal_state.current_attributes.bg_color =
2403                                        Some(palette_index);
2404                                }
2405                            }
2406                            _ => {} // Unknown extended color mode
2407                        }
2408                    }
2409                }
2410                _ => {
2411                    // Regular SGR parameter
2412                    self.apply_sgr_param(param);
2413                }
2414            }
2415        }
2416    }
2417
2418    /// F0306: Convert 24-bit RGB to nearest 256-color palette index
2419    fn rgb_to_palette(r: u8, g: u8, b: u8) -> u8 {
2420        // Standard colors 0-15 (handled by existing logic)
2421        // 216 color cube: 16-231
2422        // Grayscale: 232-255
2423
2424        // Simple approximation: map RGB to 6x6x6 color cube
2425        let r6 = ((r as f32 / 255.0) * 5.0).round() as u8;
2426        let g6 = ((g as f32 / 255.0) * 5.0).round() as u8;
2427        let b6 = ((b as f32 / 255.0) * 5.0).round() as u8;
2428
2429        16 + (36 * r6) + (6 * g6) + b6
2430    }
2431
2432    // Helper to extract first parameter from Params
2433    fn get_param(params: &Params, index: usize) -> u16 {
2434        if index < params.len() {
2435            if let Some(param_slice) = params.iter().nth(index) {
2436                if !param_slice.is_empty() {
2437                    return param_slice[0];
2438                }
2439            }
2440        }
2441        0
2442    }
2443
2444    /// F0311: Get DEC private mode status for DECRQM queries
2445    fn get_private_mode_status(&self, mode: u16) -> u8 {
2446        let terminal_mode = &self.terminal_state.mode;
2447        match mode {
2448            1 => {
2449                if terminal_mode.cursor_key_mode {
2450                    1
2451                } else {
2452                    2
2453                }
2454            } // DECCKM - Application Cursor Keys
2455            2 => 4, // DECANM - ANSI mode (always permanently set)
2456            3 => 2, // DECCOLM - 80/132 column mode (not supported, permanently reset)
2457            6 => {
2458                if terminal_mode.origin_mode {
2459                    1
2460                } else {
2461                    2
2462                }
2463            } // DECOM - Origin Mode
2464            7 => {
2465                if terminal_mode.auto_wrap_mode {
2466                    1
2467                } else {
2468                    2
2469                }
2470            } // DECAWM - Auto Wrap Mode
2471            25 => {
2472                if self.terminal_state.get_cursor().visible {
2473                    1
2474                } else {
2475                    2
2476                }
2477            } // DECTCEM - Cursor Visible
2478            47 => {
2479                if self.alternate_screen_mode {
2480                    1
2481                } else {
2482                    2
2483                }
2484            } // Alternate Screen (Simple)
2485            1000 => {
2486                if terminal_mode.mouse_x10_mode {
2487                    1
2488                } else {
2489                    2
2490                }
2491            } // Mouse X10 mode
2492            1002 => {
2493                if terminal_mode.mouse_button_event_mode {
2494                    1
2495                } else {
2496                    2
2497                }
2498            } // Mouse Button Event mode
2499            1003 => {
2500                if terminal_mode.mouse_any_event_mode {
2501                    1
2502                } else {
2503                    2
2504                }
2505            } // Mouse Any Event mode
2506            1006 => {
2507                if terminal_mode.mouse_sgr_mode {
2508                    1
2509                } else {
2510                    2
2511                }
2512            } // Mouse SGR mode
2513            1047 => {
2514                if self.alternate_screen_mode {
2515                    1
2516                } else {
2517                    2
2518                }
2519            } // Alternate Screen Buffer (Clear)
2520            1049 => {
2521                if self.alternate_screen_mode {
2522                    1
2523                } else {
2524                    2
2525                }
2526            } // Alternate Screen Buffer (Cursor Save)
2527            2004 => {
2528                if terminal_mode.bracketed_paste_mode {
2529                    1
2530                } else {
2531                    2
2532                }
2533            } // Bracketed Paste Mode
2534            _ => 0, // Mode not recognized
2535        }
2536    }
2537
2538    /// F0311: Get standard mode status for DECRQM queries
2539    fn get_standard_mode_status(&self, mode: u16) -> u8 {
2540        let terminal_mode = &self.terminal_state.mode;
2541        match mode {
2542            4 => {
2543                if terminal_mode.insert_mode {
2544                    1
2545                } else {
2546                    2
2547                }
2548            } // IRM - Insert/Replace Mode
2549            20 => {
2550                if terminal_mode.local_echo_mode {
2551                    1
2552                } else {
2553                    2
2554                }
2555            } // LNM - Line Feed/New Line Mode
2556            _ => 0, // Mode not recognized
2557        }
2558    }
2559
2560    // F0315: Terminal Title Support - Title change detection and consumption methods
2561
2562    /// Check if the terminal title has changed since last consumption
2563    pub fn has_title_changed(&self) -> bool {
2564        self.terminal_state.title_changed
2565    }
2566
2567    /// Get the current terminal title without consuming the change flag
2568    pub fn get_current_terminal_title(&self) -> Option<String> {
2569        self.terminal_state.terminal_title.clone()
2570    }
2571
2572    /// Get the terminal title and mark the change as consumed
2573    pub fn get_and_consume_terminal_title(&mut self) -> Option<String> {
2574        if self.terminal_state.title_changed {
2575            self.terminal_state.title_changed = false;
2576            self.terminal_state.terminal_title.clone()
2577        } else {
2578            None
2579        }
2580    }
2581
2582    /// Get the current icon name
2583    pub fn get_current_icon_name(&self) -> Option<String> {
2584        self.terminal_state.icon_name.clone()
2585    }
2586}
2587
2588impl Perform for AnsiProcessor {
2589    fn print(&mut self, c: char) {
2590        // F0308: Handle insert mode - shift characters right before inserting
2591        if self.use_screen_buffer && self.terminal_state.mode.insert_mode {
2592            self.terminal_state.insert_character_at_cursor();
2593        }
2594
2595        self.put_char_at_cursor(c);
2596        self.terminal_state.get_cursor_mut().x += 1;
2597
2598        // F0308: Handle auto-wrap mode
2599        let screen_width = self.terminal_state.screen_width;
2600        let auto_wrap_enabled = self.terminal_state.mode.auto_wrap_mode;
2601
2602        if self.use_screen_buffer && self.terminal_state.get_cursor().x >= screen_width {
2603            if auto_wrap_enabled {
2604                // Auto-wrap: move to next line
2605                self.terminal_state.get_cursor_mut().x = 0;
2606                self.terminal_state.line_feed_with_scrolling(); // Use scrolling-aware line feed
2607            } else {
2608                // No auto-wrap: keep cursor at right margin
2609                self.terminal_state.get_cursor_mut().x = screen_width.saturating_sub(1);
2610            }
2611        }
2612    }
2613
2614    fn execute(&mut self, byte: u8) {
2615        match byte {
2616            b'\n' => {
2617                if !self.use_screen_buffer {
2618                    self.processed_text.push('\n');
2619                    // Simple line tracking for non-screen buffer mode
2620                    self.terminal_state.get_cursor_mut().y += 1;
2621                    self.terminal_state.get_cursor_mut().x = 0;
2622                } else {
2623                    // F0307: Use scrolling region aware line feed for screen buffer mode
2624                    self.terminal_state.line_feed_with_scrolling();
2625                    // Line feed doesn't reset column in screen buffer mode - that's \r (carriage return)
2626                }
2627            }
2628            b'\r' => {
2629                self.terminal_state.get_cursor_mut().x = 0;
2630            }
2631            b'\t' => {
2632                // F0313: Use proper tab stops for horizontal tab
2633                self.terminal_state.tab_forward();
2634            }
2635            b'\x08' => {
2636                // Backspace
2637                if self.terminal_state.get_cursor().x > 0 {
2638                    self.terminal_state.get_cursor_mut().x -= 1;
2639                    if self.use_screen_buffer
2640                        && self.terminal_state.get_cursor().y < self.terminal_state.screen_height
2641                        && self.terminal_state.get_cursor().x < self.terminal_state.screen_width
2642                    {
2643                        let cursor_y = self.terminal_state.get_cursor().y;
2644                        let cursor_x = self.terminal_state.get_cursor().x;
2645                        let screen = self.terminal_state.get_active_screen();
2646                        screen[cursor_y][cursor_x] = TerminalCell::default();
2647                    } else {
2648                        self.processed_text.pop();
2649                    }
2650                }
2651            }
2652            0x0E => {
2653                // F0318: SO (Shift Out) - Switch to G1 character set
2654                self.terminal_state.active_charset = 1;
2655            }
2656            0x0F => {
2657                // F0318: SI (Shift In) - Switch to G0 character set
2658                self.terminal_state.active_charset = 0;
2659            }
2660            _ => {
2661                // Other control characters - for now just ignore
2662            }
2663        }
2664    }
2665
2666    fn hook(&mut self, params: &Params, intermediates: &[u8], _ignore: bool, c: char) {
2667        // Device Control String (DCS) - Enhanced implementation
2668        match c {
2669            'q' => {
2670                // DCS sequences starting with 'q' - terminal queries
2671                if intermediates.is_empty() && !params.is_empty() {
2672                    let query_type = Self::get_param(params, 0);
2673                    if query_type == 1 {
2674                        // Request terminal ID
2675                        self.terminal_state.pending_response = Some("\x1b[>0;276;0c".to_string());
2676                    }
2677                }
2678            }
2679            '+' => {
2680                // DCS + sequences - extended capabilities
2681                // Store for processing in put() method
2682                self.terminal_state.dcs_sequence_type = Some(c);
2683            }
2684            _ => {
2685                // Store DCS sequence type for processing
2686                self.terminal_state.dcs_sequence_type = Some(c);
2687            }
2688        }
2689    }
2690
2691    fn put(&mut self, byte: u8) {
2692        // Put character in DCS - Enhanced implementation
2693        if self.terminal_state.dcs_buffer.is_none() {
2694            self.terminal_state.dcs_buffer = Some(Vec::new());
2695        }
2696        if let Some(ref mut buffer) = self.terminal_state.dcs_buffer {
2697            buffer.push(byte);
2698            // Limit DCS buffer size to prevent memory issues
2699            if buffer.len() > 4096 {
2700                buffer.clear();
2701                self.terminal_state.dcs_buffer = None;
2702            }
2703        }
2704    }
2705
2706    fn unhook(&mut self) {
2707        // End of DCS - Process accumulated DCS sequence
2708        // Extract data first to avoid borrow checker issues
2709        let dcs_data = self
2710            .terminal_state
2711            .dcs_buffer
2712            .as_ref()
2713            .map(|buffer| String::from_utf8_lossy(buffer).to_string());
2714
2715        if let Some(dcs_type) = self.terminal_state.dcs_sequence_type {
2716            if let Some(data) = dcs_data {
2717                match dcs_type {
2718                    'q' => {
2719                        // Process terminal queries
2720                        self.terminal_state.process_dcs_query(&data);
2721                    }
2722                    '+' => {
2723                        // Process extended capabilities
2724                        self.terminal_state.process_dcs_extended(&data);
2725                    }
2726                    _ => {
2727                        // Log unknown DCS sequence for debugging
2728                        log::debug!("Unknown DCS sequence type: {}", dcs_type);
2729                    }
2730                }
2731            }
2732        }
2733        // Clean up DCS state
2734        self.terminal_state.dcs_sequence_type = None;
2735        self.terminal_state.dcs_buffer = None;
2736    }
2737
2738    fn osc_dispatch(&mut self, params: &[&[u8]], _bell_terminated: bool) {
2739        // Operating System Command - Enhanced implementation
2740        if params.is_empty() {
2741            return;
2742        }
2743
2744        // VTE parser already splits parameters for us
2745        if params.len() >= 2 {
2746            let command = String::from_utf8_lossy(params[0]);
2747            // Concatenate all data parameters (in case of multiple semicolons in data)
2748            let data_parts: Vec<String> = params[1..]
2749                .iter()
2750                .map(|p| String::from_utf8_lossy(p).to_string())
2751                .collect();
2752            let data = data_parts.join(";");
2753
2754            match command.as_ref() {
2755                "0" | "2" => {
2756                    // Set terminal title (0 = both icon and title, 2 = title)
2757                    self.terminal_state.terminal_title = Some(data.to_string());
2758                    self.terminal_state.title_changed = true; // F0315: Mark title as changed
2759                    log::debug!("Terminal title set to: {}", data);
2760                }
2761                "1" => {
2762                    // Set icon name
2763                    self.terminal_state.icon_name = Some(data.to_string());
2764                    log::debug!("Icon name set to: {}", data);
2765                }
2766                "4" => {
2767                    // Set color palette (simplified - just log for now)
2768                    log::debug!("Color palette change: {}", data);
2769                }
2770                "10" => {
2771                    // Set foreground color
2772                    log::debug!("Foreground color change: {}", data);
2773                }
2774                "11" => {
2775                    // Set background color
2776                    log::debug!("Background color change: {}", data);
2777                }
2778                "52" => {
2779                    // Clipboard operations (simplified - just log for security)
2780                    log::debug!("Clipboard operation: {}", data);
2781                }
2782                _ => {
2783                    log::debug!("Unknown OSC command: {} with data: {}", command, data);
2784                }
2785            }
2786        } else if params.len() == 1 {
2787            // Handle single parameter case (might contain semicolon-separated data)
2788            let first_param = String::from_utf8_lossy(params[0]);
2789            let parts: Vec<&str> = first_param.splitn(2, ';').collect();
2790
2791            if parts.len() >= 2 {
2792                match parts[0] {
2793                    "0" | "2" => {
2794                        self.terminal_state.terminal_title = Some(parts[1].to_string());
2795                        self.terminal_state.title_changed = true; // F0315: Mark title as changed
2796                        log::debug!("Terminal title set to: {}", parts[1]);
2797                    }
2798                    "1" => {
2799                        self.terminal_state.icon_name = Some(parts[1].to_string());
2800                        log::debug!("Icon name set to: {}", parts[1]);
2801                    }
2802                    _ => {
2803                        log::debug!("Unknown OSC command: {} with data: {}", parts[0], parts[1]);
2804                    }
2805                }
2806            } else {
2807                log::debug!("Invalid OSC format: {}", first_param);
2808            }
2809        } else {
2810            log::debug!("No OSC data provided");
2811        }
2812    }
2813
2814    fn csi_dispatch(&mut self, params: &Params, _intermediates: &[u8], _ignore: bool, c: char) {
2815        match c {
2816            'm' => {
2817                // SGR - Set Graphics Rendition (colors, bold, etc.)
2818                // F0306: Use enhanced SGR sequence processing
2819                self.apply_sgr_sequence(params);
2820            }
2821            'H' | 'f' => {
2822                // Cursor position - CUP or HVP
2823                let row = if !params.is_empty() {
2824                    Self::get_param(params, 0).max(1)
2825                } else {
2826                    1
2827                };
2828                let col = if params.len() > 1 {
2829                    Self::get_param(params, 1).max(1)
2830                } else {
2831                    1
2832                };
2833
2834                // Direct cursor positioning often indicates full-screen programs
2835                if row == 1 && col == 1 {
2836                    // Home cursor position - very common in full-screen apps
2837                    self.terminal_state.full_screen_program_detected = true;
2838                    self.use_screen_buffer = true;
2839                }
2840
2841                // F0305: Use cursor management system
2842                self.terminal_state.set_cursor_position(
2843                    (col.saturating_sub(1)) as usize,
2844                    (row.saturating_sub(1)) as usize,
2845                );
2846            }
2847            'A' => {
2848                // Cursor up - CUU
2849                let n = if !params.is_empty() {
2850                    Self::get_param(params, 0).max(1)
2851                } else {
2852                    1
2853                };
2854                // F0305: Use cursor management system
2855                self.terminal_state.cursor_up(n as usize);
2856            }
2857            'B' => {
2858                // Cursor down - CUD
2859                let n = if !params.is_empty() {
2860                    Self::get_param(params, 0).max(1)
2861                } else {
2862                    1
2863                };
2864                // F0305: Use cursor management system
2865                self.terminal_state.cursor_down(n as usize);
2866            }
2867            'C' => {
2868                // Cursor forward - CUF
2869                let n = if !params.is_empty() {
2870                    Self::get_param(params, 0).max(1)
2871                } else {
2872                    1
2873                };
2874                // F0305: Use cursor management system
2875                self.terminal_state.cursor_right(n as usize);
2876            }
2877            'D' => {
2878                // Cursor backward - CUB
2879                let n = if !params.is_empty() {
2880                    Self::get_param(params, 0).max(1)
2881                } else {
2882                    1
2883                };
2884                // F0305: Use cursor management system
2885                self.terminal_state.cursor_left(n as usize);
2886            }
2887            'J' => {
2888                // Erase in Display
2889                let n = if !params.is_empty() {
2890                    Self::get_param(params, 0)
2891                } else {
2892                    0
2893                };
2894
2895                // Clear screen commands often indicate full-screen programs
2896                if n == 2 || n == 1 {
2897                    self.terminal_state.full_screen_program_detected = true;
2898                    self.use_screen_buffer = true;
2899                }
2900
2901                if self.use_screen_buffer {
2902                    // Extract values to avoid borrow checker issues
2903                    let cursor_x = self.terminal_state.get_cursor().x;
2904                    let cursor_y = self.terminal_state.get_cursor().y;
2905                    let screen_width = self.terminal_state.screen_width;
2906                    let screen_height = self.terminal_state.screen_height;
2907
2908                    match n {
2909                        0 => {
2910                            // Clear from cursor to end of display
2911                            let screen = self.terminal_state.get_active_screen();
2912                            for y in cursor_y..screen_height {
2913                                let start_x = if y == cursor_y { cursor_x } else { 0 };
2914                                for x in start_x..screen_width {
2915                                    screen[y][x] = TerminalCell::default();
2916                                }
2917                            }
2918                        }
2919                        1 => {
2920                            // Clear from start of display to cursor
2921                            let screen = self.terminal_state.get_active_screen();
2922                            for y in 0..=cursor_y.min(screen_height.saturating_sub(1)) {
2923                                let end_x = if y == cursor_y {
2924                                    cursor_x
2925                                } else {
2926                                    screen_width
2927                                };
2928                                for x in 0..end_x.min(screen_width) {
2929                                    screen[y][x] = TerminalCell::default();
2930                                }
2931                            }
2932                        }
2933                        2 => {
2934                            // Clear entire display - definitely full-screen program
2935                            self.clear_screen_buffer();
2936                        }
2937                        _ => {}
2938                    }
2939                } else if n == 2 {
2940                    self.processed_text.clear();
2941                    self.terminal_state.get_cursor_mut().x = 0;
2942                    self.terminal_state.get_cursor_mut().y = 0;
2943                }
2944            }
2945            'K' => {
2946                // Erase in Line
2947                let n = if !params.is_empty() {
2948                    Self::get_param(params, 0)
2949                } else {
2950                    0
2951                };
2952
2953                if self.use_screen_buffer
2954                    && self.terminal_state.get_cursor().y < self.terminal_state.screen_height
2955                {
2956                    // Extract values to avoid borrow checker issues
2957                    let cursor_x = self.terminal_state.get_cursor().x;
2958                    let cursor_y = self.terminal_state.get_cursor().y;
2959                    let screen_width = self.terminal_state.screen_width;
2960
2961                    let screen = self.terminal_state.get_active_screen();
2962                    match n {
2963                        0 => {
2964                            // Clear from cursor to end of line
2965                            for x in cursor_x..screen_width {
2966                                screen[cursor_y][x] = TerminalCell::default();
2967                            }
2968                        }
2969                        1 => {
2970                            // Clear from start of line to cursor
2971                            for x in 0..=cursor_x.min(screen_width.saturating_sub(1)) {
2972                                screen[cursor_y][x] = TerminalCell::default();
2973                            }
2974                        }
2975                        2 => {
2976                            // Clear entire line
2977                            for x in 0..screen_width {
2978                                screen[cursor_y][x] = TerminalCell::default();
2979                            }
2980                        }
2981                        _ => {}
2982                    }
2983                }
2984            }
2985            'h' => {
2986                // Set Mode
2987                if _intermediates.contains(&b'?') && !params.is_empty() {
2988                    // DEC private mode set
2989                    let mode = Self::get_param(params, 0);
2990                    match mode {
2991                        1 => {
2992                            // DECCKM - Application Cursor Keys
2993                            self.terminal_state.mode.cursor_key_mode = true;
2994                        }
2995                        6 => {
2996                            // DECOM - Origin Mode
2997                            self.terminal_state.mode.origin_mode = true;
2998                            // Move cursor to origin
2999                            self.terminal_state.get_cursor_mut().x = 0;
3000                            self.terminal_state.get_cursor_mut().y =
3001                                self.terminal_state.scroll_region.top;
3002                        }
3003                        7 => {
3004                            // DECAWM - Auto Wrap Mode
3005                            self.terminal_state.mode.auto_wrap_mode = true;
3006                        }
3007                        25 => {
3008                            // DECTCEM - Cursor Visibility
3009                            self.terminal_state.get_cursor_mut().visible = true;
3010                        }
3011                        1000 => {
3012                            // F0310: Mouse reporting - X10 mode
3013                            self.terminal_state.mode.mouse_x10_mode = true;
3014                            // Clear other mouse modes (mutually exclusive)
3015                            self.terminal_state.mode.mouse_normal_mode = false;
3016                            self.terminal_state.mode.mouse_button_event_mode = false;
3017                            self.terminal_state.mode.mouse_any_event_mode = false;
3018                            log::debug!("F0310: Mouse X10 mode enabled");
3019                        }
3020                        1002 => {
3021                            // F0310: Mouse reporting - Button Event mode
3022                            self.terminal_state.mode.mouse_button_event_mode = true;
3023                            // Clear other mouse modes (mutually exclusive)
3024                            self.terminal_state.mode.mouse_x10_mode = false;
3025                            self.terminal_state.mode.mouse_normal_mode = false;
3026                            self.terminal_state.mode.mouse_any_event_mode = false;
3027                            log::debug!("F0310: Mouse Button Event mode enabled");
3028                        }
3029                        1003 => {
3030                            // F0310: Mouse reporting - Any Event mode
3031                            self.terminal_state.mode.mouse_any_event_mode = true;
3032                            // Clear other mouse modes (mutually exclusive)
3033                            self.terminal_state.mode.mouse_x10_mode = false;
3034                            self.terminal_state.mode.mouse_normal_mode = false;
3035                            self.terminal_state.mode.mouse_button_event_mode = false;
3036                            log::debug!("F0310: Mouse Any Event mode enabled");
3037                        }
3038                        1006 => {
3039                            // F0310: Mouse reporting - SGR mode
3040                            self.terminal_state.mode.mouse_sgr_mode = true;
3041                            log::debug!("F0310: Mouse SGR extended reporting enabled");
3042                        }
3043                        47 => {
3044                            // F0312: Simple Alternate Screen (no cursor save, no clear)
3045                            self.alternate_screen_mode = true;
3046                            self.terminal_state.full_screen_program_detected = true;
3047                            self.terminal_state.switch_to_alternate_screen();
3048                            self.use_screen_buffer = true;
3049                        }
3050                        1047 => {
3051                            // F0312: Alternate Screen Buffer (with clear, no cursor save)
3052                            self.alternate_screen_mode = true;
3053                            self.terminal_state.full_screen_program_detected = true;
3054                            self.terminal_state.switch_to_alternate_screen();
3055                            self.use_screen_buffer = true;
3056                            self.terminal_state.clear_alternate_screen();
3057                        }
3058                        1049 => {
3059                            // F0312: Alternate Screen Buffer (with cursor save/restore and clear)
3060                            self.alternate_screen_mode = true;
3061                            self.terminal_state.full_screen_program_detected = true;
3062                            // Save cursor position before switching
3063                            self.terminal_state.save_cursor();
3064                            self.terminal_state.switch_to_alternate_screen();
3065                            self.use_screen_buffer = true;
3066                            self.terminal_state.clear_alternate_screen();
3067                        }
3068                        2004 => {
3069                            // F0310: Bracketed paste mode
3070                            self.terminal_state.mode.bracketed_paste_mode = true;
3071                            log::debug!("F0310: Bracketed paste mode enabled");
3072                        }
3073                        _ => {
3074                            log::debug!("Unknown DEC private mode set: {}", mode);
3075                        }
3076                    }
3077                } else if !params.is_empty() {
3078                    // Standard mode set
3079                    let mode = Self::get_param(params, 0);
3080                    match mode {
3081                        4 => {
3082                            // IRM - Insert/Replace Mode
3083                            self.terminal_state.mode.insert_mode = true;
3084                        }
3085                        20 => {
3086                            // LNM - Linefeed/Newline Mode
3087                            self.terminal_state.mode.local_echo_mode = true;
3088                        }
3089                        _ => {
3090                            log::debug!("Unknown standard mode set: {}", mode);
3091                        }
3092                    }
3093                }
3094            }
3095            'l' => {
3096                // Reset Mode
3097                if _intermediates.contains(&b'?') && !params.is_empty() {
3098                    // DEC private mode reset
3099                    let mode = Self::get_param(params, 0);
3100                    match mode {
3101                        1 => {
3102                            // DECCKM - Normal Cursor Keys
3103                            self.terminal_state.mode.cursor_key_mode = false;
3104                        }
3105                        6 => {
3106                            // DECOM - Absolute Origin Mode
3107                            self.terminal_state.mode.origin_mode = false;
3108                            // Move cursor to absolute origin
3109                            self.terminal_state.get_cursor_mut().x = 0;
3110                            self.terminal_state.get_cursor_mut().y = 0;
3111                        }
3112                        7 => {
3113                            // DECAWM - No Auto Wrap
3114                            self.terminal_state.mode.auto_wrap_mode = false;
3115                        }
3116                        25 => {
3117                            // DECTCEM - Cursor Invisible
3118                            self.terminal_state.get_cursor_mut().visible = false;
3119                        }
3120                        1000 => {
3121                            // F0310: Mouse reporting - X10 mode disable
3122                            self.terminal_state.mode.mouse_x10_mode = false;
3123                            log::debug!("F0310: Mouse X10 mode disabled");
3124                        }
3125                        1002 => {
3126                            // F0310: Mouse reporting - Button Event mode disable
3127                            self.terminal_state.mode.mouse_button_event_mode = false;
3128                            log::debug!("F0310: Mouse Button Event mode disabled");
3129                        }
3130                        1003 => {
3131                            // F0310: Mouse reporting - Any Event mode disable
3132                            self.terminal_state.mode.mouse_any_event_mode = false;
3133                            log::debug!("F0310: Mouse Any Event mode disabled");
3134                        }
3135                        1006 => {
3136                            // F0310: Mouse reporting - SGR mode disable
3137                            self.terminal_state.mode.mouse_sgr_mode = false;
3138                            log::debug!("F0310: Mouse SGR extended reporting disabled");
3139                        }
3140                        47 => {
3141                            // F0312: Exit Simple Alternate Screen (no cursor restore)
3142                            self.alternate_screen_mode = false;
3143                            self.terminal_state.switch_to_primary_screen();
3144                            // Keep full_screen_program_detected true once detected
3145                        }
3146                        1047 => {
3147                            // F0312: Exit Alternate Screen Buffer (no cursor restore)
3148                            self.alternate_screen_mode = false;
3149                            self.terminal_state.switch_to_primary_screen();
3150                            // Keep full_screen_program_detected true once detected
3151                        }
3152                        1049 => {
3153                            // F0312: Exit Alternate Screen Buffer (with cursor restore)
3154                            self.alternate_screen_mode = false;
3155                            self.terminal_state.switch_to_primary_screen();
3156                            // Restore cursor position after switching back
3157                            self.terminal_state.restore_cursor();
3158                            // Keep full_screen_program_detected true once detected
3159                        }
3160                        2004 => {
3161                            // F0310: Bracketed paste mode disable
3162                            self.terminal_state.mode.bracketed_paste_mode = false;
3163                            log::debug!("F0310: Bracketed paste mode disabled");
3164                        }
3165                        _ => {
3166                            log::debug!("Unknown DEC private mode reset: {}", mode);
3167                        }
3168                    }
3169                } else if !params.is_empty() {
3170                    // Standard mode reset
3171                    let mode = Self::get_param(params, 0);
3172                    match mode {
3173                        4 => {
3174                            // IRM - Replace Mode
3175                            self.terminal_state.mode.insert_mode = false;
3176                        }
3177                        20 => {
3178                            // LNM - Linefeed Mode
3179                            self.terminal_state.mode.local_echo_mode = false;
3180                        }
3181                        _ => {
3182                            log::debug!("Unknown standard mode reset: {}", mode);
3183                        }
3184                    }
3185                }
3186            }
3187            'L' => {
3188                // Insert Lines (IL)
3189                let count = if !params.is_empty() {
3190                    Self::get_param(params, 0).max(1) as usize
3191                } else {
3192                    1
3193                };
3194                self.terminal_state.get_active_buffer().insert_lines(count);
3195            }
3196            'M' => {
3197                // Delete Lines (DL)
3198                let count = if !params.is_empty() {
3199                    Self::get_param(params, 0).max(1) as usize
3200                } else {
3201                    1
3202                };
3203                self.terminal_state.get_active_buffer().delete_lines(count);
3204            }
3205            'P' => {
3206                // Delete Characters (DCH)
3207                let count = if !params.is_empty() {
3208                    Self::get_param(params, 0).max(1) as usize
3209                } else {
3210                    1
3211                };
3212                // Simplified - just clear characters for now
3213                let cursor_x = self.terminal_state.get_cursor().x;
3214                let cursor_y = self.terminal_state.get_cursor().y;
3215                let screen_width = self.terminal_state.screen_width;
3216                let screen_height = self.terminal_state.screen_height;
3217                if cursor_y < screen_height {
3218                    let screen = self.terminal_state.get_active_screen();
3219                    for i in 0..count {
3220                        if cursor_x + i < screen_width {
3221                            screen[cursor_y][cursor_x + i] = TerminalCell::default();
3222                        }
3223                    }
3224                }
3225            }
3226            'S' => {
3227                // SU - Scroll Up
3228                // F0307: Scroll up within scrolling region
3229                let lines = if !params.is_empty() {
3230                    Self::get_param(params, 0).max(1) as usize
3231                } else {
3232                    1
3233                };
3234                self.terminal_state.scroll_up_in_region(lines);
3235            }
3236            'T' => {
3237                // SD - Scroll Down
3238                // F0307: Scroll down within scrolling region
3239                let lines = if !params.is_empty() {
3240                    Self::get_param(params, 0).max(1) as usize
3241                } else {
3242                    1
3243                };
3244                self.terminal_state.scroll_down_in_region(lines);
3245            }
3246            'r' => {
3247                // DECSTBM - Set Top and Bottom Margins (Set Scrolling Region)
3248                // F0307: Scrolling Region Support
3249                let top = if !params.is_empty() {
3250                    Some(Self::get_param(params, 0) as usize)
3251                } else {
3252                    None
3253                };
3254                let bottom = if params.len() > 1 {
3255                    Some(Self::get_param(params, 1) as usize)
3256                } else {
3257                    None
3258                };
3259
3260                // Use F0307 scrolling region methods
3261                self.terminal_state.set_scrolling_region(top, bottom);
3262
3263                // DECSTBM also moves cursor to home position within the scrolling region
3264                let region_top = self.terminal_state.scroll_region.top;
3265                self.terminal_state.set_cursor_position(0, region_top);
3266            }
3267            'n' => {
3268                // F0311: Device Status Report (DSR) - Enhanced with all standard reports
3269                if !params.is_empty() {
3270                    let report_type = Self::get_param(params, 0);
3271                    match report_type {
3272                        5 => {
3273                            // Terminal status - always ready
3274                            self.terminal_state.pending_response = Some("\x1b[0n".to_string());
3275                        }
3276                        6 => {
3277                            // Cursor Position Report (CPR)
3278                            let cursor_x = self.terminal_state.get_cursor().x + 1;
3279                            let cursor_y = self.terminal_state.get_cursor().y + 1;
3280                            self.terminal_state.pending_response =
3281                                Some(format!("\x1b[{};{}R", cursor_y, cursor_x));
3282                        }
3283                        14 => {
3284                            // F0311: Terminal Size Report (TSR) - Window size in characters
3285                            let cols = self.terminal_state.screen_width;
3286                            let rows = self.terminal_state.screen_height;
3287                            self.terminal_state.pending_response =
3288                                Some(format!("\x1b[8;{};{}t", rows, cols));
3289                        }
3290                        15 => {
3291                            // F0311: Terminal Size Report in pixels (if supported)
3292                            // Report approximate pixel size (assume 8x16 character cell)
3293                            let pixel_width = self.terminal_state.screen_width * 8;
3294                            let pixel_height = self.terminal_state.screen_height * 16;
3295                            self.terminal_state.pending_response =
3296                                Some(format!("\x1b[4;{};{}t", pixel_height, pixel_width));
3297                        }
3298                        _ => {
3299                            log::debug!("Unknown DSR request: {}", report_type);
3300                        }
3301                    }
3302                } else if params.is_empty() {
3303                    // Default DSR - cursor position report
3304                    let cursor_x = self.terminal_state.get_cursor().x + 1;
3305                    let cursor_y = self.terminal_state.get_cursor().y + 1;
3306                    self.terminal_state.pending_response =
3307                        Some(format!("\x1b[{};{}R", cursor_y, cursor_x));
3308                }
3309            }
3310            'c' => {
3311                // F0311: Device Attributes (DA) - Enhanced terminal identification
3312                if params.is_empty() || Self::get_param(params, 0) == 0 {
3313                    // Primary Device Attributes - VT102/VT220 compatible terminal
3314                    // ?1 = VT101/VT102; ?6 = VT102; ?62 = VT220; ?63 = VT320; ?64 = VT420; ?65 = VT520
3315                    self.terminal_state.pending_response =
3316                        Some("\x1b[?62;1;2;6;7;8;9c".to_string());
3317                } else if Self::get_param(params, 0) == 1 {
3318                    // Secondary Device Attributes - Terminal version and capabilities
3319                    // Format: ESC[>Pp;Pv;Pc where:
3320                    // Pp = Terminal type (0 = VT100-series)
3321                    // Pv = Firmware version (276 = common version number)
3322                    // Pc = ROM cartridge registration number (0 = no cartridge)
3323                    self.terminal_state.pending_response = Some("\x1b[>0;276;0c".to_string());
3324                } else if Self::get_param(params, 0) == 2 {
3325                    // Tertiary Device Attributes - Unit ID (rarely supported)
3326                    self.terminal_state.pending_response = Some("\x1b[P!|00000000".to_string());
3327                }
3328            }
3329            'x' => {
3330                // F0311: Request Terminal Parameters (DECREQTPARM)
3331                if params.is_empty() || Self::get_param(params, 0) == 0 {
3332                    // Solicit terminal parameters report
3333                    self.terminal_state.pending_response =
3334                        Some("\x1b[2;1;1;128;128;1;0x".to_string());
3335                } else if Self::get_param(params, 0) == 1 {
3336                    // Request terminal parameters report
3337                    self.terminal_state.pending_response =
3338                        Some("\x1b[3;1;1;128;128;1;0x".to_string());
3339                }
3340            }
3341            '$' => {
3342                // F0311: Request Mode (DECRQM) - Query terminal mode status
3343                if let Some(intermediate) = _intermediates.first() {
3344                    if *intermediate == b'?' {
3345                        // DEC private mode query
3346                        let mode = Self::get_param(params, 0);
3347                        let status = self.get_private_mode_status(mode);
3348                        self.terminal_state.pending_response =
3349                            Some(format!("\x1b[?{};{}$y", mode, status));
3350                    } else {
3351                        // Standard mode query
3352                        let mode = Self::get_param(params, 0);
3353                        let status = self.get_standard_mode_status(mode);
3354                        self.terminal_state.pending_response =
3355                            Some(format!("\x1b[{};{}$y", mode, status));
3356                    }
3357                } else {
3358                    // Standard mode query (no intermediate)
3359                    let mode = Self::get_param(params, 0);
3360                    let status = self.get_standard_mode_status(mode);
3361                    self.terminal_state.pending_response =
3362                        Some(format!("\x1b[{};{}$y", mode, status));
3363                }
3364            }
3365            'g' => {
3366                // F0313: TBC - Tab Clear
3367                let mode = if !params.is_empty() {
3368                    Self::get_param(params, 0)
3369                } else {
3370                    0
3371                };
3372
3373                match mode {
3374                    0 => {
3375                        // Clear tab stop at current column
3376                        let cursor_x = self.terminal_state.get_cursor().x;
3377                        if cursor_x < self.terminal_state.tab_stops.len() {
3378                            self.terminal_state.tab_stops[cursor_x] = false;
3379                        }
3380                    }
3381                    3 => {
3382                        // Clear all tab stops
3383                        for stop in &mut self.terminal_state.tab_stops {
3384                            *stop = false;
3385                        }
3386                    }
3387                    _ => {
3388                        log::debug!("Unknown TBC mode: {}", mode);
3389                    }
3390                }
3391            }
3392            'I' => {
3393                // F0313: CHT - Cursor Horizontal Tabulation (Tab Forward)
3394                let count = if !params.is_empty() {
3395                    Self::get_param(params, 0).max(1) as usize
3396                } else {
3397                    1
3398                };
3399
3400                for _ in 0..count {
3401                    self.terminal_state.tab_forward();
3402                }
3403            }
3404            'Z' => {
3405                // F0313: CBT - Cursor Backward Tabulation (Tab Backward)
3406                let count = if !params.is_empty() {
3407                    Self::get_param(params, 0).max(1) as usize
3408                } else {
3409                    1
3410                };
3411
3412                for _ in 0..count {
3413                    self.terminal_state.tab_backward();
3414                }
3415            }
3416            _ => {
3417                log::debug!("Unknown CSI sequence: {:?} '{}'", params, { c });
3418            }
3419        }
3420    }
3421
3422    fn esc_dispatch(&mut self, intermediates: &[u8], _ignore: bool, byte: u8) {
3423        match byte {
3424            b'7' => {
3425                // Save cursor position (DECSC)
3426                self.terminal_state.save_cursor();
3427            }
3428            b'8' => {
3429                // Restore cursor position (DECRC)
3430                self.terminal_state.restore_cursor();
3431            }
3432            b'c' => {
3433                // Reset terminal (RIS) - indicates full-screen program
3434                self.terminal_state.full_screen_program_detected = true;
3435                self.use_screen_buffer = true;
3436                self.clear_screen_buffer();
3437            }
3438            b'Z' => {
3439                // F0311: Identify Terminal (DECID) - respond with device attributes
3440                self.terminal_state.pending_response = Some("\x1b[?62;1;2;6;7;8;9c".to_string());
3441            }
3442            5 => {
3443                // F0311: ENQ (Enquiry) - respond with ANSWERBACK string
3444                self.terminal_state.pending_response = Some("BoxMux Terminal\r".to_string());
3445            }
3446            b'D' => {
3447                // Index (IND) - cursor down with scroll
3448                if self.terminal_state.get_cursor().y
3449                    >= self.terminal_state.screen_height.saturating_sub(1)
3450                {
3451                    self.terminal_state.scroll_up(1);
3452                } else {
3453                    self.terminal_state.get_cursor_mut().y += 1;
3454                }
3455            }
3456            b'M' => {
3457                // Reverse Index (RI) - cursor up with scroll
3458                if self.terminal_state.get_cursor().y == 0 {
3459                    self.terminal_state.scroll_down(1);
3460                } else {
3461                    self.terminal_state.get_cursor_mut().y =
3462                        self.terminal_state.get_cursor().y.saturating_sub(1);
3463                }
3464            }
3465            b'E' => {
3466                // Next Line (NEL) - cursor to start of next line
3467                self.terminal_state.get_cursor_mut().x = 0;
3468                if self.terminal_state.get_cursor().y
3469                    >= self.terminal_state.screen_height.saturating_sub(1)
3470                {
3471                    self.terminal_state.scroll_up(1);
3472                } else {
3473                    self.terminal_state.get_cursor_mut().y += 1;
3474                }
3475            }
3476            b'H' => {
3477                // Tab Set (HTS)
3478                let cursor_x = self.terminal_state.get_cursor().x;
3479                if cursor_x < self.terminal_state.tab_stops.len() {
3480                    self.terminal_state.tab_stops[cursor_x] = true;
3481                }
3482            }
3483            b'=' => {
3484                // Application Keypad (DECKPAM)
3485                self.terminal_state.mode.keypad_mode = true;
3486            }
3487            b'>' => {
3488                // Normal Keypad (DECKPNM)
3489                self.terminal_state.mode.keypad_mode = false;
3490            }
3491            _ => {
3492                // Handle intermediate-dependent sequences
3493                if intermediates.len() == 1 {
3494                    match intermediates[0] {
3495                        b'(' => {
3496                            // Designate G0 Character Set
3497                            match byte {
3498                                b'A' => self.terminal_state.charset_g0 = Some("UK".to_string()),
3499                                b'B' => self.terminal_state.charset_g0 = Some("ASCII".to_string()),
3500                                b'0' => self.terminal_state.charset_g0 = Some("DEC".to_string()),
3501                                _ => {}
3502                            }
3503                        }
3504                        b')' => {
3505                            // Designate G1 Character Set
3506                            match byte {
3507                                b'A' => self.terminal_state.charset_g1 = Some("UK".to_string()),
3508                                b'B' => self.terminal_state.charset_g1 = Some("ASCII".to_string()),
3509                                b'0' => self.terminal_state.charset_g1 = Some("DEC".to_string()),
3510                                _ => {}
3511                            }
3512                        }
3513                        b'#' => {
3514                            // F0314: Line attribute sequences
3515                            match byte {
3516                                b'3' => {
3517                                    // DECDHL - Double Height Line (top half)
3518                                    self.terminal_state.set_double_height_line_top();
3519                                }
3520                                b'4' => {
3521                                    // DECDHL - Double Height Line (bottom half)
3522                                    self.terminal_state.set_double_height_line_bottom();
3523                                }
3524                                b'5' => {
3525                                    // DECSWL - Single Width Line (normal)
3526                                    self.terminal_state.set_normal_line();
3527                                }
3528                                b'6' => {
3529                                    // DECDWL - Double Width Line
3530                                    self.terminal_state.set_double_width_line();
3531                                }
3532                                _ => {
3533                                    log::debug!("Unknown ESC # sequence: {}", byte as char);
3534                                }
3535                            }
3536                        }
3537                        _ => {
3538                            log::debug!(
3539                                "Unknown ESC intermediate sequence: {:?} {}",
3540                                intermediates,
3541                                byte as char
3542                            );
3543                        }
3544                    }
3545                } else {
3546                    log::debug!("Unknown ESC sequence: {:?} {}", intermediates, byte as char);
3547                }
3548            }
3549        }
3550    }
3551}
3552
3553impl Default for AnsiProcessor {
3554    fn default() -> Self {
3555        Self::new()
3556    }
3557}
3558
3559#[cfg(test)]
3560mod tests {
3561    use super::*;
3562
3563    #[test]
3564    fn test_ansi_processor_basic_text() {
3565        let mut processor = AnsiProcessor::new();
3566        processor.process_string("Hello World");
3567        assert_eq!(processor.get_processed_text(), "Hello World");
3568    }
3569
3570    #[test]
3571    fn test_ansi_processor_color_codes() {
3572        let mut processor = AnsiProcessor::new();
3573        processor.process_string("\x1b[31mRed Text\x1b[0m");
3574        assert_eq!(processor.get_processed_text(), "Red Text");
3575    }
3576
3577    #[test]
3578    fn test_ansi_processor_newlines() {
3579        let mut processor = AnsiProcessor::new();
3580        processor.process_string("Line 1\nLine 2\n");
3581        assert_eq!(processor.get_processed_text(), "Line 1\nLine 2\n");
3582        assert_eq!(processor.get_cursor_y(), 2);
3583        assert_eq!(processor.get_cursor_x(), 0);
3584    }
3585
3586    #[test]
3587    fn test_ansi_processor_clear_screen() {
3588        let mut processor = AnsiProcessor::new();
3589        processor.process_string("Some text\x1b[2JCleared");
3590        assert_eq!(processor.get_processed_text(), "Cleared");
3591    }
3592
3593    #[test]
3594    fn test_ansi_processor_stream_integration() {
3595        let mut processor = AnsiProcessor::new();
3596
3597        // Test non-screen buffer mode (line-based)
3598        processor.set_screen_mode(false);
3599        processor.process_string("Line 1\nLine 2");
3600        let stream_content = processor.get_screen_content_for_stream();
3601        assert_eq!(stream_content, "Line 1\nLine 2");
3602
3603        // Test screen buffer mode with ANSI colors
3604        processor.set_screen_mode(true);
3605        processor.process_string("\x1b[31mRed text\x1b[0m");
3606        let screen_stream_content = processor.get_screen_content_for_stream();
3607
3608        // Should contain ANSI formatting codes for proper BoxMux rendering
3609        assert!(screen_stream_content.contains("Red text"));
3610        assert!(!screen_stream_content.is_empty());
3611
3612        // Test terminal content lines extraction
3613        let content_lines = processor.get_terminal_content_lines(false);
3614        assert!(!content_lines.is_empty());
3615    }
3616
3617    #[test]
3618    fn test_terminal_screen_buffer_to_content_lines() {
3619        let mut buffer = TerminalScreenBuffer::new(80, 24, 1000);
3620
3621        // Add some content with formatting
3622        buffer.content[0][0] = TerminalCell {
3623            character: 'H',
3624            fg_color: Some(1), // Red foreground
3625            bold: true,
3626            ..Default::default()
3627        };
3628        buffer.content[0][1] = TerminalCell {
3629            character: 'i',
3630            fg_color: Some(1),
3631            bold: true,
3632            ..Default::default()
3633        };
3634
3635        let lines = buffer.to_content_lines(false);
3636        assert!(!lines.is_empty());
3637        let first_line = &lines[0];
3638
3639        // Should contain ANSI escape codes for formatting
3640        assert!(first_line.contains("Hi"));
3641        assert!(first_line.contains("\x1b[")); // ANSI escape sequence
3642    }
3643
3644    #[test]
3645    fn test_enhanced_vte_parser_integration() {
3646        let mut processor = AnsiProcessor::new();
3647        processor.set_screen_mode(true);
3648
3649        // Test application keypad mode (ESC sequences)
3650        processor.process_string("\x1b="); // ESC =
3651        assert!(processor.terminal_state.mode.keypad_mode);
3652
3653        processor.process_string("\x1b>"); // ESC >
3654        assert!(!processor.terminal_state.mode.keypad_mode);
3655
3656        // Test device status report (CSI sequence)
3657        processor.process_string("\x1b[6n");
3658        assert!(processor.terminal_state.pending_response.is_some());
3659        let response = processor.terminal_state.pending_response.as_ref().unwrap();
3660        assert!(response.contains("R")); // Cursor position report
3661
3662        // Test scrolling region (CSI sequence)
3663        processor.process_string("\x1b[5;20r"); // Set scroll region lines 5-20
3664        assert_eq!(processor.terminal_state.scroll_region.top, 4); // 0-indexed
3665        assert_eq!(processor.terminal_state.scroll_region.bottom, 19); // 0-indexed
3666
3667        // Test enhanced cursor movements
3668        processor.process_string("\x1b[10A"); // Cursor up 10 lines
3669        processor.process_string("\x1b[5B"); // Cursor down 5 lines
3670        processor.process_string("\x1b[3C"); // Cursor forward 3 columns
3671        processor.process_string("\x1b[2D"); // Cursor backward 2 columns
3672
3673        // Test that processor handles enhanced sequences without crashing
3674        assert_eq!(processor.terminal_state.scroll_region.top, 4);
3675        assert_eq!(processor.terminal_state.scroll_region.bottom, 19);
3676    }
3677
3678    #[test]
3679    fn test_vte_parser_dcs_sequences() {
3680        let mut processor = AnsiProcessor::new();
3681
3682        // Test DCS sequence processing
3683        processor.process_string("\x1bP1$q\x1b\\"); // DCS query sequence
3684
3685        // Verify DCS state was cleared
3686        assert!(processor.terminal_state.dcs_sequence_type.is_none());
3687        assert!(processor.terminal_state.dcs_buffer.is_none());
3688    }
3689
3690    #[test]
3691    fn test_terminal_message_architecture() {
3692        let mut processor = TerminalMessageProcessor::new();
3693
3694        // Test basic message processing
3695        let message = TerminalMessage::ResizeTerminal {
3696            width: 100,
3697            height: 50,
3698        };
3699        processor.process_message(message);
3700        assert_eq!(processor.ansi_processor.terminal_state.screen_width, 100);
3701        assert_eq!(processor.ansi_processor.terminal_state.screen_height, 50);
3702
3703        // Test cursor movement
3704        let cursor_msg = TerminalMessage::MoveCursor { x: 10, y: 5 };
3705        processor.process_message(cursor_msg);
3706        assert_eq!(processor.ansi_processor.terminal_state.get_cursor().x, 10);
3707        assert_eq!(processor.ansi_processor.terminal_state.get_cursor().y, 5);
3708
3709        // Test cursor visibility
3710        let visibility_msg = TerminalMessage::SetCursorVisibility { visible: false };
3711        processor.process_message(visibility_msg);
3712        assert!(!processor.ansi_processor.terminal_state.get_cursor().visible);
3713
3714        // Test terminal modes
3715        let mode_msg = TerminalMessage::SetMode {
3716            mode: TerminalModeType::AutoWrap,
3717            enabled: true,
3718        };
3719        processor.process_message(mode_msg);
3720        assert!(processor.ansi_processor.terminal_state.mode.auto_wrap_mode);
3721
3722        // Test terminal title
3723        let title_msg = TerminalMessage::SetTerminalTitle {
3724            title: "Test Terminal".to_string(),
3725        };
3726        processor.process_message(title_msg);
3727        assert_eq!(
3728            processor.ansi_processor.terminal_state.terminal_title,
3729            Some("Test Terminal".to_string())
3730        );
3731    }
3732
3733    #[test]
3734    fn test_terminal_message_queue() {
3735        let mut processor = TerminalMessageProcessor::new();
3736
3737        // Queue multiple messages
3738        processor.queue_message(TerminalMessage::MoveCursor { x: 5, y: 10 });
3739        processor.queue_message(TerminalMessage::SetCursorVisibility { visible: false });
3740        processor.queue_message(TerminalMessage::ResizeTerminal {
3741            width: 120,
3742            height: 40,
3743        });
3744
3745        // Process all queued messages
3746        processor.process_queued_messages();
3747
3748        // Verify all messages were processed
3749        assert_eq!(processor.ansi_processor.terminal_state.get_cursor().x, 5);
3750        assert_eq!(processor.ansi_processor.terminal_state.get_cursor().y, 10);
3751        assert!(!processor.ansi_processor.terminal_state.get_cursor().visible);
3752        assert_eq!(processor.ansi_processor.terminal_state.screen_width, 120);
3753        assert_eq!(processor.ansi_processor.terminal_state.screen_height, 40);
3754
3755        // Queue should be empty after processing
3756        assert!(processor.message_queue.is_empty());
3757    }
3758
3759    #[test]
3760    fn test_device_status_reports() {
3761        let mut processor = TerminalMessageProcessor::new();
3762
3763        // Test cursor position report
3764        processor.process_message(TerminalMessage::MoveCursor { x: 20, y: 15 });
3765        processor.process_message(TerminalMessage::DeviceStatusReport {
3766            report_type: DeviceReportType::CursorPosition,
3767        });
3768
3769        let responses = processor.get_pending_responses();
3770        assert_eq!(responses.len(), 1);
3771        assert_eq!(responses[0], "\x1b[16;21R"); // 1-indexed coordinates
3772
3773        // Test status report
3774        processor.process_message(TerminalMessage::DeviceStatusReport {
3775            report_type: DeviceReportType::Status,
3776        });
3777
3778        let responses = processor.get_pending_responses();
3779        assert_eq!(responses.len(), 1);
3780        assert_eq!(responses[0], "\x1b[0n"); // Terminal OK
3781    }
3782
3783    #[test]
3784    fn test_f0311_terminal_queries() {
3785        let mut processor = AnsiProcessor::new();
3786
3787        // Test Primary Device Attributes via VTE parser
3788        processor.process_bytes("\x1b[c".as_bytes());
3789        assert!(processor.terminal_state.pending_response.is_some());
3790        let response = processor.terminal_state.pending_response.take().unwrap();
3791        assert!(response.contains("[?62")); // VT220 compatible terminal
3792
3793        // Test Device Status Report - cursor position
3794        processor.process_bytes("\x1b[6n".as_bytes());
3795        assert!(processor.terminal_state.pending_response.is_some());
3796        let response = processor.terminal_state.pending_response.take().unwrap();
3797        assert!(response.ends_with("R")); // Cursor Position Report format
3798
3799        // Test Secondary Device Attributes
3800        processor.process_bytes("\x1b[1c".as_bytes());
3801        assert!(processor.terminal_state.pending_response.is_some());
3802        let response = processor.terminal_state.pending_response.take().unwrap();
3803        assert_eq!(response, "\x1b[>0;276;0c"); // Secondary DA format
3804
3805        // Test Terminal Status Report
3806        processor.process_bytes("\x1b[5n".as_bytes());
3807        assert!(processor.terminal_state.pending_response.is_some());
3808        let response = processor.terminal_state.pending_response.take().unwrap();
3809        assert_eq!(response, "\x1b[0n"); // Terminal OK
3810    }
3811
3812    #[test]
3813    fn test_f0312_alternate_screen_buffer() {
3814        let mut processor = AnsiProcessor::new();
3815
3816        // Test initial state - should be on primary screen
3817        assert!(!processor.is_using_alternate_screen());
3818        assert!(!processor.should_replace_content());
3819
3820        // Add some content to primary screen
3821        processor.process_string("Primary screen content");
3822        let primary_content = processor.get_processed_text();
3823        assert!(primary_content.contains("Primary"));
3824
3825        // Test Mode 47 - Simple Alternate Screen
3826        processor.process_bytes("\x1b[?47h".as_bytes());
3827        assert!(processor.is_using_alternate_screen());
3828        assert!(processor.should_replace_content());
3829
3830        // Add content to alternate screen
3831        processor.process_string("Alternate screen content");
3832        let alt_content = processor.get_processed_text();
3833
3834        // Exit Mode 47
3835        processor.process_bytes("\x1b[?47l".as_bytes());
3836        assert!(!processor.is_using_alternate_screen());
3837
3838        // Should return to primary screen with preserved content
3839        let restored_content = processor.get_processed_text();
3840        // Note: Content handling depends on screen buffer mode
3841
3842        // Test Mode 1047 - Alternate Screen with Clear
3843        processor.process_bytes("\x1b[?1047h".as_bytes());
3844        assert!(processor.is_using_alternate_screen());
3845
3846        // Exit Mode 1047
3847        processor.process_bytes("\x1b[?1047l".as_bytes());
3848        assert!(!processor.is_using_alternate_screen());
3849
3850        // Test Mode 1049 - Alternate Screen with Cursor Save/Restore
3851        // Set cursor position first
3852        processor.terminal_state.set_cursor_position(10, 5);
3853        let saved_x = processor.terminal_state.get_cursor().x;
3854        let saved_y = processor.terminal_state.get_cursor().y;
3855
3856        processor.process_bytes("\x1b[?1049h".as_bytes());
3857        assert!(processor.is_using_alternate_screen());
3858
3859        // Move cursor in alternate screen
3860        processor.terminal_state.set_cursor_position(20, 15);
3861        assert_ne!(processor.terminal_state.get_cursor().x, saved_x);
3862        assert_ne!(processor.terminal_state.get_cursor().y, saved_y);
3863
3864        // Exit Mode 1049 - should restore cursor position
3865        processor.process_bytes("\x1b[?1049l".as_bytes());
3866        assert!(!processor.is_using_alternate_screen());
3867
3868        // Verify cursor was restored
3869        assert_eq!(processor.terminal_state.get_cursor().x, saved_x);
3870        assert_eq!(processor.terminal_state.get_cursor().y, saved_y);
3871    }
3872
3873    #[test]
3874    fn test_f0312_buffer_isolation() {
3875        let mut processor = AnsiProcessor::new();
3876
3877        // Enable screen buffer mode for proper isolation testing
3878        processor.set_screen_mode(true);
3879
3880        // Add content to primary screen
3881        processor.process_string("Primary line 1\n");
3882        processor.process_string("Primary line 2\n");
3883
3884        // Get primary screen content
3885        let primary_lines = processor.get_terminal_content_lines(false);
3886        assert!(primary_lines.len() >= 2);
3887        assert!(primary_lines[0].contains("Primary line 1"));
3888
3889        // Switch to alternate screen with clear
3890        processor.process_bytes("\x1b[?1047h".as_bytes());
3891        assert!(processor.is_using_alternate_screen());
3892
3893        // Add different content to alternate screen
3894        processor.process_string("Alternate line 1\n");
3895        processor.process_string("Alternate line 2\n");
3896
3897        // Get alternate screen content
3898        let alt_lines = processor.get_terminal_content_lines(false);
3899        assert!(alt_lines.len() >= 2);
3900        assert!(alt_lines[0].contains("Alternate line 1"));
3901
3902        // Switch back to primary screen
3903        processor.process_bytes("\x1b[?1047l".as_bytes());
3904        assert!(!processor.is_using_alternate_screen());
3905
3906        // Verify primary screen content is preserved
3907        let restored_lines = processor.get_terminal_content_lines(false);
3908        // Primary content should be restored (buffer isolation working)
3909
3910        // Verify buffer isolation is working
3911        assert!(processor.terminal_state.verify_buffer_isolation());
3912    }
3913
3914    #[test]
3915    fn test_terminal_message_content_update() {
3916        let mut processor = TerminalMessageProcessor::new();
3917
3918        // Test content update with replace mode
3919        let content_msg = TerminalMessage::ContentUpdate {
3920            content: "New content".to_string(),
3921            dirty_regions: vec![DirtyRegion {
3922                x: 0,
3923                y: 0,
3924                width: 80,
3925                height: 1,
3926            }],
3927            replace_mode: true,
3928        };
3929        processor.process_message(content_msg);
3930        assert_eq!(processor.ansi_processor.processed_text, "New content");
3931
3932        // Test content update with append mode
3933        let append_msg = TerminalMessage::ContentUpdate {
3934            content: " appended".to_string(),
3935            dirty_regions: vec![],
3936            replace_mode: false,
3937        };
3938        processor.process_message(append_msg);
3939        assert_eq!(
3940            processor.ansi_processor.processed_text,
3941            "New content appended"
3942        );
3943    }
3944
3945    #[test]
3946    fn test_cursor_management_system() {
3947        let mut terminal_state = TerminalState::new(80, 24);
3948
3949        // Test basic cursor positioning
3950        terminal_state.set_cursor_position(10, 5);
3951        assert_eq!(terminal_state.get_cursor().x, 10);
3952        assert_eq!(terminal_state.get_cursor().y, 5);
3953
3954        // Test bounds checking
3955        terminal_state.set_cursor_position(100, 30); // Beyond screen bounds
3956        assert_eq!(terminal_state.get_cursor().x, 79); // Clamped to screen width - 1
3957        assert_eq!(terminal_state.get_cursor().y, 23); // Clamped to screen height - 1
3958
3959        // Test relative movement
3960        terminal_state.set_cursor_position(10, 10);
3961        terminal_state.move_cursor_relative(5, -3);
3962        assert_eq!(terminal_state.get_cursor().x, 15);
3963        assert_eq!(terminal_state.get_cursor().y, 7);
3964
3965        // Test negative relative movement with bounds
3966        terminal_state.move_cursor_relative(-20, -10);
3967        assert_eq!(terminal_state.get_cursor().x, 0); // Saturated at 0
3968        assert_eq!(terminal_state.get_cursor().y, 0); // Saturated at 0
3969    }
3970
3971    #[test]
3972    fn test_cursor_save_restore() {
3973        let mut terminal_state = TerminalState::new(80, 24);
3974
3975        // Set initial position and style
3976        terminal_state.set_cursor_position(15, 10);
3977        terminal_state.set_cursor_visibility(false);
3978        terminal_state.set_cursor_style(CursorStyle::Underline);
3979
3980        // Save cursor state
3981        terminal_state.save_cursor();
3982
3983        // Change cursor state
3984        terminal_state.set_cursor_position(30, 20);
3985        terminal_state.set_cursor_visibility(true);
3986        terminal_state.set_cursor_style(CursorStyle::Block);
3987
3988        // Verify changed state
3989        assert_eq!(terminal_state.get_cursor().x, 30);
3990        assert_eq!(terminal_state.get_cursor().y, 20);
3991        assert!(terminal_state.get_cursor().visible);
3992        assert_eq!(terminal_state.get_cursor().style, CursorStyle::Block);
3993
3994        // Restore cursor state
3995        terminal_state.restore_cursor();
3996
3997        // Verify restored state
3998        assert_eq!(terminal_state.get_cursor().x, 15);
3999        assert_eq!(terminal_state.get_cursor().y, 10);
4000        assert!(!terminal_state.get_cursor().visible);
4001        assert_eq!(terminal_state.get_cursor().style, CursorStyle::Underline);
4002    }
4003
4004    #[test]
4005    fn test_cursor_movement_operations() {
4006        let mut terminal_state = TerminalState::new(80, 24);
4007        terminal_state.set_cursor_position(10, 10);
4008
4009        // Test directional movements
4010        terminal_state.cursor_up(3);
4011        assert_eq!(terminal_state.get_cursor().y, 7);
4012
4013        terminal_state.cursor_down(5);
4014        assert_eq!(terminal_state.get_cursor().y, 12);
4015
4016        terminal_state.cursor_left(4);
4017        assert_eq!(terminal_state.get_cursor().x, 6);
4018
4019        terminal_state.cursor_right(8);
4020        assert_eq!(terminal_state.get_cursor().x, 14);
4021
4022        // Test line operations
4023        terminal_state.cursor_to_line_start();
4024        assert_eq!(terminal_state.get_cursor().x, 0);
4025        assert_eq!(terminal_state.get_cursor().y, 12);
4026
4027        terminal_state.cursor_next_line(2);
4028        assert_eq!(terminal_state.get_cursor().x, 0);
4029        assert_eq!(terminal_state.get_cursor().y, 14);
4030
4031        terminal_state.set_cursor_position(20, 10);
4032        terminal_state.cursor_previous_line(3);
4033        assert_eq!(terminal_state.get_cursor().x, 0);
4034        assert_eq!(terminal_state.get_cursor().y, 7);
4035    }
4036
4037    #[test]
4038    fn test_cursor_column_line_positioning() {
4039        let mut terminal_state = TerminalState::new(80, 24);
4040
4041        terminal_state.set_cursor_position(10, 10);
4042
4043        // Test column positioning
4044        terminal_state.set_cursor_column(25);
4045        assert_eq!(terminal_state.get_cursor().x, 25);
4046        assert_eq!(terminal_state.get_cursor().y, 10); // Y unchanged
4047
4048        // Test line positioning
4049        terminal_state.set_cursor_line(15);
4050        assert_eq!(terminal_state.get_cursor().x, 25); // X unchanged
4051        assert_eq!(terminal_state.get_cursor().y, 15);
4052
4053        // Test bounds checking
4054        terminal_state.set_cursor_column(100);
4055        assert_eq!(terminal_state.get_cursor().x, 79); // Clamped
4056
4057        terminal_state.set_cursor_line(50);
4058        assert_eq!(terminal_state.get_cursor().y, 23); // Clamped
4059    }
4060
4061    #[test]
4062    fn test_cursor_styles() {
4063        let mut terminal_state = TerminalState::new(80, 24);
4064
4065        // Test all cursor styles
4066        terminal_state.set_cursor_style(CursorStyle::Block);
4067        assert_eq!(terminal_state.get_cursor().style, CursorStyle::Block);
4068
4069        terminal_state.set_cursor_style(CursorStyle::Underline);
4070        assert_eq!(terminal_state.get_cursor().style, CursorStyle::Underline);
4071
4072        terminal_state.set_cursor_style(CursorStyle::Bar);
4073        assert_eq!(terminal_state.get_cursor().style, CursorStyle::Bar);
4074
4075        terminal_state.set_cursor_style(CursorStyle::BlinkingBlock);
4076        assert_eq!(
4077            terminal_state.get_cursor().style,
4078            CursorStyle::BlinkingBlock
4079        );
4080
4081        terminal_state.set_cursor_style(CursorStyle::BlinkingUnderline);
4082        assert_eq!(
4083            terminal_state.get_cursor().style,
4084            CursorStyle::BlinkingUnderline
4085        );
4086
4087        terminal_state.set_cursor_style(CursorStyle::BlinkingBar);
4088        assert_eq!(terminal_state.get_cursor().style, CursorStyle::BlinkingBar);
4089    }
4090
4091    #[test]
4092    fn test_cursor_message_operations() {
4093        let mut processor = TerminalMessageProcessor::new();
4094
4095        // Test cursor movement messages
4096        processor.process_message(TerminalMessage::MoveCursor { x: 20, y: 15 });
4097        assert_eq!(processor.ansi_processor.terminal_state.get_cursor().x, 20);
4098        assert_eq!(processor.ansi_processor.terminal_state.get_cursor().y, 15);
4099
4100        // Test directional movement messages
4101        processor.process_message(TerminalMessage::CursorUp { lines: 5 });
4102        assert_eq!(processor.ansi_processor.terminal_state.get_cursor().y, 10);
4103
4104        processor.process_message(TerminalMessage::CursorRight { cols: 10 });
4105        assert_eq!(processor.ansi_processor.terminal_state.get_cursor().x, 30);
4106
4107        processor.process_message(TerminalMessage::CursorDown { lines: 3 });
4108        assert_eq!(processor.ansi_processor.terminal_state.get_cursor().y, 13);
4109
4110        processor.process_message(TerminalMessage::CursorLeft { cols: 15 });
4111        assert_eq!(processor.ansi_processor.terminal_state.get_cursor().x, 15);
4112
4113        // Test line operations messages
4114        processor.process_message(TerminalMessage::CursorToLineStart);
4115        assert_eq!(processor.ansi_processor.terminal_state.get_cursor().x, 0);
4116
4117        processor.process_message(TerminalMessage::CursorNextLine { lines: 2 });
4118        assert_eq!(processor.ansi_processor.terminal_state.get_cursor().x, 0);
4119        assert_eq!(processor.ansi_processor.terminal_state.get_cursor().y, 15);
4120
4121        // Test column/line positioning messages
4122        processor.process_message(TerminalMessage::SetCursorColumn { col: 40 });
4123        assert_eq!(processor.ansi_processor.terminal_state.get_cursor().x, 40);
4124
4125        processor.process_message(TerminalMessage::SetCursorLine { line: 5 });
4126        assert_eq!(processor.ansi_processor.terminal_state.get_cursor().y, 5);
4127
4128        // Test save/restore messages
4129        processor.process_message(TerminalMessage::SaveCursor);
4130        processor.process_message(TerminalMessage::MoveCursor { x: 60, y: 20 });
4131        processor.process_message(TerminalMessage::RestoreCursor);
4132        assert_eq!(processor.ansi_processor.terminal_state.get_cursor().x, 40);
4133        assert_eq!(processor.ansi_processor.terminal_state.get_cursor().y, 5);
4134    }
4135
4136    #[test]
4137    fn test_character_attribute_system() {
4138        let mut processor = AnsiProcessor::new();
4139
4140        // Test basic text attributes
4141        processor.apply_sgr_param(1); // Bold
4142        assert!(processor.terminal_state.current_attributes.bold);
4143
4144        processor.apply_sgr_param(3); // Italic
4145        assert!(processor.terminal_state.current_attributes.italic);
4146
4147        processor.apply_sgr_param(4); // Underline
4148        assert!(processor.terminal_state.current_attributes.underline);
4149
4150        processor.apply_sgr_param(7); // Reverse
4151        assert!(processor.terminal_state.current_attributes.reverse);
4152
4153        processor.apply_sgr_param(9); // Strikethrough
4154        assert!(processor.terminal_state.current_attributes.strikethrough);
4155
4156        // Test extended attributes
4157        processor.apply_sgr_param(2); // Dim
4158        assert!(processor.terminal_state.current_attributes.dim);
4159
4160        processor.apply_sgr_param(5); // Blink
4161        assert!(processor.terminal_state.current_attributes.blink);
4162
4163        processor.apply_sgr_param(8); // Hidden
4164        assert!(processor.terminal_state.current_attributes.hidden);
4165
4166        // Test reset attributes
4167        processor.apply_sgr_param(22); // Reset bold and dim
4168        assert!(!processor.terminal_state.current_attributes.bold);
4169        assert!(!processor.terminal_state.current_attributes.dim);
4170
4171        processor.apply_sgr_param(23); // Reset italic
4172        assert!(!processor.terminal_state.current_attributes.italic);
4173
4174        processor.apply_sgr_param(24); // Reset underline
4175        assert!(!processor.terminal_state.current_attributes.underline);
4176
4177        // Test complete reset
4178        processor.apply_sgr_param(0); // Reset all
4179        let default_cell = TerminalCell::default();
4180        assert_eq!(
4181            processor.terminal_state.current_attributes.bold,
4182            default_cell.bold
4183        );
4184        assert_eq!(
4185            processor.terminal_state.current_attributes.italic,
4186            default_cell.italic
4187        );
4188        assert_eq!(
4189            processor.terminal_state.current_attributes.underline,
4190            default_cell.underline
4191        );
4192        assert_eq!(
4193            processor.terminal_state.current_attributes.reverse,
4194            default_cell.reverse
4195        );
4196        assert_eq!(
4197            processor.terminal_state.current_attributes.strikethrough,
4198            default_cell.strikethrough
4199        );
4200    }
4201
4202    #[test]
4203    fn test_standard_color_support() {
4204        let mut processor = AnsiProcessor::new();
4205
4206        // Test standard 8 colors (foreground)
4207        processor.apply_sgr_param(30); // Black
4208        assert_eq!(
4209            processor.terminal_state.current_attributes.fg_color,
4210            Some(0)
4211        );
4212
4213        processor.apply_sgr_param(31); // Red
4214        assert_eq!(
4215            processor.terminal_state.current_attributes.fg_color,
4216            Some(1)
4217        );
4218
4219        processor.apply_sgr_param(37); // White
4220        assert_eq!(
4221            processor.terminal_state.current_attributes.fg_color,
4222            Some(7)
4223        );
4224
4225        // Test bright colors (foreground)
4226        processor.apply_sgr_param(90); // Bright black
4227        assert_eq!(
4228            processor.terminal_state.current_attributes.fg_color,
4229            Some(8)
4230        );
4231
4232        processor.apply_sgr_param(97); // Bright white
4233        assert_eq!(
4234            processor.terminal_state.current_attributes.fg_color,
4235            Some(15)
4236        );
4237
4238        // Test standard 8 colors (background)
4239        processor.apply_sgr_param(40); // Black background
4240        assert_eq!(
4241            processor.terminal_state.current_attributes.bg_color,
4242            Some(0)
4243        );
4244
4245        processor.apply_sgr_param(47); // White background
4246        assert_eq!(
4247            processor.terminal_state.current_attributes.bg_color,
4248            Some(7)
4249        );
4250
4251        // Test bright colors (background)
4252        processor.apply_sgr_param(100); // Bright black background
4253        assert_eq!(
4254            processor.terminal_state.current_attributes.bg_color,
4255            Some(8)
4256        );
4257
4258        processor.apply_sgr_param(107); // Bright white background
4259        assert_eq!(
4260            processor.terminal_state.current_attributes.bg_color,
4261            Some(15)
4262        );
4263
4264        // Test color reset
4265        processor.apply_sgr_param(39); // Default foreground
4266        assert_eq!(processor.terminal_state.current_attributes.fg_color, None);
4267
4268        processor.apply_sgr_param(49); // Default background
4269        assert_eq!(processor.terminal_state.current_attributes.bg_color, None);
4270    }
4271
4272    #[test]
4273    fn test_extended_attributes() {
4274        let mut processor = AnsiProcessor::new();
4275
4276        // Test double underline
4277        processor.apply_sgr_param(21);
4278        assert!(processor.terminal_state.current_attributes.double_underline);
4279
4280        // Test framed and encircled
4281        processor.apply_sgr_param(51);
4282        assert!(processor.terminal_state.current_attributes.framed);
4283
4284        processor.apply_sgr_param(52);
4285        assert!(processor.terminal_state.current_attributes.encircled);
4286
4287        processor.apply_sgr_param(53);
4288        assert!(processor.terminal_state.current_attributes.overlined);
4289
4290        // Test frame/encircle reset
4291        processor.apply_sgr_param(54);
4292        assert!(!processor.terminal_state.current_attributes.framed);
4293        assert!(!processor.terminal_state.current_attributes.encircled);
4294
4295        processor.apply_sgr_param(55);
4296        assert!(!processor.terminal_state.current_attributes.overlined);
4297
4298        // Test font selection
4299        processor.apply_sgr_param(11); // Alternative font 1
4300        assert_eq!(processor.terminal_state.current_attributes.font_id, Some(1));
4301
4302        processor.apply_sgr_param(19); // Alternative font 9
4303        assert_eq!(processor.terminal_state.current_attributes.font_id, Some(9));
4304    }
4305
4306    #[test]
4307    fn test_ideogram_attributes() {
4308        let mut processor = AnsiProcessor::new();
4309
4310        // Test ideogram attributes
4311        processor.apply_sgr_param(60); // Ideogram underline
4312        assert!(
4313            processor
4314                .terminal_state
4315                .current_attributes
4316                .ideogram_underline
4317        );
4318
4319        processor.apply_sgr_param(61); // Ideogram double underline
4320        assert!(
4321            processor
4322                .terminal_state
4323                .current_attributes
4324                .ideogram_double_underline
4325        );
4326
4327        processor.apply_sgr_param(62); // Ideogram overline
4328        assert!(
4329            processor
4330                .terminal_state
4331                .current_attributes
4332                .ideogram_overline
4333        );
4334
4335        processor.apply_sgr_param(63); // Ideogram double overline
4336        assert!(
4337            processor
4338                .terminal_state
4339                .current_attributes
4340                .ideogram_double_overline
4341        );
4342
4343        processor.apply_sgr_param(64); // Ideogram stress
4344        assert!(processor.terminal_state.current_attributes.ideogram_stress);
4345
4346        // Test ideogram reset
4347        processor.apply_sgr_param(65);
4348        assert!(
4349            !processor
4350                .terminal_state
4351                .current_attributes
4352                .ideogram_underline
4353        );
4354        assert!(
4355            !processor
4356                .terminal_state
4357                .current_attributes
4358                .ideogram_double_underline
4359        );
4360        assert!(
4361            !processor
4362                .terminal_state
4363                .current_attributes
4364                .ideogram_overline
4365        );
4366        assert!(
4367            !processor
4368                .terminal_state
4369                .current_attributes
4370                .ideogram_double_overline
4371        );
4372        assert!(!processor.terminal_state.current_attributes.ideogram_stress);
4373    }
4374
4375    #[test]
4376    fn test_rgb_to_palette_conversion() {
4377        // Test primary colors
4378        assert_eq!(
4379            AnsiProcessor::rgb_to_palette(255, 0, 0),
4380            16 + 36 * 5 + 6 * 0 + 0
4381        ); // Red
4382        assert_eq!(
4383            AnsiProcessor::rgb_to_palette(0, 255, 0),
4384            16 + 36 * 0 + 6 * 5 + 0
4385        ); // Green
4386        assert_eq!(
4387            AnsiProcessor::rgb_to_palette(0, 0, 255),
4388            16 + 36 * 0 + 6 * 0 + 5
4389        ); // Blue
4390
4391        // Test white and black
4392        assert_eq!(
4393            AnsiProcessor::rgb_to_palette(255, 255, 255),
4394            16 + 36 * 5 + 6 * 5 + 5
4395        ); // White
4396        assert_eq!(
4397            AnsiProcessor::rgb_to_palette(0, 0, 0),
4398            16 + 36 * 0 + 6 * 0 + 0
4399        ); // Black
4400
4401        // Test mid-range color
4402        assert_eq!(
4403            AnsiProcessor::rgb_to_palette(128, 128, 128),
4404            16 + 36 * 3 + 6 * 3 + 3
4405        ); // Gray
4406    }
4407
4408    #[test]
4409    fn test_sgr_sequence_processing() {
4410        let mut processor = AnsiProcessor::new();
4411
4412        // Test basic bold parameter directly
4413        processor.apply_sgr_param(1);
4414        assert!(processor.terminal_state.current_attributes.bold);
4415
4416        // Test that apply_sgr_param works correctly for various parameters
4417        processor.apply_sgr_param(0); // Reset
4418        assert!(!processor.terminal_state.current_attributes.bold);
4419
4420        processor.apply_sgr_param(31); // Red foreground
4421        assert_eq!(
4422            processor.terminal_state.current_attributes.fg_color,
4423            Some(1)
4424        );
4425    }
4426
4427    #[test]
4428    fn test_terminal_cell_extended_attributes() {
4429        let mut cell = TerminalCell::default();
4430
4431        // Test all default values
4432        assert!(!cell.bold);
4433        assert!(!cell.dim);
4434        assert!(!cell.italic);
4435        assert!(!cell.underline);
4436        assert!(!cell.double_underline);
4437        assert!(!cell.blink);
4438        assert!(!cell.reverse);
4439        assert!(!cell.hidden);
4440        assert!(!cell.strikethrough);
4441        assert!(!cell.framed);
4442        assert!(!cell.encircled);
4443        assert!(!cell.overlined);
4444        assert!(cell.font_id.is_none());
4445
4446        // Test setting attributes
4447        cell.bold = true;
4448        cell.dim = true;
4449        cell.double_underline = true;
4450        cell.font_id = Some(5);
4451
4452        assert!(cell.bold);
4453        assert!(cell.dim);
4454        assert!(cell.double_underline);
4455        assert_eq!(cell.font_id, Some(5));
4456    }
4457
4458    #[test]
4459    fn test_scrolling_region_support() {
4460        let mut terminal_state = TerminalState::new(80, 24);
4461
4462        // Test setting scrolling region
4463        terminal_state.set_scrolling_region(Some(5), Some(20));
4464        assert_eq!(terminal_state.scroll_region.top, 4); // 5-1 (1-based to 0-based)
4465        assert_eq!(terminal_state.scroll_region.bottom, 19); // 20-1
4466
4467        // Test invalid regions reset to full screen
4468        terminal_state.set_scrolling_region(Some(25), Some(30)); // Beyond screen bounds
4469        assert_eq!(terminal_state.scroll_region.top, 0);
4470        assert_eq!(terminal_state.scroll_region.bottom, 23);
4471
4472        // Test invalid order resets to full screen
4473        terminal_state.set_scrolling_region(Some(15), Some(10)); // Bottom < top
4474        assert_eq!(terminal_state.scroll_region.top, 0);
4475        assert_eq!(terminal_state.scroll_region.bottom, 23);
4476
4477        // Test reset scrolling region
4478        terminal_state.set_scrolling_region(Some(5), Some(15));
4479        terminal_state.reset_scrolling_region();
4480        assert_eq!(terminal_state.scroll_region.top, 0);
4481        assert_eq!(terminal_state.scroll_region.bottom, 23);
4482    }
4483
4484    #[test]
4485    fn test_scrolling_within_region() {
4486        let mut terminal_state = TerminalState::new(80, 24);
4487
4488        // Set scrolling region from lines 5-15 (1-based input)
4489        terminal_state.set_scrolling_region(Some(5), Some(15));
4490        assert_eq!(terminal_state.scroll_region.top, 4); // 0-based
4491        assert_eq!(terminal_state.scroll_region.bottom, 14); // 0-based
4492
4493        // Test basic scrolling operations (without complex content verification)
4494        // These operations should not panic and should complete successfully
4495        terminal_state.scroll_up_in_region(1);
4496        terminal_state.scroll_down_in_region(1);
4497
4498        // Verify the scrolling region is still properly set after operations
4499        assert_eq!(terminal_state.scroll_region.top, 4);
4500        assert_eq!(terminal_state.scroll_region.bottom, 14);
4501    }
4502
4503    #[test]
4504    fn test_cursor_in_scrolling_region() {
4505        let mut terminal_state = TerminalState::new(80, 24);
4506
4507        // Set scrolling region
4508        terminal_state.set_scrolling_region(Some(10), Some(20));
4509
4510        // Test cursor outside region
4511        terminal_state.set_cursor_position(0, 5);
4512        assert!(!terminal_state.is_cursor_in_scrolling_region());
4513
4514        // Test cursor inside region
4515        terminal_state.set_cursor_position(0, 15);
4516        assert!(terminal_state.is_cursor_in_scrolling_region());
4517
4518        // Test cursor at boundaries
4519        terminal_state.set_cursor_position(0, 9); // Top boundary (0-based)
4520        assert!(terminal_state.is_cursor_in_scrolling_region());
4521
4522        terminal_state.set_cursor_position(0, 19); // Bottom boundary (0-based)
4523        assert!(terminal_state.is_cursor_in_scrolling_region());
4524    }
4525
4526    #[test]
4527    fn test_line_feed_with_scrolling_region() {
4528        let mut terminal_state = TerminalState::new(80, 24);
4529
4530        // Set scrolling region from lines 10-15
4531        terminal_state.set_scrolling_region(Some(10), Some(15));
4532
4533        // Position cursor at bottom of scrolling region
4534        terminal_state.set_cursor_position(5, 14); // Line 15 (1-based)
4535
4536        // Line feed should trigger scroll and keep cursor at bottom
4537        let original_y = terminal_state.get_cursor().y;
4538        terminal_state.line_feed_with_scrolling();
4539        assert_eq!(terminal_state.get_cursor().y, original_y); // Should stay at bottom
4540        assert_eq!(terminal_state.get_cursor().x, 5); // X position unchanged
4541
4542        // Position cursor within scrolling region
4543        terminal_state.set_cursor_position(10, 12); // Line 13 (1-based)
4544        terminal_state.line_feed_with_scrolling();
4545        assert_eq!(terminal_state.get_cursor().y, 13); // Should move down one line
4546        assert_eq!(terminal_state.get_cursor().x, 10); // X position unchanged
4547    }
4548
4549    #[test]
4550    fn test_reverse_line_feed_with_scrolling_region() {
4551        let mut terminal_state = TerminalState::new(80, 24);
4552
4553        // Set scrolling region from lines 10-15
4554        terminal_state.set_scrolling_region(Some(10), Some(15));
4555
4556        // Position cursor at top of scrolling region
4557        terminal_state.set_cursor_position(5, 9); // Line 10 (1-based)
4558
4559        // Reverse line feed should trigger scroll and keep cursor at top
4560        let original_y = terminal_state.get_cursor().y;
4561        terminal_state.reverse_line_feed_with_scrolling();
4562        assert_eq!(terminal_state.get_cursor().y, original_y); // Should stay at top
4563        assert_eq!(terminal_state.get_cursor().x, 5); // X position unchanged
4564
4565        // Position cursor within scrolling region
4566        terminal_state.set_cursor_position(10, 12); // Line 13 (1-based)
4567        terminal_state.reverse_line_feed_with_scrolling();
4568        assert_eq!(terminal_state.get_cursor().y, 11); // Should move up one line
4569        assert_eq!(terminal_state.get_cursor().x, 10); // X position unchanged
4570    }
4571
4572    #[test]
4573    fn test_scrolling_region_message_operations() {
4574        let mut processor = TerminalMessageProcessor::new();
4575
4576        // Test set scrolling region message
4577        processor.process_message(TerminalMessage::SetScrollingRegion { top: 5, bottom: 15 });
4578        assert_eq!(processor.ansi_processor.terminal_state.scroll_region.top, 5); // 0-based (6-1)
4579        assert_eq!(
4580            processor.ansi_processor.terminal_state.scroll_region.bottom,
4581            15
4582        ); // 0-based (16-1)
4583
4584        // Test reset scrolling region message
4585        processor.process_message(TerminalMessage::ResetScrollingRegion);
4586        assert_eq!(processor.ansi_processor.terminal_state.scroll_region.top, 0);
4587        assert_eq!(
4588            processor.ansi_processor.terminal_state.scroll_region.bottom,
4589            23
4590        ); // Screen height - 1
4591
4592        // Test scroll up in region message
4593        processor.process_message(TerminalMessage::SetScrollingRegion { top: 5, bottom: 10 });
4594        processor.process_message(TerminalMessage::ScrollUpInRegion { lines: 2 });
4595        // Verify scrolling occurred (content would be moved, but we can't easily test without content setup)
4596
4597        // Test scroll down in region message
4598        processor.process_message(TerminalMessage::ScrollDownInRegion { lines: 1 });
4599        // Verify scrolling occurred
4600    }
4601
4602    #[test]
4603    fn test_decstbm_command_processing() {
4604        let mut processor = AnsiProcessor::new();
4605
4606        // Test DECSTBM command with parameters
4607        processor.process_string("\x1b[10;20r"); // Set margins 10-20
4608        assert_eq!(processor.terminal_state.scroll_region.top, 9); // 10-1 (1-based to 0-based)
4609        assert_eq!(processor.terminal_state.scroll_region.bottom, 19); // 20-1
4610
4611        // DECSTBM should move cursor to home position of scrolling region
4612        assert_eq!(processor.terminal_state.get_cursor().x, 0);
4613        assert_eq!(processor.terminal_state.get_cursor().y, 9); // Top of scrolling region
4614
4615        // Test DECSTBM without parameters (reset to full screen)
4616        processor.process_string("\x1b[r");
4617        assert_eq!(processor.terminal_state.scroll_region.top, 0);
4618        assert_eq!(processor.terminal_state.scroll_region.bottom, 23);
4619
4620        // Test SU (Scroll Up) command
4621        processor.process_string("\x1b[10;15r"); // Set region first
4622        processor.process_string("\x1b[3S"); // Scroll up 3 lines
4623                                             // Scrolling would occur within the region
4624
4625        // Test SD (Scroll Down) command
4626        processor.process_string("\x1b[2T"); // Scroll down 2 lines
4627                                             // Scrolling would occur within the region
4628    }
4629
4630    #[test]
4631    fn test_terminal_mode_management() {
4632        let mut terminal_state = TerminalState::new(80, 24);
4633
4634        // Test cursor key mode (DECCKM)
4635        assert!(!terminal_state.mode.cursor_key_mode); // Default is disabled
4636        let normal_up = terminal_state.get_cursor_key_sequence("up");
4637        assert_eq!(normal_up, "\x1b[A");
4638
4639        terminal_state.mode.cursor_key_mode = true;
4640        let app_up = terminal_state.get_cursor_key_sequence("up");
4641        assert_eq!(app_up, "\x1bOA");
4642
4643        // Test keypad mode (DECPAM)
4644        assert!(!terminal_state.mode.keypad_mode); // Default is disabled
4645        let normal_keypad = terminal_state.get_keypad_sequence("5");
4646        assert_eq!(normal_keypad, "5");
4647
4648        terminal_state.mode.keypad_mode = true;
4649        let app_keypad = terminal_state.get_keypad_sequence("5");
4650        assert_eq!(app_keypad, "\x1bOu");
4651
4652        // Test origin mode (DECOM)
4653        terminal_state.set_scrolling_region(Some(10), Some(20));
4654        terminal_state.mode.origin_mode = false;
4655        terminal_state.set_cursor_position(5, 15);
4656        assert_eq!(terminal_state.get_cursor().y, 15); // Absolute positioning
4657
4658        terminal_state.mode.origin_mode = true;
4659        terminal_state.set_cursor_position(5, 5);
4660        assert_eq!(terminal_state.get_cursor().y, 14); // 9 + 5 (relative to scrolling region)
4661    }
4662
4663    #[test]
4664    fn test_insert_and_auto_wrap_modes() {
4665        let mut terminal_state = TerminalState::new(80, 24);
4666
4667        // Test insert mode effects
4668        terminal_state.set_cursor_position(0, 0);
4669        terminal_state.mode.insert_mode = true;
4670
4671        // Insert mode should shift characters right
4672        terminal_state.insert_character_at_cursor();
4673        // Verify the method completes without panic
4674
4675        // Test delete character functionality
4676        terminal_state.delete_character_at_cursor(1);
4677        // Verify the method completes without panic
4678
4679        // Test auto-wrap mode
4680        terminal_state.mode.auto_wrap_mode = true;
4681        assert!(terminal_state.mode.auto_wrap_mode);
4682
4683        terminal_state.mode.auto_wrap_mode = false;
4684        assert!(!terminal_state.mode.auto_wrap_mode);
4685    }
4686
4687    #[test]
4688    fn test_cursor_key_sequences() {
4689        let mut terminal_state = TerminalState::new(80, 24);
4690
4691        // Test all cursor keys in normal mode
4692        terminal_state.mode.cursor_key_mode = false;
4693        assert_eq!(terminal_state.get_cursor_key_sequence("up"), "\x1b[A");
4694        assert_eq!(terminal_state.get_cursor_key_sequence("down"), "\x1b[B");
4695        assert_eq!(terminal_state.get_cursor_key_sequence("right"), "\x1b[C");
4696        assert_eq!(terminal_state.get_cursor_key_sequence("left"), "\x1b[D");
4697        assert_eq!(terminal_state.get_cursor_key_sequence("home"), "\x1b[H");
4698        assert_eq!(terminal_state.get_cursor_key_sequence("end"), "\x1b[F");
4699
4700        // Test all cursor keys in application mode
4701        terminal_state.mode.cursor_key_mode = true;
4702        assert_eq!(terminal_state.get_cursor_key_sequence("up"), "\x1bOA");
4703        assert_eq!(terminal_state.get_cursor_key_sequence("down"), "\x1bOB");
4704        assert_eq!(terminal_state.get_cursor_key_sequence("right"), "\x1bOC");
4705        assert_eq!(terminal_state.get_cursor_key_sequence("left"), "\x1bOD");
4706        assert_eq!(terminal_state.get_cursor_key_sequence("home"), "\x1bOH");
4707        assert_eq!(terminal_state.get_cursor_key_sequence("end"), "\x1bOF");
4708    }
4709
4710    #[test]
4711    fn test_keypad_sequences() {
4712        let mut terminal_state = TerminalState::new(80, 24);
4713
4714        // Test keypad keys in normal mode
4715        terminal_state.mode.keypad_mode = false;
4716        assert_eq!(terminal_state.get_keypad_sequence("0"), "0");
4717        assert_eq!(terminal_state.get_keypad_sequence("5"), "5");
4718        assert_eq!(terminal_state.get_keypad_sequence("+"), "+");
4719        assert_eq!(terminal_state.get_keypad_sequence("enter"), "enter");
4720
4721        // Test keypad keys in application mode
4722        terminal_state.mode.keypad_mode = true;
4723        assert_eq!(terminal_state.get_keypad_sequence("0"), "\x1bOp");
4724        assert_eq!(terminal_state.get_keypad_sequence("1"), "\x1bOq");
4725        assert_eq!(terminal_state.get_keypad_sequence("2"), "\x1bOr");
4726        assert_eq!(terminal_state.get_keypad_sequence("5"), "\x1bOu");
4727        assert_eq!(terminal_state.get_keypad_sequence("9"), "\x1bOy");
4728        assert_eq!(terminal_state.get_keypad_sequence("."), "\x1bOn");
4729        assert_eq!(terminal_state.get_keypad_sequence("+"), "\x1bOk");
4730        assert_eq!(terminal_state.get_keypad_sequence("-"), "\x1bOm");
4731        assert_eq!(terminal_state.get_keypad_sequence("*"), "\x1bOj");
4732        assert_eq!(terminal_state.get_keypad_sequence("/"), "\x1bOo");
4733        assert_eq!(terminal_state.get_keypad_sequence("="), "\x1bOX");
4734        assert_eq!(terminal_state.get_keypad_sequence("enter"), "\x1bOM");
4735    }
4736
4737    #[test]
4738    fn test_newline_mode() {
4739        let mut terminal_state = TerminalState::new(80, 24);
4740
4741        // Position cursor away from origin
4742        terminal_state.set_cursor_position(10, 5);
4743        let initial_x = terminal_state.get_cursor().x;
4744        let initial_y = terminal_state.get_cursor().y;
4745
4746        // Test LNM disabled (default) - newline is just LF
4747        terminal_state.mode.local_echo_mode = false;
4748        terminal_state.process_newline();
4749        assert_eq!(terminal_state.get_cursor().x, initial_x); // X unchanged
4750        assert_eq!(terminal_state.get_cursor().y, initial_y + 1); // Y incremented
4751
4752        // Reset position
4753        terminal_state.set_cursor_position(10, 5);
4754
4755        // Test LNM enabled - newline is CR+LF
4756        terminal_state.mode.local_echo_mode = true;
4757        terminal_state.process_newline();
4758        assert_eq!(terminal_state.get_cursor().x, 0); // X reset to 0 (CR)
4759        assert_eq!(terminal_state.get_cursor().y, 6); // Y incremented (LF)
4760    }
4761
4762    #[test]
4763    fn test_origin_mode_with_scrolling_region() {
4764        let mut terminal_state = TerminalState::new(80, 24);
4765
4766        // Set scrolling region from lines 10-20 (1-based input)
4767        terminal_state.set_scrolling_region(Some(10), Some(20));
4768
4769        // Test absolute positioning (origin mode disabled)
4770        terminal_state.mode.origin_mode = false;
4771        terminal_state.set_cursor_position(5, 15);
4772        assert_eq!(terminal_state.get_cursor().x, 5);
4773        assert_eq!(terminal_state.get_cursor().y, 15); // Absolute position
4774
4775        // Test relative positioning (origin mode enabled)
4776        terminal_state.mode.origin_mode = true;
4777        terminal_state.set_cursor_position(7, 3);
4778        assert_eq!(terminal_state.get_cursor().x, 7);
4779        assert_eq!(terminal_state.get_cursor().y, 12); // 9 (region_top) + 3 = 12
4780
4781        // Test bounds checking in origin mode
4782        terminal_state.set_cursor_position(10, 50); // Y beyond region
4783        assert_eq!(terminal_state.get_cursor().y, 19); // Clamped to region bottom
4784    }
4785
4786    #[test]
4787    fn test_reverse_video_mode() {
4788        let mut terminal_state = TerminalState::new(80, 24);
4789
4790        // Test reverse video mode state
4791        assert!(!terminal_state.mode.reverse_video); // Default is disabled
4792        terminal_state.mode.reverse_video = true;
4793        assert!(terminal_state.mode.reverse_video);
4794
4795        // Reverse video effects are tested implicitly through put_char_at_cursor
4796        // The color swapping logic is applied when characters are written
4797    }
4798
4799    #[test]
4800    fn test_terminal_mode_message_integration() {
4801        let mut processor = TerminalMessageProcessor::new();
4802
4803        // Test mode setting through messages
4804        processor.process_message(TerminalMessage::SetMode {
4805            mode: TerminalModeType::CursorKeys,
4806            enabled: true,
4807        });
4808        assert!(processor.ansi_processor.terminal_state.mode.cursor_key_mode);
4809
4810        processor.process_message(TerminalMessage::SetMode {
4811            mode: TerminalModeType::AutoWrap,
4812            enabled: true,
4813        });
4814        assert!(processor.ansi_processor.terminal_state.mode.auto_wrap_mode);
4815
4816        processor.process_message(TerminalMessage::SetMode {
4817            mode: TerminalModeType::Origin,
4818            enabled: true,
4819        });
4820        assert!(processor.ansi_processor.terminal_state.mode.origin_mode);
4821
4822        // Test disabling modes
4823        processor.process_message(TerminalMessage::SetMode {
4824            mode: TerminalModeType::CursorKeys,
4825            enabled: false,
4826        });
4827        assert!(!processor.ansi_processor.terminal_state.mode.cursor_key_mode);
4828    }
4829}