petitcarnets 0.0.10

Terminal user interfaces in the Elm architecture (model, update, view), with no dependencies.
Documentation
//! The guard's bookkeeping, without a terminal.

use super::*;

#[test]
#[cfg_attr(miri, ignore)] // calls libc through src/sys.rs
fn entering_needs_a_terminal() {
    assert!(TerminalGuard::enter(-1, -1).is_err());
}

#[test]
fn restoring_with_nothing_saved_does_nothing() {
    assert!(restore(None).is_ok());
}

#[test]
fn modes_turn_off_newest_first_and_toggled_ones_drop_out() {
    let paste = ModeKey::Mode(TerminalMode::BracketedPaste);
    let mouse = ModeKey::Mode(TerminalMode::MouseCellMotion);
    let focus = ModeKey::Mode(TerminalMode::ReportFocus);
    let mut active = Active::default();
    active.on(ModeKey::Mode(TerminalMode::AltScreen), b"<alt>");
    active.on(ModeKey::HiddenCursor, b"<cursor>");
    active.on(paste, b"<paste>");
    active.on(mouse, b"<mouse>");
    active.on(focus, b"<focus>");
    assert_eq!(active.off(mouse), Some(&b"<mouse>"[..]));
    assert_eq!(active.off(mouse), None, "already off");
    active.on(paste, b"<paste2>");
    active.on(mouse, b"<mouse>");
    assert_eq!(
        active.leave_all(),
        b"<mouse><focus><paste2><cursor><alt>",
        "newest first; turning paste on again keeps its place"
    );
}

/// Every byte the master end has to read now.
fn drain(master: c_int) -> Vec<u8> {
    let mut out = Vec::new();
    let mut buf = [0u8; 256];
    while sys::wait_readable([master], Some(std::time::Duration::ZERO)).is_ok_and(|[r]| r) {
        match sys::read_fd(master, &mut buf) {
            Ok(n) if n > 0 => out.extend_from_slice(&buf[..n]),
            _ => break,
        }
    }
    out
}

/// Runs `f` while a thread reads what reaches the master end, as a
/// terminal emulator does: a mode change that flushes waits for output
/// to drain, and FreeBSD waits for a reader (up to its
/// `kern.tty_drainwait`, 300 seconds) where Linux does not. What `f`
/// gave, and every byte read.
fn reading<T>(master: c_int, f: impl FnOnce() -> T) -> (T, Vec<u8>) {
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, Ordering};
    let stop = Arc::new(AtomicBool::new(false));
    let reader = {
        let stop = Arc::clone(&stop);
        std::thread::spawn(move || {
            let mut out = Vec::new();
            loop {
                // Read once more after the stop, for the last bytes.
                let last = stop.load(Ordering::SeqCst);
                out.extend(drain(master));
                if last {
                    return out;
                }
                std::thread::sleep(std::time::Duration::from_millis(2));
            }
        })
    };
    let value = f();
    stop.store(true, Ordering::SeqCst);
    (value, reader.join().expect("the reader thread"))
}

/// The step the guard test has reached, for the watchdog.
static STEP: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);

/// Records that the guard test reached `n`.
fn step(n: u32) {
    STEP.store(n, std::sync::atomic::Ordering::SeqCst);
}

/// Ends the process, naming the step, if the guard test has not reached
/// step 99 within a minute: a hang fails fast instead of holding CI.
fn watchdog() {
    use std::io::Write as _;
    let _ = std::thread::spawn(|| {
        let start = std::time::Instant::now();
        while STEP.load(std::sync::atomic::Ordering::SeqCst) != 99 {
            if start.elapsed() > std::time::Duration::from_secs(60) {
                let at = STEP.load(std::sync::atomic::Ordering::SeqCst);
                // Straight to stderr: the harness captures eprintln!.
                let _ = writeln!(io::stderr(), "the guard test hung after step {at}");
                std::process::exit(2);
            }
            std::thread::sleep(std::time::Duration::from_millis(50));
        }
    });
}

/// One test, as the guard's state is the process's: raw mode, modes on
/// and off, handing over and back, and restoring, on a real
/// pseudo-terminal. A watchdog ends the process if a step hangs, naming
/// the step (macOS CI once hung here for hours).
#[test]
#[cfg_attr(miri, ignore)] // calls libc through src/sys.rs
fn a_guard_drives_a_real_terminal_and_gives_it_back() {
    use std::os::fd::AsRawFd;
    watchdog();
    let (master, slave) = sys::open_pty().unwrap();
    step(1);
    let (m, s) = (master.as_raw_fd(), slave.as_raw_fd());
    let before = sys::get_mode(s).unwrap();
    // A panic in another test would run the guard's hook and restore
    // this terminal mid-test: the hook is installed, then set aside
    // until the end.
    install_panic_hook();
    let hook = std::panic::take_hook();
    let guard = TerminalGuard::enter(s, s).unwrap();
    step(2);
    assert!(
        TerminalGuard::enter(s, s).is_err(),
        "a second guard would lose the first's saved mode"
    );
    assert_eq!(
        sys::get_mode(s).unwrap(),
        sys::make_raw(&before),
        "untouched"
    );
    let raw = sys::get_mode(s).unwrap();
    assert_ne!(raw, before, "raw mode is on");
    assert_eq!(raw, sys::make_raw(&before));
    let paste = ModeKey::Mode(TerminalMode::BracketedPaste);
    guard.on(paste, b"<paste on>", b"<paste off>").unwrap();
    guard
        .on(HIDDEN_CURSOR.0, HIDDEN_CURSOR.1, HIDDEN_CURSOR.2)
        .unwrap();
    guard.write(b"<flags>").unwrap();
    guard.off(HIDDEN_CURSOR.0).unwrap();
    guard.off(HIDDEN_CURSOR.0).unwrap();
    step(3);
    assert_eq!(drain(m), b"<paste on>\x1b[?25l<flags>\x1b[?25h");
    step(4);
    guard.cook().unwrap();
    step(5);
    assert_eq!(
        sys::get_mode(s).unwrap(),
        before,
        "the saved mode for a child"
    );
    guard.raw().unwrap();
    assert_eq!(sys::get_mode(s).unwrap(), raw, "and raw again");
    step(6);
    let (restored, out) = reading(m, || guard.restore());
    step(7);
    restored.unwrap();
    assert_eq!(out, b"<paste off>", "what is still on is turned off");
    assert_eq!(sys::get_mode(s).unwrap(), before, "the mode is back");
    let again = TerminalGuard::enter(s, s).unwrap();
    again.on(paste, b"", b"<off on drop>").unwrap();
    step(8);
    let ((), out) = reading(m, || drop(again));
    step(9);
    assert_eq!(out, b"<off on drop>");
    assert_eq!(sys::get_mode(s).unwrap(), before);
    let late = TerminalGuard {
        input: s,
        output: s,
    };
    assert!(
        late.cook().is_ok() && late.raw().is_ok(),
        "no guard, nothing to do"
    );
    assert_eq!(sys::get_mode(s).unwrap(), before);
    std::panic::set_hook(hook);
    step(99);
}