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::terminal::editing::{self, Move};
use crate::terminal::inject::{Injector, Outcome};
use crate::terminal::links::Target;
use crate::terminal::pane::GridSize;
use crate::terminal::prompt::{awaiting_more, command_line, cursor_at_prompt, show_selection, typed_text};
use crate::terminal::search::row_chars;
#[derive(Clone, Default)]
struct Replies(Arc<Mutex<Option<EventLoopSender>>>, Arc<Mutex<Vec<String>>>);
impl EventListener for Replies {
fn send_event(&self, event: Event) {
if let Event::Title(title) = &event {
self.1.lock().unwrap().push(title.clone());
}
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 {
titles: Arc<Mutex<Vec<String>>>,
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::platform::winenv::fresh() {
env.entry(k).or_insert(v);
}
env.extend(config.shell_env());
env.insert("RUSTIMAL_PANE".into(), format!("test-{}", std::process::id()));
env.insert("RUSTIMAL_REVIEW_TOKEN".into(), "tok".into());
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 { titles: replies.1, 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);
}
}
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
}
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));
}
}
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::terminal::links::entry_command(&dir.join(name), name).expect("a folder");
let outcome = inject(&session, &cmd);
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();
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:?}");
}
#[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());
}
#[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());
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::terminal::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}");
}
#[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();
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");
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");
run("no_such_thing", "command not found");
let _ = std::fs::remove_dir_all(&dir);
}
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]); std::thread::sleep(Duration::from_millis(200));
}
panic!("could not type {text:?}; screen:\n{}", session.screen());
}
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);
}
#[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));
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");
let cl = command_line(&session.term.lock()).unwrap();
let mid = 6; 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");
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, "");
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, "");
}
#[test]
#[ignore]
fn review_and_pr_ask_for_the_panel() {
let session = Session::start(&std::env::current_dir().unwrap());
session.wait_until("the first prompt", 30, |s| s.at_prompt());
let request = |s: &Session| {
s.titles.lock().unwrap().iter().find_map(|t| t.strip_prefix("__rustimal_review__:tok:").map(str::to_string))
};
for round in 0..3 {
for (typed, args) in [
("review", ""),
("review demo", "demo"),
("review --uncommitted", "--uncommitted"),
("pr", ""),
("pr 12", "#12"),
("pr '#7'", "#7"),
("pr new", "--new"),
("pr new topic", "--new topic"),
] {
session.titles.lock().unwrap().clear();
session.send(format!("{typed}\r").as_bytes());
session.wait_until(&format!("{typed} #{round}"), 15, |s| request(s).is_some());
let asked = request(&session).unwrap();
let (dir, given) = asked.split_once('|').expect("a folder and arguments");
assert!(dir.starts_with('/') && dir.ends_with("rustimal"), "{dir}");
assert_eq!(given, args, "{typed}");
session.send(b"\r");
session.wait_until("the prompt after the answer", 2, |s| s.at_prompt());
}
}
assert!(!session.screen().contains("did not answer"), "{}", session.screen());
session.send(b"pr\r");
session.wait_until("giving up", 10, |s| s.screen().contains("did not answer") && s.at_prompt());
session.titles.lock().unwrap().clear();
session.send(b"pr -t -l 1000 Cargo.toml | head -n 1\r");
session.wait_until("coreutils pr", 15, |s| s.screen().lines().any(|l| l.starts_with("[package]")) && s.at_prompt());
assert!(request(&session).is_none());
}
#[test]
#[ignore]
fn pty_do_is_handed_to_rustimal_and_loops_still_work() {
let s = Session::start(&std::env::temp_dir());
s.wait_until("prompt", 30, |s| s.at_prompt());
let step = |line: &str| {
s.send(line.as_bytes());
std::thread::sleep(Duration::from_millis(700));
};
let asked = || {
s.titles
.lock()
.unwrap()
.iter()
.filter_map(|t| t.strip_prefix("__rustimal_do__:tok:").map(str::to_string))
.collect::<Vec<_>>()
};
let task_file = crate::config::state_dir().unwrap().join(format!("do-test-{}.txt", std::process::id()));
step("do why doesn't \"this\" work? (see $HOME & `x`)\r");
s.wait_until("the request", 10, |_| asked().len() == 1);
assert!(asked()[0].ends_with("|claude"), "{:?}", asked());
assert_eq!(std::fs::read_to_string(&task_file).unwrap(), "why doesn't \"this\" work? (see $HOME & `x`)");
step("\r");
step("do -x árvÃztűrÅ‘\r");
s.wait_until("the second request", 10, |_| asked().len() == 2);
assert!(asked()[1].ends_with("|codex"), "{:?}", asked());
assert_eq!(std::fs::read_to_string(&task_file).unwrap(), "árvÃztűrÅ‘");
step("\r");
step("do\r");
s.wait_until("a bare do", 10, |_| asked().len() == 3);
assert_eq!(std::fs::read_to_string(&task_file).unwrap(), "");
step("\r");
let _ = std::fs::remove_file(&task_file);
step("for i in 1 2\r");
step("do echo loop-$i\r");
step("done\r");
s.wait_until("the loop", 10, |s| s.screen().contains("loop-2"));
step("for i in 3\r");
step("do\r");
step("echo bare-$i; done\r");
s.wait_until("a loop with do on its own line", 10, |s| s.screen().contains("bare-3"));
step("while true\r");
step("\x03");
step("do after\r");
s.wait_until("do after Ctrl+C", 10, |_| asked().len() == 4);
step("\r");
let _ = std::fs::remove_file(&task_file);
assert_eq!(asked().len(), 4, "the loops asked for nothing:\n{}", s.screen());
step("sleep 0.4\r");
let ran: Vec<String> = s
.titles
.lock()
.unwrap()
.iter()
.filter_map(|t| t.strip_prefix("__rustimal_cmd__:").map(str::to_string))
.collect();
assert!(ran.iter().any(|c| c.starts_with("sleep")), "{ran:?}");
assert!(!ran.iter().any(|c| c.starts_with("__rustimal_")), "{ran:?}");
}
#[test]
#[ignore]
fn pty_vscode_asks_first_and_then_hands_files_to_rustimal() {
let state = std::env::temp_dir().join(format!("rustimal-code-test-{}", std::process::id()));
std::fs::create_dir_all(&state).unwrap();
let s = Session::start(&std::env::current_dir().unwrap());
s.wait_until("prompt", 30, |s| s.at_prompt());
let step = |line: &str| {
s.send(line.as_bytes());
std::thread::sleep(Duration::from_millis(900));
};
let asked = || {
let titles = s.titles.lock().unwrap();
titles.iter().filter_map(|t| t.strip_prefix("__rustimal_code__:tok:").map(str::to_string)).collect::<Vec<_>>()
};
let request = state.join(format!("code-test-{}.txt", std::process::id()));
let read = || std::fs::read_to_string(&request).unwrap_or_default().replace(std::path::MAIN_SEPARATOR, "/");
step(&format!("RUSTIMAL_STATE=$(cygpath -u '{}')\r", state.display()));
step("vscode .\r");
s.wait_until("the license question", 10, |s| s.screen().contains("Do you accept them? [y/N]"));
assert!(s.screen().contains("https://aka.ms/vscode-server-license"), "{}", s.screen());
step("\r");
s.wait_until("no is the default", 10, |s| s.screen().contains("Not accepted"));
assert!(asked().is_empty() && !state.join("vscode-license-accepted").exists());
step("vscode Cargo.toml:3:2\r");
step("y\r");
s.wait_until("the first request", 10, |_| asked().len() == 1);
assert!(asked()[0].ends_with("|vscode"), "{:?}", asked());
assert!(read().ends_with("/Cargo.toml\n3:2\n"), "{}", read());
step("\r");
assert!(state.join("vscode-license-accepted").exists(), "remembered");
step("vscode\r");
s.wait_until("no argument is this folder", 10, |_| asked().len() == 2);
assert!(read().trim_end().ends_with("rustimal"), "{}", read());
step("\r");
step("open README.md\r");
s.wait_until("open a text file", 10, |_| asked().len() == 3);
assert!(asked()[2].ends_with("|open") && read().ends_with("/README.md\n\n"), "{}", read());
step("\r");
step("open src/main.rs:5\r");
s.wait_until("open at a line", 10, |_| asked().len() == 4);
assert!(read().ends_with("/src/main.rs\n5\n"), "{}", read());
step("\r");
step("vscode no-such-thing\r");
s.wait_until("a missing file", 10, |s| s.screen().contains("no such file or folder"));
assert_eq!(asked().len(), 4);
let _ = std::fs::remove_dir_all(&state);
}
#[test]
#[ignore]
fn pty_embed_asks_rustimal_and_then_runs_the_command() {
let dir = std::env::temp_dir().join(format!("rustimal-embed-test-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let log = dir.join("ran.log");
let log_for_bash = log.display().to_string().replace('\\', "/");
let fake = dir.join("fake-rustimal.sh");
let script = format!(
"#!/bin/bash\necho \"RAN:$*\" >>'{log_for_bash}'\n[ -n \"$FAKE_SLEEP\" ] && sleep \"$FAKE_SLEEP\"\nexit 0\n"
);
std::fs::write(&fake, script).unwrap();
let s = Session::start(&dir);
s.wait_until("prompt", 30, |s| s.at_prompt());
let step = |line: &str| {
s.send(line.as_bytes());
std::thread::sleep(Duration::from_millis(900));
};
let asked = || {
let titles = s.titles.lock().unwrap();
titles.iter().filter_map(|t| t.strip_prefix("__rustimal_embed__:tok:").map(str::to_string)).collect::<Vec<_>>()
};
let ran = || std::fs::read_to_string(&log).unwrap_or_default();
step(&format!("RUSTIMAL_EXE=$(cygpath -u '{}')\r", fake.display()));
step("search rust window embedding\r");
s.wait_until("the first request", 10, |_| asked().len() == 1);
let request = &asked()[0];
let (_, args) = request.split_once('|').unwrap();
let pid = args.strip_prefix("start:").and_then(|a| a.strip_suffix(":browser")).expect(request);
assert!(pid.parse::<u32>().is_ok_and(|p| p > 0), "{request}");
assert!(ran().is_empty(), "{}", ran());
step("\r");
s.wait_until("the command", 10, |_| ran().contains("RAN:--browser --search rust window embedding"));
s.wait_until("the prompt", 10, |s| s.at_prompt());
step("export FAKE_SLEEP=8\r");
let before = asked().len();
step("zen localhost:3000\r");
s.wait_until("a request", 10, |_| asked().len() == before + 1);
step("\r");
s.wait_until("the command", 10, |_| ran().contains("RAN:--browser localhost:3000"));
s.wait_until("the prompt back while the browser runs", 4, |s| s.at_prompt());
step("unset FAKE_SLEEP\r");
let before = asked().len();
step("zen asd\r");
s.wait_until("a request", 10, |_| asked().len() == before + 1);
s.send(b"reuse\r");
s.wait_until("the page handed over", 10, |_| ran().contains("RAN:--browser --reuse asd"));
s.wait_until("the prompt", 10, |s| s.at_prompt());
let before = asked().len();
step("fork\r");
s.wait_until("a request", 10, |_| asked().len() == before + 1);
assert!(asked()[before].ends_with(":fork"), "{:?}", asked());
step("\r");
s.wait_until("the command", 10, |_| ran().lines().any(|l| l == "RAN:--fork"));
step("fork some-folder\r");
s.wait_until("a request", 10, |_| asked().len() == before + 2);
s.send(b"reuse\r");
s.wait_until("the folder handed over", 10, |_| ran().contains("RAN:--fork --reuse some-folder"));
s.wait_until("the prompt", 10, |s| s.at_prompt());
let requests = asked().len();
step("search\r");
s.wait_until("usage", 10, |s| s.screen().contains("usage: search TERMS"));
step("embed\r");
s.wait_until("usage", 10, |s| s.screen().contains("usage: embed [-f] COMMAND"));
assert_eq!(asked().len(), requests, "nothing is asked for when nothing is run");
step("embed echo quiet-output\r");
s.wait_until("a request", 10, |_| asked().len() == requests + 1);
step("\r");
s.wait_until("the note", 10, |s| s.screen().contains("running in the background"));
s.wait_until("the prompt", 10, |s| s.at_prompt());
assert_eq!(s.screen().matches("quiet-output").count(), 1, "only the typed command: {}", s.screen());
step("embed -f echo hello world\r");
s.wait_until("a request", 10, |_| asked().len() == requests + 2);
step("\r");
s.wait_until("the command", 10, |s| s.screen().contains("hello world"));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
#[ignore]
fn names_with_spaces_are_links_and_clicks() {
use alacritty_terminal::index::{Column, Line, Point};
let dir = std::env::temp_dir().join(format!("rustimal-spaces-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
for folder in ["my folder", "plain", "it's here"] {
std::fs::create_dir_all(dir.join(folder)).unwrap();
}
std::fs::write(dir.join("a b.txt"), "x").unwrap();
std::fs::write(dir.join("c.txt"), "x").unwrap();
let session = noisy_session(&dir);
session.wait_until("the first prompt", 30, |s| s.at_prompt());
assert_eq!(inject(&session, "ls"), Outcome::Done);
session.wait_until("ls", 30, |s| s.screen().contains("plain") && s.at_prompt());
let mut found = Vec::new();
{
let term = session.term.lock();
for line in 0..term.screen_lines() as i32 {
for column in 0..term.columns() {
let at = Point::new(Line(line), Column(column));
if let Some(link) = crate::terminal::links::find(&term, at, Some(&dir))
&& let crate::terminal::links::Target::Entry { name, .. } = link.target
&& !found.contains(&name)
{
found.push(name);
}
}
}
}
found.sort();
assert_eq!(found, ["a b.txt", "c.txt", "it's here", "my folder", "plain"], "{}", session.screen());
drop(session);
for (name, ls_first) in [("my folder", false), ("my folder", true), ("it's here", true)] {
assert!(click_scenario(&format!("spaced {name}"), &dir, name, ls_first), "{name}");
}
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
#[ignore]
fn pty_a_folder_name_lists_it_like_the_users_ls() {
use alacritty_terminal::index::{Column, Line};
use alacritty_terminal::vte::ansi::{Color, NamedColor};
let dir = std::env::temp_dir().join(format!("rustimal-autocd-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("sub").join("inner")).unwrap();
std::fs::write(dir.join("sub").join("f.txt"), "x").unwrap();
let session = Session::start(&dir);
session.wait_until("the first prompt", 30, |s| s.at_prompt());
session.send(b"alias ls='ls -1F --color=auto'\r");
std::thread::sleep(Duration::from_millis(600));
session.send(b"sub\r");
session.wait_until("the listing", 30, |s| s.screen().contains("f.txt") && s.at_prompt());
std::thread::sleep(Duration::from_millis(400));
let term = session.term.lock();
let mut inner = None;
for line in 0..term.screen_lines() as i32 {
let text: String = (0..term.columns()).map(|c| term.grid()[Line(line)][Column(c)].c).collect();
if let Some(at) = text.find("inner") {
inner = Some(term.grid()[Line(line)][Column(at)].fg);
assert!(text[at..].starts_with("inner/"), "the -F marker of the alias: {text:?}");
assert!(!text.contains("f.txt"), "the alias's -1, one name to a line: {text:?}");
}
}
let blue = matches!(inner, Some(Color::Named(NamedColor::Blue | NamedColor::BrightBlue)));
assert!(blue, "a folder is blue in the listing, not plain: {inner:?}");
drop(term);
drop(session);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
#[ignore]
fn pty_tab_tab_lists_choices_in_color() {
use alacritty_terminal::index::{Column, Line};
use alacritty_terminal::vte::ansi::{Color, NamedColor};
let dir = std::env::temp_dir().join(format!("rustimal-tabtab-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("alpha_dir")).unwrap();
std::fs::write(dir.join("alpha_file.txt"), "x").unwrap();
let session = Session::start(&dir);
session.wait_until("the first prompt", 30, |s| s.at_prompt());
session.send(b"ls alpha_\t");
std::thread::sleep(Duration::from_millis(500));
session.send(b"\t");
session.wait_until("the choices", 30, |s| s.screen().contains("alpha_file.txt"));
std::thread::sleep(Duration::from_millis(400));
let term = session.term.lock();
let mut found = None;
for line in 0..term.screen_lines() as i32 {
let text: String = (0..term.columns()).map(|c| term.grid()[Line(line)][Column(c)].c).collect();
if text.contains("alpha_file.txt")
&& !text.contains('\u{276f}')
&& let Some(at) = text.find("alpha_dir")
{
found = Some((text[at..].starts_with("alpha_dir/"), term.grid()[Line(line)][Column(at + 6)].fg));
}
}
let (marked, color) = found.unwrap_or_else(|| panic!("no list on screen: {}", session.screen()));
assert!(marked, "the / after a folder");
assert!(matches!(color, Color::Named(NamedColor::Blue | NamedColor::BrightBlue)), "a folder is blue: {color:?}");
drop(term);
drop(session);
let _ = std::fs::remove_dir_all(&dir);
}