use super::*;
use crate::color::ResolvedColor;
use crate::compositor::layout::cell::{Cell, CellBuffer, CellStyle};
use crate::compositor::present::render_full;
use std::fmt::Write as _;
use std::path::PathBuf;
use std::time::{Duration, Instant};
fn fixtures_dir() -> PathBuf {
let mut p = crate::repository_root();
p.push("tests");
p.push("integration");
p.push("fixtures");
p.push("parity");
p
}
fn parse_aml(src: &str) -> Document {
let mut scanner = crate::scanner::Scanner::new(src.as_bytes()).unwrap();
let tokens = scanner.scan_all().unwrap();
crate::parser::parse(tokens)
.document
.expect("AML parse failed in parity harness")
}
async fn build_page(aml: &str, term_w: u16, term_h: u16) -> LoadedPage {
let doc = parse_aml(aml);
layout_page(
doc,
term_w,
term_h,
ColorSupport::Truecolor,
WidthConfig::default(),
None,
None,
None,
)
.await
}
struct Frame {
bytes: Vec<u8>,
grid: CellBuffer,
}
fn render_composite_frame(
compositor: &mut Compositor,
page: &mut LoadedPage,
state: &ViewportState,
) -> Frame {
let grid_rc = composite_pass(compositor, page, state).unwrap();
let mut bytes: Vec<u8> = Vec::new();
render_full(
&mut bytes,
&grid_rc,
state.scroll_offset,
state.scroll_height(),
)
.unwrap();
let grid = grid_rc.try_clone().unwrap();
Frame { bytes, grid }
}
async fn capture_frames(aml: &str, term_w: u16, term_h: u16, n_ticks: usize) -> Vec<Frame> {
let mut page = build_page(aml, term_w, term_h).await;
let mut compositor = Compositor::new(term_w, page.buf.height);
let state = ViewportState::with_sticky(term_w, term_h, page.buf.height, &page.sticky_buf);
let mut frames = Vec::with_capacity(n_ticks + 1);
frames.push(render_composite_frame(&mut compositor, &mut page, &state));
if n_ticks == 0 {
return frames;
}
let base = Instant::now();
for i in 0..n_ticks {
let now = base + Duration::from_millis(33 * (i as u64 + 1));
let tick_result = page.anim_rt.tick(
&mut page.scene,
now,
state.scroll_offset,
state.viewport_height(),
);
if tick_result.changed {
PatchApplier::apply_all(&mut page.scene, tick_result.patches);
page.anim_rt.paint_into_scene(&mut page.scene);
}
frames.push(render_composite_frame(&mut compositor, &mut page, &state));
}
frames
}
fn serialize_color(c: ResolvedColor) -> String {
match c {
ResolvedColor::Named(n) => format!("n:{:?}", n),
ResolvedColor::Palette(i) => format!("p:{}", i),
ResolvedColor::Rgb(r, g, b) => format!("r:{:02x}{:02x}{:02x}", r, g, b),
}
}
fn cell_is_default(cell: &Cell) -> bool {
cell.ch == ' ' && cell.style == CellStyle::default()
}
fn serialize_cell_record(x: u16, y: u16, cell: &Cell) -> String {
let mut s = format!("{},{} {:?}", x, y, cell.ch);
if let Some(fg) = cell.style.fg {
write!(&mut s, " fg={}", serialize_color(fg)).unwrap();
}
if let Some(bg) = cell.style.bg {
write!(&mut s, " bg={}", serialize_color(bg)).unwrap();
}
for (flag, tag) in [
(cell.style.bold, "bold"),
(cell.style.italic, "italic"),
(cell.style.underline, "underline"),
(cell.style.strikethrough, "strike"),
(cell.style.dim, "dim"),
(cell.style.blink, "blink"),
] {
if flag {
s.push(' ');
s.push_str(tag);
}
}
s
}
fn serialize_grid(buf: &CellBuffer) -> String {
let mut out = String::new();
writeln!(&mut out, "grid {}x{}", buf.width, buf.height).unwrap();
for y in 0..buf.height {
for x in 0..buf.width {
let cell = buf.get(x, y).expect("in-bounds cell");
if cell_is_default(cell) {
continue;
}
out.push_str(&serialize_cell_record(x, y, cell));
out.push('\n');
}
}
out
}
fn update_goldens() -> bool {
std::env::var("UPDATE_GOLDENS")
.map(|v| v == "1")
.unwrap_or(false)
}
fn assert_byte_golden(actual: &[u8], name: &str) {
let dir = fixtures_dir();
std::fs::create_dir_all(&dir).expect("create parity fixtures dir");
let path = dir.join(format!("{name}.ansi"));
if update_goldens() {
std::fs::write(&path, actual).expect("write byte golden");
return;
}
let expected = std::fs::read(&path).unwrap_or_else(|_| {
panic!(
"byte golden missing: {}\nrun `UPDATE_GOLDENS=1 cargo test` to create",
path.display()
)
});
if actual != expected.as_slice() {
panic!(
"byte parity mismatch for {name}: {} vs {} bytes\n(rerun with UPDATE_GOLDENS=1 to regenerate, only after auditing the diff)",
actual.len(),
expected.len(),
);
}
}
fn assert_grid_golden(actual: &CellBuffer, name: &str) {
let dir = fixtures_dir();
std::fs::create_dir_all(&dir).expect("create parity fixtures dir");
let path = dir.join(format!("{name}.grid"));
let serialized = serialize_grid(actual);
if update_goldens() {
std::fs::write(&path, &serialized).expect("write grid golden");
return;
}
let expected = std::fs::read_to_string(&path).unwrap_or_else(|_| {
panic!(
"grid golden missing: {}\nrun `UPDATE_GOLDENS=1 cargo test` to create",
path.display()
)
});
if serialized != expected {
let diff_line = serialized
.lines()
.zip(expected.lines())
.enumerate()
.find(|(_, (a, b))| a != b)
.map(|(i, (a, b))| format!("line {i}: actual=`{a}` expected=`{b}`"))
.unwrap_or_else(|| {
format!(
"length differs: actual={} expected={}",
serialized.lines().count(),
expected.lines().count()
)
});
panic!(
"grid parity mismatch for {name}: {}\n(rerun with UPDATE_GOLDENS=1 to regenerate, only after auditing the diff)",
diff_line
);
}
}
fn assert_frame_golden(frame: &Frame, name: &str) {
assert_grid_golden(&frame.grid, name);
assert_byte_golden(&frame.bytes, name);
}
const AML_STATIC_TEXT: &str = r#"[page mode=document]
[text]Hello, world[/text]
[box w=20 border=single]
[text]Inside a box[/text]
[/box]
[/page]"#;
const AML_PANEL: &str = r#"[page mode=screen cols=40 rows=10]
[panel id="p" state="a"]
[state name="a" x=0 y=0 w=40 h=5][text]State A[/text][/state]
[state name="b" x=0 y=0 w=40 h=5][text]State B[/text][/state]
[/panel]
[/page]"#;
const AML_LAYERS: &str = r#"[page mode=screen cols=40 rows=10]
[box x=0 y=0 w=40 h=10 bg=blue][text]background[/text][/box]
[box x=5 y=2 w=20 h=4 border=single bg=black][text]foreground[/text][/box]
[/page]"#;
const AML_ABSOLUTE_OVER_FLOW: &str = r#"[page mode=screen cols=40 rows=10]
[text fg=yellow]aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[/text]
[text fg=yellow]bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb[/text]
[text fg=yellow]cccccccccccccccccccccccccccccccccccccccc[/text]
[box x=10 y=1 w=15 h=3 border=single bg=red fg=white][text]OVERLAY[/text][/box]
[/page]"#;
const AML_INLINE_LINK_IN_TEXT: &str = r#"[page mode=screen cols=40 rows=6]
[text]Click [link href="atp://example.com"]here[/link] to navigate, then read on.[/text]
[/page]"#;
const AML_TABLE_CELLS: &str = r#"[page mode=screen cols=40 rows=8]
[table]
[thead]
[tr][th]Name[/th][th]Qty[/th][/tr]
[/thead]
[tbody]
[tr][td]apple[/td][td]3[/td][/tr]
[tr][td]pear[/td][td]12[/td][/tr]
[/tbody]
[/table]
[/page]"#;
const AML_STICKY_WITH_SCROLL: &str = r#"[page mode=document]
[box sticky=top w=40 bg=blue fg=white][text]STICKY HEADER[/text][/box]
[text]row 1[/text]
[text]row 2[/text]
[text]row 3[/text]
[text]row 4[/text]
[/page]"#;
const AML_NESTED_PANELS: &str = r#"[page mode=screen cols=40 rows=10]
[panel id="outer" state="x"]
[state name="x" x=0 y=0 w=40 h=10]
[box w=40 bg=blue fg=white][text]outer X[/text][/box]
[panel id="inner" state="p"]
[state name="p" x=0 y=3 w=20 h=4][text]inner P[/text][/state]
[state name="q" x=0 y=3 w=20 h=4][text]inner Q[/text][/state]
[/panel]
[/state]
[state name="y" x=0 y=0 w=40 h=10][text]outer Y[/text][/state]
[/panel]
[/page]"#;
const AML_LIVE_REGION: &str = r#"[page mode=screen cols=40 rows=6]
[text]before[/text]
[live src="atp://example.com/events" h=3][/live]
[text]after[/text]
[/page]"#;
#[cfg_attr(miri, ignore = "tokio runtime needs kqueue, which Miri cannot emulate")]
#[tokio::test]
async fn parity_static_text() {
let frames = capture_frames(AML_STATIC_TEXT, 40, 10, 0).await;
assert_eq!(frames.len(), 1);
assert_frame_golden(&frames[0], "static_text");
}
#[cfg_attr(miri, ignore = "tokio runtime needs kqueue, which Miri cannot emulate")]
#[tokio::test]
async fn parity_panel_static() {
let frames = capture_frames(AML_PANEL, 40, 10, 0).await;
assert_eq!(frames.len(), 1);
assert_frame_golden(&frames[0], "panel_static");
}
#[cfg_attr(miri, ignore = "tokio runtime needs kqueue, which Miri cannot emulate")]
#[tokio::test]
async fn parity_layers() {
let frames = capture_frames(AML_LAYERS, 40, 10, 0).await;
assert_eq!(frames.len(), 1);
assert_frame_golden(&frames[0], "layers");
}
#[cfg_attr(miri, ignore = "tokio runtime needs kqueue, which Miri cannot emulate")]
#[tokio::test]
async fn parity_absolute_over_flow() {
let frames = capture_frames(AML_ABSOLUTE_OVER_FLOW, 40, 10, 0).await;
assert_eq!(frames.len(), 1);
assert_frame_golden(&frames[0], "absolute_over_flow");
}
#[cfg_attr(miri, ignore = "tokio runtime needs kqueue, which Miri cannot emulate")]
#[tokio::test]
async fn parity_inline_link_in_text() {
let frames = capture_frames(AML_INLINE_LINK_IN_TEXT, 40, 6, 0).await;
assert_eq!(frames.len(), 1);
assert_frame_golden(&frames[0], "inline_link_in_text");
}
#[cfg_attr(miri, ignore = "tokio runtime needs kqueue, which Miri cannot emulate")]
#[tokio::test]
async fn parity_table_cells() {
let frames = capture_frames(AML_TABLE_CELLS, 40, 8, 0).await;
assert_eq!(frames.len(), 1);
assert_frame_golden(&frames[0], "table_cells");
}
#[cfg_attr(miri, ignore = "tokio runtime needs kqueue, which Miri cannot emulate")]
#[tokio::test]
async fn parity_sticky_with_scroll() {
let frames = capture_frames(AML_STICKY_WITH_SCROLL, 40, 8, 0).await;
assert_eq!(frames.len(), 1);
assert_frame_golden(&frames[0], "sticky_with_scroll");
}
#[cfg_attr(miri, ignore = "tokio runtime needs kqueue, which Miri cannot emulate")]
#[tokio::test]
async fn parity_nested_panels() {
let frames = capture_frames(AML_NESTED_PANELS, 40, 10, 0).await;
assert_eq!(frames.len(), 1);
assert_frame_golden(&frames[0], "nested_panels");
}
#[cfg_attr(miri, ignore = "tokio runtime needs kqueue, which Miri cannot emulate")]
#[tokio::test]
async fn parity_live_region() {
let frames = capture_frames(AML_LIVE_REGION, 40, 6, 0).await;
assert_eq!(frames.len(), 1);
assert_frame_golden(&frames[0], "live_region");
}
#[test]
fn grid_serializer_skips_default_cells() {
use crate::color::NamedColor;
let mut buf = CellBuffer::new(4, 2);
buf.put_char(
1,
0,
'X',
&CellStyle {
fg: Some(ResolvedColor::Named(NamedColor::Red)),
bold: true,
..Default::default()
},
);
let out = serialize_grid(&buf);
assert_eq!(out, "grid 4x2\n1,0 'X' fg=n:Red bold\n");
}
#[test]
fn grid_serializer_is_deterministic() {
let mut buf = CellBuffer::new(3, 3);
buf.put_char(2, 1, 'b', &CellStyle::default());
buf.put_char(0, 2, 'a', &CellStyle::default());
let s1 = serialize_grid(&buf);
let s2 = serialize_grid(&buf);
assert_eq!(s1, s2);
let idx_b = s1.find("2,1 'b'").unwrap();
let idx_a = s1.find("0,2 'a'").unwrap();
assert!(idx_b < idx_a, "records must be sorted by (y,x) row-major");
}