rustimal 0.7.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
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
//! 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>>>, 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::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);
    }
}

/// 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, "");
}

/// `review` and `pr` ask the window to open the panel; any other use of `pr` is coreutils'.
#[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))
    };
    // Repeated, because a request lost between two titles shows up only now and then.
    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}");
            // The window's answer; the next prompt follows it.
            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());

    // With no answer it gives up and says so.
    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());
}

/// `do` is a reserved word, so Enter rewrites a line starting with it, and only that.
#[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`)");
    // The app answers with Enter once it has the task.
    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"));
    // A loop dropped with Ctrl+C doesn't disarm the next `do`.
    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());
    // rustimal hears which command was typed, not what the Enter key or Ctrl+C ran. (It
    // has to last a moment: the console drops a title that another one follows at once.)
    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:?}");
}