1use vte::{Params, Parser, Perform};
2
3#[derive(Debug, Clone, PartialEq)]
5pub enum TerminalMessage {
6 ProcessBytes(Vec<u8>),
8 SendInput(String),
9 ResizeTerminal {
10 width: usize,
11 height: usize,
12 },
13
14 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 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 SetMode {
77 mode: TerminalModeType,
78 enabled: bool,
79 },
80
81 SetAttributes {
83 attributes: TerminalAttributes,
84 },
85 ResetAttributes,
86
87 SetScrollingRegion {
89 top: usize,
90 bottom: usize,
91 },
92 ResetScrollingRegion,
93 ScrollUpInRegion {
94 lines: usize,
95 }, ScrollDownInRegion {
97 lines: usize,
98 }, SetTabStop,
102 ClearTabStop,
103 ClearAllTabStops,
104 TabForward {
105 count: usize,
106 },
107 TabBackward {
108 count: usize,
109 },
110
111 DeviceStatusReport {
113 report_type: DeviceReportType,
114 },
115 DeviceAttributes {
116 primary: bool,
117 },
118 TerminalIdentification,
119
120 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 ContentUpdate {
137 content: String,
138 dirty_regions: Vec<DirtyRegion>,
139 replace_mode: bool,
140 },
141
142 MouseEvent {
144 event_type: MouseEventType,
145 x: usize,
146 y: usize,
147 button: Option<MouseButton>,
148 modifiers: MouseModifiers,
149 },
150
151 SetCharacterSet {
153 set: CharacterSetType,
154 charset: String,
155 },
156
157 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, Keypad, AutoWrap, Origin, Insert, LocalEcho, ReverseVideo, MouseX10, MouseNormal,
182 MouseButtonEvent,
183 MouseAnyEvent,
184 MouseSgr,
185 BracketedPaste,
186 AlternateScreen, }
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), Palette(u8), Rgb { r: u8, g: u8, b: u8 }, }
208
209#[derive(Debug, Clone, PartialEq)]
210pub enum DeviceReportType {
211 Status, CursorPosition, PrinterStatus, UdkStatus, KeyboardStatus, LocatorStatus, }
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)]
282pub struct TerminalCell {
284 pub character: char,
285 pub fg_color: Option<u8>,
286 pub bg_color: Option<u8>,
287
288 pub bold: bool,
290 pub dim: bool, pub italic: bool,
292 pub underline: bool,
293 pub double_underline: bool, pub blink: bool, pub reverse: bool,
296 pub hidden: bool, pub strikethrough: bool,
298
299 pub font_id: Option<u8>, pub framed: bool, pub encircled: bool, pub overlined: bool, pub ideogram_underline: bool, pub ideogram_double_underline: bool, pub ideogram_overline: bool, pub ideogram_double_overline: bool, pub ideogram_stress: bool, }
312
313impl Default for TerminalCell {
314 fn default() -> Self {
315 TerminalCell {
316 character: ' ',
317 fg_color: None,
318 bg_color: None,
319
320 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 font_id: None,
333 framed: false,
334 encircled: false,
335 overlined: false,
336
337 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
368pub enum LineAttribute {
369 #[default]
370 Normal, DoubleWidth, DoubleHeightTop, DoubleHeightBottom, }
375
376#[derive(Debug, Clone, PartialEq, Default)]
378pub struct SGRState {
379 pub expecting_extended_fg: bool, pub expecting_extended_bg: bool, pub extended_fg_mode: Option<u8>, pub extended_bg_mode: Option<u8>, pub rgb_components: Vec<u8>, pub palette_index: Option<u8>, }
386
387#[derive(Debug, Clone)]
388pub struct TerminalMode {
389 pub cursor_key_mode: bool, pub keypad_mode: bool, pub auto_wrap_mode: bool, pub origin_mode: bool, pub insert_mode: bool, pub local_echo_mode: bool, pub reverse_video: bool, pub mouse_x10_mode: bool, pub mouse_normal_mode: bool, pub mouse_button_event_mode: bool, pub mouse_any_event_mode: bool, pub mouse_sgr_mode: bool, pub bracketed_paste_mode: bool, }
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 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#[derive(Default)]
429pub struct ScrollRegion {
430 pub top: usize, pub bottom: usize, }
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, pub max_scrollback: usize,
442 pub width: usize,
443 pub height: usize,
444 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 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 if let Some(top_line) = self.content.first().cloned() {
474 self.scrollback.push(top_line);
475
476 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 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 self.content.remove(0);
493 self.content.push(vec![TerminalCell::default(); self.width]);
494
495 self.line_attributes.push(LineAttribute::Normal);
497 }
498
499 pub fn scroll_down_one_line(&mut self) {
500 if let Some(line) = self.scrollback.pop() {
502 self.content.remove(self.content.len() - 1);
503 self.content.insert(0, line);
504
505 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 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 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 for row in &mut self.content {
592 row.resize(new_width, TerminalCell::default());
593 }
594
595 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 self.line_attributes
606 .resize(new_height, LineAttribute::Normal);
607
608 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 pub fn to_content_lines(&self, include_scrollback: bool) -> Vec<String> {
616 let mut lines = Vec::new();
617
618 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 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 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 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 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 result.push(cell.character);
696 }
697
698 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"); }
709
710 result
711 }
712
713 fn generate_ansi_formatting(&self, formatting: &TextFormatting) -> String {
715 let mut codes = Vec::new();
716
717 codes.push("0".to_string()); 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 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 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 pub fn get_content_for_stream(&self) -> String {
768 let lines = self.to_content_lines(true); lines.join("\n")
770 }
771}
772
773#[derive(Debug, Clone)]
774pub struct TerminalState {
775 pub screen_width: usize,
777 pub screen_height: usize,
778
779 pub primary_buffer: TerminalScreenBuffer,
781 pub alternate_buffer: TerminalScreenBuffer,
782 pub use_alternate_screen: bool,
783
784 pub cursor_save_stack: Vec<CursorState>,
786
787 pub current_attributes: TerminalCell,
789
790 pub mode: TerminalMode,
792 pub scroll_region: ScrollRegion,
793
794 pub tab_stops: Vec<bool>,
796
797 pub charset_g0: Option<String>,
799 pub charset_g1: Option<String>,
800 pub active_charset: u8, pub terminal_title: Option<String>,
804 pub icon_name: Option<String>,
805 pub title_changed: bool, pub full_screen_program_detected: bool,
809
810 pub sgr_state: SGRState,
812
813 pub dcs_sequence_type: Option<char>,
815 pub dcs_buffer: Option<Vec<u8>>,
816 pub pending_response: Option<String>,
817
818 pub osc_buffer: Option<Vec<u8>>,
820}
821
822impl TerminalState {
823 pub fn new(width: usize, height: usize) -> Self {
824 let max_scrollback = 10000; 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, 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 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 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 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 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 if origin_mode {
926 cursor.y = (region_top + y).min(region_bottom);
929 cursor.x = x.min(screen_width.saturating_sub(1));
930 } else {
931 cursor.x = x.min(screen_width.saturating_sub(1));
933 cursor.y = y.min(screen_height.saturating_sub(1));
934 }
935 }
936
937 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 pub fn set_cursor_visibility(&mut self, visible: bool) {
959 self.get_cursor_mut().visible = visible;
960 }
961
962 pub fn set_cursor_style(&mut self, style: CursorStyle) {
964 self.get_cursor_mut().style = style;
965 }
966
967 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 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 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 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 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 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 pub fn cursor_to_line_start(&mut self) {
1009 self.get_cursor_mut().x = 0;
1010 }
1011
1012 pub fn cursor_next_line(&mut self, lines: usize) {
1014 self.cursor_down(lines);
1015 self.cursor_to_line_start();
1016 }
1017
1018 pub fn cursor_previous_line(&mut self, lines: usize) {
1020 self.cursor_up(lines);
1021 self.cursor_to_line_start();
1022 }
1023
1024 pub fn tab_forward(&mut self) {
1026 let cursor_x = self.get_cursor().x;
1027 let screen_width = self.screen_width;
1028
1029 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 self.get_cursor_mut().x = screen_width.saturating_sub(1);
1039 }
1040
1041 pub fn tab_backward(&mut self) {
1043 let cursor_x = self.get_cursor().x;
1044
1045 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 self.get_cursor_mut().x = 0;
1057 }
1058
1059 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 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 pub fn set_double_width_line(&mut self) {
1090 self.set_line_attribute(LineAttribute::DoubleWidth);
1091 }
1092
1093 pub fn set_double_height_line_top(&mut self) {
1095 self.set_line_attribute(LineAttribute::DoubleHeightTop);
1096 }
1097
1098 pub fn set_double_height_line_bottom(&mut self) {
1100 self.set_line_attribute(LineAttribute::DoubleHeightBottom);
1101 }
1102
1103 pub fn set_normal_line(&mut self) {
1105 self.set_line_attribute(LineAttribute::Normal);
1106 }
1107
1108 pub fn set_scrolling_region(&mut self, top: Option<usize>, bottom: Option<usize>) {
1110 let screen_height = self.screen_height;
1111
1112 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 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 else {
1125 self.scroll_region.top = 0;
1126 self.scroll_region.bottom = screen_height.saturating_sub(1);
1127 }
1128 }
1129
1130 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 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 for _ in 0..lines {
1148 {
1150 let buffer = self.get_active_buffer();
1151 if top <= bottom && top < buffer.content.len() && bottom < buffer.content.len() {
1152 let _removed_line = buffer.content.remove(top);
1154
1155 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 let blank_line = vec![TerminalCell::default(); screen_width];
1167 buffer.content.push(blank_line);
1168 }
1169 }
1170 }
1171 }
1172 }
1173
1174 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 for _ in 0..lines {
1186 {
1188 let buffer = self.get_active_buffer();
1189 if top <= bottom && top < buffer.content.len() && bottom < buffer.content.len() {
1190 if bottom < buffer.content.len() {
1192 let _removed_line = buffer.content.remove(bottom);
1193 }
1194
1195 let blank_line = vec![TerminalCell::default(); screen_width];
1197 buffer.content.insert(top, blank_line);
1198 }
1199 }
1200 }
1201 }
1202
1203 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 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 current_y >= bottom {
1216 self.scroll_up_in_region(1);
1217 self.get_cursor_mut().y = bottom;
1219 } else {
1220 self.get_cursor_mut().y = (current_y + 1).min(bottom);
1222 }
1223 }
1224
1225 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 current_y <= top {
1232 self.scroll_down_in_region(1);
1233 self.get_cursor_mut().y = top;
1235 } else {
1236 self.get_cursor_mut().y = current_y.saturating_sub(1).max(top);
1238 }
1239 }
1240
1241 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 let line = &mut buffer.content[cursor_y];
1251 if cursor_x < line.len() {
1252 let blank_cell = TerminalCell::default();
1254 line.insert(cursor_x, blank_cell);
1255
1256 if line.len() > screen_width {
1258 line.truncate(screen_width);
1259 }
1260 }
1261 }
1262 }
1263
1264 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 while line.len() < screen_width {
1281 line.push(TerminalCell::default());
1282 }
1283 }
1284 }
1285
1286 pub fn get_cursor_key_sequence(&self, key: &str) -> String {
1288 if self.mode.cursor_key_mode {
1289 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), }
1299 } else {
1300 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 pub fn get_keypad_sequence(&self, key: &str) -> String {
1315 if self.mode.keypad_mode {
1316 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(), }
1337 } else {
1338 key.to_string()
1340 }
1341 }
1342
1343 pub fn process_newline(&mut self) {
1345 if self.mode.local_echo_mode {
1346 self.get_cursor_mut().x = 0; self.line_feed_with_scrolling(); } else {
1350 self.line_feed_with_scrolling();
1352 }
1353 }
1354
1355 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 }
1363 }
1364
1365 pub fn switch_to_primary_screen(&mut self) {
1367 if self.use_alternate_screen {
1368 self.use_alternate_screen = false;
1369 }
1371 }
1372
1373 pub fn clear_alternate_screen(&mut self) {
1375 self.alternate_buffer.clear_screen();
1376 }
1377
1378 pub fn verify_buffer_isolation(&self) -> bool {
1380 !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 self.primary_buffer.resize(new_width, new_height);
1402 self.alternate_buffer.resize(new_width, new_height);
1403
1404 self.scroll_region.bottom = new_height.saturating_sub(1);
1406
1407 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 pub fn process_dcs_query(&mut self, data: &str) {
1431 match data {
1432 "1c" => {
1433 self.pending_response = Some("\x1b[?6c".to_string());
1435 }
1436 "2c" => {
1437 self.pending_response = Some("\x1b[>0;276;0c".to_string());
1439 }
1440 _ => {
1441 log::debug!("Unknown DCS query: {}", data);
1442 }
1443 }
1444 }
1445
1446 pub fn process_dcs_extended(&mut self, data: &str) {
1448 log::debug!("DCS extended capability: {}", data);
1451 }
1452
1453 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 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 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 let x = (x + 1).min(255); let y = (y + 1).min(255); if self.mode.mouse_sgr_mode {
1494 self.generate_sgr_mouse_report(event_type, x, y, button, modifiers)
1496 } else {
1497 self.generate_standard_mouse_report(event_type, x, y, button, modifiers)
1499 }
1500 }
1501
1502 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; 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 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 match event_type {
1538 MouseEventType::Press => {} MouseEventType::Release => {
1540 if self.mode.mouse_x10_mode {
1541 return None; }
1543 cb |= 3; }
1545 MouseEventType::Motion => {
1546 if !self.mode.mouse_any_event_mode {
1547 return None; }
1549 cb |= 32; }
1551 MouseEventType::Wheel => {
1552 }
1554 }
1555
1556 cb += 32;
1558
1559 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 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 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 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 if event_type == MouseEventType::Motion && self.mode.mouse_any_event_mode {
1604 cb |= 32;
1605 }
1606
1607 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
1617pub 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 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 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 self.ansi_processor
1740 .terminal_state
1741 .set_scrolling_region(Some(top + 1), Some(bottom + 1));
1742 }
1743 TerminalMessage::ResetScrollingRegion => {
1744 self.ansi_processor.terminal_state.reset_scrolling_region();
1746 }
1747 TerminalMessage::ScrollUpInRegion { lines } => {
1748 self.ansi_processor
1750 .terminal_state
1751 .scroll_up_in_region(lines);
1752 }
1753 TerminalMessage::ScrollDownInRegion { lines } => {
1754 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 _ => {
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 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 fn generate_device_status_report(&self, report_type: DeviceReportType) -> String {
1839 match report_type {
1840 DeviceReportType::Status => "\x1b[0n".to_string(), 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 "\x1b[?10n".to_string()
1848 }
1849 DeviceReportType::UdkStatus => {
1850 "\x1b[?20n".to_string()
1852 }
1853 DeviceReportType::KeyboardStatus => {
1854 "\x1b[?27;1n".to_string()
1856 }
1857 DeviceReportType::LocatorStatus => {
1858 "\x1b[?50n".to_string()
1860 }
1861 }
1862 }
1863
1864 pub fn get_pending_responses(&mut self) -> Vec<String> {
1866 std::mem::take(&mut self.pending_responses)
1867 }
1868
1869 pub fn queue_message(&mut self, message: TerminalMessage) {
1871 self.message_queue.push(message);
1872 }
1873
1874 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, 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 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 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 pub fn get_screen_content_for_stream(&self) -> String {
1946 if self.use_screen_buffer {
1947 self.terminal_state
1949 .get_active_buffer_ref()
1950 .get_content_for_stream()
1951 } else {
1952 self.get_processed_text()
1954 }
1955 }
1956
1957 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 self.processed_text.lines().map(|s| s.to_string()).collect()
1966 }
1967 }
1968
1969 pub fn get_state_changes(&self) -> Vec<TerminalMessage> {
1971 let mut messages = Vec::new();
1972
1973 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 if let Some(title) = &self.terminal_state.terminal_title {
1984 messages.push(TerminalMessage::SetTerminalTitle {
1985 title: title.clone(),
1986 });
1987 }
1988
1989 if self.terminal_state.use_alternate_screen {
1991 messages.push(TerminalMessage::SwitchScreenBuffer { to_alternate: true });
1992 }
1993
1994 messages
1995 }
1996
1997 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 let dirty_regions = self.calculate_dirty_regions();
2007
2008 TerminalMessage::ContentUpdate {
2009 content,
2010 dirty_regions,
2011 replace_mode,
2012 }
2013 }
2014
2015 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 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 pub fn has_baseline(&self) -> bool {
2034 self.baseline_captured && self.previous_screen_state.is_some()
2035 }
2036
2037 pub fn get_terminal_state(&self) -> &TerminalState {
2039 &self.terminal_state
2040 }
2041
2042 fn calculate_dirty_regions(&self) -> Vec<DirtyRegion> {
2044 if !self.use_screen_buffer {
2046 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 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 for y in 0..self.terminal_state.screen_height.min(previous_state.len()) {
2074 let mut line_has_changes = false;
2075 let current_line = ¤t_screen[y];
2076 let previous_line = &previous_state[y];
2077
2078 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 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 region.height += 1;
2110 }
2111 Some(region) => {
2112 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 current_region = Some(DirtyRegion {
2124 x: first_x,
2125 y,
2126 width,
2127 height: 1,
2128 });
2129 }
2130 }
2131 }
2132 }
2133
2134 if let Some(region) = current_region {
2136 dirty_regions.push(region);
2137 }
2138
2139 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 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 if reverse_video {
2157 std::mem::swap(&mut cell.fg_color, &mut cell.bg_color);
2159
2160 if cell.fg_color.is_none() && cell.bg_color.is_none() {
2162 cell.fg_color = Some(0); cell.bg_color = Some(15); }
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() } 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 fn apply_sgr_param(&mut self, param: u16) {
2229 match param {
2230 0 => {
2231 self.terminal_state.current_attributes = TerminalCell::default();
2233 }
2234 1 => self.terminal_state.current_attributes.bold = true,
2236 2 => self.terminal_state.current_attributes.dim = true, 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, 6 => self.terminal_state.current_attributes.blink = true, 7 => self.terminal_state.current_attributes.reverse = true,
2242 8 => self.terminal_state.current_attributes.hidden = true, 9 => self.terminal_state.current_attributes.strikethrough = true,
2244
2245 10 => { }
2247 11..=19 => {
2248 self.terminal_state.current_attributes.font_id = Some((param - 10) as u8);
2250 }
2251 20 => { }
2252 21 => {
2253 self.terminal_state.current_attributes.double_underline = true;
2255 }
2256
2257 22 => {
2259 self.terminal_state.current_attributes.bold = false;
2261 self.terminal_state.current_attributes.dim = false;
2262 }
2263 23 => {
2264 self.terminal_state.current_attributes.italic = false;
2266 }
2267 24 => {
2268 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, 26 => { }
2274 27 => self.terminal_state.current_attributes.reverse = false,
2275 28 => self.terminal_state.current_attributes.hidden = false, 29 => self.terminal_state.current_attributes.strikethrough = false,
2277
2278 30..=37 => self.terminal_state.current_attributes.fg_color = Some((param - 30) as u8),
2280 38 => {
2281 self.terminal_state.sgr_state.expecting_extended_fg = true;
2283 }
2284 39 => self.terminal_state.current_attributes.fg_color = None, 40..=47 => self.terminal_state.current_attributes.bg_color = Some((param - 40) as u8),
2288 48 => {
2289 self.terminal_state.sgr_state.expecting_extended_bg = true;
2291 }
2292 49 => self.terminal_state.current_attributes.bg_color = None, 50 => { }
2296 51 => self.terminal_state.current_attributes.framed = true, 52 => self.terminal_state.current_attributes.encircled = true, 53 => self.terminal_state.current_attributes.overlined = true, 54 => {
2300 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, 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 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 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 _ => {} }
2343 }
2344
2345 fn apply_sgr_sequence(&mut self, params: &Params) {
2347 if params.is_empty() {
2348 self.apply_sgr_param(0); return;
2350 }
2351
2352 let mut param_iter = params.iter().flat_map(|slice| slice.iter());
2353
2354 while let Some(¶m) = param_iter.next() {
2355 match param {
2356 38 => {
2357 if let Some(&mode) = param_iter.next() {
2359 match mode {
2360 5 => {
2361 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 if let (Some(&r), Some(&g), Some(&b)) =
2370 (param_iter.next(), param_iter.next(), param_iter.next())
2371 {
2372 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 _ => {} }
2381 }
2382 }
2383 48 => {
2384 if let Some(&mode) = param_iter.next() {
2386 match mode {
2387 5 => {
2388 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 if let (Some(&r), Some(&g), Some(&b)) =
2397 (param_iter.next(), param_iter.next(), param_iter.next())
2398 {
2399 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 _ => {} }
2408 }
2409 }
2410 _ => {
2411 self.apply_sgr_param(param);
2413 }
2414 }
2415 }
2416 }
2417
2418 fn rgb_to_palette(r: u8, g: u8, b: u8) -> u8 {
2420 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 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 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 } 2 => 4, 3 => 2, 6 => {
2458 if terminal_mode.origin_mode {
2459 1
2460 } else {
2461 2
2462 }
2463 } 7 => {
2465 if terminal_mode.auto_wrap_mode {
2466 1
2467 } else {
2468 2
2469 }
2470 } 25 => {
2472 if self.terminal_state.get_cursor().visible {
2473 1
2474 } else {
2475 2
2476 }
2477 } 47 => {
2479 if self.alternate_screen_mode {
2480 1
2481 } else {
2482 2
2483 }
2484 } 1000 => {
2486 if terminal_mode.mouse_x10_mode {
2487 1
2488 } else {
2489 2
2490 }
2491 } 1002 => {
2493 if terminal_mode.mouse_button_event_mode {
2494 1
2495 } else {
2496 2
2497 }
2498 } 1003 => {
2500 if terminal_mode.mouse_any_event_mode {
2501 1
2502 } else {
2503 2
2504 }
2505 } 1006 => {
2507 if terminal_mode.mouse_sgr_mode {
2508 1
2509 } else {
2510 2
2511 }
2512 } 1047 => {
2514 if self.alternate_screen_mode {
2515 1
2516 } else {
2517 2
2518 }
2519 } 1049 => {
2521 if self.alternate_screen_mode {
2522 1
2523 } else {
2524 2
2525 }
2526 } 2004 => {
2528 if terminal_mode.bracketed_paste_mode {
2529 1
2530 } else {
2531 2
2532 }
2533 } _ => 0, }
2536 }
2537
2538 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 } 20 => {
2550 if terminal_mode.local_echo_mode {
2551 1
2552 } else {
2553 2
2554 }
2555 } _ => 0, }
2558 }
2559
2560 pub fn has_title_changed(&self) -> bool {
2564 self.terminal_state.title_changed
2565 }
2566
2567 pub fn get_current_terminal_title(&self) -> Option<String> {
2569 self.terminal_state.terminal_title.clone()
2570 }
2571
2572 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 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 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 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 self.terminal_state.get_cursor_mut().x = 0;
2606 self.terminal_state.line_feed_with_scrolling(); } else {
2608 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 self.terminal_state.get_cursor_mut().y += 1;
2621 self.terminal_state.get_cursor_mut().x = 0;
2622 } else {
2623 self.terminal_state.line_feed_with_scrolling();
2625 }
2627 }
2628 b'\r' => {
2629 self.terminal_state.get_cursor_mut().x = 0;
2630 }
2631 b'\t' => {
2632 self.terminal_state.tab_forward();
2634 }
2635 b'\x08' => {
2636 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 self.terminal_state.active_charset = 1;
2655 }
2656 0x0F => {
2657 self.terminal_state.active_charset = 0;
2659 }
2660 _ => {
2661 }
2663 }
2664 }
2665
2666 fn hook(&mut self, params: &Params, intermediates: &[u8], _ignore: bool, c: char) {
2667 match c {
2669 'q' => {
2670 if intermediates.is_empty() && !params.is_empty() {
2672 let query_type = Self::get_param(params, 0);
2673 if query_type == 1 {
2674 self.terminal_state.pending_response = Some("\x1b[>0;276;0c".to_string());
2676 }
2677 }
2678 }
2679 '+' => {
2680 self.terminal_state.dcs_sequence_type = Some(c);
2683 }
2684 _ => {
2685 self.terminal_state.dcs_sequence_type = Some(c);
2687 }
2688 }
2689 }
2690
2691 fn put(&mut self, byte: u8) {
2692 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 if buffer.len() > 4096 {
2700 buffer.clear();
2701 self.terminal_state.dcs_buffer = None;
2702 }
2703 }
2704 }
2705
2706 fn unhook(&mut self) {
2707 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 self.terminal_state.process_dcs_query(&data);
2721 }
2722 '+' => {
2723 self.terminal_state.process_dcs_extended(&data);
2725 }
2726 _ => {
2727 log::debug!("Unknown DCS sequence type: {}", dcs_type);
2729 }
2730 }
2731 }
2732 }
2733 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 if params.is_empty() {
2741 return;
2742 }
2743
2744 if params.len() >= 2 {
2746 let command = String::from_utf8_lossy(params[0]);
2747 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 self.terminal_state.terminal_title = Some(data.to_string());
2758 self.terminal_state.title_changed = true; log::debug!("Terminal title set to: {}", data);
2760 }
2761 "1" => {
2762 self.terminal_state.icon_name = Some(data.to_string());
2764 log::debug!("Icon name set to: {}", data);
2765 }
2766 "4" => {
2767 log::debug!("Color palette change: {}", data);
2769 }
2770 "10" => {
2771 log::debug!("Foreground color change: {}", data);
2773 }
2774 "11" => {
2775 log::debug!("Background color change: {}", data);
2777 }
2778 "52" => {
2779 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 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; 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 self.apply_sgr_sequence(params);
2820 }
2821 'H' | 'f' => {
2822 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 if row == 1 && col == 1 {
2836 self.terminal_state.full_screen_program_detected = true;
2838 self.use_screen_buffer = true;
2839 }
2840
2841 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 let n = if !params.is_empty() {
2850 Self::get_param(params, 0).max(1)
2851 } else {
2852 1
2853 };
2854 self.terminal_state.cursor_up(n as usize);
2856 }
2857 'B' => {
2858 let n = if !params.is_empty() {
2860 Self::get_param(params, 0).max(1)
2861 } else {
2862 1
2863 };
2864 self.terminal_state.cursor_down(n as usize);
2866 }
2867 'C' => {
2868 let n = if !params.is_empty() {
2870 Self::get_param(params, 0).max(1)
2871 } else {
2872 1
2873 };
2874 self.terminal_state.cursor_right(n as usize);
2876 }
2877 'D' => {
2878 let n = if !params.is_empty() {
2880 Self::get_param(params, 0).max(1)
2881 } else {
2882 1
2883 };
2884 self.terminal_state.cursor_left(n as usize);
2886 }
2887 'J' => {
2888 let n = if !params.is_empty() {
2890 Self::get_param(params, 0)
2891 } else {
2892 0
2893 };
2894
2895 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 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 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 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 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 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 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 for x in cursor_x..screen_width {
2966 screen[cursor_y][x] = TerminalCell::default();
2967 }
2968 }
2969 1 => {
2970 for x in 0..=cursor_x.min(screen_width.saturating_sub(1)) {
2972 screen[cursor_y][x] = TerminalCell::default();
2973 }
2974 }
2975 2 => {
2976 for x in 0..screen_width {
2978 screen[cursor_y][x] = TerminalCell::default();
2979 }
2980 }
2981 _ => {}
2982 }
2983 }
2984 }
2985 'h' => {
2986 if _intermediates.contains(&b'?') && !params.is_empty() {
2988 let mode = Self::get_param(params, 0);
2990 match mode {
2991 1 => {
2992 self.terminal_state.mode.cursor_key_mode = true;
2994 }
2995 6 => {
2996 self.terminal_state.mode.origin_mode = true;
2998 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 self.terminal_state.mode.auto_wrap_mode = true;
3006 }
3007 25 => {
3008 self.terminal_state.get_cursor_mut().visible = true;
3010 }
3011 1000 => {
3012 self.terminal_state.mode.mouse_x10_mode = true;
3014 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 self.terminal_state.mode.mouse_button_event_mode = true;
3023 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 self.terminal_state.mode.mouse_any_event_mode = true;
3032 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 self.terminal_state.mode.mouse_sgr_mode = true;
3041 log::debug!("F0310: Mouse SGR extended reporting enabled");
3042 }
3043 47 => {
3044 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 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 self.alternate_screen_mode = true;
3061 self.terminal_state.full_screen_program_detected = true;
3062 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 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 let mode = Self::get_param(params, 0);
3080 match mode {
3081 4 => {
3082 self.terminal_state.mode.insert_mode = true;
3084 }
3085 20 => {
3086 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 if _intermediates.contains(&b'?') && !params.is_empty() {
3098 let mode = Self::get_param(params, 0);
3100 match mode {
3101 1 => {
3102 self.terminal_state.mode.cursor_key_mode = false;
3104 }
3105 6 => {
3106 self.terminal_state.mode.origin_mode = false;
3108 self.terminal_state.get_cursor_mut().x = 0;
3110 self.terminal_state.get_cursor_mut().y = 0;
3111 }
3112 7 => {
3113 self.terminal_state.mode.auto_wrap_mode = false;
3115 }
3116 25 => {
3117 self.terminal_state.get_cursor_mut().visible = false;
3119 }
3120 1000 => {
3121 self.terminal_state.mode.mouse_x10_mode = false;
3123 log::debug!("F0310: Mouse X10 mode disabled");
3124 }
3125 1002 => {
3126 self.terminal_state.mode.mouse_button_event_mode = false;
3128 log::debug!("F0310: Mouse Button Event mode disabled");
3129 }
3130 1003 => {
3131 self.terminal_state.mode.mouse_any_event_mode = false;
3133 log::debug!("F0310: Mouse Any Event mode disabled");
3134 }
3135 1006 => {
3136 self.terminal_state.mode.mouse_sgr_mode = false;
3138 log::debug!("F0310: Mouse SGR extended reporting disabled");
3139 }
3140 47 => {
3141 self.alternate_screen_mode = false;
3143 self.terminal_state.switch_to_primary_screen();
3144 }
3146 1047 => {
3147 self.alternate_screen_mode = false;
3149 self.terminal_state.switch_to_primary_screen();
3150 }
3152 1049 => {
3153 self.alternate_screen_mode = false;
3155 self.terminal_state.switch_to_primary_screen();
3156 self.terminal_state.restore_cursor();
3158 }
3160 2004 => {
3161 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 let mode = Self::get_param(params, 0);
3172 match mode {
3173 4 => {
3174 self.terminal_state.mode.insert_mode = false;
3176 }
3177 20 => {
3178 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 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 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 let count = if !params.is_empty() {
3208 Self::get_param(params, 0).max(1) as usize
3209 } else {
3210 1
3211 };
3212 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 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 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 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 self.terminal_state.set_scrolling_region(top, bottom);
3262
3263 let region_top = self.terminal_state.scroll_region.top;
3265 self.terminal_state.set_cursor_position(0, region_top);
3266 }
3267 'n' => {
3268 if !params.is_empty() {
3270 let report_type = Self::get_param(params, 0);
3271 match report_type {
3272 5 => {
3273 self.terminal_state.pending_response = Some("\x1b[0n".to_string());
3275 }
3276 6 => {
3277 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 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 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 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 if params.is_empty() || Self::get_param(params, 0) == 0 {
3313 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 self.terminal_state.pending_response = Some("\x1b[>0;276;0c".to_string());
3324 } else if Self::get_param(params, 0) == 2 {
3325 self.terminal_state.pending_response = Some("\x1b[P!|00000000".to_string());
3327 }
3328 }
3329 'x' => {
3330 if params.is_empty() || Self::get_param(params, 0) == 0 {
3332 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 self.terminal_state.pending_response =
3338 Some("\x1b[3;1;1;128;128;1;0x".to_string());
3339 }
3340 }
3341 '$' => {
3342 if let Some(intermediate) = _intermediates.first() {
3344 if *intermediate == b'?' {
3345 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 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 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 let mode = if !params.is_empty() {
3368 Self::get_param(params, 0)
3369 } else {
3370 0
3371 };
3372
3373 match mode {
3374 0 => {
3375 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 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 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 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 self.terminal_state.save_cursor();
3427 }
3428 b'8' => {
3429 self.terminal_state.restore_cursor();
3431 }
3432 b'c' => {
3433 self.terminal_state.full_screen_program_detected = true;
3435 self.use_screen_buffer = true;
3436 self.clear_screen_buffer();
3437 }
3438 b'Z' => {
3439 self.terminal_state.pending_response = Some("\x1b[?62;1;2;6;7;8;9c".to_string());
3441 }
3442 5 => {
3443 self.terminal_state.pending_response = Some("BoxMux Terminal\r".to_string());
3445 }
3446 b'D' => {
3447 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 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 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 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 self.terminal_state.mode.keypad_mode = true;
3486 }
3487 b'>' => {
3488 self.terminal_state.mode.keypad_mode = false;
3490 }
3491 _ => {
3492 if intermediates.len() == 1 {
3494 match intermediates[0] {
3495 b'(' => {
3496 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 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 match byte {
3516 b'3' => {
3517 self.terminal_state.set_double_height_line_top();
3519 }
3520 b'4' => {
3521 self.terminal_state.set_double_height_line_bottom();
3523 }
3524 b'5' => {
3525 self.terminal_state.set_normal_line();
3527 }
3528 b'6' => {
3529 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 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 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 assert!(screen_stream_content.contains("Red text"));
3610 assert!(!screen_stream_content.is_empty());
3611
3612 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 buffer.content[0][0] = TerminalCell {
3623 character: 'H',
3624 fg_color: Some(1), 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 assert!(first_line.contains("Hi"));
3641 assert!(first_line.contains("\x1b[")); }
3643
3644 #[test]
3645 fn test_enhanced_vte_parser_integration() {
3646 let mut processor = AnsiProcessor::new();
3647 processor.set_screen_mode(true);
3648
3649 processor.process_string("\x1b="); assert!(processor.terminal_state.mode.keypad_mode);
3652
3653 processor.process_string("\x1b>"); assert!(!processor.terminal_state.mode.keypad_mode);
3655
3656 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")); processor.process_string("\x1b[5;20r"); assert_eq!(processor.terminal_state.scroll_region.top, 4); assert_eq!(processor.terminal_state.scroll_region.bottom, 19); processor.process_string("\x1b[10A"); processor.process_string("\x1b[5B"); processor.process_string("\x1b[3C"); processor.process_string("\x1b[2D"); 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 processor.process_string("\x1bP1$q\x1b\\"); 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 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 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 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 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 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 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 processor.process_queued_messages();
3747
3748 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 assert!(processor.message_queue.is_empty());
3757 }
3758
3759 #[test]
3760 fn test_device_status_reports() {
3761 let mut processor = TerminalMessageProcessor::new();
3762
3763 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"); 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"); }
3782
3783 #[test]
3784 fn test_f0311_terminal_queries() {
3785 let mut processor = AnsiProcessor::new();
3786
3787 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")); 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")); 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"); 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"); }
3811
3812 #[test]
3813 fn test_f0312_alternate_screen_buffer() {
3814 let mut processor = AnsiProcessor::new();
3815
3816 assert!(!processor.is_using_alternate_screen());
3818 assert!(!processor.should_replace_content());
3819
3820 processor.process_string("Primary screen content");
3822 let primary_content = processor.get_processed_text();
3823 assert!(primary_content.contains("Primary"));
3824
3825 processor.process_bytes("\x1b[?47h".as_bytes());
3827 assert!(processor.is_using_alternate_screen());
3828 assert!(processor.should_replace_content());
3829
3830 processor.process_string("Alternate screen content");
3832 let alt_content = processor.get_processed_text();
3833
3834 processor.process_bytes("\x1b[?47l".as_bytes());
3836 assert!(!processor.is_using_alternate_screen());
3837
3838 let restored_content = processor.get_processed_text();
3840 processor.process_bytes("\x1b[?1047h".as_bytes());
3844 assert!(processor.is_using_alternate_screen());
3845
3846 processor.process_bytes("\x1b[?1047l".as_bytes());
3848 assert!(!processor.is_using_alternate_screen());
3849
3850 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 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 processor.process_bytes("\x1b[?1049l".as_bytes());
3866 assert!(!processor.is_using_alternate_screen());
3867
3868 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 processor.set_screen_mode(true);
3879
3880 processor.process_string("Primary line 1\n");
3882 processor.process_string("Primary line 2\n");
3883
3884 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 processor.process_bytes("\x1b[?1047h".as_bytes());
3891 assert!(processor.is_using_alternate_screen());
3892
3893 processor.process_string("Alternate line 1\n");
3895 processor.process_string("Alternate line 2\n");
3896
3897 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 processor.process_bytes("\x1b[?1047l".as_bytes());
3904 assert!(!processor.is_using_alternate_screen());
3905
3906 let restored_lines = processor.get_terminal_content_lines(false);
3908 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 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 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 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 terminal_state.set_cursor_position(100, 30); assert_eq!(terminal_state.get_cursor().x, 79); assert_eq!(terminal_state.get_cursor().y, 23); 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 terminal_state.move_cursor_relative(-20, -10);
3967 assert_eq!(terminal_state.get_cursor().x, 0); assert_eq!(terminal_state.get_cursor().y, 0); }
3970
3971 #[test]
3972 fn test_cursor_save_restore() {
3973 let mut terminal_state = TerminalState::new(80, 24);
3974
3975 terminal_state.set_cursor_position(15, 10);
3977 terminal_state.set_cursor_visibility(false);
3978 terminal_state.set_cursor_style(CursorStyle::Underline);
3979
3980 terminal_state.save_cursor();
3982
3983 terminal_state.set_cursor_position(30, 20);
3985 terminal_state.set_cursor_visibility(true);
3986 terminal_state.set_cursor_style(CursorStyle::Block);
3987
3988 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 terminal_state.restore_cursor();
3996
3997 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 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 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 terminal_state.set_cursor_column(25);
4045 assert_eq!(terminal_state.get_cursor().x, 25);
4046 assert_eq!(terminal_state.get_cursor().y, 10); terminal_state.set_cursor_line(15);
4050 assert_eq!(terminal_state.get_cursor().x, 25); assert_eq!(terminal_state.get_cursor().y, 15);
4052
4053 terminal_state.set_cursor_column(100);
4055 assert_eq!(terminal_state.get_cursor().x, 79); terminal_state.set_cursor_line(50);
4058 assert_eq!(terminal_state.get_cursor().y, 23); }
4060
4061 #[test]
4062 fn test_cursor_styles() {
4063 let mut terminal_state = TerminalState::new(80, 24);
4064
4065 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 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 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 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 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 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 processor.apply_sgr_param(1); assert!(processor.terminal_state.current_attributes.bold);
4143
4144 processor.apply_sgr_param(3); assert!(processor.terminal_state.current_attributes.italic);
4146
4147 processor.apply_sgr_param(4); assert!(processor.terminal_state.current_attributes.underline);
4149
4150 processor.apply_sgr_param(7); assert!(processor.terminal_state.current_attributes.reverse);
4152
4153 processor.apply_sgr_param(9); assert!(processor.terminal_state.current_attributes.strikethrough);
4155
4156 processor.apply_sgr_param(2); assert!(processor.terminal_state.current_attributes.dim);
4159
4160 processor.apply_sgr_param(5); assert!(processor.terminal_state.current_attributes.blink);
4162
4163 processor.apply_sgr_param(8); assert!(processor.terminal_state.current_attributes.hidden);
4165
4166 processor.apply_sgr_param(22); assert!(!processor.terminal_state.current_attributes.bold);
4169 assert!(!processor.terminal_state.current_attributes.dim);
4170
4171 processor.apply_sgr_param(23); assert!(!processor.terminal_state.current_attributes.italic);
4173
4174 processor.apply_sgr_param(24); assert!(!processor.terminal_state.current_attributes.underline);
4176
4177 processor.apply_sgr_param(0); 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 processor.apply_sgr_param(30); assert_eq!(
4209 processor.terminal_state.current_attributes.fg_color,
4210 Some(0)
4211 );
4212
4213 processor.apply_sgr_param(31); assert_eq!(
4215 processor.terminal_state.current_attributes.fg_color,
4216 Some(1)
4217 );
4218
4219 processor.apply_sgr_param(37); assert_eq!(
4221 processor.terminal_state.current_attributes.fg_color,
4222 Some(7)
4223 );
4224
4225 processor.apply_sgr_param(90); assert_eq!(
4228 processor.terminal_state.current_attributes.fg_color,
4229 Some(8)
4230 );
4231
4232 processor.apply_sgr_param(97); assert_eq!(
4234 processor.terminal_state.current_attributes.fg_color,
4235 Some(15)
4236 );
4237
4238 processor.apply_sgr_param(40); assert_eq!(
4241 processor.terminal_state.current_attributes.bg_color,
4242 Some(0)
4243 );
4244
4245 processor.apply_sgr_param(47); assert_eq!(
4247 processor.terminal_state.current_attributes.bg_color,
4248 Some(7)
4249 );
4250
4251 processor.apply_sgr_param(100); assert_eq!(
4254 processor.terminal_state.current_attributes.bg_color,
4255 Some(8)
4256 );
4257
4258 processor.apply_sgr_param(107); assert_eq!(
4260 processor.terminal_state.current_attributes.bg_color,
4261 Some(15)
4262 );
4263
4264 processor.apply_sgr_param(39); assert_eq!(processor.terminal_state.current_attributes.fg_color, None);
4267
4268 processor.apply_sgr_param(49); 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 processor.apply_sgr_param(21);
4278 assert!(processor.terminal_state.current_attributes.double_underline);
4279
4280 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 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 processor.apply_sgr_param(11); assert_eq!(processor.terminal_state.current_attributes.font_id, Some(1));
4301
4302 processor.apply_sgr_param(19); 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 processor.apply_sgr_param(60); assert!(
4313 processor
4314 .terminal_state
4315 .current_attributes
4316 .ideogram_underline
4317 );
4318
4319 processor.apply_sgr_param(61); assert!(
4321 processor
4322 .terminal_state
4323 .current_attributes
4324 .ideogram_double_underline
4325 );
4326
4327 processor.apply_sgr_param(62); assert!(
4329 processor
4330 .terminal_state
4331 .current_attributes
4332 .ideogram_overline
4333 );
4334
4335 processor.apply_sgr_param(63); assert!(
4337 processor
4338 .terminal_state
4339 .current_attributes
4340 .ideogram_double_overline
4341 );
4342
4343 processor.apply_sgr_param(64); assert!(processor.terminal_state.current_attributes.ideogram_stress);
4345
4346 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 assert_eq!(
4379 AnsiProcessor::rgb_to_palette(255, 0, 0),
4380 16 + 36 * 5 + 6 * 0 + 0
4381 ); assert_eq!(
4383 AnsiProcessor::rgb_to_palette(0, 255, 0),
4384 16 + 36 * 0 + 6 * 5 + 0
4385 ); assert_eq!(
4387 AnsiProcessor::rgb_to_palette(0, 0, 255),
4388 16 + 36 * 0 + 6 * 0 + 5
4389 ); assert_eq!(
4393 AnsiProcessor::rgb_to_palette(255, 255, 255),
4394 16 + 36 * 5 + 6 * 5 + 5
4395 ); assert_eq!(
4397 AnsiProcessor::rgb_to_palette(0, 0, 0),
4398 16 + 36 * 0 + 6 * 0 + 0
4399 ); assert_eq!(
4403 AnsiProcessor::rgb_to_palette(128, 128, 128),
4404 16 + 36 * 3 + 6 * 3 + 3
4405 ); }
4407
4408 #[test]
4409 fn test_sgr_sequence_processing() {
4410 let mut processor = AnsiProcessor::new();
4411
4412 processor.apply_sgr_param(1);
4414 assert!(processor.terminal_state.current_attributes.bold);
4415
4416 processor.apply_sgr_param(0); assert!(!processor.terminal_state.current_attributes.bold);
4419
4420 processor.apply_sgr_param(31); 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 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 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 terminal_state.set_scrolling_region(Some(5), Some(20));
4464 assert_eq!(terminal_state.scroll_region.top, 4); assert_eq!(terminal_state.scroll_region.bottom, 19); terminal_state.set_scrolling_region(Some(25), Some(30)); assert_eq!(terminal_state.scroll_region.top, 0);
4470 assert_eq!(terminal_state.scroll_region.bottom, 23);
4471
4472 terminal_state.set_scrolling_region(Some(15), Some(10)); assert_eq!(terminal_state.scroll_region.top, 0);
4475 assert_eq!(terminal_state.scroll_region.bottom, 23);
4476
4477 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 terminal_state.set_scrolling_region(Some(5), Some(15));
4490 assert_eq!(terminal_state.scroll_region.top, 4); assert_eq!(terminal_state.scroll_region.bottom, 14); terminal_state.scroll_up_in_region(1);
4496 terminal_state.scroll_down_in_region(1);
4497
4498 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 terminal_state.set_scrolling_region(Some(10), Some(20));
4509
4510 terminal_state.set_cursor_position(0, 5);
4512 assert!(!terminal_state.is_cursor_in_scrolling_region());
4513
4514 terminal_state.set_cursor_position(0, 15);
4516 assert!(terminal_state.is_cursor_in_scrolling_region());
4517
4518 terminal_state.set_cursor_position(0, 9); assert!(terminal_state.is_cursor_in_scrolling_region());
4521
4522 terminal_state.set_cursor_position(0, 19); 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 terminal_state.set_scrolling_region(Some(10), Some(15));
4532
4533 terminal_state.set_cursor_position(5, 14); 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); assert_eq!(terminal_state.get_cursor().x, 5); terminal_state.set_cursor_position(10, 12); terminal_state.line_feed_with_scrolling();
4545 assert_eq!(terminal_state.get_cursor().y, 13); assert_eq!(terminal_state.get_cursor().x, 10); }
4548
4549 #[test]
4550 fn test_reverse_line_feed_with_scrolling_region() {
4551 let mut terminal_state = TerminalState::new(80, 24);
4552
4553 terminal_state.set_scrolling_region(Some(10), Some(15));
4555
4556 terminal_state.set_cursor_position(5, 9); 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); assert_eq!(terminal_state.get_cursor().x, 5); terminal_state.set_cursor_position(10, 12); terminal_state.reverse_line_feed_with_scrolling();
4568 assert_eq!(terminal_state.get_cursor().y, 11); assert_eq!(terminal_state.get_cursor().x, 10); }
4571
4572 #[test]
4573 fn test_scrolling_region_message_operations() {
4574 let mut processor = TerminalMessageProcessor::new();
4575
4576 processor.process_message(TerminalMessage::SetScrollingRegion { top: 5, bottom: 15 });
4578 assert_eq!(processor.ansi_processor.terminal_state.scroll_region.top, 5); assert_eq!(
4580 processor.ansi_processor.terminal_state.scroll_region.bottom,
4581 15
4582 ); 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 ); processor.process_message(TerminalMessage::SetScrollingRegion { top: 5, bottom: 10 });
4594 processor.process_message(TerminalMessage::ScrollUpInRegion { lines: 2 });
4595 processor.process_message(TerminalMessage::ScrollDownInRegion { lines: 1 });
4599 }
4601
4602 #[test]
4603 fn test_decstbm_command_processing() {
4604 let mut processor = AnsiProcessor::new();
4605
4606 processor.process_string("\x1b[10;20r"); assert_eq!(processor.terminal_state.scroll_region.top, 9); assert_eq!(processor.terminal_state.scroll_region.bottom, 19); assert_eq!(processor.terminal_state.get_cursor().x, 0);
4613 assert_eq!(processor.terminal_state.get_cursor().y, 9); 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 processor.process_string("\x1b[10;15r"); processor.process_string("\x1b[3S"); processor.process_string("\x1b[2T"); }
4629
4630 #[test]
4631 fn test_terminal_mode_management() {
4632 let mut terminal_state = TerminalState::new(80, 24);
4633
4634 assert!(!terminal_state.mode.cursor_key_mode); 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 assert!(!terminal_state.mode.keypad_mode); 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 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); terminal_state.mode.origin_mode = true;
4659 terminal_state.set_cursor_position(5, 5);
4660 assert_eq!(terminal_state.get_cursor().y, 14); }
4662
4663 #[test]
4664 fn test_insert_and_auto_wrap_modes() {
4665 let mut terminal_state = TerminalState::new(80, 24);
4666
4667 terminal_state.set_cursor_position(0, 0);
4669 terminal_state.mode.insert_mode = true;
4670
4671 terminal_state.insert_character_at_cursor();
4673 terminal_state.delete_character_at_cursor(1);
4677 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 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 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 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 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 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 terminal_state.mode.local_echo_mode = false;
4748 terminal_state.process_newline();
4749 assert_eq!(terminal_state.get_cursor().x, initial_x); assert_eq!(terminal_state.get_cursor().y, initial_y + 1); terminal_state.set_cursor_position(10, 5);
4754
4755 terminal_state.mode.local_echo_mode = true;
4757 terminal_state.process_newline();
4758 assert_eq!(terminal_state.get_cursor().x, 0); assert_eq!(terminal_state.get_cursor().y, 6); }
4761
4762 #[test]
4763 fn test_origin_mode_with_scrolling_region() {
4764 let mut terminal_state = TerminalState::new(80, 24);
4765
4766 terminal_state.set_scrolling_region(Some(10), Some(20));
4768
4769 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); 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); terminal_state.set_cursor_position(10, 50); assert_eq!(terminal_state.get_cursor().y, 19); }
4785
4786 #[test]
4787 fn test_reverse_video_mode() {
4788 let mut terminal_state = TerminalState::new(80, 24);
4789
4790 assert!(!terminal_state.mode.reverse_video); terminal_state.mode.reverse_video = true;
4793 assert!(terminal_state.mode.reverse_video);
4794
4795 }
4798
4799 #[test]
4800 fn test_terminal_mode_message_integration() {
4801 let mut processor = TerminalMessageProcessor::new();
4802
4803 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 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}