virtual-tty 0.1.0

Core virtual TTY implementation for testing terminal applications
Documentation
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
use std::sync::{Arc, Mutex};

mod ansi;
mod buffer;
mod cursor;
mod errors;
mod state;

use ansi::{parse_escape_sequence, AnsiCommand, AnsiParser, ClearMode, ControlChar, Token};
use state::TtyState;

pub struct VirtualTty {
    state: Arc<Mutex<TtyState>>,
    width: usize,
    height: usize,
}

impl VirtualTty {
    pub fn new(width: usize, height: usize) -> Self {
        let state = TtyState::new(width, height);

        Self {
            state: Arc::new(Mutex::new(state)),
            width,
            height,
        }
    }

    pub fn get_width(&self) -> usize {
        self.width
    }

    pub fn get_height(&self) -> usize {
        self.height
    }

    pub fn get_size(&self) -> (usize, usize) {
        (self.width, self.height)
    }

    pub fn stdout_write(&mut self, data: &str) {
        self.write_internal(data);
    }

    pub fn stderr_write(&mut self, data: &str) {
        self.write_internal(data);
    }

    pub fn send_input(&mut self, input: &str) {
        self.write_internal(input);
    }

    fn write_internal(&mut self, data: &str) {
        // Use the new tokenized parser
        match AnsiParser::parse(data) {
            Ok(tokens) => {
                let mut state = self.state.lock().unwrap();
                for token in tokens {
                    self.process_token(token, &mut state);
                }
            }
            Err(_) => {
                // Fallback to legacy parsing for compatibility
                self.write_internal_legacy(data);
            }
        }
    }

    fn process_token(&self, token: Token, state: &mut TtyState) {
        match token {
            Token::Text(text) => {
                for ch in text.chars() {
                    let cursor_row = state.cursor.row;
                    let cursor_col = state.cursor.col;
                    if cursor_row < self.height && cursor_col < self.width {
                        state.buffer.set_char(cursor_row, cursor_col, ch);
                        if state.cursor.advance(self.width, self.height) {
                            state.buffer.scroll_up();
                        }
                    }
                }
            }
            Token::Command(command) => {
                // Validate command before executing
                if command.validate().is_ok() {
                    self.execute_ansi_command(&command, state);
                }
                // If validation fails, silently ignore the command
            }
            Token::ControlChar(ctrl_char) => {
                match ctrl_char {
                    ControlChar::LineFeed => {
                        if state.cursor.newline(self.height) {
                            state.buffer.scroll_up();
                        }
                    }
                    ControlChar::CarriageReturn => {
                        state.cursor.carriage_return();
                    }
                    ControlChar::Backspace => {
                        state.cursor.backspace();
                    }
                    ControlChar::Tab => {
                        // Simple tab handling - advance to next tab stop (8 chars)
                        let tab_width = 8;
                        let cursor_col = state.cursor.col;
                        let next_tab_stop = ((cursor_col / tab_width) + 1) * tab_width;
                        let spaces_to_add = next_tab_stop - cursor_col;
                        for _ in 0..spaces_to_add {
                            let cursor_row = state.cursor.row;
                            let cursor_col = state.cursor.col;
                            if cursor_row < self.height && cursor_col < self.width {
                                state.buffer.set_char(cursor_row, cursor_col, ' ');
                                if state.cursor.advance(self.width, self.height) {
                                    state.buffer.scroll_up();
                                }
                            }
                        }
                    }
                    ControlChar::Bell => {
                        // Bell character - typically ignored in terminal emulation
                    }
                    ControlChar::VerticalTab => {
                        // Vertical tab - move to next line
                        if state.cursor.newline(self.height) {
                            state.buffer.scroll_up();
                        }
                    }
                    ControlChar::FormFeed => {
                        // Form feed - clear screen and move to top
                        state.buffer.clear();
                        state.cursor.set_position(0, 0, self.height, self.width);
                    }
                }
            }
            Token::Invalid(_) => {
                // Ignore invalid tokens for now
            }
        }
    }

    fn write_internal_legacy(&mut self, data: &str) {
        let mut state = self.state.lock().unwrap();
        let mut chars = data.chars();
        while let Some(ch) = chars.next() {
            if ch == '\x1b' {
                // Start of escape sequence
                if chars.next() == Some('[') {
                    if let Some(command) = parse_escape_sequence(&mut chars) {
                        self.execute_ansi_command(&command, &mut state);
                    }
                }
            } else if ch == '\r' {
                // Carriage return
                state.cursor.carriage_return();
            } else if ch == '\n' {
                // Newline
                if state.cursor.newline(self.height) {
                    state.buffer.scroll_up();
                }
            } else if ch == '\x08' {
                // Backspace
                state.cursor.backspace();
            } else {
                // Regular character
                let cursor_row = state.cursor.row;
                let cursor_col = state.cursor.col;
                if cursor_row < self.height && cursor_col < self.width {
                    state.buffer.set_char(cursor_row, cursor_col, ch);
                    if state.cursor.advance(self.width, self.height) {
                        state.buffer.scroll_up();
                    }
                }
            }
        }
    }

    fn execute_ansi_command(&self, command: &AnsiCommand, state: &mut TtyState) {
        match command {
            AnsiCommand::CursorUp(n) => {
                state.cursor.move_up(*n);
            }
            AnsiCommand::CursorDown(n) => {
                state.cursor.move_down(*n, self.height);
            }
            AnsiCommand::CursorForward(n) => {
                state.cursor.move_forward(*n, self.width);
            }
            AnsiCommand::CursorBack(n) => {
                state.cursor.move_back(*n);
            }
            AnsiCommand::CursorPosition { row, col } => {
                state
                    .cursor
                    .set_position(*row, *col, self.height, self.width);
            }
            AnsiCommand::ClearScreen(clear_mode) => match clear_mode {
                ClearMode::Entire => {
                    state.buffer.clear();
                    state.cursor.set_position(0, 0, self.height, self.width);
                }
                ClearMode::ToBeginning => {
                    let cursor_row = state.cursor.row;
                    let cursor_col = state.cursor.col;
                    state
                        .buffer
                        .clear_from_beginning_to_cursor(cursor_row, cursor_col);
                }
                ClearMode::ToEnd => {
                    let cursor_row = state.cursor.row;
                    let cursor_col = state.cursor.col;
                    state
                        .buffer
                        .clear_from_cursor_to_end(cursor_row, cursor_col);
                }
            },
            AnsiCommand::ClearLine(clear_mode) => match clear_mode {
                ClearMode::Entire => {
                    let cursor_row = state.cursor.row;
                    state.buffer.clear_entire_line(cursor_row);
                }
                ClearMode::ToBeginning => {
                    let cursor_row = state.cursor.row;
                    let cursor_col = state.cursor.col;
                    state
                        .buffer
                        .clear_line_from_beginning_to_cursor(cursor_row, cursor_col);
                }
                ClearMode::ToEnd => {
                    let cursor_row = state.cursor.row;
                    let cursor_col = state.cursor.col;
                    state
                        .buffer
                        .clear_line_from_cursor_to_end(cursor_row, cursor_col);
                }
            },
            AnsiCommand::SetGraphicsRendition => {
                // SGR (Select Graphic Rendition) - ignore for now
            }
        }
    }

    pub fn get_snapshot(&self) -> String {
        let state = self.state.lock().unwrap();
        state.get_snapshot()
    }

    pub fn clear(&mut self) {
        let mut state = self.state.lock().unwrap();
        state.clear(self.width, self.height);
    }

    pub fn get_cursor_position(&self) -> (usize, usize) {
        let state = self.state.lock().unwrap();
        state.get_cursor_position()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_new() {
        let tty = VirtualTty::new(80, 24);
        assert_eq!(tty.get_width(), 80);
        assert_eq!(tty.get_height(), 24);
        assert_eq!(tty.get_size(), (80, 24));
    }

    #[test]
    fn test_basic_write() {
        let mut tty = VirtualTty::new(10, 3);
        tty.stdout_write("Hello");
        let snapshot = tty.get_snapshot();
        insta::assert_snapshot!(snapshot, @r"
        Hello     \n
                  \n
                  \n
        ");
    }

    #[test]
    fn test_newline() {
        let mut tty = VirtualTty::new(10, 3);
        tty.stdout_write("Line1\nLine2");
        let snapshot = tty.get_snapshot();
        insta::assert_snapshot!(snapshot, @r"
        Line1     \n
        Line2     \n
                  \n
        ");
    }

    #[test]
    fn test_line_wrap() {
        let mut tty = VirtualTty::new(5, 3);
        tty.stdout_write("HelloWorld");
        let snapshot = tty.get_snapshot();
        insta::assert_snapshot!(snapshot, @r"
        Hello\n
        World\n
             \n
        ");
    }

    #[test]
    fn test_clear_screen() {
        let mut tty = VirtualTty::new(10, 3);
        tty.stdout_write("Hello\nWorld");
        tty.stdout_write("\x1b[2J");
        let snapshot = tty.get_snapshot();
        insta::assert_snapshot!(snapshot, @r"
        \n
        \n
        \n
        ");
    }

    #[test]
    fn test_stderr() {
        let mut tty = VirtualTty::new(10, 3);
        tty.stderr_write("Error!");
        let snapshot = tty.get_snapshot();
        insta::assert_snapshot!(snapshot, @r"
        Error!    \n
                  \n
                  \n
        ");
    }

    #[test]
    fn test_scroll() {
        let mut tty = VirtualTty::new(10, 2);
        tty.stdout_write("Line1\nLine2\nLine3");
        let snapshot = tty.get_snapshot();
        insta::assert_snapshot!(snapshot, @r"
        Line2     \n
        Line3     \n
        ");
    }

    #[test]
    fn test_clear() {
        let mut tty = VirtualTty::new(10, 3);
        tty.stdout_write("Hello\nWorld");
        tty.clear();
        let snapshot = tty.get_snapshot();
        insta::assert_snapshot!(snapshot, @r"
        \n
        \n
        \n
        ");
    }

    // =============================================================================
    // STDERR TESTS - Mirror of stdout tests but using stderr_write()
    // =============================================================================

    #[test]
    fn test_stderr_basic_write() {
        let mut tty = VirtualTty::new(10, 3);
        tty.stderr_write("Hello");
        let snapshot = tty.get_snapshot();
        insta::assert_snapshot!(snapshot, @r"
        Hello     \n
                  \n
                  \n
        ");
    }

    #[test]
    fn test_stderr_newline() {
        let mut tty = VirtualTty::new(10, 3);
        tty.stderr_write("Line1\nLine2");
        let snapshot = tty.get_snapshot();
        insta::assert_snapshot!(snapshot, @r"
        Line1     \n
        Line2     \n
                  \n
        ");
    }

    #[test]
    fn test_stderr_line_wrap() {
        let mut tty = VirtualTty::new(5, 3);
        tty.stderr_write("HelloWorld");
        let snapshot = tty.get_snapshot();
        insta::assert_snapshot!(snapshot, @r"
        Hello\n
        World\n
             \n
        ");
    }

    #[test]
    fn test_stderr_clear_screen() {
        let mut tty = VirtualTty::new(10, 3);
        tty.stderr_write("Hello\nWorld");
        tty.stderr_write("\x1b[2J");
        let snapshot = tty.get_snapshot();
        insta::assert_snapshot!(snapshot, @r"
        \n
        \n
        \n
        ");
    }

    #[test]
    fn test_stderr_scroll() {
        let mut tty = VirtualTty::new(10, 2);
        tty.stderr_write("Line1\nLine2\nLine3");
        let snapshot = tty.get_snapshot();
        insta::assert_snapshot!(snapshot, @r"
        Line2     \n
        Line3     \n
        ");
    }

    #[test]
    fn test_mixed_stdout_stderr() {
        let mut tty = VirtualTty::new(15, 3);
        tty.stdout_write("Hello");
        tty.stderr_write(" World");
        let snapshot = tty.get_snapshot();
        insta::assert_snapshot!(snapshot, @r"
        Hello World    \n
                       \n
                       \n
        ");
    }

    #[test]
    fn test_stderr_with_ansi_escape() {
        let mut tty = VirtualTty::new(10, 3);
        tty.stderr_write("Hello");
        tty.stderr_write("\x1b[1A"); // Move up 1 line
        tty.stderr_write("X");
        let snapshot = tty.get_snapshot();
        insta::assert_snapshot!(snapshot, @r"
        HelloX    \n
                  \n
                  \n
        ");
    }
}