use super::*;
#[test]
fn minimap_rgba_paints_chars_skips_whitespace() {
let mut e = crate::widgets::editor::Editor::new();
e.lines = vec![String::from(" x"), String::new()];
let bg = (0u8, 0, 0);
let fg = (200u8, 200, 200);
let buf = e.minimap_rgba(4, 2, 2, bg, fg);
let px = |x: u32, y: u32| {
let i = ((y * 4 + x) * 4) as usize;
(buf[i], buf[i + 1], buf[i + 2])
};
assert_eq!(px(0, 0), bg, "indentation stays background");
assert_eq!(px(1, 0), bg, "indentation stays background");
assert_eq!(px(2, 0), fg, "the glyph is painted in the default fg");
}
#[test]
fn minimap_goto_moves_the_cursor() {
let mut e = crate::widgets::editor::Editor::new();
e.lines = (0..200).map(|i| format!("line {i}")).collect();
e.goto_line_centered(100);
assert_eq!(e.cursor_row, 100, "caret jumps to the clicked line");
assert!(e.scroll <= 100, "viewport scrolls toward the target");
}
#[test]
fn minimap_short_file_does_not_stretch() {
let mut e = crate::widgets::editor::Editor::new();
e.lines = vec![String::from("x"), String::from("y")];
let bg = (0u8, 0, 0);
let fg = (200u8, 200, 200);
let buf = e.minimap_rgba(1, 10, 4, bg, fg);
let px = |y: u32| {
let i = (y * 4) as usize;
(buf[i], buf[i + 1], buf[i + 2])
};
assert_eq!(px(0), fg, "first line sits at the top");
assert_eq!(
px(8),
bg,
"rows past the content stay background, not stretched"
);
}
#[test]
fn minimap_viewport_box_lightens_visible_rows_only() {
let base = vec![0u8; 4 * 4];
let out = composite_minimap_viewport(
&base,
1,
4,
MinimapOverlay {
top: 0,
rows: 2,
total: 4,
light: false,
selection: None,
sel_rgb: (0, 0, 0),
content_h: 4,
},
);
let row = |y: usize| out[y * 4]; assert!(row(0) > 0, "a visible row is lightened toward white");
assert!(row(1) > 0, "a visible row is lightened toward white");
assert_eq!(row(3), 0, "an off-screen row is untouched");
}
#[test]
fn minimap_selection_band_tints_selected_rows() {
let base = vec![0u8; 4 * 4];
let out = composite_minimap_viewport(
&base,
1,
4,
MinimapOverlay {
top: 0,
rows: 1,
total: 4,
light: false,
selection: Some((2, 3)),
sel_rgb: (255, 0, 0),
content_h: 4,
},
);
let r = |y: usize| out[y * 4];
assert!(r(2) > 0, "selected row picks up the selection color");
assert!(r(3) > 0, "selected row picks up the selection color");
}
#[test]
fn minimap_rgba_to_png_roundtrips() {
let png = rgba_to_png(vec![1u8; 2 * 2 * 4], 2, 2).expect("encode");
assert_eq!(
&png[1..4],
b"PNG",
"emits a PNG the inline-image path can use"
);
}
#[test]
fn a_click_on_the_line_number_or_the_text_sets_no_breakpoint() {
let (mut app, _tmp, f) = app_with_painted_file("l1\nl2\nl3\nl4\nl5\n");
let number = app.editor.last_inner.x + 2;
let text_x = app.editor.last_inner.x + app.editor.last_gutter_width + 1;
let (row2, row3) = (app.editor.last_inner.y + 2, app.editor.last_inner.y + 3);
click_and_release(&mut app, number, row2);
assert_eq!(
app.editor.selection.map(|s| s.normalised()),
Some(((2, 0), (3, 0))),
"the number click selects its line"
);
app.editor_click.clear();
click_and_release(&mut app, text_x + 1, row3);
assert_eq!(app.editor.cursor_row, 3, "the text click moves the caret");
assert!(app.editor.breakpoint_lines(&f).is_empty());
}
#[test]
fn a_triple_click_selects_the_line_and_a_drag_extends_it_by_lines() {
use crossterm::event::{MouseButton, MouseEventKind};
let (mut app, _tmp, _f) = app_with_painted_file("def f():\n return 1\n pass\n");
let col = app.editor.last_inner.x + app.editor.last_gutter_width + 1 + 6;
let row = app.editor.last_inner.y + 1;
click_and_release(&mut app, col, row);
click_and_release(&mut app, col, row);
assert_eq!(
app.editor.selection.map(|s| s.normalised()),
Some(((1, 4), (1, 10))),
"the double selects `return`"
);
click_and_release(&mut app, col, row);
assert_eq!(
app.editor.selection.map(|s| s.normalised()),
Some(((1, 0), (2, 0))),
"the triple selects line 2 through the start of line 3"
);
app.handle_key(key(KeyCode::Char('Z'), KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.lines, ["def f():", "Z pass"]);
let (mut app, _tmp, _f) = app_with_painted_file("def f():\n return 1\n pass\n");
click_and_release(&mut app, col, row);
click_and_release(&mut app, col, row);
app.handle_mouse(mouse(MouseEventKind::Down(MouseButton::Left), col, row));
app.handle_mouse(mouse(MouseEventKind::Drag(MouseButton::Left), col, row + 1));
app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), col, row + 1));
assert_eq!(
app.editor.selection.map(|s| s.normalised()),
Some(((1, 0), (2, 8))),
"the drag takes whole lines 2 and 3, the last to its end"
);
}
#[test]
fn a_line_number_press_selects_the_line_and_a_drag_selects_lines() {
use crossterm::event::{MouseButton, MouseEventKind};
let (mut app, _tmp, _f) = app_with_painted_file("l1\nl2\nl3\nl4\nl5\n");
let number = app.editor.last_inner.x + 2;
let y = app.editor.last_inner.y;
click_and_release(&mut app, number, y + 1);
assert_eq!(
app.editor.selection.map(|s| s.normalised()),
Some(((1, 0), (2, 0)))
);
for (from, to, want, caret) in [(1, 3, ((1, 0), (4, 0)), 4), (3, 0, ((0, 0), (4, 0)), 0)] {
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Left),
number,
y + from,
));
app.handle_mouse(mouse(
MouseEventKind::Drag(MouseButton::Left),
number,
y + to,
));
app.handle_mouse(mouse(MouseEventKind::Up(MouseButton::Left), number, y + to));
assert_eq!(app.editor.selection.map(|s| s.normalised()), Some(want));
assert_eq!(app.editor.cursor_row, caret, "{from}->{to}");
}
}
#[test]
fn dragging_line_numbers_into_the_explorer_does_not_change_the_tree_selection() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("a.txt");
std::fs::write(&f, "l1\nl2\nl3\nl4\n").unwrap();
std::fs::write(tmp.path().join("b.txt"), "b").unwrap();
std::fs::write(tmp.path().join("c.txt"), "c").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
draw(&mut app, 120, 40);
app.tree.select(0);
let number = app.editor.last_inner.x + 2;
let y = app.editor.last_inner.y;
let tree_col = app.tree.last_inner.x + 2;
let tree_row = app.tree.last_inner.y + 2;
assert!(
app.tree.node_at_y(tree_row).is_some_and(|i| i != 0),
"precondition: target tree row must name a different node than index 0"
);
app.handle_mouse(mouse(
MouseEventKind::Down(MouseButton::Left),
number,
y + 1,
));
app.handle_mouse(mouse(
MouseEventKind::Drag(MouseButton::Left),
tree_col,
tree_row,
));
assert_eq!(
app.tree.selected, 0,
"an editor line-number drag crossing into Explorer must not move the tree selection"
);
app.handle_mouse(mouse(
MouseEventKind::Up(MouseButton::Left),
tree_col,
tree_row,
));
assert_eq!(
app.editor.selection.map(|s| s.normalised()),
Some(((1, 0), (2, 0)))
);
assert!(app.gesture.is_none());
}
#[test]
fn only_the_line_number_columns_select_the_line() {
use crate::widgets::editor::LineNumbers;
let (mut app, _tmp, _f) = app_with_painted_file("l1\nl2\nl3\n");
let x = app.editor.last_inner.x;
let row = app.editor.last_inner.y + 1;
let spacer = x + app.editor.last_gutter_width - 1;
let selected = |app: &App| app.editor.selection.map(|s| s.normalised());
for col in [x + 1, spacer] {
app.editor_click.clear();
click_and_release(&mut app, col, row);
assert_eq!(selected(&app), None, "column {col} selects nothing");
assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (1, 0));
}
app.editor_click.clear();
click_and_release(&mut app, x + 2, row);
assert_eq!(selected(&app), Some(((1, 0), (2, 0))), "the number does");
app.editor.line_numbers = LineNumbers::Off;
draw(&mut app, 100, 30);
app.editor_click.clear();
click_and_release(&mut app, x + 2, row + 1);
assert_eq!(selected(&app), None, "no numbers, no line selection");
assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (2, 0));
}
#[test]
fn the_chevron_still_folds_and_off_line_or_shift_lane_clicks_set_nothing() {
use crossterm::event::{MouseButton, MouseEventKind};
let (mut app, _tmp, f) = app_with_painted_file("def f():\n a = 1\n b = 2\n");
let x = app.editor.last_inner.x;
let y = app.editor.last_inner.y;
click_and_release(&mut app, x + 1, y);
assert!(app.editor.is_line_hidden(1), "the chevron folds the body");
assert!(app.editor.breakpoint_lines(&f).is_empty());
app.editor_click.clear();
click_and_release(&mut app, x, y + 20);
assert!(app.editor.breakpoint_lines(&f).is_empty(), "no line there");
app.editor_click.clear();
let mut shift = mouse(MouseEventKind::Down(MouseButton::Left), x, y);
shift.modifiers = KeyModifiers::SHIFT;
app.handle_mouse(shift);
assert!(
app.editor.breakpoint_lines(&f).is_empty(),
"Shift+click keeps extending the selection"
);
}
#[test]
fn wrapped_arrows_reach_the_ends_of_the_first_and_last_rows() {
use ratatui::widgets::Widget as _;
let (_tmp, mut app) = app_with_run_script();
let last = app.editor.lines.len() - 1;
let long = "done # ".to_string() + &"word ".repeat(30);
app.editor.lines[last] = long.clone();
app.editor.toggle_wrap();
assert!(app.editor.wrap_enabled());
let area = Rect::new(0, 0, 40, 20);
let mut buf = ratatui::buffer::Buffer::empty(area);
(&mut *app.editor).render(area, &mut buf);
app.editor.cursor_row = last;
app.editor.cursor_col = 2;
for _ in 0..10 {
app.handle_key(key(KeyCode::Down, KeyModifiers::NONE))
.unwrap();
}
assert_eq!(
(app.editor.cursor_row, app.editor.cursor_col),
(last, long.chars().count())
);
app.editor.cursor_row = 0;
app.editor.cursor_col = 6;
app.handle_key(key(KeyCode::Up, KeyModifiers::NONE))
.unwrap();
assert_eq!((app.editor.cursor_row, app.editor.cursor_col), (0, 0));
}
#[test]
fn dragging_editor_horizontal_scrollbar_pans_the_buffer() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let f = tmp.path().join("long.txt");
let long: String = std::iter::repeat_n('z', 500).collect();
std::fs::write(&f, format!("{long}\n")).unwrap();
app.editor.open(&f).unwrap();
app.focus_pane(Pane::Editor);
let backend = ratatui::backend::TestBackend::new(80, 24);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let bar = app.editor.last_hscrollbar;
assert!(
bar.width > 0 && bar.height == 1,
"an overflowing line must paint a horizontal scrollbar"
);
let right_x = bar.x + bar.width - 1;
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
column: right_x,
row: bar.y,
modifiers: KeyModifiers::NONE,
});
assert!(
app.editor.scroll_col > 0,
"clicking the right of the track must pan right"
);
let after_down = app.editor.scroll_col;
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Drag(crossterm::event::MouseButton::Left),
column: bar.x,
row: bar.y,
modifiers: KeyModifiers::NONE,
});
assert_eq!(
app.editor.scroll_col, 0,
"dragging to the left edge pans home"
);
assert_ne!(after_down, app.editor.scroll_col);
app.handle_mouse(crossterm::event::MouseEvent {
kind: crossterm::event::MouseEventKind::Up(crossterm::event::MouseButton::Left),
column: bar.x,
row: bar.y,
modifiers: KeyModifiers::NONE,
});
assert!(
app.gesture != Some(Gesture::EditorHScrollbar),
"releasing must clear the drag flag"
);
}
#[test]
fn next_change_in_the_editor_walks_the_change_bars_and_wraps() {
let (mut app, _t) = app_with_change_bars();
app.editor.cursor_row = 0;
let f7 = |app: &mut App, m: KeyModifiers| {
app.handle_key(key(KeyCode::F(7), m)).unwrap();
app.editor.cursor_row
};
assert_eq!(f7(&mut app, KeyModifiers::NONE), 4);
assert_eq!(f7(&mut app, KeyModifiers::NONE), 8);
assert_eq!(f7(&mut app, KeyModifiers::NONE), 4, "wraps to the first");
assert_eq!(f7(&mut app, KeyModifiers::SHIFT), 8, "Shift+F7 wraps back");
assert_eq!(f7(&mut app, KeyModifiers::SHIFT), 4);
}
#[test]
fn inline_blame_annotation_paints_on_the_cursor_line() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("m.rs");
std::fs::write(&f, "fn main() {}\nlet x = 1;\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&f).unwrap();
app.focus_pane(Pane::Editor);
app.editor.cursor_row = 0;
app.editor.set_blame(
f.clone(),
Some(crate::git::Blame::new(
vec![
std::sync::Arc::new(crate::git::BlameCommit {
hash: "abc12345".into(),
summary: "init".into(),
author: "Vitali".into(),
age_secs: 3600,
uncommitted: false,
}),
std::sync::Arc::new(crate::git::BlameCommit {
hash: "abc12345".into(),
summary: "add x".into(),
author: "Alice".into(),
age_secs: 60,
uncommitted: false,
}),
],
None,
)),
);
let backend = ratatui::backend::TestBackend::new(120, 30);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|frame| app.render(frame)).unwrap();
let buf = term.backend().buffer();
let mut whole = String::new();
for y in 0..30 {
for x in 0..120 {
whole.push_str(buf[(x, y)].symbol());
}
whole.push('\n');
}
assert!(
whole.contains("Vitali, 1 hour ago"),
"the cursor line's blame annotation must render; got:\n{whole}"
);
assert!(
!whole.contains("Alice"),
"only the cursor line is annotated, not every line"
);
}
#[test]
fn toggle_provenance_command_flips_the_editor_lens() {
let mut app = editor_app_with_lines(&["one", "two"]);
assert!(!app.editor.provenance_overlay, "the lens is off by default");
app.run_command(crate::widgets::command_palette::Command::ToggleProvenance);
assert!(app.editor.provenance_overlay, "the command turns it on");
assert_eq!(app.status, "Provenance: on");
app.sync_blame();
assert!(
app.editor.provenance_overlay,
"and the tick sync keeps it on"
);
app.run_command(crate::widgets::command_palette::Command::ToggleProvenance);
app.sync_blame();
assert!(
!app.editor.provenance_overlay,
"toggling again turns it off"
);
}
#[test]
fn the_group_by_seat_lens_reports_who_wrote_the_added_lines() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "kept\nmine\nnobody's\n").unwrap();
let mut seats = crate::provenance::Provenance::new();
seats.record(1..2, Seat::Me);
crate::history::record_with_seats_in(
hist.path(),
&f,
&std::fs::read(&f).unwrap(),
1_000,
&seats,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.focus_pane(Pane::Editor);
app.editor
.open_head_diff_with_text(
std::path::PathBuf::from("note.txt (HEAD)"),
"kept\n",
&f,
true,
)
.unwrap();
assert!(app.editor.diff.is_some(), "staging: a diff view is open");
assert!(
!app.editor.diff.as_ref().unwrap().group_by_seat,
"staging: the lens is off by default"
);
app.run_command(crate::widgets::command_palette::Command::DiffToggleGroupBySeat);
let diff = app.editor.diff.as_ref().unwrap();
assert!(diff.group_by_seat, "the command turns the lens on");
assert_eq!(
diff.seat_summary(),
"you 1 \u{2022} unrecorded 1",
"the added lines are reported per seat, the unwatched one as unrecorded"
);
assert_eq!(
app.status, "Diff: group by seat \u{2022} you 1 \u{2022} unrecorded 1",
"and the status line says the same"
);
app.run_command(crate::widgets::command_palette::Command::DiffToggleGroupBySeat);
assert!(
!app.editor.diff.as_ref().unwrap().group_by_seat,
"toggling again turns it off"
);
}
#[test]
fn the_group_by_seat_lens_survives_a_rebuild_of_the_view() {
use crate::provenance::Seat;
let (tmp, f) = repo_with_seed("kept\n");
let hist = tempfile::tempdir().unwrap();
std::fs::write(&f, "kept\nmine\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.focus_pane(Pane::Editor);
let record = |millis: u64, seats: &crate::provenance::Provenance| {
crate::history::record_with_seats_in(
hist.path(),
&f,
&std::fs::read(&f).unwrap(),
millis,
seats,
)
.unwrap();
};
let mut seats = crate::provenance::Provenance::new();
seats.record(1..2, Seat::Me);
record(1_000, &seats);
app.editor
.open_head_diff_with_text(
std::path::PathBuf::from("seed.txt (HEAD)"),
"kept\n",
&f,
true,
)
.unwrap();
app.tag_open_diff(crate::widgets::diff::DiffSource::HeadVsWorking {
root: tmp.path().to_path_buf(),
rel: String::from("seed.txt"),
});
app.run_command(crate::widgets::command_palette::Command::DiffToggleGroupBySeat);
assert_eq!(
app.editor.diff.as_ref().unwrap().seat_summary(),
"you 1",
"staging: the lens is on and reports the one added line"
);
rewrite_later(&f, "kept\nmine\ntheirs\n");
let mut seats2 = crate::provenance::Provenance::new();
seats2.record(1..2, Seat::Me);
seats2.record(2..3, Seat::Agent(String::from("pane 2")));
record(500_000, &seats2);
let no_paths = std::collections::BTreeSet::new();
assert!(
app.refresh_open_diff_views(false, &[], &no_paths),
"staging: the refresh rebuilt the view"
);
let diff = app.editor.diff.as_ref().unwrap();
assert_eq!(
diff.right_lines.len(),
3,
"staging: the rebuilt view shows the new line"
);
assert!(
diff.group_by_seat,
"the lens stays on across the rebuild rather than going dark"
);
assert_eq!(
diff.seat_summary(),
"you 1 \u{2022} agent (pane 2) 1",
"and its map is reloaded against the rebuilt rows: {}",
diff.seat_summary()
);
}
#[test]
fn the_group_by_seat_lens_refuses_a_map_for_lines_the_view_does_not_show() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "kept\nmine\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.focus_pane(Pane::Editor);
app.editor
.open_head_diff_with_text(
std::path::PathBuf::from("note.txt (HEAD)"),
"kept\n",
&f,
true,
)
.unwrap();
std::fs::write(&f, "kept\nelse\n").unwrap();
let mut seats = crate::provenance::Provenance::new();
seats.record(1..2, Seat::Me);
crate::history::record_with_seats_in(
hist.path(),
&f,
&std::fs::read(&f).unwrap(),
1_000,
&seats,
)
.unwrap();
app.run_command(crate::widgets::command_palette::Command::DiffToggleGroupBySeat);
let diff = app.editor.diff.as_ref().unwrap();
assert_eq!(
diff.right_lines,
vec![String::from("kept"), String::from("mine")],
"staging: the view still shows the pre-rewrite lines"
);
assert_eq!(
diff.seat_summary(),
"unrecorded 1",
"the newer map is refused rather than joined onto lines it never described"
);
}
#[test]
fn the_group_by_seat_lens_handles_a_lone_carriage_return() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "kept\na\rb\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.focus_pane(Pane::Editor);
let mut seats = crate::provenance::Provenance::new();
seats.record(1..2, Seat::Me);
crate::history::record_with_seats_in(
hist.path(),
&f,
&std::fs::read(&f).unwrap(),
1_000,
&seats,
)
.unwrap();
app.editor
.open_head_diff_with_text(
std::path::PathBuf::from("note.txt (HEAD)"),
"kept\n",
&f,
true,
)
.unwrap();
assert_eq!(
app.editor.diff.as_ref().unwrap().right_lines.len(),
2,
"staging: the opener made two lines, the lone CR inside the second"
);
app.run_command(crate::widgets::command_palette::Command::DiffToggleGroupBySeat);
assert_eq!(
app.editor.diff.as_ref().unwrap().seat_summary(),
"you 1",
"the map is applied rather than refused over a splitting difference"
);
}
#[test]
fn the_group_by_seat_lens_refuses_a_diff_that_is_not_the_working_tree() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "one\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus_pane(Pane::Editor);
app.editor
.open_head_diff_with_text(
std::path::PathBuf::from("note.txt (snapshot)"),
"old\n",
&f,
false,
)
.unwrap();
app.run_command(crate::widgets::command_palette::Command::DiffToggleGroupBySeat);
assert!(
!app.editor.diff.as_ref().unwrap().group_by_seat,
"the lens stays off on a diff it cannot key"
);
assert!(
app.status.contains("working tree"),
"and says why: {}",
app.status
);
}
#[test]
fn provenance_survives_a_restart_when_the_file_is_unchanged() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "one\ntwo\nthree\n").unwrap();
{
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
app.focus_pane(Pane::Editor);
app.editor.provenance.record(0..1, Seat::Navigator);
app.editor
.provenance
.record(1..2, Seat::Agent(String::from("pane 2")));
app.editor.dirty = true;
app.save();
let snaps = wait_for_snapshots(&app.history_root, &f);
assert_eq!(snaps.len(), 1, "staging: the save recorded a snapshot");
assert_eq!(
std::fs::read(&snaps[0].file).unwrap(),
std::fs::read(&f).unwrap(),
"staging: the snapshot holds the saved bytes"
);
wait_for_seats(&app.history_root, &f, snaps[0].millis);
}
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
assert_eq!(
app.editor.provenance.attributed(),
0,
"staging: a fresh open knows nothing yet"
);
app.sync_provenance();
assert_eq!(
app.editor.provenance.seat(0),
Some(&Seat::Navigator),
"the navigator's line comes back: {:?}",
app.editor.provenance
);
assert_eq!(
app.editor.provenance.seat(1),
Some(&Seat::Agent(String::from("pane 2"))),
"and the agent's: {:?}",
app.editor.provenance
);
assert_eq!(
app.editor.provenance.seat(2),
None,
"the untouched line stays unknown"
);
}
#[test]
fn provenance_comes_back_after_every_same_path_swap() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "one\ntwo\n").unwrap();
let mut seats = crate::provenance::Provenance::new();
seats.record(0..1, Seat::Navigator);
crate::history::record_with_seats_in(
hist.path(),
&f,
&std::fs::read(&f).unwrap(),
1_000,
&seats,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
app.sync_provenance();
assert_eq!(
app.editor.provenance, seats,
"staging: the first sync restores"
);
app.editor.revert_to_disk().unwrap();
assert_eq!(
app.editor.provenance.attributed(),
0,
"staging: the revert cleared the map"
);
app.sync_provenance();
assert_eq!(
app.editor.provenance, seats,
"the map comes back after a revert of the same path"
);
app.editor.open(&f).unwrap();
assert_eq!(
app.editor.provenance.attributed(),
0,
"staging: the reopen cleared the map"
);
app.sync_provenance();
assert_eq!(
app.editor.provenance, seats,
"and after a reopen of the same path"
);
}
#[test]
fn a_tab_with_no_history_is_looked_up_once_until_croft_records_one() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "one\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
app.sync_provenance();
assert_eq!(
app.editor.provenance_synced_seq,
Some(app.editor.edit_seq),
"a file with no history is looked at once, not on every pass"
);
let mut seats = crate::provenance::Provenance::new();
seats.record(0..1, Seat::Navigator);
crate::history::record_with_seats_in(
hist.path(),
&f,
&std::fs::read(&f).unwrap(),
1_000,
&seats,
)
.unwrap();
app.sync_provenance();
assert_eq!(
app.editor.provenance.attributed(),
0,
"the next pass does not look again"
);
app.history_done_tx.send(f.clone()).unwrap();
app.sync_explorer_panels();
app.sync_provenance();
assert_eq!(
app.editor.provenance, seats,
"a snapshot croft records is looked at"
);
}
#[test]
fn a_split_of_a_synced_file_gets_the_map_in_the_new_group() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "one\n").unwrap();
let mut seats = crate::provenance::Provenance::new();
seats.record(0..1, Seat::Navigator);
crate::history::record_with_seats_in(
hist.path(),
&f,
&std::fs::read(&f).unwrap(),
1_000,
&seats,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
app.focus_pane(Pane::Editor);
app.sync_provenance();
assert_eq!(
app.editor.provenance, seats,
"staging: the first tab is synced"
);
app.split_editor();
assert_eq!(
app.editor.path.as_deref(),
Some(f.as_path()),
"staging: the split opened the same file in the focused group"
);
assert_eq!(
app.editor.provenance.attributed(),
0,
"staging: the new group's tab knows nothing yet"
);
app.sync_provenance();
assert_eq!(
app.editor.provenance, seats,
"the split pane's buffer is synced on its own"
);
}
#[test]
fn provenance_is_synced_onto_the_inactive_group_too() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "one\n").unwrap();
let mut seats = crate::provenance::Provenance::new();
seats.record(0..1, Seat::Navigator);
crate::history::record_with_seats_in(
hist.path(),
&f,
&std::fs::read(&f).unwrap(),
1_000,
&seats,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
app.focus_pane(Pane::Editor);
app.split_editor();
let inactive = app.editor_layout.inactive_groups().collect::<Vec<_>>();
assert_eq!(inactive.len(), 1, "staging: one inactive group");
assert_eq!(
inactive[0].path.as_deref(),
Some(f.as_path()),
"staging: the inactive group holds the file"
);
app.sync_provenance();
assert_eq!(
app.editor.provenance, seats,
"staging: the focused tab is synced"
);
assert_eq!(
app.editor_layout
.inactive_groups()
.next()
.unwrap()
.provenance,
seats,
"the inactive group's tab is synced too"
);
}
#[test]
fn an_inactive_group_save_records_the_map_of_that_buffer() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "one\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
app.focus_pane(Pane::Editor);
app.split_editor();
app.editor
.provenance
.record(0..1, Seat::Peer(String::from("ana")));
{
let mut groups = app.editor_layout.inactive_groups_mut().collect::<Vec<_>>();
let other: &mut crate::widgets::editor::Editor = &mut *groups[0];
assert_eq!(
other.path.as_deref(),
Some(f.as_path()),
"staging: same file"
);
other.cursor_row = 0;
other.cursor_col = 0;
other.insert_str_as("nav\n", Seat::Navigator);
assert!(other.dirty, "staging: the inactive buffer is dirty");
age_last_edit(other);
}
app.auto_save = true;
assert!(
app.tick_auto_save(),
"staging: the sweep saved the dirty buffer"
);
assert!(
std::fs::read_to_string(&f).unwrap().starts_with("nav\n"),
"staging: the inactive buffer's text is what hit the disk"
);
let snaps = wait_for_snapshots(&app.history_root, &f);
assert_eq!(snaps.len(), 1, "staging: the save recorded a snapshot");
wait_for_seats(&app.history_root, &f, snaps[0].millis);
let recorded = crate::history::seats_for(&app.history_root, &f, snaps[0].millis).unwrap();
assert_eq!(
recorded.seat(0),
Some(&Seat::Navigator),
"the sidecar holds the saved buffer's map, not the focused tab's: {recorded:?}"
);
}
#[test]
fn a_stale_tab_is_not_credited_with_the_map_of_the_saving_tab() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "one\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
app.focus_pane(Pane::Editor);
app.split_editor();
{
let mut groups = app.editor_layout.inactive_groups_mut().collect::<Vec<_>>();
let other: &mut crate::widgets::editor::Editor = &mut *groups[0];
other.cursor_row = 0;
other.cursor_col = 0;
other.insert_str_as("nav\n", Seat::Navigator);
age_last_edit(other);
}
app.auto_save = true;
assert!(
app.tick_auto_save(),
"staging: the sweep saved the other buffer"
);
let snaps = wait_for_snapshots(&app.history_root, &f);
wait_for_seats(&app.history_root, &f, snaps[0].millis);
assert_eq!(
std::fs::read(&snaps[0].file).unwrap(),
std::fs::read(&f).unwrap(),
"staging: the newest snapshot matches the file on disk"
);
assert!(!app.editor.dirty, "staging: the focused tab is clean");
assert_eq!(
app.editor.lines,
vec![String::from("one")],
"staging: and still holds the pre-save text"
);
app.sync_provenance();
assert_eq!(
app.editor.provenance.attributed(),
0,
"a stale buffer is not credited from a snapshot of text it never held: {:?}",
app.editor.provenance
);
}
#[test]
fn the_map_of_an_emptied_file_survives_a_restart() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "").unwrap();
let mut seats = crate::provenance::Provenance::new();
seats.record(0..1, Seat::Navigator);
crate::history::record_with_seats_in(hist.path(), &f, b"", 1_000, &seats).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
assert_eq!(
app.editor.lines,
vec![String::new()],
"staging: an empty file opens as one empty line"
);
app.sync_provenance();
assert_eq!(
app.editor.provenance, seats,
"the emptied file's map comes back: {:?}",
app.editor.provenance
);
}
#[test]
fn the_map_of_a_utf16_file_survives_a_restart() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
let mut bytes = vec![0xFF, 0xFE];
for unit in "one
two
"
.encode_utf16()
{
bytes.extend_from_slice(&unit.to_le_bytes());
}
std::fs::write(&f, &bytes).unwrap();
let mut seats = crate::provenance::Provenance::new();
seats.record(0..1, Seat::Navigator);
crate::history::record_with_seats_in(hist.path(), &f, &bytes, 1_000, &seats).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
assert_eq!(
app.editor.lines,
vec![String::from("one"), String::from("two")],
"staging: the file opened as UTF-16 text"
);
app.sync_provenance();
assert_eq!(
app.editor.provenance, seats,
"the UTF-16 file's map comes back: {:?}",
app.editor.provenance
);
}
#[test]
fn the_map_is_not_recorded_against_another_save_s_bytes() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "one\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
app.focus_pane(Pane::Editor);
let mut seats = crate::provenance::Provenance::new();
seats.record(0..1, Seat::Navigator);
std::fs::write(&f, "someone else\n").unwrap();
app.record_history_snapshot_of(&f, seats, Some(b"one\n".to_vec()));
let snaps = wait_for_snapshots(&app.history_root, &f);
assert_eq!(snaps.len(), 1, "the snapshot is still recorded");
assert_eq!(
std::fs::read(&snaps[0].file).unwrap(),
b"someone else\n",
"and holds the bytes that were actually on disk"
);
assert_eq!(
crate::history::seats_for(&app.history_root, &f, snaps[0].millis),
None,
"but wears no map, rather than one describing text it does not hold"
);
let mut seats2 = crate::provenance::Provenance::new();
seats2.record(0..1, Seat::Peer(String::from("ana")));
let on_disk = std::fs::read(&f).unwrap();
app.record_history_snapshot_of(&f, seats2, Some(on_disk));
crate::test_budget::await_spawned(
std::time::Duration::from_millis(500),
"the control's sidecar",
|| {
crate::history::entries_in(&app.history_root, &f)
.first()
.is_some_and(|s| {
crate::history::seats_for(&app.history_root, &f, s.millis).is_some()
})
},
);
}
#[test]
fn a_dirty_tab_is_reconsidered_for_provenance_once_it_is_clean() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "one\n").unwrap();
let mut seats = crate::provenance::Provenance::new();
seats.record(0..1, Seat::Peer(String::from("ana")));
crate::history::record_with_seats_in(
hist.path(),
&f,
&std::fs::read(&f).unwrap(),
1_000,
&seats,
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
app.editor.dirty = true;
app.sync_provenance();
assert_eq!(
app.editor.provenance.attributed(),
0,
"staging: a dirty buffer takes no map"
);
app.editor.dirty = false;
app.sync_provenance();
assert_eq!(
app.editor.provenance, seats,
"the same buffer, clean, gets the map on the next tick"
);
}
#[test]
fn provenance_is_not_restored_onto_text_the_snapshot_never_saw() {
use crate::provenance::Seat;
let tmp = tempfile::tempdir().unwrap();
let hist = tempfile::tempdir().unwrap();
let f = tmp.path().join("note.txt");
std::fs::write(&f, "v1\n").unwrap();
{
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
app.focus_pane(Pane::Editor);
app.editor.cursor_row = 0;
app.editor.cursor_col = 0;
app.editor.insert_str_as("nav\n", Seat::Navigator);
app.save();
let snaps = wait_for_snapshots(&app.history_root, &f);
assert_eq!(snaps.len(), 1, "staging: the save recorded a snapshot");
wait_for_seats(&app.history_root, &f, snaps[0].millis);
}
let mut on_disk = std::fs::read_to_string(&f).unwrap();
on_disk.insert_str(0, "someone else\n");
std::fs::write(&f, on_disk).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.history_root = hist.path().to_path_buf();
app.editor.open(&f).unwrap();
app.sync_provenance();
assert_eq!(
app.editor.provenance.attributed(),
0,
"a changed file is not credited from a stale map: {:?}",
app.editor.provenance
);
}
#[test]
fn the_provenance_lens_reaches_every_editor_after_the_flag_sync() {
let mut app = editor_app_with_lines(&["one", "two"]);
app.editor
.push_editor(crate::widgets::editor::Editor::new());
assert!(app.editor.editors.len() >= 2, "fixture: two tabs");
app.editor.path = Some(std::path::PathBuf::from("split-anchor.txt"));
app.split_editor();
app.run_command(crate::widgets::command_palette::Command::ToggleProvenance);
app.sync_focus_flags();
let every_editor_on = app.editor.editors.iter().all(|e| e.provenance_overlay)
&& app
.editor_layout
.inactive_groups()
.flat_map(|g| g.editors.iter())
.all(|e| e.provenance_overlay);
assert!(
every_editor_on,
"every tab in every group carries the lens after the sync"
);
app.run_command(crate::widgets::command_palette::Command::ToggleProvenance);
app.sync_focus_flags();
assert!(
app.editor.editors.iter().all(|e| !e.provenance_overlay),
"and every tab drops it"
);
}
#[test]
fn toggle_inline_blame_command_flips_the_editor_flag_and_pref() {
let mut app = editor_app_with_lines(&["one", "two"]);
assert!(
app.inline_blame_enabled,
"inline blame is on by default (GitLens parity)"
);
app.run_command(crate::widgets::command_palette::Command::ToggleInlineBlame);
assert!(!app.inline_blame_enabled, "the command turns it off");
app.sync_blame();
assert!(!app.editor.blame_enabled);
app.run_command(crate::widgets::command_palette::Command::ToggleInlineBlame);
assert!(app.inline_blame_enabled, "toggling again turns it back on");
app.sync_blame();
assert!(app.editor.blame_enabled);
}
#[test]
fn toggle_indent_guides_command_flips_every_editor_via_the_frame_sync() {
let mut app = editor_app_with_lines(&["fn a() {", " x();", "}"]);
assert!(
app.indent_guides_enabled,
"indent guides are on by default (VS Code editor.guides.indentation)"
);
app.run_command(crate::widgets::command_palette::Command::ToggleIndentGuides);
assert!(!app.indent_guides_enabled, "the command turns them off");
app.sync_focus_flags();
assert!(app.editor.editors.iter().all(|e| !e.show_indent_guides));
app.editor
.open_text_buffer(std::path::Path::new("later.rs"), "fn x() {\n y();\n}")
.unwrap();
assert!(
app.editor.show_indent_guides,
"a fresh tab starts on the default, proving the sync below does the work"
);
app.sync_focus_flags();
assert!(
app.editor.editors.iter().all(|e| !e.show_indent_guides),
"the frame sync disables guides on the tab opened after the toggle"
);
app.run_command(crate::widgets::command_palette::Command::ToggleIndentGuides);
assert!(app.indent_guides_enabled);
app.editor
.open_text_buffer(std::path::Path::new("even-later.rs"), "fn z() {}")
.unwrap();
app.sync_focus_flags();
assert!(
app.editor.editors.iter().all(|e| e.show_indent_guides),
"re-enabling reaches tabs opened before and after the toggle"
);
}
#[test]
fn toggle_bracket_colors_command_flips_every_editor_via_the_frame_sync() {
let mut app = editor_app_with_lines(&["fn a(x: u8) {}"]);
assert!(
app.bracket_colors_enabled,
"bracket colorization is on by default (VS Code default since 1.67)"
);
app.run_command(crate::widgets::command_palette::Command::ToggleBracketColors);
assert!(!app.bracket_colors_enabled, "the command turns it off");
app.editor
.open_text_buffer(std::path::Path::new("later.rs"), "g(1)")
.unwrap();
app.sync_focus_flags();
assert!(
app.editor.editors.iter().all(|e| !e.show_bracket_colors),
"the frame sync disables the tab opened after the toggle too"
);
app.run_command(crate::widgets::command_palette::Command::ToggleBracketColors);
app.sync_focus_flags();
assert!(app.editor.editors.iter().all(|e| e.show_bracket_colors));
}
#[test]
fn toggle_render_whitespace_cycles_modes_across_every_editor() {
use crate::widgets::editor::WhitespaceMode;
let mut app = editor_app_with_lines(&["a b"]);
let all_editors_in = |app: &App, mode: WhitespaceMode| {
app.editor.editors.iter().all(|e| e.whitespace_mode == mode)
};
assert_eq!(
app.whitespace_mode,
WhitespaceMode::Selection,
"selection is the default (VS Code editor.renderWhitespace)"
);
app.sync_focus_flags();
assert!(all_editors_in(&app, WhitespaceMode::Selection));
app.run_command(crate::widgets::command_palette::Command::ToggleRenderWhitespace);
assert_eq!(app.whitespace_mode, WhitespaceMode::All);
app.editor
.open_text_buffer(std::path::Path::new("later.txt"), "c d")
.unwrap();
app.sync_focus_flags();
assert!(
all_editors_in(&app, WhitespaceMode::All),
"the frame sync carries the mode to tabs opened after the toggle"
);
app.run_command(crate::widgets::command_palette::Command::ToggleRenderWhitespace);
assert_eq!(app.whitespace_mode, WhitespaceMode::None);
app.sync_focus_flags();
assert!(all_editors_in(&app, WhitespaceMode::None));
app.run_command(crate::widgets::command_palette::Command::ToggleRenderWhitespace);
assert_eq!(app.whitespace_mode, WhitespaceMode::Selection, "full cycle");
app.sync_focus_flags();
assert!(all_editors_in(&app, WhitespaceMode::Selection));
}
#[test]
fn reloaded_rulers_reach_every_open_editor() {
let mut app = editor_app_with_lines(&["a b"]);
app.editor
.open_text_buffer(std::path::Path::new("later.txt"), "c d")
.unwrap();
app.apply_merged_settings(&crate::prefs::Prefs {
rulers: vec![80, 100],
..Default::default()
});
assert!(app.editor.editors.len() >= 2);
assert!(app.editor.editors.iter().all(|e| e.rulers == vec![80, 100]));
app.apply_merged_settings(&crate::prefs::Prefs {
rulers: vec![100, 80, 100],
..Default::default()
});
assert!(
app.editor.editors.iter().all(|e| e.rulers == vec![80, 100]),
"normalized on the way in"
);
app.apply_merged_settings(&crate::prefs::Prefs::default());
assert!(app.editor.editors.iter().all(|e| e.rulers.is_empty()));
}
#[test]
fn reloaded_home_walk_reaches_every_open_editor() {
let mut app = editor_app_with_lines(&["a b"]);
app.editor
.open_text_buffer(std::path::Path::new("later.txt"), "c d")
.unwrap();
app.apply_merged_settings(&crate::prefs::Prefs {
home_walks_wrapped_rows: true,
..Default::default()
});
assert!(app.editor.editors.len() >= 2);
assert!(app.editor.editors.iter().all(|e| e.home_walks_rows));
app.apply_merged_settings(&crate::prefs::Prefs::default());
assert!(app.editor.editors.iter().all(|e| !e.home_walks_rows));
}
fn every_editor(app: &App) -> Vec<&crate::widgets::editor::Editor> {
app.editor
.editors
.iter()
.chain(
app.editor_layout
.inactive_groups()
.flat_map(|g| g.editors.iter()),
)
.collect()
}
#[test]
fn view_settings_reach_every_tab_of_every_group_without_a_focus_change() {
use crate::widgets::command_palette::Command;
use crate::widgets::editor::WhitespaceMode;
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.rs", "fn a() {\n (1)\n}\n");
let b = tmp.path().join("b.rs");
std::fs::write(&b, "fn b() {\n (2)\n}\n").unwrap();
app.editor.open_pinned(&b).unwrap();
app.split_editor();
assert_eq!(every_editor(&app).len(), 3, "setup: two tabs and a split");
app.apply_merged_settings(&crate::prefs::Prefs {
disable_indent_guides: true,
disable_bracket_colors: true,
render_whitespace: String::from("all"),
..Default::default()
});
for ed in every_editor(&app) {
assert!(!ed.show_indent_guides, "{:?}: indent guides", ed.path);
assert!(!ed.show_bracket_colors, "{:?}: bracket colours", ed.path);
assert_eq!(ed.whitespace_mode, WhitespaceMode::All, "{:?}", ed.path);
}
app.run_command(Command::ToggleIndentGuides);
app.run_command(Command::ToggleBracketColors);
app.run_command(Command::ToggleRenderWhitespace);
for ed in every_editor(&app) {
assert!(ed.show_indent_guides, "{:?}: indent guides", ed.path);
assert!(ed.show_bracket_colors, "{:?}: bracket colours", ed.path);
assert_eq!(ed.whitespace_mode, WhitespaceMode::None, "{:?}", ed.path);
}
}
#[test]
fn build_sticky_lines_pins_enclosing_headers_scrolled_above_the_viewport() {
use crate::lsp::manager::OutlineKind;
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("m.rs");
std::fs::write(&f, "x\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&f).unwrap();
app.outline.set_symbols(
f.clone(),
vec![
sym("Widget", OutlineKind::Class, 0, 0, 40),
sym("build", OutlineKind::Method, 1, 10, 30),
],
);
app.editor.scroll = 20;
assert_eq!(app.build_sticky_lines(), vec![0, 10], "outermost first");
app.editor.scroll = 5;
assert_eq!(app.build_sticky_lines(), vec![0]);
app.editor.scroll = 0;
assert!(app.build_sticky_lines().is_empty());
}
#[test]
fn sticky_scroll_pins_the_name_line_of_a_decorated_definition() {
use crate::lsp::manager::OutlineKind;
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("api.py");
std::fs::write(&f, "x\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&f).unwrap();
let mut order = sym("Order", OutlineKind::Class, 0, 3, 40);
order.line = 4;
let mut validate = sym("validate", OutlineKind::Method, 1, 6, 30);
validate.line = 7;
app.outline.set_symbols(f.clone(), vec![order, validate]);
app.editor.scroll = 20;
assert_eq!(app.build_sticky_lines(), vec![4, 7], "the name lines");
app.editor.scroll = 4;
assert!(app.build_sticky_lines().is_empty());
}
#[test]
fn minimap_edit_rebakes_in_place_but_a_moved_strip_arms_the_clear() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.cell_pixel = Some((8, 16));
app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::Kitty;
app.editor.lines = (0..80).map(|i| format!("line {i}")).collect();
let strip = ratatui::layout::Rect {
x: 100,
y: 1,
width: 6,
height: 40,
};
app.update_minimap_overlay(strip);
assert!(app.minimap_image_payload().is_some(), "minimap must bake");
let _ = app.consume_minimap_image_clear();
app.mark_minimap_image_displayed();
app.editor.lines.push(String::from("one more line"));
app.editor.edit_seq += 1;
app.update_minimap_overlay(strip);
assert!(
!app.consume_minimap_image_clear(),
"a content-only minimap change must replace the image in place, not blank the screen"
);
assert!(
app.minimap_image_payload().is_some(),
"the rebaked raster must still be there to re-emit"
);
app.mark_minimap_image_displayed();
let moved = ratatui::layout::Rect { x: 60, ..strip };
app.update_minimap_overlay(moved);
assert!(
app.consume_minimap_image_clear(),
"a moved minimap strip must arm the eviction clear so no ghost remains"
);
}
#[test]
fn timestamps_gutter_toggles_on_and_shows_arrival_times() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[
String::from("-c"),
String::from("g=gutter; echo ${g}-row-9; sleep 30"),
],
tmp.path(),
)
.unwrap();
app.focus_pane(Pane::Terminal);
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the pane output \"gutter-row-9\"",
|| {
app.terminals[0]
.grid_lines()
.0
.iter()
.any(|l| l.starts_with("gutter-row-9"))
},
);
fn gutter_of(rows: &[String], needle: &str) -> Option<String> {
let row = rows.iter().find(|r| r.contains(needle))?;
let inner = row.trim_end().trim_end_matches(['│', '┃']);
Some(
inner
.chars()
.rev()
.take(8)
.collect::<String>()
.chars()
.rev()
.collect(),
)
}
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let g = gutter_of(&screen_char_rows(&term), "gutter-row-9").unwrap_or_default();
assert!(
!g.chars().filter(|c| *c == ':').count().eq(&2),
"no gutter while the toggle is off: {g:?}"
);
app.toggle_terminal_timestamps();
assert!(app.show_terminal_timestamps);
term.draw(|f| app.render(f)).unwrap();
let g = gutter_of(&screen_char_rows(&term), "gutter-row-9").expect("row still on screen");
let looks_like_clock = g.len() == 8
&& g.as_bytes()[2] == b':'
&& g.as_bytes()[5] == b':'
&& g.chars().filter(|c| c.is_ascii_digit()).count() == 6;
assert!(
looks_like_clock,
"the toggled gutter shows HH:MM:SS at the row's right edge: {g:?}"
);
app.toggle_terminal_timestamps();
term.draw(|f| app.render(f)).unwrap();
let g = gutter_of(&screen_char_rows(&term), "gutter-row-9").unwrap_or_default();
assert!(
!(g.len() == 8 && g.as_bytes()[2] == b':' && g.as_bytes()[5] == b':'),
"toggling off removes the gutter: {g:?}"
);
}
#[test]
fn sticky_command_header_pins_the_command_while_scrolled_into_its_output() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
let script = "b=build; printf \"\\033]133;A\\007$ \\033]133;B\\007${b}-it-77 now\\n\\033]133;C\\007\"; i=0; while [ $i -lt 80 ]; do echo out-$i; i=$((i+1)); done; printf '\\033]133;D;0\\007'; sleep 30";
app.terminals[0] = crate::widgets::terminal::PtyTerminal::new_running(
"/bin/sh",
&[String::from("-c"), String::from(script)],
tmp.path(),
)
.unwrap();
app.focus_pane(Pane::Terminal);
crate::test_budget::await_spawned(
crate::test_budget::tests::SHELL_PAINT_BASE,
"the command to finish",
|| !app.terminals[0].command_decorations().is_empty(),
);
let backend = ratatui::backend::TestBackend::new(120, 40);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let inner = app.terminals[0].last_inner;
let rows = screen_char_rows(&term);
assert!(
!rows[inner.y as usize].contains("build-it-77"),
"no header at the live bottom: {:?}",
rows[inner.y as usize]
);
app.terminals[0].scroll_to_top();
for _ in 0..4 {
app.terminals[0].scroll_down(1);
}
term.draw(|f| app.render(f)).unwrap();
let rows = screen_char_rows(&term);
assert!(
rows[inner.y as usize].contains("build-it-77 now"),
"the command must pin to the pane's top row: {:?}",
rows[inner.y as usize]
);
app.terminals[0].reset_scrollback();
term.draw(|f| app.render(f)).unwrap();
let rows = screen_char_rows(&term);
assert!(
!rows[inner.y as usize].contains("build-it-77"),
"the header unpins at the live bottom: {:?}",
rows[inner.y as usize]
);
}
#[test]
fn the_wheel_still_scrolls_a_long_text_file() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("long.txt");
let body: String = (0..500).map(|i| format!("line {i}\n")).collect();
std::fs::write(&path, body).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&path).unwrap();
let (col, row) = place_editor_pane(&mut app);
wheel(&mut app, MouseEventKind::ScrollDown, col, row);
assert_eq!(app.editor.scroll, 3, "wheel down still scrolls text");
wheel(&mut app, MouseEventKind::ScrollUp, col, row);
assert_eq!(app.editor.scroll, 0, "wheel up still scrolls text back");
}
#[test]
fn drag_target_over_the_sticky_band_is_the_pinned_directory() {
use crossterm::event::{MouseButton, MouseEventKind};
let tmp = tempfile::tempdir().unwrap();
std::fs::create_dir_all(tmp.path().join("outer/inner")).unwrap();
for i in 0..25 {
std::fs::write(tmp.path().join(format!("outer/inner/f{i:02}.rs")), "x\n").unwrap();
}
std::fs::write(tmp.path().join("loose.txt"), "x\n").unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.tree.set_compact_folders(false);
let outer = app
.tree
.nodes
.iter()
.position(|n| n.path.ends_with("outer"))
.unwrap();
app.tree.selected = outer;
app.tree.expand_selected();
let inner = app
.tree
.nodes
.iter()
.position(|n| n.path.ends_with("inner"))
.unwrap();
app.tree.selected = inner;
app.tree.expand_selected();
let deep = app
.tree
.nodes
.iter()
.position(|n| n.path.ends_with("f20.rs"))
.unwrap();
app.tree.selected = deep;
app.tree.scroll = deep.saturating_sub(3);
let backend = ratatui::backend::TestBackend::new(120, 20);
let mut term = ratatui::Terminal::new(backend).unwrap();
term.draw(|f| app.render(f)).unwrap();
let (band_y, pinned_idx) = {
let rows = app.tree.sticky_rows_for_test();
assert!(rows.len() >= 3, "band must pin root/outer/inner here");
rows[1]
};
let loose = tmp.path().join("loose.txt");
let target = drag_target_index(&app.tree, band_y, std::slice::from_ref(&loose))
.expect("a pinned directory is a valid drop target");
assert_eq!(
target, pinned_idx,
"the drop target under the band is the PINNED directory, not the covered row"
);
let covered = app.tree.node_at_y(band_y);
assert_ne!(
covered,
Some(target),
"precondition: the band actually covers a different row there"
);
let _ = MouseEventKind::Down(MouseButton::Left); }
#[test]
fn fold_all_regions_command_works_with_no_language_server_attached() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
tmp.path().join("notes.txt"),
"#region setup\nline a\nline b\n#endregion\nrest\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor
.open_pinned(&tmp.path().join("notes.txt"))
.unwrap();
app.focus_pane(Pane::Editor);
app.run_command(crate::widgets::command_palette::Command::FoldAllRegions);
assert!(app.editor.is_line_hidden(1) && app.editor.is_line_hidden(2));
assert!(!app.editor.is_line_hidden(0) && !app.editor.is_line_hidden(4));
app.run_command(crate::widgets::command_palette::Command::UnfoldAllRegions);
assert!(!app.editor.is_line_hidden(1), "regions expanded again");
}
fn nested_fold_app(dir: &std::path::Path) -> App {
std::fs::write(
dir.join("nested.py"),
"class Outer:\n def method_one(self):\n if True:\n for i in range(10):\n print(i)\n def method_two(self):\n return 1\n",
)
.unwrap();
let mut app = App::new(dir.to_path_buf()).unwrap();
app.editor.open_pinned(&dir.join("nested.py")).unwrap();
app.focus_pane(Pane::Editor);
app
}
fn visible_lines(app: &App) -> Vec<usize> {
(0..app.editor.lines.len())
.filter(|&l| !app.editor.is_line_hidden(l))
.collect()
}
fn run_fold_command(app: &mut App, id: &str) {
let cmd = crate::widgets::command_palette::Command::from_id(id)
.unwrap_or_else(|| panic!("croft has no {id} command"));
app.run_command(cmd);
}
#[test]
fn fold_level_2_keeps_the_class_and_its_methods_in_view() {
let tmp = tempfile::tempdir().unwrap();
let mut app = nested_fold_app(tmp.path());
run_fold_command(&mut app, "fold_level_2");
assert_eq!(visible_lines(&app), vec![0, 1, 5]);
}
#[test]
fn fold_level_1_collapses_only_the_class() {
let tmp = tempfile::tempdir().unwrap();
let mut app = nested_fold_app(tmp.path());
run_fold_command(&mut app, "fold_level_1");
assert_eq!(visible_lines(&app), vec![0]);
app.editor.toggle_fold(0);
assert_eq!(visible_lines(&app), (0..7).collect::<Vec<_>>());
app.editor.toggle_fold(2);
run_fold_command(&mut app, "fold_level_1");
app.editor.toggle_fold(0);
assert_eq!(visible_lines(&app), vec![0, 1, 2, 5, 6]);
}
#[test]
fn cmd_k_cmd_3_folds_level_3() {
let tmp = tempfile::tempdir().unwrap();
let mut app = nested_fold_app(tmp.path());
app.handle_key(key(KeyCode::Char('k'), KeyModifiers::SUPER))
.unwrap();
app.handle_key(key(KeyCode::Char('3'), KeyModifiers::SUPER))
.unwrap();
assert_eq!(visible_lines(&app), vec![0, 1, 2, 5, 6]);
}
#[test]
fn fold_recursively_collapses_the_block_and_everything_inside() {
let tmp = tempfile::tempdir().unwrap();
let mut app = nested_fold_app(tmp.path());
app.editor.cursor_row = 1;
run_fold_command(&mut app, "fold_recursively");
assert_eq!(visible_lines(&app), vec![0, 1, 5, 6]);
app.editor.toggle_fold(1);
assert_eq!(
visible_lines(&app),
vec![0, 1, 2, 5, 6],
"the if stays folded"
);
app.editor.toggle_fold(1);
run_fold_command(&mut app, "unfold_recursively");
assert_eq!(visible_lines(&app), (0..7).collect::<Vec<_>>());
}
#[test]
fn recursive_and_level_folds_stay_inside_their_scope() {
let tmp = tempfile::tempdir().unwrap();
let mut app = nested_fold_app(tmp.path());
app.editor.toggle_fold(5);
app.editor.cursor_row = 1;
run_fold_command(&mut app, "fold_recursively");
run_fold_command(&mut app, "unfold_recursively");
assert_eq!(
visible_lines(&app),
vec![0, 1, 2, 3, 4, 5],
"method_two is still folded"
);
std::fs::write(tmp.path().join("flat.txt"), "one\ntwo\nthree\n").unwrap();
app.editor
.open_pinned(&tmp.path().join("flat.txt"))
.unwrap();
run_fold_command(&mut app, "fold_level_1");
assert_eq!(visible_lines(&app), vec![0, 1, 2]);
}
#[test]
fn vscode_fold_level_keybindings_import() {
let mut report = crate::import_vscode::Report::default();
crate::import_vscode::convert_keybindings(
&serde_json::json!([
{ "key": "ctrl+alt+2", "command": "editor.foldLevel2" },
{ "key": "ctrl+alt+r", "command": "editor.foldRecursively" },
{ "key": "ctrl+alt+u", "command": "editor.unfoldRecursively" }
]),
&mut report,
);
assert!(
report.dropped_keybindings.is_empty(),
"{:?}",
report.dropped_keybindings
);
let commands: Vec<String> = serde_json::to_value(&report.keybindings)
.unwrap()
.as_array()
.unwrap()
.iter()
.map(|row| row[1].as_str().unwrap().to_string())
.collect();
assert_eq!(
commands,
vec!["fold_level_2", "fold_recursively", "unfold_recursively"]
);
}
#[test]
fn expand_selection_falls_back_to_tree_sitter_when_the_lsp_cannot_route() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(
tmp.path().join("lib.rs"),
"fn main() {\n let value = 1;\n}\n",
)
.unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&tmp.path().join("lib.rs")).unwrap();
app.focus_pane(Pane::Editor);
app.editor.cursor_row = 1;
app.editor.cursor_col = 9; app.run_command(crate::widgets::command_palette::Command::ExpandSelection);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while app.editor.selection.is_none() && std::time::Instant::now() < deadline {
app.drain_lsp_selection_ranges();
std::thread::sleep(std::time::Duration::from_millis(20));
}
let sel = app
.editor
.selection
.expect("the fallback grew a selection")
.normalised();
assert!(
sel.0 <= (1, 8) && sel.1 >= (1, 13),
"the identifier (or an enclosing node) is selected: {sel:?}"
);
app.run_command(crate::widgets::command_palette::Command::ShrinkSelection);
assert!(app.editor.selection.is_none(), "back to the bare caret");
}
#[test]
fn cmd_k_shift_e_runs_the_caret_lines_only_lens() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.rs", "fn main() {}\n");
app.editor.code_lenses = vec![lens_at(
0,
"fn main() {}",
"Frobnicate",
"vendor.frobnicate",
)];
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('E'), KeyModifiers::SHIFT)));
assert!(app.status.starts_with("Code lens:"), "{}", app.status);
app.editor
.code_lenses
.push(lens_at(0, "fn main() {}", "Other", "vendor.other"));
assert!(app.handle_cmd_k_chord(key(KeyCode::Char('e'), KeyModifiers::SHIFT)));
assert!(
app.context_menu.is_some(),
"two lenses open a menu to pick from"
);
}
#[test]
fn minimap_rebakes_for_typing_at_most_every_few_hundred_ms() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.cell_pixel = Some((8, 16));
app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::Kitty;
app.editor.lines = (0..80).map(|i| format!("line {i}")).collect();
let strip = ratatui::layout::Rect {
x: 100,
y: 1,
width: 6,
height: 40,
};
app.update_minimap_overlay(strip);
let first = app.minimap_image_payload().map(|(o, _)| o.to_string());
assert!(first.is_some());
app.editor.lines[0] = String::from("changed");
app.editor.edit_seq += 1;
app.update_minimap_overlay(strip);
assert_eq!(
app.minimap_image_payload().map(|(o, _)| o.to_string()),
first,
"a keystroke right after a bake waits"
);
assert!(!app.tick_minimap(), "not due yet");
app.minimap.baked_at = Some(std::time::Instant::now() - super::MINIMAP_EDIT_REBAKE);
assert!(app.tick_minimap(), "the wait is over: redraw");
assert!(
!app.tick_minimap(),
"one redraw per deferred bake, even if the minimap is gone by then"
);
app.update_minimap_overlay(strip);
assert_ne!(
app.minimap_image_payload().map(|(o, _)| o.to_string()),
first,
"the deferred edit is baked"
);
assert!(!app.tick_minimap());
app.editor.scroll = 5;
let before = app.minimap_image_payload().map(|(o, _)| o.to_string());
app.update_minimap_overlay(strip);
assert_ne!(
app.minimap_image_payload().map(|(o, _)| o.to_string()),
before
);
}
#[test]
fn a_syntax_pass_that_outlives_the_keystroke_lands_on_a_later_tick() {
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "main.rs", "fn main() {\n let x = 1;\n}\n");
app.split_editor();
let path = tmp.path().join("main.rs");
let type_into = |ed: &mut crate::widgets::editor::Editor| {
ed.defer_highlights_for_test();
ed.cursor_row = 1;
ed.cursor_col = 4;
ed.insert_str("let y = \"s\"; // (note)\n ");
assert!(ed.highlight_pending(), "the keystroke did not wait");
};
type_into(&mut app.editor);
type_into(app.editor_layout.inactive_groups_mut().next().unwrap());
app.cell_pixel = Some((8, 16));
app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::Kitty;
let strip = ratatui::layout::Rect {
x: 100,
y: 1,
width: 6,
height: 40,
};
app.update_minimap_overlay(strip);
let carried = app.minimap_image_payload().map(|(o, _)| o.to_string());
assert!(carried.is_some());
let pending = |app: &mut App| {
app.editor.highlight_pending()
|| app
.editor_layout
.inactive_groups()
.next()
.unwrap()
.highlight_pending()
};
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(60);
let mut landed = false;
while pending(&mut app) {
landed |= app.poll_highlights();
assert!(
std::time::Instant::now() < deadline,
"the passes never landed"
);
std::thread::sleep(std::time::Duration::from_millis(1));
}
assert!(
landed,
"the tick reported the landing, so the frame repaints"
);
let want = |lines: &[String]| {
let fresh =
crate::widgets::editor::Editor::historical(&path, &lines.join("\n"), Vec::new());
format!("{:?}", fresh.highlights_for_test())
};
let inactive = &app.editor_layout.inactive_groups().next().unwrap();
assert_eq!(
format!("{:?}", inactive.highlights_for_test()),
want(&inactive.lines),
"the other group's tab"
);
assert_eq!(
format!("{:?}", app.editor.highlights_for_test()),
want(&app.editor.lines),
"the focused tab"
);
app.minimap.baked_at = Some(std::time::Instant::now() - super::MINIMAP_EDIT_REBAKE);
app.update_minimap_overlay(strip);
assert_ne!(
app.minimap_image_payload().map(|(o, _)| o.to_string()),
carried,
"the strip re-bakes in the landed colors"
);
}
#[test]
fn the_minimap_png_is_small() {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.lines = (0..400)
.map(|i| format!(" let value_{i} = compute(a, b, {i}); // note"))
.collect();
let (w, h) = (6 * 9, 45 * 18);
let rgba = app
.editor
.minimap_rgba(w, h, h, (30, 30, 30), (200, 200, 200));
let png = super::rgba_to_png(rgba, w, h).unwrap();
assert!(png.len() < 1500, "{} bytes", png.len());
assert!(image::load_from_memory(&png).is_ok());
}
#[test]
fn home_after_scrolling_right_brings_the_view_back() {
let tmp = tempfile::tempdir().unwrap();
let (mut app, _term) = wide_line_app(tmp.path());
app.handle_key(key(KeyCode::End, KeyModifiers::NONE))
.unwrap();
app.editor.scroll_col = 500;
app.editor.cursor_col = 600;
app.handle_key(key(KeyCode::Home, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.cursor_col, 0);
assert_eq!(app.editor.scroll_col, 0);
}
#[test]
fn a_windows_1252_file_gets_gutter_marks_after_reopen_with_encoding() {
let (tmp, f) = encoded_repo("latin1.txt", LATIN1_HEAD, LATIN1_ADDED);
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
app.sync_git_gutters();
app.editor
.reopen_with_encoding(encoding_rs::WINDOWS_1252)
.unwrap();
app.sync_git_gutters();
assert_eq!(
app.editor.git_head_lines,
Some(crate::packed_lines::PackedLines::from(
&["name;city", "Müller;Köln", "José;Málaga"][..]
))
);
draw(&mut app, 100, 30);
assert_eq!(
app.editor.git_mark_at(3),
Some(crate::widgets::editor::GitMark::Added)
);
assert_eq!(app.editor.git_mark_at(1), None);
}
#[test]
fn a_utf16_file_gets_gutter_marks() {
let utf16 = |s: &str| -> Vec<u8> { s.encode_utf16().flat_map(u16::to_le_bytes).collect() };
let head = [&[0xff, 0xfe][..], &utf16("one\ntwo\n")].concat();
let (tmp, f) = encoded_repo("app.rc", &head, &utf16("three\n"));
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open_pinned(&f).unwrap();
app.sync_git_gutters();
assert_eq!(
app.editor.git_head_lines,
Some(crate::packed_lines::PackedLines::from(&["one", "two"][..]))
);
draw(&mut app, 100, 30);
assert_eq!(
app.editor.git_mark_at(2),
Some(crate::widgets::editor::GitMark::Added)
);
}
fn text_minimap_app() -> (tempfile::TempDir, App) {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("long.rs");
let body: String = (0..300)
.map(|i| format!("fn f{i}() {{ let value = {i}; }}\n"))
.collect();
std::fs::write(&path, body).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.inline_protocol = crate::iterm2_inline::InlineImageProtocol::None;
app.cell_pixel = None;
app.editor.open(&path).unwrap();
(tmp, app)
}
fn is_braille(s: &str) -> bool {
s.chars()
.next()
.is_some_and(|c| ('\u{2801}'..='\u{28ff}').contains(&c))
}
fn braille_in(term: &ratatui::Terminal<ratatui::backend::TestBackend>, r: Rect) -> usize {
let buf = term.backend().buffer();
let mut n = 0;
for y in r.y..r.y + r.height {
for x in r.x..r.x + r.width {
if is_braille(buf[(x, y)].symbol()) {
n += 1;
}
}
}
n
}
#[test]
fn the_minimap_draws_as_braille_without_inline_images() {
let (_tmp, mut app) = text_minimap_app();
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 40)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let strip = app.minimap.img_rect;
assert_eq!(strip.width, 6, "the strip is carved: {strip:?}");
assert!(
braille_in(&term, strip) > 0,
"the strip shows the file's shape:\n{}",
screen_text(&term)
);
let text = app.editor.last_full_area;
assert_eq!(
strip.x,
text.x + text.width,
"the strip sits right of the text"
);
}
#[test]
fn a_loch_tab_strip_and_header_seam_run_through_the_minimap_column() {
let (_tmp, mut app) = text_minimap_app();
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 40)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let t = crate::theme::tones(app.theme).expect("Loch is the default");
let strip = app.minimap.img_rect;
let top = app.editor.last_full_area.y;
let seam_y = app.editor.last_body.y;
let buf = term.backend().buffer();
for x in strip.x..strip.x + strip.width {
assert_eq!(buf[(x, top)].bg, app.theme.tab_strip_bg(), "column {x}");
assert_eq!(buf[(x, seam_y)].symbol(), "\u{2594}", "column {x}");
assert_eq!(buf[(x, seam_y)].fg, t.hairline());
}
}
#[test]
fn a_modal_quick_input_takes_the_accent_off_the_editor_seam() {
let (_tmp, mut app) = text_minimap_app();
app.focus_pane(Pane::Editor);
let t = crate::theme::tones(app.theme).expect("Loch is the default");
let seam = |app: &mut App| {
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 40)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let body = app.editor.last_body;
term.backend().buffer()[(body.x, body.y)].fg
};
let theme = app.theme;
let behind_scrim = |c: ratatui::style::Color| {
let mut b = ratatui::buffer::Buffer::empty(Rect::new(0, 0, 1, 1));
b[(0, 0)].set_fg(c).set_bg(t.canvas());
crate::widgets::surface::dim_backdrop(&mut b, Rect::default(), theme);
b[(0, 0)].fg
};
assert_eq!(seam(&mut app), t.accent(), "the focused editor's lip");
app.open_command_palette();
let palette_open = seam(&mut app);
assert_eq!(
palette_open,
behind_scrim(t.hairline()),
"the palette has the keyboard"
);
assert_ne!(palette_open, behind_scrim(t.accent()));
assert!(app.focus == Pane::Editor && app.editor.focused);
app.command_palette = None;
assert_eq!(seam(&mut app), t.accent());
}
#[test]
fn loch_layout_icons_rest_muted_and_lift_on_a_chip() {
let (_tmp, mut app) = text_minimap_app();
app.chrome_bake = None;
app.overlays.activity.clear_images();
draw(&mut app, 160, 40);
let t = crate::theme::tones(app.theme).expect("Loch is the default");
let side = app.layout_icon_areas.toggle_side_bar;
let cust = app.layout_icon_areas.customize;
assert!(side.width == 2 && cust.width == 2);
app.pointer_cell = Some((cust.x, cust.y));
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 40)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let buf = term.backend().buffer();
let idle = &buf[(side.x + 1, side.y)];
assert_eq!(idle.fg, t.muted());
assert_eq!(idle.bg, app.theme.tab_strip_bg(), "no chip at rest");
let chip = t.hover_on(t.chrome);
assert_eq!(buf[(cust.x + 1, cust.y)].fg, t.strong());
assert_eq!(buf[(cust.x, cust.y)].bg, chip);
assert_eq!(buf[(cust.x + 1, cust.y)].bg, chip);
}
#[test]
fn a_click_on_the_text_minimap_jumps_to_that_part_of_the_file() {
let (_tmp, mut app) = text_minimap_app();
draw(&mut app, 160, 40);
let strip = app.minimap.img_rect;
assert!(strip.height > 0);
assert_eq!(app.editor.scroll, 0);
left_click(&mut app, strip.x + 2, strip.y + strip.height - 1);
assert!(
app.editor.cursor_row > 250,
"the bottom of the strip is the end of the file: row {}",
app.editor.cursor_row
);
}
#[test]
fn the_minimap_stays_on_the_active_group_in_a_split() {
let (_tmp, mut app) = text_minimap_app();
app.split_editor();
assert!(app.editor_layout.is_split());
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(200, 40)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let strip = app.minimap.img_rect;
let active = app.editor.last_full_area;
assert_eq!(strip.width, 6, "a split keeps the minimap: {strip:?}");
assert!(braille_in(&term, strip) > 0, "{}", screen_text(&term));
assert!(
strip.x == active.x + active.width || strip.x + strip.width == active.x,
"the strip is beside the active group: strip {strip:?}, group {active:?}"
);
}
#[test]
fn the_minimap_off_draws_no_strip() {
let (_tmp, mut app) = text_minimap_app();
app.toggle_minimap();
assert_eq!(app.status, "Minimap off");
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(160, 40)).unwrap();
term.draw(|f| app.render(f)).unwrap();
assert_eq!(app.minimap.img_rect, Rect::default());
let screen = screen_text(&term);
assert!(
!screen.chars().any(|c| is_braille(&c.to_string())),
"{screen}"
);
}
#[test]
fn turning_the_minimap_on_in_a_narrow_editor_says_why_it_is_hidden() {
let (_tmp, mut app) = text_minimap_app();
app.toggle_minimap();
draw(&mut app, 70, 30);
app.toggle_minimap();
assert!(
app.status.starts_with("Minimap on") && app.status.contains("wide"),
"{}",
app.status
);
app.toggle_minimap();
draw(&mut app, 160, 40);
app.toggle_minimap();
assert_eq!(app.status, "Minimap on");
}
#[test]
fn braille_minimap_folds_each_two_by_four_dot_block_into_a_cell() {
let bg = (0, 0, 0);
let ink = (200, 100, 50);
let (w, h) = (2 * MINIMAP_TEXT_CHARS_PER_DOT, 4);
let mut rgba = vec![0u8; (w * h * 4) as usize];
for px in rgba.chunks_exact_mut(4) {
px[3] = 0xff;
}
let cells = braille_minimap(&rgba, w, h, bg, 1, 1);
assert_eq!(cells, vec![None], "a blank block is a blank cell");
let idx = 4;
rgba[idx..idx + 3].copy_from_slice(&[ink.0, ink.1, ink.2]);
assert_eq!(
braille_minimap(&rgba, w, h, bg, 1, 1),
vec![Some(('\u{2801}', ink))]
);
for px in rgba.chunks_exact_mut(4) {
px[..3].copy_from_slice(&[ink.0, ink.1, ink.2]);
}
assert_eq!(
braille_minimap(&rgba, w, h, bg, 1, 1),
vec![Some(('\u{28ff}', ink))]
);
}
#[test]
fn shift_end_in_a_wrapped_paragraph_selects_to_the_end_of_the_row() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("long.txt");
let words: Vec<String> = (0..60).map(|i| format!("word{i}")).collect();
std::fs::write(&f, format!("Notes: {}\n", words.join(" "))).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&f).unwrap();
app.editor.toggle_wrap();
assert!(app.editor.wrap_enabled());
app.focus_pane(Pane::Editor);
draw(&mut app, 100, 30);
app.handle_editor_key(key(KeyCode::Down, KeyModifiers::NONE));
let row_start = app.editor.cursor_col;
assert!(row_start > 0, "Down moved onto row 2 of line 1");
app.handle_editor_key(key(KeyCode::End, KeyModifiers::SHIFT));
let selected = app.editor.selection_text();
assert!(
!selected.is_empty() && selected.len() < 60,
"one row, not the paragraph: {selected:?}"
);
assert_eq!(
app.editor.lines[0].chars().nth(app.editor.cursor_col),
Some(' '),
"up to the space the row breaks at: {selected:?}"
);
app.handle_editor_key(key(KeyCode::End, KeyModifiers::SHIFT));
let selected = app.editor.selection_text();
assert!(selected.ends_with("word59"), "{selected:?}");
}
#[test]
fn ctrl_a_and_ctrl_e_reach_the_line_ends_in_a_wrapped_paragraph() {
let tmp = tempfile::tempdir().unwrap();
let f = tmp.path().join("long.txt");
let words: Vec<String> = (0..60).map(|i| format!("word{i}")).collect();
std::fs::write(&f, format!("Notes: {}\n", words.join(" "))).unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.editor.open(&f).unwrap();
app.editor.toggle_wrap();
assert!(app.editor.wrap_enabled());
app.focus_pane(Pane::Editor);
draw(&mut app, 100, 30);
app.handle_editor_key(key(KeyCode::Down, KeyModifiers::NONE));
assert!(app.editor.cursor_col > 0, "Down moved onto row 2 of line 1");
let mid_row = app.editor.cursor_col + 3;
app.handle_editor_key(key(KeyCode::Char('e'), KeyModifiers::CONTROL));
assert_eq!(app.editor.cursor_col, app.editor.lines[0].chars().count());
app.editor.cursor_col = mid_row;
app.handle_editor_key(key(KeyCode::Char('a'), KeyModifiers::CONTROL));
assert_eq!(app.editor.cursor_col, 0);
}
#[test]
fn change_line_numbers_cycles_modes_across_every_editor() {
use crate::widgets::editor::LineNumbers;
let mut app = editor_app_with_lines(&["a b"]);
let all_in =
|app: &App, mode: LineNumbers| app.editor.editors.iter().all(|e| e.line_numbers == mode);
assert_eq!(app.line_numbers, LineNumbers::On, "on by default");
let mut seen = Vec::new();
for _ in 0..4 {
app.run_command(crate::widgets::command_palette::Command::CycleLineNumbers);
app.editor
.open_text_buffer(std::path::Path::new("later.txt"), "c d")
.unwrap();
app.sync_focus_flags();
assert!(all_in(&app, app.line_numbers), "{:?}", app.line_numbers);
seen.push(app.status.clone());
}
assert_eq!(
seen,
[
"Line Numbers: relative",
"Line Numbers: interval",
"Line Numbers: off",
"Line Numbers: on"
]
);
}
#[test]
fn line_numbers_reach_every_split_group() {
use crate::widgets::editor::LineNumbers;
let tmp = tempfile::tempdir().unwrap();
let mut app = app_with_open_file(tmp.path(), "a.txt", "a\nb\n");
app.split_editor_dir(editor_layout::SplitDir::Horizontal, true);
let modes = |app: &App| -> Vec<LineNumbers> {
app.editor_layout
.all_groups(&app.editor)
.flat_map(|group| group.editors.iter().map(|e| e.line_numbers))
.collect()
};
assert_eq!(modes(&app), [LineNumbers::On, LineNumbers::On]);
app.run_command(crate::widgets::command_palette::Command::CycleLineNumbers);
assert_eq!(modes(&app), [LineNumbers::Relative, LineNumbers::Relative]);
let prefs = crate::prefs::Prefs {
line_numbers: String::from("off"),
..Default::default()
};
app.apply_merged_settings(&prefs);
assert_eq!(modes(&app), [LineNumbers::Off, LineNumbers::Off]);
}
fn overwrite_app(text: &str) -> (tempfile::TempDir, App) {
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
app.focus = Pane::Editor;
app.editor.lines = text.lines().map(String::from).collect();
app.editor.cursor_row = 0;
app.editor.cursor_col = 0;
(tmp, app)
}
#[test]
fn insert_key_toggles_overwrite_mode_and_typing_replaces() {
let (_t, mut app) = overwrite_app("abcdef");
app.handle_key(key(KeyCode::Char('X'), KeyModifiers::NONE))
.unwrap();
assert_eq!(
app.editor.lines[0], "Xabcdef",
"insert mode pushes the text"
);
app.handle_key(key(KeyCode::Insert, KeyModifiers::NONE))
.unwrap();
assert!(app.overwrite_mode);
assert_eq!(app.status, "Overwrite mode");
app.handle_key(key(KeyCode::Char('Y'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('Z'), KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.lines[0], "XYZcdef", "overwrite replaces a, b");
assert_eq!(app.editor.cursor_col, 3);
app.handle_key(key(KeyCode::Insert, KeyModifiers::NONE))
.unwrap();
assert!(!app.overwrite_mode);
assert_eq!(app.status, "Insert mode");
app.handle_key(key(KeyCode::Char('!'), KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.lines[0], "XYZ!cdef");
}
#[test]
fn overwrite_appends_at_the_end_of_a_line_and_replaces_a_whole_emoji() {
let (_t, mut app) = overwrite_app("a\u{1F468}\u{200D}\u{1F469}b");
app.overwrite_mode = true;
app.editor.cursor_col = 1;
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.lines[0], "axb", "the ZWJ cluster goes as one");
app.editor.cursor_col = 3;
app.handle_key(key(KeyCode::Char('!'), KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.lines[0], "axb!", "at the line end it appends");
}
#[test]
fn overwrite_typing_undoes_in_one_step_and_a_selection_is_replaced_as_usual() {
let (_t, mut app) = overwrite_app("hello");
app.overwrite_mode = true;
app.handle_key(key(KeyCode::Char('J'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('K'), KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.lines[0], "JKllo");
app.editor.undo();
assert_eq!(app.editor.lines[0], "hello", "one undo step for the run");
app.editor.cursor_col = 1;
app.editor.selection = Some(crate::widgets::editor::EditorSelection {
anchor: (0, 1),
head: (0, 4),
});
app.editor.cursor_col = 4;
app.handle_key(key(KeyCode::Char('_'), KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.lines[0], "h_o", "a selection is replaced, once");
}
#[test]
fn switching_the_typing_mode_starts_a_new_undo_step() {
let (_t, mut app) = overwrite_app("hello");
app.handle_key(key(KeyCode::Char('A'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Insert, KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('B'), KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.lines[0], "ABello");
app.editor.undo();
assert_eq!(
app.editor.lines[0], "Ahello",
"the overwrite run undoes on its own"
);
app.editor.undo();
assert_eq!(app.editor.lines[0], "hello");
}
#[test]
fn overwrite_leaves_the_caret_after_a_cluster_the_typed_char_joins() {
let (_t, mut app) = overwrite_app("a\u{1F1EB}\u{1F1F7}");
app.overwrite_mode = true;
app.handle_key(key(KeyCode::Char('\u{1F1FA}'), KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.lines[0], "\u{1F1FA}\u{1F1EB}\u{1F1F7}");
assert_eq!(app.editor.cursor_col, 2, "after the joined pair");
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
assert_eq!(
app.editor.lines[0], "\u{1F1FA}\u{1F1EB}x",
"the next key replaces the cluster after the caret"
);
}
#[test]
fn overwrite_adds_a_combining_mark_to_the_letter_before_the_caret() {
let (_t, mut app) = overwrite_app("abcd");
app.overwrite_mode = true;
app.handle_key(key(KeyCode::Char('e'), KeyModifiers::NONE))
.unwrap();
app.handle_key(key(KeyCode::Char('\u{301}'), KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.lines[0], "e\u{301}bcd");
assert_eq!(app.editor.cursor_col, 2);
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
assert_eq!(
app.editor.lines[0], "e\u{301}xcd",
"the next key replaces again"
);
app.editor.undo();
assert_eq!(
app.editor.lines[0], "abcd",
"still one undo step for the run"
);
}
#[test]
fn overwrite_steps_past_an_emoji_a_typed_zwj_joins() {
let (_t, mut app) = overwrite_app("\u{1F469}\u{1F4BB}x");
app.overwrite_mode = true;
app.editor.cursor_col = 1;
app.handle_key(key(KeyCode::Char('\u{200D}'), KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.lines[0], "\u{1F469}\u{200D}\u{1F4BB}x");
assert_eq!(app.editor.cursor_col, 3, "after the joined emoji");
app.handle_key(key(KeyCode::Char('a'), KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.lines[0], "\u{1F469}\u{200D}\u{1F4BB}a");
}
#[test]
fn overwrite_drops_the_empty_selection_a_click_leaves() {
let (_t, mut app) = overwrite_app("abcd");
app.overwrite_mode = true;
app.editor.selection = Some(crate::widgets::editor::EditorSelection {
anchor: (0, 0),
head: (0, 0),
});
app.handle_key(key(KeyCode::Char('x'), KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.lines[0], "xbcd");
assert!(
app.editor.selection.is_none(),
"no stale anchor for a later Shift+arrow"
);
}
#[test]
fn overwrite_mode_is_shown_by_a_glyph_after_the_workspace_cap_not_in_the_position() {
let (_t, mut app) = overwrite_app("abc");
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 30)).unwrap();
let bar = |t: &ratatui::Terminal<ratatui::backend::TestBackend>| -> String {
let b = t.backend().buffer();
let y = b.area.height - 1;
(0..b.area.width)
.map(|x| b[(x, y)].symbol().to_string())
.collect()
};
term.draw(|f| app.render(f)).unwrap();
let insert = bar(&term);
assert!(
!insert.contains('\u{2380}') && !insert.contains('\u{2381}'),
"Insert, the default, adds nothing to the bar: {insert}"
);
app.handle_key(key(KeyCode::Insert, KeyModifiers::NONE))
.unwrap();
term.draw(|f| app.render(f)).unwrap();
let over = bar(&term);
assert!(
over.contains("\u{e0b4} \u{2381}"),
"overwrite glyph after the workspace cap: {over}"
);
assert!(!over.contains("OVR"), "the Ln/Col segment stays unchanged");
}
#[test]
fn centring_a_line_before_the_first_render_leaves_context_above() {
let mut e = crate::widgets::editor::Editor::new();
e.lines = (0..200).map(|i| format!("line {i}")).collect();
assert_eq!(e.text_rows(), 0, "precondition: not rendered yet");
e.goto_line_centered(100);
assert_eq!(e.cursor_row, 100);
assert_eq!(e.scroll, 95, "five lines of context above the target");
e.goto_line_centered(2);
assert_eq!(e.scroll, 0, "near the top it saturates at 0");
}
#[test]
fn a_crowded_tab_strip_offers_a_list_of_all_open_tabs() {
use crate::widgets::list_picker::ListPurpose;
let tmp = tempfile::tempdir().unwrap();
let mut app = App::new(tmp.path().to_path_buf()).unwrap();
for i in 0..14 {
let f = tmp.path().join(format!("a_rather_long_name_{i:02}.txt"));
std::fs::write(&f, "x\n").unwrap();
app.editor.open_pinned(&f).unwrap();
}
let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 30)).unwrap();
term.draw(|f| app.render(f)).unwrap();
let y = app.editor.tab_strip_y_for_test();
let col = (0..100)
.find(|&c| app.editor.tab_list_button_at(c, y))
.expect("the tabs overflow, so the strip draws the list button");
assert_eq!(app.ui_tooltip_at(col, y), Some("Show All Open Tabs"));
app.handle_mouse(mouse(
crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
col,
y,
));
let picker = app.list_picker.as_ref().expect("the button opens the list");
assert_eq!(picker.purpose, ListPurpose::OpenTab);
assert_eq!(picker.rows.len(), 14);
assert_eq!(picker.selected, 13, "the active tab is the selected row");
for _ in 0..13 {
app.handle_key(key(KeyCode::Up, KeyModifiers::NONE))
.unwrap();
}
app.handle_key(key(KeyCode::Enter, KeyModifiers::NONE))
.unwrap();
assert_eq!(app.editor.active_index(), 0);
term.draw(|f| app.render(f)).unwrap();
assert!(
app.editor.tab_screen_x(0).is_some_and(|(_, w)| w > 0),
"the picked tab is on screen"
);
}