Damson/tests/shots.rs
astar76 1c1dab0a5d Detect the language of unnamed files from their text
Untitled files had no language, so they showed no colours. They now read
shebangs, modelines and headers, then score how the code reads, as the
text changes. The tab and save dialog take a matching name. Save As now
re-detects, and ties between definitions go to the first one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-06 17:49:30 -06:00

291 lines
12 KiB
Rust

//! Drives the real app with no window and saves screenshots:
//! `DAMSON_SHOTS=/some/dir cargo test --test shots -- --nocapture --test-threads=1`
use damson::app::App;
use damson::ui::commands::Cmd;
use eframe::egui::{self, pos2, vec2, Event, Modifiers, PointerButton, Pos2};
use egui_kittest::Harness;
type H<'a> = Harness<'a, App>;
fn settle(h: &mut H, n: usize) {
for _ in 0..n {
h.step();
std::thread::sleep(std::time::Duration::from_millis(16));
}
}
fn shot(h: &mut H, out: &str, name: &str) {
h.render().expect("render").save(format!("{out}/{name}.png")).unwrap();
}
fn cmd(h: &mut H, c: Cmd) {
let ctx = h.ctx.clone();
h.state_mut().run(&ctx, c);
settle(h, 34);
}
fn mv(h: &mut H, p: Pos2) {
h.input_mut().events.push(Event::PointerMoved(p));
h.step();
}
fn press(h: &mut H, p: Pos2, down: bool) {
h.input_mut().events.push(Event::PointerButton { pos: p, button: PointerButton::Primary, pressed: down, modifiers: Modifiers::NONE });
h.step();
}
#[test]
fn tour() {
let out = std::env::var("DAMSON_SHOTS").expect("set DAMSON_SHOTS");
std::fs::create_dir_all(&out).unwrap();
let sc = std::path::PathBuf::from(&out).join("home");
std::fs::create_dir_all(&sc).unwrap();
std::env::set_var("XDG_CONFIG_HOME", sc.join("config"));
std::env::set_var("XDG_DATA_HOME", sc.join("data"));
let root = env!("CARGO_MANIFEST_DIR");
let file = format!("{root}/src/text/commands.rs");
let mut h: H = Harness::builder().with_size(vec2(1400.0, 900.0)).wgpu().build_eframe(move |cc| App::new(cc, vec![file.clone()]));
h.ctx.set_missing_glyph_policy(eframe::epaint::text::MissingGlyphPolicy::Tofu);
settle(&mut h, 40);
assert!(h.state().panes[0].mini.ready(*h.state().docs.keys().next().unwrap()), "preview is up within a moment of opening");
assert_eq!(h.state().docs.len(), 1, "file opened");
assert_eq!(h.state().cur_doc().unwrap().language, "Rust");
shot(&mut h, &out, "01-editor");
// typing goes through the real input path
let before = h.state().cur_doc().unwrap().buf.len();
h.input_mut().events.push(Event::Text("x".into()));
settle(&mut h, 3);
assert_eq!(h.state().cur_doc().unwrap().buf.len(), before + 1, "typing reaches the buffer");
h.state_mut().cur_doc_mut().unwrap().buf.undo();
settle(&mut h, 3);
// grab the preview, drag, and catch it while popped out
let rail = pos2(1330.0, 300.0);
mv(&mut h, rail);
press(&mut h, rail, true);
settle(&mut h, 6);
shot(&mut h, &out, "02-preview-popping");
for i in 0..24 {
mv(&mut h, pos2(1330.0, 300.0 + i as f32 * 12.0));
std::thread::sleep(std::time::Duration::from_millis(16));
}
settle(&mut h, 24);
assert!(h.state().panes[0].dragging_mini, "rail is being dragged");
assert!(h.state().panes[0].tabs[0].scroll.x > 100.0, "dragging scrolled the file");
shot(&mut h, &out, "03-preview-lens");
press(&mut h, pos2(1330.0, 588.0), false);
settle(&mut h, 40);
assert!(!h.state().panes[0].dragging_mini);
shot(&mut h, &out, "04-preview-released");
cmd(&mut h, Cmd::Side(2));
shot(&mut h, &out, "05-outline");
cmd(&mut h, Cmd::Find);
h.state_mut().find.query = "fn ".into();
settle(&mut h, 20);
assert!(h.state().find.hits.len() > 10, "find works");
shot(&mut h, &out, "06-find");
let ctx = h.ctx.clone();
h.state_mut().find_close(&ctx);
settle(&mut h, 20);
cmd(&mut h, Cmd::Palette);
shot(&mut h, &out, "07-palette");
let ctx = h.ctx.clone();
h.state_mut().close_palette(&ctx);
settle(&mut h, 20);
// terminal: mid-morph, then open and running a real command
let ctx = h.ctx.clone();
h.state_mut().run(&ctx, Cmd::ToggleTerminal);
settle(&mut h, 7);
shot(&mut h, &out, "08-terminal-morph");
settle(&mut h, 40);
h.state().terms[0].write("printf '\\033[1;35mdamson\\033[0m terminal: '; echo $((6*7)); ls src | head -4\r");
for _ in 0..60 { settle(&mut h, 1); std::thread::sleep(std::time::Duration::from_millis(16)) }
shot(&mut h, &out, "09-terminal");
cmd(&mut h, Cmd::ToggleTerminal);
settle(&mut h, 30);
cmd(&mut h, Cmd::SplitRight);
shot(&mut h, &out, "10-split");
cmd(&mut h, Cmd::CloseSplit);
cmd(&mut h, Cmd::Settings);
settle(&mut h, 20);
shot(&mut h, &out, "11-settings");
h.state_mut().settings_tab = 3;
h.state_mut().shell_open = true;
settle(&mut h, 30);
shot(&mut h, &out, "11b-shells");
h.state_mut().settings_tab = 4;
settle(&mut h, 30);
shot(&mut h, &out, "11c-toolbar");
h.state_mut().settings_tab = 5;
settle(&mut h, 30);
shot(&mut h, &out, "11d-discord");
h.state_mut().settings_tab = 0;
cmd(&mut h, Cmd::Settings);
cmd(&mut h, Cmd::ToggleDark);
settle(&mut h, 30);
shot(&mut h, &out, "12-other-mode");
cmd(&mut h, Cmd::Zen);
settle(&mut h, 20);
shot(&mut h, &out, "13-zen");
cmd(&mut h, Cmd::Zen);
h.state_mut().force_close(0, 0);
settle(&mut h, 30);
shot(&mut h, &out, "14-welcome");
let _ = egui::Key::A;
}
fn key(h: &mut H, k: egui::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();
}
/// Real key events, through the shortcut table and into the buffer and the terminal.
#[test]
fn keyboard_paths() {
let dir = std::env::temp_dir().join(format!("damson-keys-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::env::set_var("XDG_CONFIG_HOME", dir.join("config"));
let file = dir.join("t.py");
std::fs::write(&file, "def a():\n pass\n").unwrap();
let f = file.to_string_lossy().into_owned();
let mut h: H = Harness::builder().with_size(vec2(1200.0, 800.0)).wgpu().build_eframe(move |cc| App::new(cc, vec![f.clone()]));
settle(&mut h, 8);
use egui::Key::{ArrowDown, End, Enter, Escape, Home, Slash, F4, S, Y, Z};
let text = |h: &H| h.state().cur_doc().unwrap().buf.rope.to_string();
key(&mut h, ArrowDown, Modifiers::NONE);
key(&mut h, End, Modifiers::NONE);
key(&mut h, Enter, Modifiers::NONE);
h.input_mut().events.push(Event::Text("return 1".into()));
settle(&mut h, 2);
assert_eq!(text(&h), "def a():\n pass\n return 1\n", "arrows, end, auto-indent and text");
key(&mut h, Z, Modifiers::COMMAND);
settle(&mut h, 2);
assert!(!text(&h).contains("return"), "ctrl+z undoes: {}", text(&h));
key(&mut h, Y, Modifiers::COMMAND);
settle(&mut h, 2);
assert!(text(&h).contains("return 1"), "ctrl+y redoes");
key(&mut h, Slash, Modifiers::COMMAND);
settle(&mut h, 2);
assert!(text(&h).contains("# return 1"), "comment uses the Python token from Kate's definition: {}", text(&h));
key(&mut h, S, Modifiers::COMMAND);
settle(&mut h, 2);
assert_eq!(std::fs::read_to_string(&file).unwrap(), text(&h), "ctrl+s writes the file");
assert!(!h.state().cur_doc().unwrap().buf.is_modified());
// Ctrl+Alt+Down adds a cursor; typing lands at both
key(&mut h, Home, Modifiers::COMMAND);
key(&mut h, ArrowDown, Modifiers { alt: true, ctrl: true, command: true, ..Default::default() });
settle(&mut h, 2);
assert_eq!(h.state().cur_doc().unwrap().buf.sels.len(), 2, "second cursor");
key(&mut h, Escape, Modifiers::NONE);
// the terminal gets keys, and Ctrl+S goes to the shell rather than saving
key(&mut h, F4, Modifiers::NONE);
settle(&mut h, 40);
assert!(h.state().term_open);
let marker = dir.join("from-terminal");
h.input_mut().events.push(Event::Text(format!("touch '{}'", marker.display())));
settle(&mut h, 3);
key(&mut h, Enter, Modifiers::NONE);
for _ in 0..80 {
settle(&mut h, 2);
if marker.exists() { break }
}
assert!(marker.exists(), "a command typed in the terminal ran");
key(&mut h, F4, Modifiers::NONE);
settle(&mut h, 30);
assert!(!h.state().term_open, "F4 hides it even with the terminal focused");
std::fs::remove_dir_all(dir).ok();
}
/// Reopening the terminal must not make the shell print its prompt again.
#[test]
fn reopening_terminal_keeps_one_prompt() {
let dir = std::env::temp_dir().join(format!("damson-prompt-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::env::set_var("XDG_CONFIG_HOME", dir.join("config"));
let mut h: H = Harness::builder().with_size(vec2(1200.0, 800.0)).wgpu().build_eframe(|cc| App::new(cc, vec![]));
settle(&mut h, 6);
// the login shell here; bash doesn't show the problem
h.state_mut().s.shell = "/usr/bin/fish".into();
let used = |h: &H| h.state().terms[0].screen_text().iter().filter(|r| !r.trim().is_empty()).count();
key(&mut h, egui::Key::F4, Modifiers::NONE);
// let the shell finish starting, then toggle as a person would
for _ in 0..60 { settle(&mut h, 2) }
// real use has output above the prompt, and the morph squeezes the card to a few rows
for i in 0..3 {
h.state().terms[0].write(format!("echo line{i}\r"));
for _ in 0..12 { settle(&mut h, 2) }
}
let first = used(&h);
assert!(first >= 1, "shell printed a prompt");
eprintln!("before: {:#?}", h.state().terms[0].screen_text().iter().filter(|r| !r.trim().is_empty()).map(|r| r.trim_end().to_string()).collect::<Vec<_>>());
for _ in 0..3 {
key(&mut h, egui::Key::F4, Modifiers::NONE);
settle(&mut h, 40);
key(&mut h, egui::Key::F4, Modifiers::NONE);
settle(&mut h, 40);
}
for _ in 0..30 { settle(&mut h, 2) }
eprintln!("after: {:#?}", h.state().terms[0].screen_text().iter().filter(|r| !r.trim().is_empty()).map(|r| r.trim_end().to_string()).collect::<Vec<_>>());
assert_eq!(h.state().terms[0].resizes, 0, "opening and closing never resizes the shell");
assert_eq!(used(&h), first, "screen grew: {:#?}", h.state().terms[0].screen_text().iter().filter(|r| !r.trim().is_empty()).collect::<Vec<_>>());
std::fs::remove_dir_all(dir).ok();
}
/// Toggling wrap with the cursor far away must not move the view, and toggling back returns.
#[test]
fn word_wrap_keeps_your_place() {
let dir = std::env::temp_dir().join(format!("damson-wrap-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::env::set_var("XDG_CONFIG_HOME", dir.join("config"));
let file = dir.join("t.txt");
std::fs::write(&file, format!("{}\n", "a fairly long line of plain text that will wrap when the wrap is on and the width is narrow ".repeat(2)).repeat(400)).unwrap();
let f = file.to_string_lossy().into_owned();
let mut h: H = Harness::builder().with_size(vec2(1000.0, 700.0)).wgpu().build_eframe(move |cc| App::new(cc, vec![f.clone()]));
settle(&mut h, 10);
let lh = (h.state().s.font_size * 1.55).round();
h.state_mut().panes[0].tabs[0].scroll.snap(lh * 200.0);
settle(&mut h, 6);
let line_at_top = |h: &H| { let t = &h.state().panes[0].tabs[0]; t.rows.row((t.scroll.x / lh) as usize).0 };
assert_eq!(line_at_top(&h), 200);
cmd(&mut h, Cmd::ToggleWrap);
assert_eq!(line_at_top(&h), 200, "wrap on stays at the same line");
cmd(&mut h, Cmd::ToggleWrap);
assert_eq!(line_at_top(&h), 200, "wrap off is back at the same line");
assert!((h.state().panes[0].tabs[0].scroll.x - lh * 200.0).abs() < lh, "and the same position");
std::fs::remove_dir_all(dir).ok();
}
/// New file, paste code, and it colours itself and takes a name, through the real app.
#[test]
fn untitled_code_gets_colours_and_a_name() {
let dir = std::env::temp_dir().join(format!("damson-untitled-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::env::set_var("XDG_CONFIG_HOME", dir.join("config"));
let out = std::env::var("DAMSON_SHOTS").unwrap_or_else(|_| dir.to_string_lossy().into_owned());
let mut h: H = Harness::builder().with_size(vec2(1200.0, 800.0)).wgpu().build_eframe(|cc| App::new(cc, vec![]));
settle(&mut h, 6);
cmd(&mut h, Cmd::New);
h.input_mut().events.push(Event::Paste("use std::fs;\n\nfn main() {\n let mut total = 0;\n println!(\"{total}\");\n}\n".into()));
settle(&mut h, 30);
let d = h.state().cur_doc().unwrap();
assert_eq!(d.language, "Rust");
assert_eq!(d.title(), "Untitled.rs");
assert!(d.hl[3].spans.len() > 1, "lines have colours");
shot(&mut h, &out, "15-untitled-detected");
std::fs::remove_dir_all(dir).ok();
}