rustimal 0.4.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! Headless tests that start a real Git Bash the way a pane does, with the shell
//! integration, and type into it. They need Git for Windows and take a few seconds each,
//! so they only run on request: `cargo test pty -- --ignored --nocapture`.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use alacritty_terminal::event::{Event, EventListener, WindowSize};
use alacritty_terminal::event_loop::{EventLoop, EventLoopSender, Msg};
use alacritty_terminal::grid::Dimensions;
use alacritty_terminal::index::Line;
use alacritty_terminal::sync::FairMutex;
use alacritty_terminal::term::{Config as TermConfig, Term};
use alacritty_terminal::tty::{self, Options, Shell};

use crate::config::Config;
use crate::inject::{Injector, Outcome};
use crate::links::Target;
use crate::editing::{self, Move};
use crate::pane::{GridSize, awaiting_more, command_line, cursor_at_prompt, show_selection, typed_text};
use crate::search::row_chars;

/// Answers the terminal's own queries (cursor position and so on), like a pane does.
#[derive(Clone, Default)]
struct Replies(Arc<Mutex<Option<EventLoopSender>>>);

impl EventListener for Replies {
    fn send_event(&self, event: Event) {
        if let Event::PtyWrite(s) = event
            && let Some(sender) = self.0.lock().unwrap().as_ref()
        {
            let _ = sender.send(Msg::Input(s.into_bytes().into()));
        }
    }
}

struct Session {
    term: Arc<FairMutex<Term<Replies>>>,
    sender: EventLoopSender,
}

impl Session {
    fn start(dir: &Path) -> Self {
        let config = Config::default();
        let (program, args) = config.shell_program();
        let mut env: HashMap<String, String> =
            [("TERM", "xterm-256color"), ("COLORTERM", "truecolor"), ("TERM_PROGRAM", "rustimal"), ("CHERE_INVOKING", "1")]
                .into_iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect();
        for (k, v) in crate::winenv::fresh() {
            env.entry(k).or_insert(v);
        }
        env.extend(config.shell_env());
        env.insert("RUSTIMAL_PANE".into(), format!("test-{}", std::process::id()));
        let opts = Options {
            shell: Some(Shell::new(program, args)),
            working_directory: Some(dir.to_path_buf()),
            drain_on_exit: false,
            env,
            escape_args: true,
        };
        let grid = GridSize { cols: 100, rows: 30 };
        let size = WindowSize { num_lines: 30, num_cols: 100, cell_width: 9, cell_height: 20 };
        let replies = Replies::default();
        let pty = tty::new(&opts, size, 1).expect("start Git Bash");
        let term = Arc::new(FairMutex::new(Term::new(TermConfig::default(), &grid, replies.clone())));
        let event_loop = EventLoop::new(term.clone(), replies.clone(), pty, false, false).expect("event loop");
        let sender = event_loop.channel();
        *replies.0.lock().unwrap() = Some(sender.clone());
        let _ = event_loop.spawn();
        Self { term, sender }
    }

    fn send(&self, bytes: &[u8]) {
        let _ = self.sender.send(Msg::Input(bytes.to_vec().into()));
    }

    fn at_prompt(&self) -> bool {
        cursor_at_prompt(&self.term.lock())
    }

    fn screen(&self) -> String {
        let term = self.term.lock();
        let mut out = String::new();
        for line in term.topmost_line().0..=term.bottommost_line().0 {
            let text: String = row_chars(&term, Line(line)).iter().map(|&(_, c, _)| c).collect();
            let text = text.trim_end();
            if !text.is_empty() {
                out.push_str(text);
                out.push('\n');
            }
        }
        out
    }

    fn wait_until(&self, what: &str, secs: u64, done: impl Fn(&Session) -> bool) {
        let start = Instant::now();
        while !done(self) {
            assert!(start.elapsed() < Duration::from_secs(secs), "timed out waiting for {what}; screen:\n{}", self.screen());
            std::thread::sleep(Duration::from_millis(5));
        }
    }
}

impl Drop for Session {
    fn drop(&mut self) {
        let _ = self.sender.send(Msg::Shutdown);
    }
}

/// Start a session and resize it the way a window settling at startup does.
fn noisy_session(dir: &Path) -> Session {
    let session = Session::start(dir);
    for (after_ms, cols, rows) in [(150, 103, 28), (350, 129, 36), (700, 127, 33)] {
        std::thread::sleep(Duration::from_millis(after_ms));
        session.term.lock().resize(GridSize { cols, rows });
        let size = WindowSize { num_lines: rows as u16, num_cols: cols as u16, cell_width: 9, cell_height: 20 };
        let _ = session.sender.send(Msg::Resize(size));
    }
    session
}

/// Drive an `Injector` against the session until it finishes, like a pane does every frame.
fn inject(session: &Session, cmd: &str) -> Outcome {
    let mut injector = Injector::new(cmd.to_string(), Some(Target::Path(PathBuf::from("unused"))), Instant::now());
    loop {
        let (writes, outcome) = injector.tick(&session.term.lock(), Instant::now());
        for bytes in writes {
            session.send(&bytes);
        }
        if outcome != Outcome::Pending {
            return outcome;
        }
        std::thread::sleep(Duration::from_millis(10));
    }
}

/// Click `name` in `dir` right after startup. Returns whether the command ran exactly as typed.
fn click_scenario(label: &str, dir: &Path, name: &str, ls_first: bool) -> bool {
    let session = noisy_session(dir);
    session.wait_until("the first prompt", 30, |s| s.at_prompt());
    if ls_first {
        assert_eq!(inject(&session, "ls"), Outcome::Done);
        session.wait_until("ls to finish", 30, |s| s.screen().contains(name) && s.at_prompt());
    }
    let cmd = crate::links::entry_command(&dir.join(name), name).expect("a folder");
    let outcome = inject(&session, &cmd);
    // Wait for the command to run and the next prompt (in the new folder) to appear.
    session.wait_until(&format!("{cmd:?} to finish"), 30, |s| {
        s.at_prompt() && s.screen().trim_end().lines().last().is_some_and(|l| l.contains(name))
    });
    std::thread::sleep(Duration::from_millis(200));
    let screen = session.screen();
    let ok = outcome == Outcome::Done && screen.contains(&format!("\u{276f} {cmd}")) && !screen.contains("command not found");
    println!("{} {label} (dir {}, ls first: {ls_first}, {outcome:?})", if ok { "ok  " } else { "FAIL" }, dir.display());
    if !ok {
        println!("{screen}");
    }
    ok
}

#[test]
#[ignore]
fn clicking_a_folder_types_the_whole_command() {
    let repo = std::env::current_dir().unwrap();
    let home = dirs::home_dir().unwrap();
    let root = PathBuf::from("C:\\");
    let mut failures = Vec::new();
    // Typing straight after a noisy startup lost characters in about a third of runs, so
    // repeat the scenarios until a repeat of the old way would almost surely have failed.
    for round in 0..3 {
        for (label, dir, name, ls_first) in [
            ("repo: first click at start", &repo, "src", false),
            ("repo: click after ls", &repo, "src", true),
            ("home: first click at start", &home, "Music", false),
            ("home: click after ls", &home, "Music", true),
            ("drive root: first click at start", &root, "Users", false),
        ] {
            if !click_scenario(&format!("{label} #{round}"), dir, name, ls_first) {
                failures.push(label);
            }
        }
    }
    assert!(failures.is_empty(), "clicks that went wrong: {failures:?}");
}

/// The case behind the bug: while a command runs, and before its prompt is back, the app
/// must not consider the shell ready, or text typed for it gets lost.
#[test]
#[ignore]
fn no_prompt_while_a_command_runs_or_text_is_typed() {
    let session = Session::start(&std::env::current_dir().unwrap());
    session.wait_until("the first prompt", 30, |s| s.at_prompt());

    session.send(b"sleep 3\r");
    std::thread::sleep(Duration::from_millis(100));
    for _ in 0..8 {
        assert!(!session.at_prompt(), "a command is running; screen:\n{}", session.screen());
        std::thread::sleep(Duration::from_millis(200));
    }
    session.wait_until("the prompt after sleep", 20, |s| s.at_prompt());

    session.send(b"abc");
    session.wait_until("typed text to show", 10, |s| s.screen().contains("abc"));
    assert!(!session.at_prompt(), "something is typed on the line; screen:\n{}", session.screen());
}

/// A long completion list paused at `--More--` swallows what is typed. The injector must
/// dismiss it first.
#[test]
#[ignore]
fn a_click_dismisses_a_paused_listing_first() {
    let home = dirs::home_dir().unwrap();
    let session = Session::start(&home);
    session.wait_until("the first prompt", 30, |s| s.at_prompt());
    // Page long completion lists (the shell integration turns this off), then list the folder.
    assert_eq!(inject(&session, "bind 'set page-completions on'"), Outcome::Done);
    session.wait_until("the prompt", 20, |s| s.at_prompt());
    session.send(b"\t\t");
    session.wait_until("--More--", 20, |s| awaiting_more(&s.term.lock()));
    assert!(!session.at_prompt());

    let cmd = crate::links::entry_command(&home.join("Music"), "Music").expect("a folder");
    assert_eq!(inject(&session, &cmd), Outcome::Done, "screen:\n{}", session.screen());
    session.wait_until("the command to finish", 30, |s| {
        s.at_prompt() && s.screen().trim_end().lines().last().is_some_and(|l| l.contains("Music"))
    });
    let screen = session.screen();
    assert!(screen.contains(&format!("\u{276f} {cmd}")), "screen:\n{screen}");
    assert!(!screen.contains("command not found"), "screen:\n{screen}");
}

/// Typing just a name: a folder is entered and listed, a text file printed, a program run, and
/// a real command always wins over a file or folder of the same name.
#[test]
#[ignore]
fn typing_a_bare_name_does_the_obvious_thing() {
    let dir = std::env::temp_dir().join(format!("rustimal-names-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    for sub in ["sub", "echo", "weird name"] {
        std::fs::create_dir_all(dir.join(sub)).unwrap();
    }
    std::fs::write(dir.join("sub").join("inner_file.txt"), "inner\n").unwrap();
    std::fs::write(dir.join("weird name").join("in_weird.txt"), "w\n").unwrap();
    std::fs::write(dir.join("notes.txt"), "the notes say hello\n").unwrap();
    std::fs::write(dir.join("hello.sh"), "#!/bin/bash\necho hello from the script\n").unwrap();
    std::fs::write(dir.join("echo").join("not_listed.txt"), "x\n").unwrap();

    let session = Session::start(&dir);
    session.wait_until("the first prompt", 30, |s| s.at_prompt());
    let here = dir.file_name().unwrap().to_string_lossy().into_owned();

    // Type `line`, then wait until the prompt is back and `expect` is on screen.
    let run = |line: &str, expect: &str| {
        assert_eq!(inject(&session, line), Outcome::Done, "typing {line:?}");
        session.wait_until(&format!("{line:?} to show {expect:?}"), 30, |s| {
            s.at_prompt() && s.screen().rsplit_once(&format!("\u{276f} {line}")).is_some_and(|(_, after)| after.contains(expect))
        });
    };
    let last_prompt = |session: &Session| session.screen().trim_end().lines().last().unwrap_or("").to_string();

    run("sub", "inner_file.txt");
    assert!(last_prompt(&session).contains("/sub"), "should be inside sub: {}", last_prompt(&session));

    run("..", "notes.txt");
    assert!(last_prompt(&session).contains(&here) && !last_prompt(&session).contains("/sub"), "{}", last_prompt(&session));

    run("notes.txt", "the notes say hello");
    run("hello.sh", "hello from the script");

    // A folder named like a command: the command wins, nothing is entered.
    run("echo", "\u{276f}");
    assert!(!last_prompt(&session).contains("/echo"), "echo is a command: {}", last_prompt(&session));

    run("'weird name'", "in_weird.txt");
    assert!(last_prompt(&session).contains("weird name"), "{}", last_prompt(&session));
    run("..", "notes.txt");

    // No such command, folder or file.
    run("no_such_thing", "command not found");

    let _ = std::fs::remove_dir_all(&dir);
}

/// Type text at the prompt without pressing Enter, checking it arrived (input can be lost
/// right after startup) and trying again if not.
fn type_text(session: &Session, text: &str) {
    for _ in 0..4 {
        session.send(text.as_bytes());
        let start = Instant::now();
        while start.elapsed() < Duration::from_millis(1200) {
            if typed_text(&session.term.lock()).as_deref() == Some(text) {
                return;
            }
            std::thread::sleep(Duration::from_millis(10));
        }
        session.send(&[0x05, 0x15]); // clear the line and try again
        std::thread::sleep(Duration::from_millis(200));
    }
    panic!("could not type {text:?}; screen:\n{}", session.screen());
}

/// The whole command line, not just the part before the cursor.
fn command_text(session: &Session) -> String {
    command_line(&session.term.lock()).map(|cl| cl.text()).unwrap_or_default()
}

fn wait_command(session: &Session, expected: &str) {
    session.wait_until(&format!("the command line to be {expected:?}"), 10, |s| command_text(s) == expected);
}

/// The keys behind Shift+arrows, Ctrl+Shift+arrows, Ctrl+A and typing over a selection, run
/// against a real readline: select by word or all, delete or replace it, and see the line.
#[test]
#[ignore]
fn selecting_and_replacing_on_the_command_line_works_in_a_real_shell() {
    let session = Session::start(&std::env::current_dir().unwrap());
    session.wait_until("the first prompt", 30, |s| s.at_prompt());
    std::thread::sleep(Duration::from_millis(400));

    // Select the last word (Ctrl+Shift+Left) and replace it by typing.
    type_text(&session, "alpha beta gamma");
    let cl = command_line(&session.term.lock()).unwrap();
    let chars = cl.chars();
    let to = editing::target(&chars, cl.cursor, Move::WordLeft);
    assert_eq!((cl.cursor, to), (16, 11));
    session.send(&editing::move_keys(cl.cursor, to, false));
    show_selection(&mut session.term.lock(), &cl, to, cl.cursor);
    assert_eq!(session.term.lock().selection_to_string().as_deref(), Some("gamma"));
    session.send(&editing::delete_keys(to, cl.cursor, to, false));
    wait_command(&session, "alpha beta ");
    session.send(b"delta");
    wait_command(&session, "alpha beta delta");

    // Select from the middle to the start (Shift+Home) and delete it: the cursor was moved
    // back into the line first.
    let cl = command_line(&session.term.lock()).unwrap();
    let mid = 6; // before "beta"
    session.send(&editing::move_keys(cl.cursor, mid, false));
    std::thread::sleep(Duration::from_millis(150));
    let cl = command_line(&session.term.lock()).unwrap();
    assert_eq!(cl.cursor, mid, "the shell's cursor followed the keys");
    session.send(&editing::delete_keys(0, mid, cl.cursor, false));
    wait_command(&session, "beta delta");

    // Select all (Ctrl+A) and delete it.
    let cl = command_line(&session.term.lock()).unwrap();
    let n = cl.cells.len();
    session.send(&editing::move_keys(cl.cursor, n, false));
    show_selection(&mut session.term.lock(), &cl, 0, n);
    assert_eq!(session.term.lock().selection_to_string().as_deref(), Some("beta delta"));
    session.send(&editing::delete_keys(0, n, n, false));
    wait_command(&session, "");

    // Words stop at separators: select "src" then "/" then "main" of a path, going right.
    type_text(&session, "cat src/main.rs");
    let cl = command_line(&session.term.lock()).unwrap();
    let chars = cl.chars();
    let mut at = 0;
    let mut stops = Vec::new();
    for _ in 0..4 {
        at = editing::target(&chars, at, Move::WordRight);
        stops.push(at);
    }
    assert_eq!(stops, vec![3, 7, 8, 12], "cat, src, /, main");
    session.send(&[0x05, 0x15]);
    wait_command(&session, "");
}