1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
use super::term_grid::{CharacterSet, Color, CursorShape, NamedColor, TerminalGrid};
use vte::{Params, Perform};
/// ANSI escape sequence handler that implements the VTE Perform trait
pub struct AnsiHandler<'a> {
pub grid: &'a mut TerminalGrid,
}
impl<'a> AnsiHandler<'a> {
pub fn new(grid: &'a mut TerminalGrid) -> Self {
Self { grid }
}
/// Parse a CSI parameter with default value
/// According to ECMA-48, if a parameter is 0 or omitted, use the default
fn parse_param_with_default(param: Option<&[u16]>, default: u16) -> u16 {
param
.and_then(|p| p.first())
.copied()
.map(|v| if v == 0 { default } else { v })
.unwrap_or(default)
}
/// Parse SGR (Select Graphic Rendition) parameters
fn handle_sgr(&mut self, params: &Params) {
if params.is_empty() {
// Reset all attributes (same as SGR 0)
self.grid.current_attrs = Default::default();
self.grid.current_fg = Color::Default;
self.grid.current_bg = Color::Default;
return;
}
let mut iter = params.iter();
while let Some(param) = iter.next() {
match param[0] {
0 => {
// Reset
self.grid.current_attrs = Default::default();
self.grid.current_fg = Color::Default;
self.grid.current_bg = Color::Default;
}
1 => self.grid.current_attrs.bold = true,
2 => self.grid.current_attrs.dim = true,
3 => self.grid.current_attrs.italic = true,
4 => self.grid.current_attrs.underline = true,
5 => self.grid.current_attrs.blink = true,
7 => self.grid.current_attrs.reverse = true,
8 => self.grid.current_attrs.hidden = true,
9 => self.grid.current_attrs.strikethrough = true,
22 => {
// Normal intensity (not bold, not dim)
self.grid.current_attrs.bold = false;
self.grid.current_attrs.dim = false;
}
23 => self.grid.current_attrs.italic = false,
24 => self.grid.current_attrs.underline = false,
25 => self.grid.current_attrs.blink = false,
27 => self.grid.current_attrs.reverse = false,
28 => self.grid.current_attrs.hidden = false,
29 => self.grid.current_attrs.strikethrough = false,
// Foreground colors (30-37: normal, 90-97: bright)
30 => self.grid.current_fg = Color::Named(NamedColor::Black),
31 => self.grid.current_fg = Color::Named(NamedColor::Red),
32 => self.grid.current_fg = Color::Named(NamedColor::Green),
33 => self.grid.current_fg = Color::Named(NamedColor::Yellow),
34 => self.grid.current_fg = Color::Named(NamedColor::Blue),
35 => self.grid.current_fg = Color::Named(NamedColor::Magenta),
36 => self.grid.current_fg = Color::Named(NamedColor::Cyan),
37 => self.grid.current_fg = Color::Named(NamedColor::White),
38 => {
// Extended foreground color
if let Some(next_param) = iter.next() {
match next_param[0] {
2 => {
// RGB color
if let (Some(r), Some(g), Some(b)) =
(iter.next(), iter.next(), iter.next())
{
self.grid.current_fg =
Color::Rgb(r[0] as u8, g[0] as u8, b[0] as u8);
}
}
5 => {
// 256-color palette
if let Some(idx) = iter.next() {
self.grid.current_fg = Color::Indexed(idx[0] as u8);
}
}
_ => {}
}
}
}
39 => self.grid.current_fg = Color::Default, // Default foreground
// Background colors (40-47: normal, 100-107: bright)
40 => self.grid.current_bg = Color::Named(NamedColor::Black),
41 => self.grid.current_bg = Color::Named(NamedColor::Red),
42 => self.grid.current_bg = Color::Named(NamedColor::Green),
43 => self.grid.current_bg = Color::Named(NamedColor::Yellow),
44 => self.grid.current_bg = Color::Named(NamedColor::Blue),
45 => self.grid.current_bg = Color::Named(NamedColor::Magenta),
46 => self.grid.current_bg = Color::Named(NamedColor::Cyan),
47 => self.grid.current_bg = Color::Named(NamedColor::White),
48 => {
// Extended background color
if let Some(next_param) = iter.next() {
match next_param[0] {
2 => {
// RGB color
if let (Some(r), Some(g), Some(b)) =
(iter.next(), iter.next(), iter.next())
{
self.grid.current_bg =
Color::Rgb(r[0] as u8, g[0] as u8, b[0] as u8);
}
}
5 => {
// 256-color palette
if let Some(idx) = iter.next() {
self.grid.current_bg = Color::Indexed(idx[0] as u8);
}
}
_ => {}
}
}
}
49 => self.grid.current_bg = Color::Default, // Default background
// Bright foreground colors (90-97)
90 => self.grid.current_fg = Color::Named(NamedColor::BrightBlack),
91 => self.grid.current_fg = Color::Named(NamedColor::BrightRed),
92 => self.grid.current_fg = Color::Named(NamedColor::BrightGreen),
93 => self.grid.current_fg = Color::Named(NamedColor::BrightYellow),
94 => self.grid.current_fg = Color::Named(NamedColor::BrightBlue),
95 => self.grid.current_fg = Color::Named(NamedColor::BrightMagenta),
96 => self.grid.current_fg = Color::Named(NamedColor::BrightCyan),
97 => self.grid.current_fg = Color::Named(NamedColor::BrightWhite),
// Bright background colors (100-107)
100 => self.grid.current_bg = Color::Named(NamedColor::BrightBlack),
101 => self.grid.current_bg = Color::Named(NamedColor::BrightRed),
102 => self.grid.current_bg = Color::Named(NamedColor::BrightGreen),
103 => self.grid.current_bg = Color::Named(NamedColor::BrightYellow),
104 => self.grid.current_bg = Color::Named(NamedColor::BrightBlue),
105 => self.grid.current_bg = Color::Named(NamedColor::BrightMagenta),
106 => self.grid.current_bg = Color::Named(NamedColor::BrightCyan),
107 => self.grid.current_bg = Color::Named(NamedColor::BrightWhite),
_ => {}
}
}
}
}
impl Perform for AnsiHandler<'_> {
fn print(&mut self, c: char) {
self.grid.put_char(c);
}
fn execute(&mut self, byte: u8) {
match byte {
b'\n' => self.grid.put_char('\n'),
b'\r' => self.grid.put_char('\r'),
b'\t' => self.grid.put_char('\t'),
b'\x08' => self.grid.put_char('\x08'), // Backspace
b'\x07' => {} // Bell (ignore for now)
b'\x0b' => self.grid.put_char('\n'), // Vertical Tab - treat as linefeed
b'\x0c' => {
// Form feed (Ctrl+L) - clear screen and move cursor to home
self.grid.clear_screen();
self.grid.goto(0, 0);
}
b'\x0e' => self.grid.shift_out(), // SO - Shift Out (select G1)
b'\x0f' => self.grid.shift_in(), // SI - Shift In (select G0)
_ => {}
}
}
fn hook(&mut self, _params: &Params, _intermediates: &[u8], _ignore: bool, _c: char) {
// DCS sequences (not commonly used)
}
fn put(&mut self, _byte: u8) {
// Used with hook for DCS sequences
}
fn unhook(&mut self) {
// End of DCS sequence
}
fn osc_dispatch(&mut self, _params: &[&[u8]], _bell_terminated: bool) {
// OSC (Operating System Command) sequences
// Could be used for window title, clipboard, etc.
}
fn csi_dispatch(&mut self, params: &Params, intermediates: &[u8], ignore: bool, c: char) {
if ignore {
return;
}
// CSI (Control Sequence Introducer) sequences
match (c, intermediates) {
// Cursor movement
// Per ECMA-48, parameter 0 is treated as 1 for movement commands
('A', []) => {
// Cursor Up
let n = Self::parse_param_with_default(params.iter().next(), 1) as usize;
self.grid.move_cursor(0, -(n as isize));
}
('B', []) => {
// Cursor Down
let n = Self::parse_param_with_default(params.iter().next(), 1) as usize;
self.grid.move_cursor(0, n as isize);
}
('C', []) => {
// Cursor Forward
let n = Self::parse_param_with_default(params.iter().next(), 1) as usize;
self.grid.move_cursor(n as isize, 0);
}
('D', []) => {
// Cursor Back
let n = Self::parse_param_with_default(params.iter().next(), 1) as usize;
self.grid.move_cursor(-(n as isize), 0);
}
('c', []) => {
// Primary Device Attributes (DA1)
// Respond as VT220 with no options
// Format: CSI ? 62 ; 0 c (VT220)
self.grid.queue_response("\x1b[?62;0c".to_string());
}
('c', [b'>']) => {
// Secondary Device Attributes (DA2)
// Format: CSI > Pp ; Pv ; Pc c
// Pp=0 (VT100), Pv=0 (version), Pc=0 (ROM cartridge)
self.grid.queue_response("\x1b[>0;0;0c".to_string());
}
('E', []) => {
// Cursor Next Line
let n = Self::parse_param_with_default(params.iter().next(), 1) as usize;
self.grid.move_cursor(0, n as isize);
self.grid.cursor.x = 0;
}
('F', []) => {
// Cursor Previous Line
let n = Self::parse_param_with_default(params.iter().next(), 1) as usize;
self.grid.move_cursor(0, -(n as isize));
self.grid.cursor.x = 0;
}
('G', []) => {
// Cursor Horizontal Absolute
let col = Self::parse_param_with_default(params.iter().next(), 1) as usize;
self.grid.cursor.x = col
.saturating_sub(1)
.min(self.grid.cols().saturating_sub(1));
}
('H', []) | ('f', []) => {
// Cursor Position
// When origin mode (DECOM) is set, position is relative to scroll region
// Per ECMA-48, parameter 0 is treated as 1
let mut iter = params.iter();
let row = Self::parse_param_with_default(iter.next(), 1) as usize;
let col = Self::parse_param_with_default(iter.next(), 1) as usize;
self.grid
.goto_origin_aware(col.saturating_sub(1), row.saturating_sub(1));
}
('J', []) => {
// Erase in Display
let mode = params
.iter()
.next()
.and_then(|p| p.first())
.copied()
.unwrap_or(0);
match mode {
0 => self.grid.erase_to_eos(), // Erase below
1 => self.grid.erase_from_bos(), // Erase above
2 | 3 => self.grid.clear_screen(), // Erase all
_ => {}
}
}
('K', []) => {
// Erase in Line
let mode = params
.iter()
.next()
.and_then(|p| p.first())
.copied()
.unwrap_or(0);
match mode {
0 => self.grid.erase_to_eol(), // Erase to right
1 => self.grid.erase_to_bol(), // Erase to left
2 => self.grid.clear_line(), // Erase all
_ => {}
}
}
('P', []) => {
// Delete Characters (DCH)
let n = Self::parse_param_with_default(params.iter().next(), 1) as usize;
self.grid.delete_chars(n);
}
('@', []) => {
// Insert Characters (ICH)
let n = Self::parse_param_with_default(params.iter().next(), 1) as usize;
self.grid.insert_chars(n);
}
('X', []) => {
// Erase Characters (ECH)
let n = Self::parse_param_with_default(params.iter().next(), 1) as usize;
self.grid.erase_chars(n);
}
('L', []) => {
// Insert Lines
let n = Self::parse_param_with_default(params.iter().next(), 1) as usize;
self.grid.scroll_down(n);
}
('M', []) => {
// Delete Lines
let n = Self::parse_param_with_default(params.iter().next(), 1) as usize;
self.grid.scroll_up(n);
}
('S', []) => {
// Scroll Up
let n = Self::parse_param_with_default(params.iter().next(), 1) as usize;
self.grid.scroll_up(n);
}
('T', []) => {
// Scroll Down
let n = Self::parse_param_with_default(params.iter().next(), 1) as usize;
self.grid.scroll_down(n);
}
('d', []) => {
// Vertical Position Absolute (VPA)
// When origin mode (DECOM) is set, position is relative to scroll region
let row = Self::parse_param_with_default(params.iter().next(), 1) as usize;
let y = row.saturating_sub(1);
if self.grid.origin_mode {
// In origin mode, position is relative to scroll region
let scroll_top = self.grid.scroll_region_top();
let scroll_bottom = self.grid.scroll_region_bottom();
self.grid.cursor.y = (scroll_top + y).min(scroll_bottom);
} else {
self.grid.cursor.y = y.min(self.grid.rows().saturating_sub(1));
}
}
('h', []) => {
// Standard Mode Set (SM)
for param in params.iter() {
match param[0] {
4 => self.grid.insert_mode = true, // IRM - Insert/Replace Mode
20 => self.grid.lnm_mode = true, // LNM - Line Feed/New Line Mode
_ => {}
}
}
}
('h', [b'?']) => {
// DEC Private Mode Set
for param in params.iter() {
match param[0] {
1 => self.grid.application_cursor_keys = true, // DECCKM
6 => self.grid.set_origin_mode(true), // DECOM
7 => self.grid.auto_wrap_mode = true, // DECAWM
25 => self.grid.cursor.visible = true, // Show cursor
1000 => self.grid.mouse_normal_tracking = true, // Normal mouse tracking
1002 => self.grid.mouse_button_tracking = true, // Button event tracking
1003 => self.grid.mouse_any_event_tracking = true, // Any event tracking
1004 => self.grid.focus_event_mode = true, // Focus events
1005 => self.grid.mouse_utf8_mode = true, // UTF-8 mouse encoding
1006 => self.grid.mouse_sgr_mode = true, // SGR mouse mode
1015 => self.grid.mouse_urxvt_mode = true, // URXVT mouse mode
47 => self.grid.use_alt_screen(), // Alt screen (xterm)
1047 => self.grid.use_alt_screen(), // Alt screen buffer
1048 => self.grid.save_cursor(), // Save cursor
1049 => self.grid.use_alt_screen(), // Alt screen + save cursor
2004 => self.grid.bracketed_paste_mode = true, // Bracketed paste
2026 => self.grid.begin_synchronized_output(), // Begin sync update
_ => {}
}
}
}
('l', []) => {
// Standard Mode Reset (RM)
for param in params.iter() {
match param[0] {
4 => self.grid.insert_mode = false, // IRM - Insert/Replace Mode
20 => self.grid.lnm_mode = false, // LNM - Line Feed/New Line Mode
_ => {}
}
}
}
('l', [b'?']) => {
// DEC Private Mode Reset
for param in params.iter() {
match param[0] {
1 => self.grid.application_cursor_keys = false, // DECCKM
6 => self.grid.set_origin_mode(false), // DECOM
7 => self.grid.auto_wrap_mode = false, // DECAWM
25 => self.grid.cursor.visible = false, // Hide cursor
1000 => self.grid.mouse_normal_tracking = false, // Normal mouse tracking
1002 => self.grid.mouse_button_tracking = false, // Button event tracking
1003 => self.grid.mouse_any_event_tracking = false, // Any event tracking
1004 => self.grid.focus_event_mode = false, // Focus events
1005 => self.grid.mouse_utf8_mode = false, // UTF-8 mouse encoding
1006 => self.grid.mouse_sgr_mode = false, // SGR mouse mode
1015 => self.grid.mouse_urxvt_mode = false, // URXVT mouse mode
47 => self.grid.use_main_screen(), // Main screen (xterm)
1047 => self.grid.use_main_screen(), // Main screen buffer
1048 => self.grid.restore_cursor(), // Restore cursor
1049 => self.grid.use_main_screen(), // Main screen + restore cursor
2004 => self.grid.bracketed_paste_mode = false, // Bracketed paste
2026 => self.grid.end_synchronized_output(), // End sync update
_ => {}
}
}
}
('n', []) => {
// Device Status Report (DSR)
let mode = params
.iter()
.next()
.and_then(|p| p.first())
.copied()
.unwrap_or(0);
match mode {
5 => {
// Status report - respond with "OK"
self.grid.queue_response("\x1b[0n".to_string());
}
6 => {
// Cursor position report
self.grid.queue_cursor_position_report();
}
_ => {}
}
}
('n', [b'?']) => {
// DEC Private Device Status Report
let mode = params
.iter()
.next()
.and_then(|p| p.first())
.copied()
.unwrap_or(0);
match mode {
6 => {
// DECXCPR - Extended Cursor Position Report
// Response: CSI ? row ; col R (respects origin mode)
let (row, col) = if self.grid.origin_mode {
let row = (self
.grid
.cursor
.y
.saturating_sub(self.grid.scroll_region_top()))
+ 1;
let col = self.grid.cursor.x + 1;
(row, col)
} else {
let row = self.grid.cursor.y + 1;
let col = self.grid.cursor.x + 1;
(row, col)
};
let response = format!("\x1b[?{};{}R", row, col);
self.grid.queue_response(response);
}
15 => {
// Printer status - respond with "not ready"
self.grid.queue_response("\x1b[?13n".to_string());
}
25 => {
// UDK status - respond with "locked"
self.grid.queue_response("\x1b[?21n".to_string());
}
26 => {
// Keyboard status - respond with "North American"
self.grid.queue_response("\x1b[?27;1n".to_string());
}
_ => {}
}
}
('m', []) => {
// SGR (Select Graphic Rendition)
self.handle_sgr(params);
}
('r', []) => {
// Set Scroll Region (DECSTBM)
// Parameters: top ; bottom (1-based, 0 treated as default)
let mut iter = params.iter();
let top = Self::parse_param_with_default(iter.next(), 1) as usize;
let bottom_default = self.grid.rows() as u16;
let bottom = Self::parse_param_with_default(iter.next(), bottom_default) as usize;
self.grid
.set_scroll_region(top.saturating_sub(1), bottom.saturating_sub(1));
}
('s', []) => {
// Save Cursor Position (CSI s - position only)
self.grid.save_cursor_position();
}
('u', []) => {
// Restore Cursor Position (CSI u - position only)
self.grid.restore_cursor_position();
}
('q', [b' ']) => {
// Set Cursor Shape (DECSCUSR)
let shape = params
.iter()
.next()
.and_then(|p| p.first())
.copied()
.unwrap_or(0);
self.grid.cursor.shape = match shape {
1 | 2 => CursorShape::Block,
3 | 4 => CursorShape::Underline,
5 | 6 => CursorShape::Bar,
_ => CursorShape::Block,
};
}
('t', []) => {
// Window manipulation (XTWINOPS)
let mode = params
.iter()
.next()
.and_then(|p| p.first())
.copied()
.unwrap_or(0);
match mode {
18 => {
// Report text area size in characters
// Response: CSI 8 ; height ; width t
let response = format!("\x1b[8;{};{}t", self.grid.rows(), self.grid.cols());
self.grid.queue_response(response);
}
19 => {
// Report screen size in characters
// Response: CSI 9 ; height ; width t
let response = format!("\x1b[9;{};{}t", self.grid.rows(), self.grid.cols());
self.grid.queue_response(response);
}
_ => {
// Other window manipulation commands (ignore for now)
}
}
}
_ => {
// Unknown or unimplemented sequence
}
}
}
fn esc_dispatch(&mut self, intermediates: &[u8], _ignore: bool, byte: u8) {
// ESC sequences
match (byte, intermediates) {
// ESC D - Index (IND): Move cursor down one line, scroll if needed
(b'D', []) => {
self.grid.put_char('\n');
}
// ESC M - Reverse Index (RI): Move cursor up one line, scroll if needed
(b'M', []) => {
self.grid.reverse_linefeed();
}
// ESC E - Next Line (NEL): Move to start of next line
(b'E', []) => {
self.grid.next_line();
}
// ESC 7 - Save Cursor (DECSC)
(b'7', []) => {
self.grid.save_cursor();
}
// ESC 8 - Restore Cursor (DECRC)
(b'8', []) => {
self.grid.restore_cursor();
}
// ESC c - Full Reset (RIS)
(b'c', []) => {
self.grid.reset();
}
// ESC H - Horizontal Tab Set (HTS)
(b'H', []) => {
// Set a tab stop at current cursor position
// For now, we use default tab stops every 8 columns
}
// ESC = - Application Keypad (DECKPAM)
(b'=', []) => {
// Switch keypad to application mode
// Not implemented - affects input handling
}
// ESC > - Normal Keypad (DECKPNM)
(b'>', []) => {
// Switch keypad to numeric mode
// Not implemented - affects input handling
}
// ESC \ - String Terminator (ST)
(b'\\', []) => {
// Terminates OSC, DCS, APC sequences - nothing to do here
}
// Character set designation sequences
// ESC ( 0 - Set G0 to DEC Special Graphics (line drawing)
(b'0', [b'(']) => {
self.grid.set_charset_g0(CharacterSet::DecSpecialGraphics);
}
// ESC ( B - Set G0 to ASCII
(b'B', [b'(']) => {
self.grid.set_charset_g0(CharacterSet::Ascii);
}
// ESC ( A - Set G0 to UK (treat as ASCII)
(b'A', [b'(']) => {
self.grid.set_charset_g0(CharacterSet::Ascii);
}
// ESC ) 0 - Set G1 to DEC Special Graphics (line drawing)
(b'0', [b')']) => {
self.grid.set_charset_g1(CharacterSet::DecSpecialGraphics);
}
// ESC ) B - Set G1 to ASCII
(b'B', [b')']) => {
self.grid.set_charset_g1(CharacterSet::Ascii);
}
// ESC ) A - Set G1 to UK (treat as ASCII)
(b'A', [b')']) => {
self.grid.set_charset_g1(CharacterSet::Ascii);
}
_ => {
// Unknown or unimplemented escape sequence
}
}
}
}