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
use std::fmt::{Debug, Formatter, Write as _};
use std::io::Write as _;
use std::sync::{Arc, Mutex};

use vt100::Parser;

use crate::TermLike;

/// A thin wrapper around [`vt100::Parser`].
///
/// This is just an [`Arc`] around its internal state, so it can be freely cloned.
#[cfg_attr(docsrs, doc(cfg(feature = "in_memory")))]
#[derive(Debug, Clone)]
pub struct InMemoryTerm {
    state: Arc<Mutex<InMemoryTermState>>,
}

impl InMemoryTerm {
    pub fn new(rows: u16, cols: u16) -> InMemoryTerm {
        assert!(rows > 0, "rows must be > 0");
        assert!(cols > 0, "cols must be > 0");
        InMemoryTerm {
            state: Arc::new(Mutex::new(InMemoryTermState::new(rows, cols))),
        }
    }

    pub fn reset(&self) {
        let mut state = self.state.lock().unwrap();
        *state = InMemoryTermState::new(state.height, state.width);
    }

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

        // For some reason, the `Screen::contents` method doesn't include newlines in what it
        // returns, making it useless for our purposes. So we need to manually reconstruct the
        // contents by iterating over the rows in the terminal buffer.
        let mut rows = state
            .parser
            .screen()
            .rows(0, state.width)
            .collect::<Vec<_>>();

        // Reverse the rows and trim empty lines from the end
        rows = rows
            .into_iter()
            .rev()
            .skip_while(|line| line.is_empty())
            .map(|line| line.trim_end().to_string())
            .collect();

        // Un-reverse the rows and join them up with newlines
        rows.reverse();
        rows.join("\n")
    }

    pub fn contents_formatted(&self) -> Vec<u8> {
        let state = self.state.lock().unwrap();

        // For some reason, the `Screen::contents` method doesn't include newlines in what it
        // returns, making it useless for our purposes. So we need to manually reconstruct the
        // contents by iterating over the rows in the terminal buffer.
        let mut rows = state
            .parser
            .screen()
            .rows_formatted(0, state.width)
            .collect::<Vec<_>>();

        // Reverse the rows and trim empty lines from the end
        rows = rows
            .into_iter()
            .rev()
            .skip_while(|line| line.is_empty())
            .collect();

        // Un-reverse the rows
        rows.reverse();

        // Calculate buffer size
        let reset = b"";
        let len = rows.iter().map(|line| line.len() + reset.len() + 1).sum();

        // Join rows up with reset codes and newlines
        let mut contents = rows.iter().fold(Vec::with_capacity(len), |mut acc, cur| {
            acc.extend_from_slice(cur);
            acc.extend_from_slice(reset);
            acc.push(b'\n');
            acc
        });

        // Remove last newline again, but leave the reset code
        contents.truncate(len.saturating_sub(1));
        contents
    }

    pub fn moves_since_last_check(&self) -> String {
        let mut s = String::new();
        for line in std::mem::take(&mut self.state.lock().unwrap().history) {
            writeln!(s, "{line:?}").unwrap();
        }
        s
    }
}

impl TermLike for InMemoryTerm {
    fn width(&self) -> u16 {
        self.state.lock().unwrap().width
    }

    fn height(&self) -> u16 {
        self.state.lock().unwrap().height
    }

    fn move_cursor_up(&self, n: usize) -> std::io::Result<()> {
        match n {
            0 => Ok(()),
            _ => {
                let mut state = self.state.lock().unwrap();
                state.history.push(Move::Up(n));
                state.write_str(&format!("\x1b[{n}A"))
            }
        }
    }

    fn move_cursor_down(&self, n: usize) -> std::io::Result<()> {
        match n {
            0 => Ok(()),
            _ => {
                let mut state = self.state.lock().unwrap();
                state.history.push(Move::Down(n));
                state.write_str(&format!("\x1b[{n}B"))
            }
        }
    }

    fn move_cursor_right(&self, n: usize) -> std::io::Result<()> {
        match n {
            0 => Ok(()),
            _ => {
                let mut state = self.state.lock().unwrap();
                state.history.push(Move::Right(n));
                state.write_str(&format!("\x1b[{n}C"))
            }
        }
    }

    fn move_cursor_left(&self, n: usize) -> std::io::Result<()> {
        match n {
            0 => Ok(()),
            _ => {
                let mut state = self.state.lock().unwrap();
                state.history.push(Move::Left(n));
                state.write_str(&format!("\x1b[{n}D"))
            }
        }
    }

    fn write_line(&self, s: &str) -> std::io::Result<()> {
        let mut state = self.state.lock().unwrap();
        state.history.push(Move::Str(s.into()));
        state.history.push(Move::NewLine);

        // Don't try to handle writing lines with additional newlines embedded in them - it's not
        // worth the extra code for something that indicatif doesn't even do. May revisit in future.
        debug_assert!(
            s.lines().count() <= 1,
            "calling write_line with embedded newlines is not allowed"
        );

        // vte100 needs the full \r\n sequence to jump to the next line and reset the cursor to
        // the beginning of the line. Be flexible and take either \n or \r\n
        state.write_str(s)?;
        state.write_str("\r\n")
    }

    fn write_str(&self, s: &str) -> std::io::Result<()> {
        let mut state = self.state.lock().unwrap();
        state.history.push(Move::Str(s.into()));
        state.write_str(s)
    }

    fn clear_line(&self) -> std::io::Result<()> {
        let mut state = self.state.lock().unwrap();
        state.history.push(Move::Clear);
        state.write_str("\r\x1b[2K")
    }

    fn flush(&self) -> std::io::Result<()> {
        let mut state = self.state.lock().unwrap();
        state.history.push(Move::Flush);
        state.parser.flush()
    }
}

struct InMemoryTermState {
    width: u16,
    height: u16,
    parser: vt100::Parser,
    history: Vec<Move>,
}

impl InMemoryTermState {
    pub(crate) fn new(rows: u16, cols: u16) -> InMemoryTermState {
        InMemoryTermState {
            width: cols,
            height: rows,
            parser: Parser::new(rows, cols, 0),
            history: vec![],
        }
    }

    pub(crate) fn write_str(&mut self, s: &str) -> std::io::Result<()> {
        self.parser.write_all(s.as_bytes())
    }
}

impl Debug for InMemoryTermState {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("InMemoryTermState").finish_non_exhaustive()
    }
}

#[derive(Debug, PartialEq, Clone)]
enum Move {
    Up(usize),
    Down(usize),
    Left(usize),
    Right(usize),
    Str(String),
    NewLine,
    Clear,
    Flush,
}

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

    fn cursor_pos(in_mem: &InMemoryTerm) -> (u16, u16) {
        in_mem
            .state
            .lock()
            .unwrap()
            .parser
            .screen()
            .cursor_position()
    }

    #[test]
    fn line_wrapping() {
        let in_mem = InMemoryTerm::new(10, 5);
        assert_eq!(cursor_pos(&in_mem), (0, 0));

        in_mem.write_str("ABCDE").unwrap();
        assert_eq!(in_mem.contents(), "ABCDE");
        assert_eq!(cursor_pos(&in_mem), (0, 5));
        assert_eq!(
            in_mem.moves_since_last_check(),
            r#"Str("ABCDE")
"#
        );

        // Should wrap onto next line
        in_mem.write_str("FG").unwrap();
        assert_eq!(in_mem.contents(), "ABCDE\nFG");
        assert_eq!(cursor_pos(&in_mem), (1, 2));
        assert_eq!(
            in_mem.moves_since_last_check(),
            r#"Str("FG")
"#
        );

        in_mem.write_str("HIJ").unwrap();
        assert_eq!(in_mem.contents(), "ABCDE\nFGHIJ");
        assert_eq!(cursor_pos(&in_mem), (1, 5));
        assert_eq!(
            in_mem.moves_since_last_check(),
            r#"Str("HIJ")
"#
        );
    }

    #[test]
    fn write_line() {
        let in_mem = InMemoryTerm::new(10, 5);
        assert_eq!(cursor_pos(&in_mem), (0, 0));

        in_mem.write_line("A").unwrap();
        assert_eq!(in_mem.contents(), "A");
        assert_eq!(cursor_pos(&in_mem), (1, 0));
        assert_eq!(
            in_mem.moves_since_last_check(),
            r#"Str("A")
NewLine
"#
        );

        in_mem.write_line("B").unwrap();
        assert_eq!(in_mem.contents(), "A\nB");
        assert_eq!(cursor_pos(&in_mem), (2, 0));
        assert_eq!(
            in_mem.moves_since_last_check(),
            r#"Str("B")
NewLine
"#
        );

        in_mem.write_line("Longer than cols").unwrap();
        assert_eq!(in_mem.contents(), "A\nB\nLonge\nr tha\nn col\ns");
        assert_eq!(cursor_pos(&in_mem), (6, 0));
        assert_eq!(
            in_mem.moves_since_last_check(),
            r#"Str("Longer than cols")
NewLine
"#
        );
    }

    #[test]
    fn basic_functionality() {
        let in_mem = InMemoryTerm::new(10, 80);

        in_mem.write_line("This is a test line").unwrap();
        assert_eq!(in_mem.contents(), "This is a test line");
        assert_eq!(
            in_mem.moves_since_last_check(),
            r#"Str("This is a test line")
NewLine
"#
        );

        in_mem.write_line("And another line!").unwrap();
        assert_eq!(in_mem.contents(), "This is a test line\nAnd another line!");
        assert_eq!(
            in_mem.moves_since_last_check(),
            r#"Str("And another line!")
NewLine
"#
        );

        in_mem.move_cursor_up(1).unwrap();
        in_mem.write_str("TEST").unwrap();

        assert_eq!(in_mem.contents(), "This is a test line\nTESTanother line!");
        assert_eq!(
            in_mem.moves_since_last_check(),
            r#"Up(1)
Str("TEST")
"#
        );
    }

    #[test]
    fn newlines() {
        let in_mem = InMemoryTerm::new(10, 10);
        in_mem.write_line("LINE ONE").unwrap();
        in_mem.write_line("LINE TWO").unwrap();
        in_mem.write_line("").unwrap();
        in_mem.write_line("LINE FOUR").unwrap();

        assert_eq!(in_mem.contents(), "LINE ONE\nLINE TWO\n\nLINE FOUR");

        assert_eq!(
            in_mem.moves_since_last_check(),
            r#"Str("LINE ONE")
NewLine
Str("LINE TWO")
NewLine
Str("")
NewLine
Str("LINE FOUR")
NewLine
"#
        );
    }

    #[test]
    fn cursor_zero_movement() {
        let in_mem = InMemoryTerm::new(10, 80);
        in_mem.write_line("LINE ONE").unwrap();
        assert_eq!(cursor_pos(&in_mem), (1, 0));

        // Check that moving zero rows/cols does not actually move cursor
        in_mem.move_cursor_up(0).unwrap();
        assert_eq!(cursor_pos(&in_mem), (1, 0));

        in_mem.move_cursor_down(0).unwrap();
        assert_eq!(cursor_pos(&in_mem), (1, 0));

        in_mem.move_cursor_right(1).unwrap();
        assert_eq!(cursor_pos(&in_mem), (1, 1));

        in_mem.move_cursor_left(0).unwrap();
        assert_eq!(cursor_pos(&in_mem), (1, 1));

        in_mem.move_cursor_right(0).unwrap();
        assert_eq!(cursor_pos(&in_mem), (1, 1));
    }
}