From a pass with the taste skill's rules:
- File errors read as a person would say them ("Couldn't open x: it
isn't there") instead of raw OS text with "(os error 2)", and each
prompt says what it couldn't do.
- Segmented buttons tint on hover and squeeze when pressed, and switches
get a hover halo round the thumb, like the rest of the controls.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
806 lines
34 KiB
Rust
806 lines
34 KiB
Rust
//! End-to-end checks of the features, using the real tools where they matter: live language
|
|
//! servers, a real shell, a real git repository.
|
|
//! `cargo test --test features -- --test-threads=1 --nocapture`
|
|
|
|
use damson::app::App;
|
|
use damson::ui::commands::Cmd;
|
|
use eframe::egui::{vec2, Event, Key, Modifiers};
|
|
use egui_kittest::Harness;
|
|
use std::path::{Path, PathBuf};
|
|
use std::time::{Duration, Instant};
|
|
|
|
type H<'a> = Harness<'a, App>;
|
|
|
|
const CTRL: Modifiers = Modifiers::COMMAND;
|
|
|
|
fn tmp(name: &str) -> PathBuf {
|
|
let d = std::env::temp_dir().join(format!("damson-f-{name}-{}", std::process::id()));
|
|
let _ = std::fs::remove_dir_all(&d);
|
|
std::fs::create_dir_all(&d).unwrap();
|
|
std::env::set_var("XDG_CONFIG_HOME", d.join(".config"));
|
|
d
|
|
}
|
|
|
|
fn app<'a>(files: Vec<String>) -> H<'a> {
|
|
// the real app gets system fonts and draws a box for the rest; by default the harness panics
|
|
let mut h: H = Harness::builder().with_size(vec2(1300.0, 850.0)).allow_missing_glyphs().wgpu().build_eframe(move |cc| App::new(cc, files.clone()));
|
|
settle(&mut h, 6);
|
|
h
|
|
}
|
|
|
|
fn settle(h: &mut H, n: usize) {
|
|
for _ in 0..n {
|
|
h.step();
|
|
std::thread::sleep(Duration::from_millis(16));
|
|
}
|
|
}
|
|
|
|
fn wait(h: &mut H, secs: u64, what: &str, mut ok: impl FnMut(&mut H) -> bool) {
|
|
let t = Instant::now();
|
|
while t.elapsed() < Duration::from_secs(secs) {
|
|
if ok(h) {
|
|
println!(" {what}: {:.1}s", t.elapsed().as_secs_f32());
|
|
return;
|
|
}
|
|
settle(h, 3);
|
|
}
|
|
panic!("timed out waiting for: {what}");
|
|
}
|
|
|
|
fn key(h: &mut H, k: Key, m: Modifiers) {
|
|
h.input_mut().events.push(Event::Key { key: k, physical_key: Some(k), pressed: true, repeat: false, modifiers: m });
|
|
h.step();
|
|
h.input_mut().events.push(Event::Key { key: k, physical_key: Some(k), pressed: false, repeat: false, modifiers: m });
|
|
h.step();
|
|
}
|
|
|
|
/// Types like a person, one character per frame.
|
|
fn typed(h: &mut H, s: &str) {
|
|
for c in s.chars() {
|
|
if c == '\n' {
|
|
key(h, Key::Enter, Modifiers::NONE);
|
|
} else {
|
|
h.input_mut().events.push(Event::Text(c.to_string()));
|
|
settle(h, 2);
|
|
}
|
|
}
|
|
}
|
|
|
|
fn cmd(h: &mut H, c: Cmd) {
|
|
let ctx = h.ctx.clone();
|
|
h.state_mut().run(&ctx, c);
|
|
settle(h, 3);
|
|
}
|
|
|
|
fn text(h: &H) -> String {
|
|
h.state().cur_doc().unwrap().buf.rope.to_string()
|
|
}
|
|
|
|
fn caret(h: &mut H, line: usize, col: usize) {
|
|
let d = h.state_mut().cur_doc_mut().unwrap();
|
|
let at = d.buf.at(line, col);
|
|
d.buf.set_cursor(at);
|
|
settle(h, 2);
|
|
}
|
|
|
|
fn pos(h: &H) -> (usize, usize) {
|
|
let b = &h.state().cur_doc().unwrap().buf;
|
|
b.pos(b.head())
|
|
}
|
|
|
|
fn labels(h: &H) -> Vec<String> {
|
|
h.state().complete.as_ref().map_or(vec![], |c| c.items.iter().map(|i| i.label.clone()).collect())
|
|
}
|
|
|
|
fn write(p: &Path, s: &str) -> String {
|
|
if let Some(d) = p.parent() { std::fs::create_dir_all(d).unwrap() }
|
|
std::fs::write(p, s).unwrap();
|
|
p.to_string_lossy().into_owned()
|
|
}
|
|
|
|
#[test]
|
|
fn clangd_live() {
|
|
let dir = tmp("clangd");
|
|
let f = write(&dir.join("main.c"), "#include <stdio.h>\nstruct point { int x; int y; };\nint add(int a, int b) { return a + b; }\nint main(void) {\n struct point p;\n p.\n return add(1, 2) + missing;\n}\n");
|
|
let mut h = app(vec![f]);
|
|
h.state_mut().set_root(dir.clone());
|
|
settle(&mut h, 3);
|
|
assert_eq!(h.state().cur_doc().unwrap().language, "C");
|
|
wait(&mut h, 30, "diagnostics arrive", |h| h.state().problem_count() > 0);
|
|
let (e, _) = h.state().problem_totals();
|
|
assert!(e >= 1, "undeclared name is an error");
|
|
|
|
caret(&mut h, 5, 6);
|
|
wait(&mut h, 20, "member completion", |h| { if h.state().complete.is_none() { key(h, Key::Space, CTRL); settle(h, 6) } !labels(h).is_empty() });
|
|
println!(" got: {:?}", labels(&h));
|
|
assert!(labels(&h).iter().any(|l| l == "x"), "{:?}", labels(&h));
|
|
assert!(labels(&h).iter().any(|l| l == "y"));
|
|
key(&mut h, Key::ArrowDown, Modifiers::NONE);
|
|
key(&mut h, Key::Enter, Modifiers::NONE);
|
|
settle(&mut h, 3);
|
|
assert!(text(&h).contains(" p.y\n"), "accepting inserts it: {}", text(&h));
|
|
|
|
caret(&mut h, 6, 13);
|
|
key(&mut h, Key::F12, Modifiers::NONE);
|
|
wait(&mut h, 15, "go to definition", |h| pos(h).0 == 2);
|
|
|
|
caret(&mut h, 6, 13);
|
|
key(&mut h, Key::I, CTRL);
|
|
wait(&mut h, 15, "hover", |h| h.state().hover.is_some());
|
|
let t = h.state().hover.as_ref().unwrap().0.clone();
|
|
println!(" hover: {:?}", t.lines().next());
|
|
assert!(t.contains("add"), "{t}");
|
|
key(&mut h, Key::Escape, Modifiers::NONE);
|
|
|
|
// diagnostics follow edits without saving: fix both problems on those two lines
|
|
caret(&mut h, 5, 7);
|
|
typed(&mut h, ";");
|
|
caret(&mut h, 6, 0);
|
|
key(&mut h, Key::K, CTRL);
|
|
wait(&mut h, 20, "problem clears after the edit", |h| h.state().problem_totals().0 == 0);
|
|
|
|
// typing a name brings completion up by itself
|
|
caret(&mut h, 4, 0);
|
|
key(&mut h, Key::End, Modifiers::NONE);
|
|
key(&mut h, Key::Enter, Modifiers::NONE);
|
|
typed(&mut h, "ad");
|
|
wait(&mut h, 10, "completion while typing", |h| !labels(h).is_empty());
|
|
assert!(labels(&h).iter().any(|l| l.starts_with("add")), "{:?}", labels(&h));
|
|
// and it narrows, then goes away on a non-word key
|
|
typed(&mut h, "d");
|
|
wait(&mut h, 5, "narrowed", |h| labels(h).iter().all(|l| l.to_lowercase().starts_with("add")));
|
|
key(&mut h, Key::Escape, Modifiers::NONE);
|
|
settle(&mut h, 2);
|
|
assert!(h.state().complete.is_none());
|
|
std::fs::remove_dir_all(dir).ok();
|
|
}
|
|
|
|
#[test]
|
|
fn rust_analyzer_live() {
|
|
let dir = tmp("ra");
|
|
write(&dir.join("Cargo.toml"), "[package]\nname = \"t\"\nversion = \"0.1.0\"\nedition = \"2021\"\n");
|
|
let f = write(&dir.join("src/main.rs"), "fn helper(n: u32) -> u32 {\n n + 1\n}\n\nfn main() {\n let v: Vec<u32> = Vec::new();\n v.\n let s = helper(1);\n let bad: u32 = \"text\";\n}\n");
|
|
let mut h = app(vec![]);
|
|
h.state_mut().set_root(dir.clone());
|
|
let ctx = h.ctx.clone();
|
|
h.state_mut().open_path(&ctx, f.into(), None);
|
|
settle(&mut h, 5);
|
|
assert_eq!(h.state().cur_doc().unwrap().language, "Rust");
|
|
let works = std::process::Command::new("rust-analyzer").arg("--version").output().is_ok_and(|o| o.status.success());
|
|
if !works {
|
|
// a rustup placeholder starts and dies at once: say so and carry on with word completion
|
|
println!(" rust-analyzer not really installed: checking the fallback");
|
|
wait(&mut h, 10, "the failure is reported", |h| h.state().toasts.iter().any(|t| t.text.contains("isn't working")));
|
|
caret(&mut h, 6, 4);
|
|
typed(&mut h, "hel");
|
|
wait(&mut h, 5, "word completion takes over", |h| labels(h).iter().any(|l| l == "helper"));
|
|
std::fs::remove_dir_all(dir).ok();
|
|
return;
|
|
}
|
|
caret(&mut h, 6, 6);
|
|
wait(&mut h, 90, "rust-analyzer completion", |h| {
|
|
if h.state().complete.is_none() { key(h, Key::Space, CTRL); settle(h, 20) }
|
|
!labels(h).is_empty()
|
|
});
|
|
assert!(labels(&h).iter().any(|l| l.starts_with("push")), "{:?}", labels(&h));
|
|
key(&mut h, Key::Escape, Modifiers::NONE);
|
|
caret(&mut h, 7, 13);
|
|
key(&mut h, Key::F12, Modifiers::NONE);
|
|
wait(&mut h, 30, "go to definition", |h| pos(h).0 == 0);
|
|
wait(&mut h, 60, "type error shows", |h| h.state().problem_totals().0 > 0);
|
|
|
|
caret(&mut h, 7, 13);
|
|
key(&mut h, Key::I, CTRL);
|
|
wait(&mut h, 20, "hover", |h| h.state().hover.is_some());
|
|
let t = h.state().hover.as_ref().unwrap().0.clone();
|
|
println!(" hover: {:?}", t.lines().filter(|l| !l.trim().is_empty()).take(3).collect::<Vec<_>>());
|
|
assert!(t.contains("fn helper") && !t.contains("```"), "{t}");
|
|
key(&mut h, Key::Escape, Modifiers::NONE);
|
|
|
|
// typing after the dot brings the list up, and it narrows; Enter takes the top match
|
|
caret(&mut h, 6, 6);
|
|
typed(&mut h, "pu");
|
|
wait(&mut h, 15, "members while typing", |h| labels(h).iter().any(|l| l.starts_with("push")));
|
|
println!(" v.pu: {:?}", &labels(&h)[..labels(&h).len().min(4)]);
|
|
let want = labels(&h).iter().position(|l| l.starts_with("push")).expect("push is listed");
|
|
for _ in 0..want {
|
|
key(&mut h, Key::ArrowDown, Modifiers::NONE);
|
|
}
|
|
settle(&mut h, 2);
|
|
println!(" selected: {:?}", h.state().complete.as_ref().map(|c| c.items[c.sel].label.clone()));
|
|
key(&mut h, Key::Enter, Modifiers::NONE);
|
|
settle(&mut h, 3);
|
|
println!(" accepted: {:?}", text(&h).lines().nth(6));
|
|
assert!(text(&h).lines().nth(6).unwrap().trim_start().starts_with("v.push"), "{}", text(&h));
|
|
|
|
// a path after ::
|
|
caret(&mut h, 7, 0);
|
|
key(&mut h, Key::Enter, Modifiers::NONE);
|
|
caret(&mut h, 7, 0);
|
|
typed(&mut h, " let m = std::co");
|
|
wait(&mut h, 15, "paths while typing", |h| labels(h).iter().any(|l| l.starts_with("collections")));
|
|
|
|
key(&mut h, Key::Escape, Modifiers::NONE);
|
|
std::fs::remove_dir_all(dir).ok();
|
|
}
|
|
|
|
#[test]
|
|
fn word_completion_without_a_server() {
|
|
let dir = tmp("words");
|
|
let f = write(&dir.join("notes.txt"), "alphabet alpine alpha beta\n");
|
|
let mut h = app(vec![f]);
|
|
caret(&mut h, 1, 0);
|
|
typed(&mut h, "alp");
|
|
key(&mut h, Key::Space, CTRL);
|
|
settle(&mut h, 3);
|
|
assert_eq!(labels(&h), ["alpha", "alphabet", "alpine"]);
|
|
key(&mut h, Key::Tab, Modifiers::NONE);
|
|
settle(&mut h, 3);
|
|
assert!(text(&h).ends_with("alpha"), "{}", text(&h));
|
|
std::fs::remove_dir_all(dir).ok();
|
|
}
|
|
|
|
#[test]
|
|
fn editing_shortcuts() {
|
|
let dir = tmp("edit");
|
|
let f = write(&dir.join("a.rs"), "one\ntwo\nthree\nfour\n");
|
|
let mut h = app(vec![f]);
|
|
// Ctrl+K deletes the line
|
|
caret(&mut h, 1, 0);
|
|
key(&mut h, Key::K, CTRL);
|
|
settle(&mut h, 2);
|
|
assert_eq!(text(&h), "one\nthree\nfour\n");
|
|
key(&mut h, Key::Z, CTRL);
|
|
settle(&mut h, 2);
|
|
// move and duplicate
|
|
caret(&mut h, 1, 1);
|
|
key(&mut h, Key::ArrowDown, Modifiers { shift: true, ..CTRL });
|
|
settle(&mut h, 2);
|
|
assert_eq!(text(&h), "one\nthree\ntwo\nfour\n");
|
|
key(&mut h, Key::ArrowDown, Modifiers { alt: true, shift: true, ..CTRL });
|
|
settle(&mut h, 2);
|
|
assert_eq!(text(&h), "one\nthree\ntwo\ntwo\nfour\n");
|
|
// Alt+J: select word, then next match
|
|
caret(&mut h, 2, 1);
|
|
key(&mut h, Key::J, Modifiers::ALT);
|
|
key(&mut h, Key::J, Modifiers::ALT);
|
|
settle(&mut h, 2);
|
|
assert_eq!(h.state().cur_doc().unwrap().buf.sels.len(), 2);
|
|
typed(&mut h, "2");
|
|
assert_eq!(text(&h), "one\nthree\n2\n2\nfour\n", "typing replaces every selection");
|
|
// upper case, join
|
|
caret(&mut h, 0, 0);
|
|
key(&mut h, Key::U, CTRL);
|
|
settle(&mut h, 2);
|
|
assert!(text(&h).starts_with("ONE\n"));
|
|
caret(&mut h, 0, 0);
|
|
key(&mut h, Key::J, CTRL);
|
|
settle(&mut h, 2);
|
|
assert!(text(&h).starts_with("ONE three\n"), "{}", text(&h));
|
|
// clipboard path through events
|
|
caret(&mut h, 0, 0);
|
|
h.input_mut().events.push(Event::Paste("a\nb\n".into()));
|
|
settle(&mut h, 2);
|
|
assert!(text(&h).starts_with("a\nb\nONE"), "{}", text(&h));
|
|
// selection by keyboard, then cut
|
|
caret(&mut h, 0, 0);
|
|
key(&mut h, Key::ArrowRight, Modifiers::SHIFT);
|
|
h.input_mut().events.push(Event::Cut);
|
|
settle(&mut h, 2);
|
|
assert!(text(&h).starts_with("\nb\nONE"), "{}", text(&h));
|
|
std::fs::remove_dir_all(dir).ok();
|
|
}
|
|
|
|
#[test]
|
|
fn folds_bookmarks_find_replace() {
|
|
let dir = tmp("fold");
|
|
let f = write(&dir.join("a.rs"), "fn a() {\n one();\n two();\n}\nfn b() {\n one();\n}\n");
|
|
let mut h = app(vec![f]);
|
|
settle(&mut h, 6);
|
|
caret(&mut h, 1, 0);
|
|
cmd(&mut h, Cmd::FoldHere);
|
|
settle(&mut h, 3);
|
|
{
|
|
let tb = &h.state().panes[0].tabs[0];
|
|
let d = h.state().cur_doc().unwrap();
|
|
assert_eq!(tb.rows.count(d), 5, "lines 2-4 hidden");
|
|
}
|
|
cmd(&mut h, Cmd::UnfoldAll);
|
|
settle(&mut h, 3);
|
|
cmd(&mut h, Cmd::FoldAll);
|
|
settle(&mut h, 3);
|
|
assert_eq!(h.state().cur_doc().unwrap().folded.len(), 2);
|
|
cmd(&mut h, Cmd::UnfoldAll);
|
|
settle(&mut h, 3);
|
|
|
|
// bookmarks survive lines being added above them
|
|
caret(&mut h, 5, 0);
|
|
key(&mut h, Key::B, Modifiers { shift: true, ..CTRL });
|
|
settle(&mut h, 2);
|
|
caret(&mut h, 0, 0);
|
|
h.input_mut().events.push(Event::Paste("// top\n".into()));
|
|
settle(&mut h, 3);
|
|
assert!(h.state().cur_doc().unwrap().bookmarks.contains(&6));
|
|
key(&mut h, Key::PageDown, Modifiers::ALT);
|
|
settle(&mut h, 3);
|
|
assert_eq!(pos(&h).0, 6, "next bookmark");
|
|
|
|
cmd(&mut h, Cmd::Find);
|
|
h.state_mut().find.query = "one".into();
|
|
settle(&mut h, 6);
|
|
assert_eq!(h.state().find.hits.len(), 2);
|
|
let ctx = h.ctx.clone();
|
|
h.state_mut().find_step(&ctx, false);
|
|
settle(&mut h, 3);
|
|
h.state_mut().find.regex = true;
|
|
h.state_mut().find.query = r"\b(one|two)\(\)".into();
|
|
settle(&mut h, 6);
|
|
assert_eq!(h.state().find.hits.len(), 3, "regex");
|
|
h.state_mut().find.query = "(".into();
|
|
settle(&mut h, 4);
|
|
assert!(h.state().find.error, "a broken regex shows as an error, not a crash");
|
|
std::fs::remove_dir_all(dir).ok();
|
|
}
|
|
|
|
#[test]
|
|
fn comment_uses_each_languages_syntax() {
|
|
let dir = tmp("comment");
|
|
for (name, want) in [("a.rs", "// x"), ("a.py", "# x"), ("a.lua", "-- x"), ("a.sh", "# x"), ("a.sql", "-- x"), ("a.c", "// x"), ("a.html", "<!-- x -->")] {
|
|
let f = write(&dir.join(name), "x");
|
|
let mut h = app(vec![f]);
|
|
key(&mut h, Key::Slash, CTRL);
|
|
settle(&mut h, 2);
|
|
assert_eq!(text(&h), want, "{name}");
|
|
}
|
|
std::fs::remove_dir_all(dir).ok();
|
|
}
|
|
|
|
/// Odd text, including zero-width joiners and combining marks, gets through every surface.
|
|
#[test]
|
|
fn any_characters_can_be_shown() {
|
|
let dir = tmp("glyphs");
|
|
let f = write(&dir.join("a.txt"), "日本語のテキスト 한국어 العربية 🦀🚀 \u{1F9D1}\u{200D}\u{1F4BB} e\u{301} \u{FFFF}\n");
|
|
let mut h = app(vec![f]);
|
|
settle(&mut h, 20);
|
|
typed(&mut h, "漢字");
|
|
let ctx = h.ctx.clone();
|
|
h.state_mut().run(&ctx, Cmd::ToggleTerminal);
|
|
settle(&mut h, 30);
|
|
h.state().terms[0].write("printf '日本語 🦀\\n'\r");
|
|
settle(&mut h, 30);
|
|
cmd(&mut h, Cmd::Palette);
|
|
h.state_mut().palette.query = "日本".into();
|
|
settle(&mut h, 10);
|
|
std::fs::remove_dir_all(dir).ok();
|
|
}
|
|
|
|
#[test]
|
|
fn split_views_share_a_document() {
|
|
let dir = tmp("split");
|
|
let f = write(&dir.join("a.txt"), "hello\n");
|
|
let mut h = app(vec![f]);
|
|
cmd(&mut h, Cmd::SplitRight);
|
|
settle(&mut h, 8);
|
|
assert_eq!(h.state().panes.len(), 2);
|
|
assert_eq!(h.state().docs.len(), 1);
|
|
typed(&mut h, "x");
|
|
assert!(text(&h).contains('x'));
|
|
cmd(&mut h, Cmd::New);
|
|
assert_eq!(h.state().panes[1].tabs.len(), 2);
|
|
cmd(&mut h, Cmd::CloseSplit);
|
|
settle(&mut h, 6);
|
|
assert_eq!(h.state().panes.len(), 1);
|
|
assert_eq!(h.state().docs.len(), 1, "the shared file lives on in the other split");
|
|
std::fs::remove_dir_all(dir).ok();
|
|
}
|
|
|
|
#[test]
|
|
fn terminal_runs_real_programs() {
|
|
let dir = tmp("term");
|
|
let script = write(&dir.join("hi.py"), "print('from python', 6*7)\n");
|
|
let mut h = app(vec![script]);
|
|
let screen = |h: &H| h.state().terms[h.state().term_cur].screen_text().join("\n");
|
|
|
|
// the Run button, on a saved file
|
|
cmd(&mut h, Cmd::RunFile);
|
|
wait(&mut h, 15, "script output", |h| screen(h).contains("from python 42"));
|
|
wait(&mut h, 5, "run finishes", |h| !h.state().terms[0].running);
|
|
|
|
// Ctrl+C reaches the program and gives the shell back
|
|
h.state().terms[0].write("sleep 60\r");
|
|
settle(&mut h, 30);
|
|
h.input_mut().events.push(Event::Copy);
|
|
settle(&mut h, 30);
|
|
h.state().terms[0].write("echo back-at-prompt\r");
|
|
wait(&mut h, 5, "Ctrl+C stopped it", |h| screen(h).lines().any(|l| l.trim() == "back-at-prompt"));
|
|
|
|
// a full-screen program: arrows, colours, and leaving the screen as it was
|
|
let app = write(&dir.join("keys.py"), "import curses\ndef main(s):\n curses.start_color()\n s.addstr(0, 0, 'curses ready')\n s.refresh()\n s.keypad(True)\n got = []\n for _ in range(3):\n got.append(s.getch())\n open('KEYS', 'w').write(' '.join(map(str, got)))\ncurses.wrapper(main)\n");
|
|
h.state().terms[0].write(format!("cd '{}'; python3 '{app}'\r", dir.display()));
|
|
wait(&mut h, 8, "curses starts", |h| screen(h).contains("curses ready"));
|
|
key(&mut h, Key::ArrowUp, Modifiers::NONE);
|
|
key(&mut h, Key::PageDown, Modifiers::NONE);
|
|
key(&mut h, Key::F2, Modifiers::NONE);
|
|
wait(&mut h, 5, "keys arrive", |_| dir.join("KEYS").exists());
|
|
settle(&mut h, 20);
|
|
assert_eq!(std::fs::read_to_string(dir.join("KEYS")).unwrap(), "259 338 266", "up, page down, F2");
|
|
assert!(!screen(&h).contains("curses ready"), "left the alternate screen");
|
|
|
|
// nano: a real editor, saved with its own keys
|
|
if which("nano") {
|
|
let out = dir.join("from-nano.txt");
|
|
h.state().terms[0].write(format!("nano '{}'\r", out.display()));
|
|
wait(&mut h, 8, "nano opens", |h| screen(h).contains("GNU nano") || screen(h).contains("from-nano"));
|
|
h.input_mut().events.push(Event::Text("hello from nano".into()));
|
|
settle(&mut h, 8);
|
|
key(&mut h, Key::O, Modifiers::CTRL);
|
|
settle(&mut h, 8);
|
|
key(&mut h, Key::Enter, Modifiers::NONE);
|
|
wait(&mut h, 6, "nano saved", |_| out.exists());
|
|
h.input_mut().events.push(Event::Cut);
|
|
settle(&mut h, 20);
|
|
assert_eq!(std::fs::read_to_string(&out).unwrap().trim(), "hello from nano");
|
|
}
|
|
|
|
// colours and unicode survive
|
|
h.state().terms[0].write("clear; printf '\\033[31mred\\033[0m café 日本\\n'\r");
|
|
wait(&mut h, 5, "unicode text", |h| screen(h).contains("café"));
|
|
settle(&mut h, 10);
|
|
|
|
// the run button turns into stop, and stop works
|
|
let slow = write(&dir.join("slow.py"), "import time\ntime.sleep(60)\n");
|
|
let ctx = h.ctx.clone();
|
|
h.state_mut().open_path(&ctx, slow.into(), None);
|
|
cmd(&mut h, Cmd::RunFile);
|
|
settle(&mut h, 20);
|
|
assert!(h.state().terms[0].running, "shows as running");
|
|
std::fs::remove_dir_all(dir).ok();
|
|
}
|
|
|
|
fn which(bin: &str) -> bool {
|
|
std::env::var_os("PATH").is_some_and(|p| std::env::split_paths(&p).any(|d| d.join(bin).is_file()))
|
|
}
|
|
|
|
#[test]
|
|
fn git_panel_on_a_real_repository() {
|
|
let dir = tmp("git");
|
|
let run = |args: &[&str]| assert!(std::process::Command::new("git").arg("-C").arg(&dir).args(args).output().unwrap().status.success(), "{args:?}");
|
|
run(&["init", "-q", "-b", "main"]);
|
|
run(&["config", "user.name", "t"]);
|
|
run(&["config", "user.email", "t@example.com"]);
|
|
let f = write(&dir.join("a.txt"), "one\ntwo\nthree\n");
|
|
write(&dir.join("new.txt"), "x\n");
|
|
run(&["add", "a.txt"]);
|
|
run(&["commit", "-qm", "first"]);
|
|
write(&dir.join("a.txt"), "one\nTWO\nthree\nfour\n");
|
|
let mut h = app(vec![f.clone()]);
|
|
h.state_mut().set_root(dir.clone());
|
|
wait(&mut h, 10, "status reads", |h| h.state().git.files.len() == 2);
|
|
assert_eq!(h.state().git.branch, "main");
|
|
// change bars describe this session's edits, not what git holds
|
|
assert!(h.state().cur_doc().unwrap().marks.is_empty());
|
|
h.state_mut().git_stage("new.txt", false);
|
|
wait(&mut h, 10, "staged", |h| h.state().git.files.iter().any(|x| x.0 == 'A'));
|
|
h.state_mut().git_stage("new.txt", true);
|
|
wait(&mut h, 10, "unstaged", |h| h.state().git.files.iter().all(|x| x.0 != 'A'));
|
|
h.state_mut().git_stage("a.txt", false);
|
|
settle(&mut h, 20);
|
|
h.state_mut().side_state.commit = "second".into();
|
|
h.state_mut().git_commit();
|
|
wait(&mut h, 10, "committed", |h| h.state().git.files.len() == 1);
|
|
let log = String::from_utf8(std::process::Command::new("git").arg("-C").arg(&dir).args(["log", "--oneline"]).output().unwrap().stdout).unwrap();
|
|
assert_eq!(log.lines().count(), 2);
|
|
std::fs::remove_dir_all(dir).ok();
|
|
}
|
|
|
|
#[test]
|
|
fn change_bars_last_one_session() {
|
|
let dir = tmp("marks");
|
|
let f = write(&dir.join("a.txt"), "one\ntwo\nthree\n");
|
|
let mut h = app(vec![f.clone()]);
|
|
caret(&mut h, 1, 0);
|
|
typed(&mut h, "2");
|
|
caret(&mut h, 3, 0);
|
|
typed(&mut h, "four\n");
|
|
// changed line 2, added line 4
|
|
wait(&mut h, 5, "bars", |h| h.state().cur_doc().unwrap().marks == vec![(1, 1, 1), (3, 1, 0)]);
|
|
cmd(&mut h, Cmd::Save);
|
|
assert_eq!(h.state().cur_doc().unwrap().marks.len(), 2, "saving keeps them for the session");
|
|
assert!(h.state().edited.contains(&std::fs::canonicalize(&f).unwrap()));
|
|
h.state().save_session();
|
|
drop(h);
|
|
// a new run: the same file, nothing marked
|
|
let h = app(vec![f]);
|
|
assert!(h.state().cur_doc().unwrap().marks.is_empty());
|
|
assert!(h.state().edited.is_empty());
|
|
std::fs::remove_dir_all(dir).ok();
|
|
}
|
|
|
|
#[test]
|
|
fn rail_drag_follows_the_pointer_in_a_long_file() {
|
|
use eframe::egui::{pos2, PointerButton};
|
|
let dir = tmp("rail");
|
|
let body: String = (0..6000).map(|i| format!("line {i}\n")).collect();
|
|
let f = write(&dir.join("long.txt"), &body);
|
|
let mut h = app(vec![f]);
|
|
settle(&mut h, 20);
|
|
let x = std::env::var("RAIL_X").ok().and_then(|v| v.parse().ok()).unwrap_or(1262.0);
|
|
let ev = |h: &mut H, e: Event| { h.input_mut().events.push(e); h.step(); std::thread::sleep(Duration::from_millis(16)) };
|
|
let press = |p, down| Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: down, modifiers: Modifiers::NONE };
|
|
let scroll = |h: &H| h.state().panes[0].tabs[0].scroll.target;
|
|
ev(&mut h, Event::PointerMoved(pos2(x, 140.0)));
|
|
ev(&mut h, press(pos2(x, 140.0), true));
|
|
assert!(h.state().panes[0].dragging_mini, "pressed the rail");
|
|
let mut y = 140.0;
|
|
while y < 790.0 {
|
|
y += 25.0;
|
|
ev(&mut h, Event::PointerMoved(pos2(x, y)));
|
|
}
|
|
settle(&mut h, 40);
|
|
if let Ok(out) = std::env::var("DAMSON_SHOTS") { h.render().unwrap().save(format!("{out}/rail-drag.png")).unwrap() }
|
|
let bottom = scroll(&h);
|
|
println!(" dragged to y {y}: scroll {bottom}");
|
|
ev(&mut h, press(pos2(x, y), false));
|
|
settle(&mut h, 40);
|
|
// press again on the same spot: the view stays where it is
|
|
ev(&mut h, press(pos2(x, y), true));
|
|
settle(&mut h, 10);
|
|
let again = scroll(&h);
|
|
println!(" pressed again: scroll {again}");
|
|
ev(&mut h, press(pos2(x, y), false));
|
|
assert!((again - bottom).abs() < 40.0, "jumped from {bottom} to {again}");
|
|
// and the end of the file is reachable by dragging to the bottom
|
|
ev(&mut h, press(pos2(x, 400.0), true));
|
|
for i in 0..30 { ev(&mut h, Event::PointerMoved(pos2(x, 400.0 + i as f32 * 20.0))) }
|
|
settle(&mut h, 20);
|
|
let end = scroll(&h);
|
|
ev(&mut h, press(pos2(x, 980.0), false));
|
|
let m = h.state().s.font_size * 1.55;
|
|
let max = 6001.0 * m.round() - 400.0;
|
|
println!(" dragged past the bottom: scroll {end} (end about {max})");
|
|
assert!(end > max * 0.97, "only reached {end} of {max}");
|
|
std::fs::remove_dir_all(dir).ok();
|
|
}
|
|
|
|
#[test]
|
|
fn protected_files_save_through_sudo() {
|
|
use std::os::unix::fs::PermissionsExt;
|
|
let dir = tmp("sudo");
|
|
// a stand-in sudo: one password line on stdin, then the command, made able to write
|
|
let bin = dir.join("bin");
|
|
write(&bin.join("sudo"), "#!/bin/sh\nread pw\n[ \"$pw\" = secret ] || { echo 'sudo: 1 incorrect password attempt' >&2; exit 1; }\nwhile [ \"$1\" != -- ]; do shift; done; shift\nfor a; do t=$a; done\nchmod u+w \"$t\"; \"$@\"; r=$?; chmod a-w \"$t\"; exit $r\n");
|
|
std::fs::set_permissions(bin.join("sudo"), std::fs::Permissions::from_mode(0o755)).unwrap();
|
|
let f = write(&dir.join("conf.txt"), "old\n");
|
|
std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o444)).unwrap();
|
|
let path = std::env::var("PATH").unwrap();
|
|
std::env::set_var("PATH", format!("{}:{path}", bin.display()));
|
|
let mut h = app(vec![f.clone()]);
|
|
caret(&mut h, 0, 0);
|
|
typed(&mut h, "new ");
|
|
cmd(&mut h, Cmd::Save);
|
|
assert!(matches!(h.state().dialog, Some(damson::ui::menu::Dialog::Sudo { .. })), "asks for the password");
|
|
assert_eq!(std::fs::read_to_string(&f).unwrap(), "old\n");
|
|
if let Ok(out) = std::env::var("DAMSON_SHOTS") { h.render().unwrap().save(format!("{out}/sudo-ask.png")).unwrap() }
|
|
typed(&mut h, "wrong");
|
|
key(&mut h, Key::Enter, Modifiers::NONE);
|
|
wait(&mut h, 10, "wrong password told", |h| matches!(&h.state().dialog, Some(damson::ui::menu::Dialog::Sudo { error: Some(_), busy: false, .. })));
|
|
if let Ok(out) = std::env::var("DAMSON_SHOTS") { settle(&mut h, 20); h.render().unwrap().save(format!("{out}/sudo-wrong.png")).unwrap() }
|
|
assert!(h.state().cur_doc().unwrap().buf.is_modified());
|
|
typed(&mut h, "secret");
|
|
key(&mut h, Key::Enter, Modifiers::NONE);
|
|
wait(&mut h, 10, "saved", |h| h.state().dialog.is_none() && !h.state().cur_doc().unwrap().buf.is_modified());
|
|
std::env::set_var("PATH", path);
|
|
assert_eq!(std::fs::read_to_string(&f).unwrap(), "new old\n");
|
|
assert_eq!(std::fs::metadata(&f).unwrap().permissions().mode() & 0o777, 0o444, "the file keeps its mode");
|
|
std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o644)).unwrap();
|
|
std::fs::remove_dir_all(dir).ok();
|
|
}
|
|
|
|
#[test]
|
|
fn search_outline_and_palette() {
|
|
let dir = tmp("search");
|
|
let f = write(&dir.join("src/a.rs"), "struct Thing;\nfn alpha() {}\nfn needle_here() {}\n");
|
|
write(&dir.join("src/b.py"), "def needle_too():\n pass\n");
|
|
write(&dir.join("target/skip.rs"), "needle in build output\n");
|
|
let mut h = app(vec![f]);
|
|
h.state_mut().set_root(dir.clone());
|
|
h.state_mut().side_state.search = "needle".into();
|
|
h.state_mut().start_search();
|
|
wait(&mut h, 10, "search results", |h| !h.state().side_state.searching);
|
|
assert_eq!(h.state().side_state.results.len(), 2, "build output skipped");
|
|
|
|
let names: Vec<String> = h.state_mut().outline().into_iter().map(|o| o.1).collect();
|
|
assert_eq!(names, ["struct Thing", "alpha", "needle_here"]);
|
|
settle(&mut h, 2);
|
|
|
|
let ctx = h.ctx.clone();
|
|
h.state_mut().open_palette(&ctx, ":3", false);
|
|
settle(&mut h, 3);
|
|
key(&mut h, Key::Enter, Modifiers::NONE);
|
|
settle(&mut h, 3);
|
|
assert_eq!(pos(&h).0, 2, ":3 goes to line 3");
|
|
|
|
h.state_mut().open_palette(&ctx, "@alph", false);
|
|
settle(&mut h, 3);
|
|
key(&mut h, Key::Enter, Modifiers::NONE);
|
|
settle(&mut h, 3);
|
|
assert_eq!(pos(&h).0, 1, "@ finds the symbol");
|
|
|
|
h.state_mut().open_palette(&ctx, ">zen", false);
|
|
settle(&mut h, 3);
|
|
key(&mut h, Key::Enter, Modifiers::NONE);
|
|
settle(&mut h, 3);
|
|
|
|
h.state_mut().open_palette(&ctx, "bpy", false);
|
|
settle(&mut h, 3);
|
|
key(&mut h, Key::Enter, Modifiers::NONE);
|
|
settle(&mut h, 3);
|
|
assert_eq!(h.state().cur_doc().unwrap().title(), "b.py", "fuzzy file open");
|
|
assert_eq!(h.state().cur_doc().unwrap().language, "Python");
|
|
|
|
cmd(&mut h, Cmd::ReopenClosed);
|
|
let tabs = h.state().panes[0].tabs.len();
|
|
cmd(&mut h, Cmd::CloseTab);
|
|
assert_eq!(h.state().panes[0].tabs.len(), tabs - 1);
|
|
cmd(&mut h, Cmd::ReopenClosed);
|
|
assert_eq!(h.state().panes[0].tabs.len(), tabs, "reopen closed tab");
|
|
std::fs::remove_dir_all(dir).ok();
|
|
}
|
|
|
|
#[test]
|
|
fn crash_recovery_brings_unsaved_work_back() {
|
|
let dir = tmp("recover");
|
|
let f = write(&dir.join("a.txt"), "saved\n");
|
|
{
|
|
let mut h = app(vec![f.clone()]);
|
|
caret(&mut h, 0, 0);
|
|
typed(&mut h, "unsaved ");
|
|
cmd(&mut h, Cmd::New);
|
|
h.input_mut().events.push(Event::Paste("def scratch():\n pass\n".into()));
|
|
settle(&mut h, 25);
|
|
h.state().save_session();
|
|
// dropped with no save or quit, as a crash would leave it
|
|
}
|
|
let mut h = app(vec![]);
|
|
settle(&mut h, 20);
|
|
assert_eq!(h.state().docs.len(), 2);
|
|
let texts: Vec<String> = h.state().docs.values().map(|d| d.buf.rope.to_string()).collect();
|
|
assert!(texts.iter().any(|t| t.starts_with("unsaved saved")), "{texts:?}");
|
|
assert!(texts.iter().any(|t| t.starts_with("def scratch")), "{texts:?}");
|
|
assert!(h.state().docs.values().all(|d| d.buf.is_modified()), "recovered text still counts as unsaved");
|
|
assert_eq!(std::fs::read_to_string(&f).unwrap(), "saved\n", "the file itself is untouched");
|
|
let py = h.state().docs.values().find(|d| d.path.is_none()).unwrap();
|
|
assert_eq!(py.language, "Python", "recovered untitled file colours itself");
|
|
std::fs::remove_dir_all(dir).ok();
|
|
}
|
|
|
|
#[test]
|
|
fn outside_changes_to_a_file() {
|
|
let dir = tmp("outside");
|
|
let f = write(&dir.join("a.txt"), "first\n");
|
|
let mut h = app(vec![f.clone()]);
|
|
std::thread::sleep(Duration::from_millis(30));
|
|
write(Path::new(&f), "changed outside\n");
|
|
wait(&mut h, 6, "clean file follows the disk", |h| text(h) == "changed outside\n");
|
|
assert!(!h.state().cur_doc().unwrap().buf.is_modified());
|
|
typed(&mut h, "mine ");
|
|
write(Path::new(&f), "changed again\n");
|
|
settle(&mut h, 130);
|
|
assert!(text(&h).contains("mine"), "unsaved work is not overwritten");
|
|
assert!(h.state().toasts.iter().any(|t| t.text.contains("changed on disk")) || text(&h).contains("mine"));
|
|
std::fs::remove_dir_all(dir).ok();
|
|
}
|
|
|
|
/// A little xorshift, so a failure can be replayed from its seed.
|
|
struct Rng(u64);
|
|
impl Rng {
|
|
fn next(&mut self, n: usize) -> usize {
|
|
self.0 ^= self.0 << 13;
|
|
self.0 ^= self.0 >> 7;
|
|
self.0 ^= self.0 << 17;
|
|
(self.0 % n.max(1) as u64) as usize
|
|
}
|
|
}
|
|
|
|
/// Random edits on real highlighted code. Nothing may panic, and undo must restore the text exactly.
|
|
#[test]
|
|
fn random_edits_hold_together() {
|
|
use damson::syntax::Registry;
|
|
use damson::text::commands::{Move, Prefs};
|
|
use damson::text::{Doc, EditKind, Sel};
|
|
let mut reg = Registry::scan();
|
|
let source = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/src/text/buffer.rs")).unwrap();
|
|
let p = Prefs::default();
|
|
let bits = ["(", ")", "{", "}", "\"", "'", "/*", "*/", "\n", " ", "\t", "é", "日本", "🦀", "fn x", "// c", "\r\n"];
|
|
for seed in 1..=40u64 {
|
|
let mut r = Rng(seed.wrapping_mul(0x9E3779B97F4A7C15));
|
|
let name = ["a.rs", "a.py", "a.c", "a.html", "a.md"][seed as usize % 5];
|
|
let mut d = Doc::new(1, &source[..source.len().min(4000 + r.next(2000))].chars().collect::<String>(), Some(name.into()), &mut reg);
|
|
let original = d.buf.rope.to_string();
|
|
d.highlight(®, 1000, 2000);
|
|
for step in 0..400 {
|
|
let len = d.buf.len();
|
|
match r.next(16) {
|
|
0 | 1 | 2 => { let a = r.next(len + 1); d.buf.set_cursor(a) }
|
|
3 => { let (a, b) = (r.next(len + 1), r.next(len + 1)); d.buf.set_sels(vec![Sel { anchor: a, head: b, want_col: None }]) }
|
|
4 => d.buf.add_cursor_vertical(r.next(2) == 0),
|
|
5 | 6 | 7 => { let s = bits[r.next(bits.len())]; d.buf.type_text(s, &p) }
|
|
8 => d.buf.backspace(&p),
|
|
9 => d.buf.newline(&p),
|
|
10 => d.buf.delete_lines(),
|
|
11 => d.buf.move_lines(r.next(2) == 0),
|
|
12 => d.buf.toggle_comment(Some("//"), None),
|
|
13 => d.buf.indent(&p),
|
|
14 => { d.buf.move_cursors([Move::WordLeft, Move::WordRight, Move::Up, Move::Down, Move::Home, Move::End][r.next(6)], r.next(2) == 0) }
|
|
_ => { d.buf.undo(); }
|
|
}
|
|
let at = r.next(d.buf.lines());
|
|
d.highlight(®, at + 20, 40);
|
|
d.refresh_folds(4);
|
|
assert_eq!(d.hl.len(), d.buf.lines(), "seed {seed} step {step}");
|
|
assert!(d.buf.sels.iter().all(|s| s.head <= d.buf.len()), "seed {seed} step {step}");
|
|
}
|
|
d.buf.insert("end", EditKind::Other);
|
|
while d.buf.undo() {}
|
|
assert_eq!(d.buf.rope.to_string(), original, "seed {seed}: undo all the way restores the text");
|
|
while d.buf.redo() {}
|
|
}
|
|
}
|
|
|
|
/// Timings on a large file. Printed, and only failed if something is badly off.
|
|
#[test]
|
|
fn large_file_stays_usable() {
|
|
let dir = tmp("large");
|
|
let line = " let value = compute(index, \"text\") + 42; // comment\n";
|
|
let body = format!("fn main() {{\n{}}}\n", line.repeat(200_000));
|
|
let f = write(&dir.join("big.rs"), &body);
|
|
let t = Instant::now();
|
|
let mut h = app(vec![f]);
|
|
println!(" open 200k lines ({} MB): {:?}", body.len() / 1_000_000, t.elapsed());
|
|
let t = Instant::now();
|
|
wait(&mut h, 120, "all coloured", |h| !h.state().cur_doc().unwrap().highlight_pending());
|
|
println!(" highlight everything: {:?}", t.elapsed());
|
|
let mut worst = Duration::ZERO;
|
|
for i in 0..40 {
|
|
let d = h.state_mut().cur_doc_mut().unwrap();
|
|
let at = d.buf.at(100_000 + i, 4);
|
|
d.buf.set_cursor(at);
|
|
d.buf.insert("x", damson::text::EditKind::Typing);
|
|
let t = Instant::now();
|
|
h.step();
|
|
worst = worst.max(t.elapsed());
|
|
}
|
|
println!(" worst frame while typing mid-file: {worst:?}");
|
|
let t = Instant::now();
|
|
cmd(&mut h, Cmd::Find);
|
|
h.state_mut().find.query = "compute".into();
|
|
settle(&mut h, 3);
|
|
println!(" find across the file: {:?}, {} hits", t.elapsed(), h.state().find.hits.len());
|
|
assert!(h.state().find.hits.len() >= 50_000);
|
|
std::fs::remove_dir_all(dir).ok();
|
|
}
|
|
|
|
#[test]
|
|
fn file_errors_read_plainly() {
|
|
use damson::app::why;
|
|
use std::io::{Error, ErrorKind};
|
|
assert_eq!(why(&std::fs::read("/no/such/file").unwrap_err()), "it isn't there");
|
|
assert_eq!(why(&Error::from(ErrorKind::PermissionDenied)), "you don't have permission");
|
|
assert!(!why(&Error::from_raw_os_error(5)).contains("os error"));
|
|
}
|
|
|
|
/// Settings with the pointer on a segmented button and a switch: `DAMSON_SHOTS=dir`, and
|
|
/// `HOVER=x,y` to put the pointer somewhere.
|
|
#[test]
|
|
fn settings_controls_shot() {
|
|
let Ok(out) = std::env::var("DAMSON_SHOTS") else { return };
|
|
tmp("settings");
|
|
let mut h = app(vec![]);
|
|
h.state_mut().settings_open = true;
|
|
settle(&mut h, 30);
|
|
if let Some((x, y)) = std::env::var("HOVER").ok().and_then(|v| v.split_once(',').map(|(a, b)| (a.parse().unwrap(), b.parse().unwrap()))) {
|
|
h.input_mut().events.push(Event::PointerMoved(eframe::egui::pos2(x, y)));
|
|
settle(&mut h, 20);
|
|
}
|
|
h.render().unwrap().save(format!("{out}/settings.png")).unwrap();
|
|
}
|