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
mod tty;
mod commands;

use std::borrow::Cow;
use std::collections::BTreeMap;
use std::marker::PhantomData;
use std::time::{Instant, Duration};
use std::io::{Write, Read};
use std::io::ErrorKind;

use mio::{Poll, PollOpt, Ready, Events};
#[cfg(not(windows))]
use mio::unix::UnixReady;

use tty::{EventedReadWrite, EventedPty, Pty};
use vt100;

pub use term::SizeInfo;
pub use commands::{Code, AsAnsi};

pub struct PtyTest {
    pty: Pty,
    wait_timeout: Duration,
    poll: Poll,
    events: Option<Events>,
    buf: [u8; 0x1000],
    parser: vt100::Parser,
}

#[derive(Debug)]
pub enum Error {
    ProcessExited(ScreenDiff, AsciiScreen),
    IoError(std::io::Error),
    TimeoutForScreenState(ScreenDiff, AsciiScreen),
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "PTYError {{")?;

        let maybe_ascii_state = match self {
            Error::TimeoutForScreenState(screen_diff, ascii_state) => {
                for line in format!("{}", screen_diff).split("\n") {
                    writeln!(f, "  {}", line)?;
                }

                Some(ascii_state)
            }
            Error::ProcessExited(screen_diff, ascii_state) => {
                for line in format!("{}", screen_diff).split("\n") {
                    writeln!(f, "  {}", line)?;
                }

                Some(ascii_state)
            }
            Error::IoError(_) => {
                None
            }
        };

        if let Some(ascii_state) = maybe_ascii_state {
            writeln!(f, "  Screen {{")?;
            for line in ascii_state.as_fragments().split("\n") {
                if !line.is_empty() {
                    writeln!(f, "    {}", line)?;
                }
            }
            writeln!(f, "  }}")?;
        }

        match self {
            Error::TimeoutForScreenState{..} => {
                writeln!(f, "  Screen timeout")?;
            }
            Error::ProcessExited{..} => {
                writeln!(f, "  Process exited")?;
            }
            Error::IoError(err) => {
                writeln!(f, "  IoError: {:?}", err)?;
            }
        };

        writeln!(f, "}}")?;
        Ok(())
    }
}

#[macro_export]
macro_rules! ascii_screen {
    ($($x:tt)*) => {AsciiScreen::new(file!(), line!(), &[
        $(ascii_screen_fragment!{$x}),*
    ])};
}

pub enum AsciiScreenFragment {
    Newline,
    String(&'static str),
    Underscore(usize),
    CursorPosition,
    Nothing,
}

impl AsciiScreenFragment {
    pub fn by_ident(s: &'static str) -> Self {
        let mut underscore_prefix = 0;

        for i in s.chars() {
            if i == '_' {
                underscore_prefix += 1;
                continue;
            } else {
                panic!("unknown character in indent {:?}", i);
            }
        }

        return AsciiScreenFragment::Underscore(underscore_prefix);
    }
}

#[derive(Debug)]
pub struct AsciiScreen {
    source_info: Option<(&'static str, u32)>,
    contents: String,
    cursor_rowcol: Option<(u16, u16)>,
}

impl AsciiScreen {
    pub fn new(file: &'static str, line: u32, asf_list: &[AsciiScreenFragment]) -> Self {
        let mut contents = String::new();
        let mut rows = 0;
        let mut cols = 0;
        let mut cursor_rowcol = None;

        for asf in asf_list {
            match asf {
                AsciiScreenFragment::String(line) => {
                    cols = 0;
                    contents.push_str(line);
                }
                AsciiScreenFragment::Newline => {
                    contents.push_str("\n");
                    rows += 1;
                }
                AsciiScreenFragment::Underscore(added_cols)  => {
                    cols += *added_cols;
                }
                AsciiScreenFragment::CursorPosition => {
                    if cursor_rowcol.is_some() {
                        panic!("more than one cursor defined"); // TODO;
                    }
                    cursor_rowcol = Some((rows as u16, cols as u16));
                }
                AsciiScreenFragment::Nothing => {
                    continue
                }
            }
        }

        if contents.ends_with("\n") {
            contents.pop();
        }

        AsciiScreen {
            source_info: Some((file, line)),
            contents,
            cursor_rowcol,
        }
    }

    fn as_fragments(&self) -> String {
        use std::fmt::Write;

        let mut s = String::new();

        for (_idx, line) in self.contents.split("\n").enumerate() {
            let _ = writeln!(&mut s, "{:?}, NL, ", line);

            //
            // TODO: write cursor information
            //
            // if let Some((row, col)) = self.cursor_rowcol {
            //     if row == idx as u16 + 1 {
            //         println!(",____________^,");
            //     }
            // }
        }

        s
    }
}

#[derive(Debug)]
pub struct Change<E> {
    expected: E,
    received: E,
}

#[derive(Debug)]
pub struct ScreenDiff {
    cursor_pos_diff: Option<Change<Option<(u16, u16)>>>,
    content_diff: Option<(String, String)>,
}

impl std::fmt::Display for ScreenDiff {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "ScreenDiff {{")?;

        match &self.content_diff {
            None => {},
            Some((expected, found)) => {
                let changeset = difference::Changeset::new(&expected, &found, "\n");
                use difference::Difference;

                for change in changeset.diffs {
                    match change {
                        Difference::Rem(x) => {
                            for line in x.split("\n") {
                                writeln!(f, "  -{}", line)?;
                            }
                        },
                        Difference::Add(x) => {
                            for line in x.split("\n") {
                                writeln!(f, "  +{}", line)?;
                            }
                        },
                        Difference::Same(x) => {
                            for line in x.split("\n") {
                                writeln!(f, "   {}", line)?;
                            }
                        },
                    }
                }
            }
        }

        write!(f, "}}")?;
        Ok(())
    }
}

#[macro_export]
macro_rules! ascii_screen_fragment {
    ($x:literal) => { AsciiScreenFragment::String($x) };
    (NL) => { AsciiScreenFragment::Newline };
    ($x:ident) => { AsciiScreenFragment::by_ident(stringify!($x)) };
    (^) => { AsciiScreenFragment::CursorPosition };
    (,) => { AsciiScreenFragment::Nothing };
}

impl PtyTest {
    fn from_tty(mut pty: Pty, size: &SizeInfo) -> Self {
        let poll = mio::Poll::new().expect("create mio Poll");
        let mut tokens = (0..).map(Into::into);
        let poll_opts = PollOpt::edge();
        let parser = vt100::Parser::new(size.lines as u16, size.cols as u16, 0);

        pty.register(&poll, &mut tokens, Ready::readable(), poll_opts).unwrap();

        Self {
            pty,
            parser,
            buf: [0u8; 0x1000],
            events: Some(Events::with_capacity(128)),
            wait_timeout: Duration::from_millis(1000),
            poll,
        }
    }

    pub fn ascii_state(&self) -> AsciiScreen {
        let screen = self.parser.screen();

        let cursor = if screen.hide_cursor() {
            None
        } else {
            Some(screen.cursor_position())
        };

        AsciiScreen {
            source_info: None,
            contents: screen.contents(),
            cursor_rowcol: cursor,
        }
    }

    pub fn diff(&self, screen_state: &AsciiScreen) -> Result<(), ScreenDiff> {
        let screen = self.parser.screen();
        let mut content_diff = None;
        let mut cursor_pos_diff = None;

        if screen_state.contents != screen.contents() {
            content_diff = Some((screen_state.contents.clone(), screen.contents()));
        }

        let cursor = if screen.hide_cursor() {
            None
        } else {
            Some(screen.cursor_position())
        };

        if cursor != screen_state.cursor_rowcol {
            cursor_pos_diff = Some(Change {
                expected: screen_state.cursor_rowcol,
                received: cursor,
            });
        }

        if cursor_pos_diff.is_some() || content_diff.is_some() {
            return Err(ScreenDiff {
                cursor_pos_diff,
                content_diff,
            });
        }

        Ok(())
    }

    pub fn write_str(&mut self, codes: &str) -> Result<(), Error> {
        let writer = self.pty.writer();
        match writer.write(codes.as_bytes()) {
            Err(io) => return Err(Error::IoError(io)),
            Ok(_n) => if _n != codes.len() { unimplemented!() },
        }

        Ok(())
    }

    pub fn write<D, T>(&mut self, code: D) -> Result<(), Error>
        where D: AsRef<T>, T: commands::AsAnsi
    {
        let mut s = String::new();
        code.as_ref().add_to_string(&mut s);
        self.write_str(&s)
    }

    pub fn wait_for(&mut self, screen_state: &AsciiScreen) -> Result<(), Error> {
        let mut events = self.events.take().unwrap();
        let end_time = Instant::now() + self.wait_timeout;
        let mut exited = false;
        let mut had_data = false;

        loop {
            let diff = match self.diff(screen_state) {
                Ok(()) => {
                    self.events = Some(events);
                    return Ok(());
                },
                Err(diff) => {
                    if Instant::now() >= end_time {
                        return Err(Error::TimeoutForScreenState(diff, self.ascii_state()))
                    }

                    diff
                }
            };

            if !had_data && exited {
                // println!("{:?} {:?} != {:?}", self.parser.screen().contents(), self.parser.screen().cursor_position(),
                //     screen_state);
                self.events = Some(events);
                return Err(Error::ProcessExited(diff, self.ascii_state()));
            }

            if let Err(err) = self.poll.poll(&mut events, Some(self.wait_timeout / 10)) {
                match err.kind() {
                    ErrorKind::Interrupted => continue,
                    _ => panic!("EventLoop polling error: {:?}", err),
                }
            }

            had_data = false;
            for event in events.iter() {
                match event.token() {
                    token if token == self.pty.child_event_token() => {
                        if let Some(tty::ChildEvent::Exited) = self.pty.next_child_event() {
                            exited = true;
                        }
                    }
                    token if token == self.pty.read_token() => {
                        had_data = true;
                        #[cfg(unix)]
                        {
                            if UnixReady::from(event.readiness()).is_hup() {
                                // don't try to do I/O on a dead PTY
                                continue;
                            }
                        }

                        if event.readiness().is_readable() {
                            match self.pty.reader().read(&mut self.buf[..]) {
                                Ok(nread) => {
                                    self.parser.process(&self.buf[0..nread]);
                                }
                                Err(err) => {
                                    self.events = Some(events);
                                    return Err(Error::IoError(err));
                                }
                            }
                        }
                    }
                    _ => (),
                }
            }
        }
    }

    pub fn new_with_args<S>(program: S, args: Vec<String>, size: &SizeInfo) -> Self
    where
        S: Into<Cow<'static, str>>,
    {
        let tty = pty_new_with_args(program, args, size);
        Self::from_tty(tty, size)
    }
}

fn pty_new_with_args<S>(program: S, args: Vec<String>, size: &SizeInfo) -> tty::Pty
where
    S: Into<Cow<'static, str>>,
{
    let config = config::Config::new().set_shell(config::Shell::new_with_args(program, args));
    let tty = tty::new(&config, size);

    tty
}

impl config::Config<()> {
    fn new() -> Self {
        Self {
            c: PhantomData,
            shell: None,
            env: BTreeMap::new(),
        }
    }

    fn set_shell(self, shell: config::Shell<'static>) -> Self {
        Self {
            shell: Some(shell),
            ..self
        }
    }
}

impl SizeInfo {
    pub fn new(cols: usize, lines: usize) -> Self {
        Self {
            lines, cols, width: 10, height: 5,
        }
    }
}

// Alacritty-based stubs for used by `tty`
////////////////////////////////////////////////////////////////////////////////

pub mod unused {
    pub use crate::tty::{process_should_exit, child_pid, setup_env};
}

mod event {
    use crate::SizeInfo;

    pub trait OnResize {
        fn on_resize(&mut self, size: &SizeInfo);
    }
}

mod term {
    pub struct SizeInfo {
        pub(crate) lines: usize,
        pub(crate) cols: usize,
        pub width: usize,
        pub height: usize,
    }

    impl SizeInfo {
        pub fn lines(&self) -> (usize, ()) {
            (self.lines, ())
        }

        pub fn cols(&self) -> (usize, ()) {
            (self.cols, ())
        }
    }
}

mod config {
    use std::collections::BTreeMap;
    use std::borrow::Cow;
    use std::path::PathBuf;

    #[derive(Clone, Debug, PartialEq, Eq)]
    pub struct Shell<'a> {
        pub program: Cow<'a, str>,
        pub args: Vec<String>,
    }

    impl<'a> Shell<'a> {
        pub fn new<S>(program: S) -> Shell<'a>
        where
            S: Into<Cow<'a, str>>,
        {
            Shell { program: program.into(), args: Vec::new() }
        }

        pub fn new_with_args<S>(program: S, args: Vec<String>) -> Shell<'a>
        where
            S: Into<Cow<'a, str>>,
        {
            Shell { program: program.into(), args }
        }
    }

    pub struct Config<C> {
        pub(crate) c: std::marker::PhantomData<C>,
        pub shell: Option<Shell<'static>>,
        pub env: BTreeMap<String, String>,
    }

    impl<C> Config<C> {
        pub fn working_directory(&self) -> Option<PathBuf> {
            None
        }
    }
}