From 35924cfbf591203efb5bc03336d88013cf42a5ac Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 28 Nov 2026 10:08:49 +0100 Subject: [PATCH] Thing 2.0 cut 8a: thing-tui paint, not-representable table, screen diff; Cells Button content inset one cell Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 9 + crates/thing-core/src/layout/measure.rs | 7 + crates/thing-core/src/layout/tree.rs | 5 +- crates/thing-tui/Cargo.toml | 18 ++ crates/thing-tui/src/diff.rs | 79 +++++ crates/thing-tui/src/lib.rs | 12 + crates/thing-tui/src/paint.rs | 374 ++++++++++++++++++++++++ crates/thing-tui/src/screen.rs | 117 ++++++++ crates/thing-tui/tests/common/mod.rs | 62 ++++ crates/thing-tui/tests/diff.rs | 199 +++++++++++++ crates/thing-tui/tests/paint.rs | 260 ++++++++++++++++ crates/thing-tui/tests/screen.rs | 78 +++++ 12 files changed, 1219 insertions(+), 1 deletion(-) create mode 100644 crates/thing-tui/Cargo.toml create mode 100644 crates/thing-tui/src/diff.rs create mode 100644 crates/thing-tui/src/lib.rs create mode 100644 crates/thing-tui/src/paint.rs create mode 100644 crates/thing-tui/src/screen.rs create mode 100644 crates/thing-tui/tests/common/mod.rs create mode 100644 crates/thing-tui/tests/diff.rs create mode 100644 crates/thing-tui/tests/paint.rs create mode 100644 crates/thing-tui/tests/screen.rs diff --git a/Cargo.lock b/Cargo.lock index c94a05f..322564d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -564,6 +564,15 @@ dependencies = [ "thing-state", ] +[[package]] +name = "thing-tui" +version = "0.1.0" +dependencies = [ + "thing-contract", + "thing-core", + "thing-testkit", +] + [[package]] name = "typenum" version = "1.20.1" diff --git a/crates/thing-core/src/layout/measure.rs b/crates/thing-core/src/layout/measure.rs index 079a082..5e1eadb 100644 --- a/crates/thing-core/src/layout/measure.rs +++ b/crates/thing-core/src/layout/measure.rs @@ -123,6 +123,13 @@ impl Device { if self.cells { 1.0 } else { self.px(16.0) } } + /// A Button's content inset from its border, left and right: none in Pixels (render draws the + /// chrome behind the content), one cell in Cells, where a one-row Button's `[` and `]` stand + /// in its first and last cell. + pub(super) fn button_inset(self) -> f32 { + if self.cells { 1.0 } else { 0.0 } + } + /// A Plot's size: the CSS default object size, 300x150 logical px, or 38x10 cells. A plot is /// sized by layout, never measured. pub(super) fn plot(self) -> (f32, f32) { diff --git a/crates/thing-core/src/layout/tree.rs b/crates/thing-core/src/layout/tree.rs index a5f049f..61696ae 100644 --- a/crates/thing-core/src/layout/tree.rs +++ b/crates/thing-core/src/layout/tree.rs @@ -189,7 +189,10 @@ impl<'a> Builder<'a, '_> { } Node::Button(b) => { if !self.hidden(&b.common.id) { - self.container(&b.common.id, parent, (Style::default(), Vec::new()), &Overflow::Visible, &b.content, out); + let side = taffy::LengthPercentage::length(self.dev.button_inset()); + let none = taffy::LengthPercentage::length(0.0); + let style = Style { padding: taffy::Rect { left: side, right: side, top: none, bottom: none }, ..Style::default() }; + self.container(&b.common.id, parent, (style, Vec::new()), &Overflow::Visible, &b.content, out); } } // A Repeat has no box: its instances are its parent's children, in instance order. diff --git a/crates/thing-tui/Cargo.toml b/crates/thing-tui/Cargo.toml new file mode 100644 index 0000000..62a20e4 --- /dev/null +++ b/crates/thing-tui/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "thing-tui" +version = "0.1.0" +edition = "2024" +license = "MIT" +publish = false + +# Map rule 8 as this crate holds it: no DIRECT dependency on taffy, parley, unicode-width, +# unicode-segmentation or unicode-linebreak. Every width this crate advances by arrives in a +# `CellText` from thing-core, and layout is thing-core's. (thing-core links those crates, so they +# are in this crate's full tree; the rule is checked on `cargo tree -e normal --depth 1`.) +# No terminal I/O either: paint and diff are pure, and the live writer is a later cut. +[dependencies] +thing-contract = { path = "../thing-contract" } +thing-core = { path = "../thing-core" } + +[dev-dependencies] +thing-testkit = { path = "../thing-testkit" } diff --git a/crates/thing-tui/src/diff.rs b/crates/thing-tui/src/diff.rs new file mode 100644 index 0000000..0a4e5e7 --- /dev/null +++ b/crates/thing-tui/src/diff.rs @@ -0,0 +1,79 @@ +//! Two screens into the terminal operations between them: only the cells that changed, one move +//! per contiguous run, a style only when it changes. + +use thing_contract::Rgba; +use thing_core::layout::CellStyle; + +use crate::screen::{Cell, Screen}; + +#[derive(Clone, Debug, PartialEq)] +pub enum Op { + MoveTo(usize, usize), + Style(Option, Option, CellStyle), + Print(String), +} + +type Pen = (Option, Option, CellStyle); + +fn pen(cell: &Cell) -> Pen { + (cell.fg.clone(), cell.bg.clone(), cell.style) +} + +struct Writer { + ops: Vec, + text: String, + /// Where the next printed cell lands, when that is known. + cursor: Option<(usize, usize)>, + pen: Option, +} + +impl Writer { + fn flush(&mut self) { + if !self.text.is_empty() { + self.ops.push(Op::Print(std::mem::take(&mut self.text))); + } + } +} + +/// The operations that turn a terminal showing `old` into one showing `new`. A wide cluster is +/// repainted whole when either half changed. After a non-ASCII cluster the cursor is not trusted +/// (a terminal may draw it at another width than the policy), so the next print moves first. A +/// screen of another size repaints every cell. +pub fn diff(old: &Screen, new: &Screen) -> Vec { + let same = (old.cols, old.rows) == (new.cols, new.rows); + let mut w = Writer { ops: Vec::new(), text: String::new(), cursor: None, pen: None }; + for row in 0..new.rows { + let mut col = 0; + while col < new.cols { + let at = row * new.cols + col; + let cell = &new.cells[at]; + let width = usize::from(cell.width).clamp(1, new.cols - col); + if same && new.cells[at..at + width] == old.cells[at..at + width] { + col += width; + continue; + } + let wanted = pen(cell); + let moves = w.cursor != Some((col, row)); + let restyle = w.pen.as_ref() != Some(&wanted); + if moves || restyle { + w.flush(); + } + if moves { + w.ops.push(Op::MoveTo(col, row)); + } + if restyle { + w.ops.push(Op::Style(wanted.0.clone(), wanted.1.clone(), wanted.2)); + w.pen = Some(wanted); + } + w.text += &cell.glyph; + w.cursor = (col + width < new.cols).then_some((col + width, row)); + if !cell.glyph.is_ascii() { + w.flush(); + w.cursor = None; + } + col += width; + } + } + w.flush(); + w.ops +} diff --git a/crates/thing-tui/src/lib.rs b/crates/thing-tui/src/lib.rs new file mode 100644 index 0000000..3763786 --- /dev/null +++ b/crates/thing-tui/src/lib.rs @@ -0,0 +1,12 @@ +//! The pure half of the terminal backend: render commands become a headless cell `Screen`, and two +//! screens become the minimal terminal operations between them. Nothing here touches a terminal, +//! measures a width or breaks a line: every width arrives in a `CellText`, and the layout the +//! commands were made from is thing-core's. + +mod diff; +mod paint; +mod screen; + +pub use diff::{Op, diff}; +pub use paint::{Painted, Representation, paint, representation}; +pub use screen::{Cell, Screen}; diff --git a/crates/thing-tui/src/paint.rs b/crates/thing-tui/src/paint.rs new file mode 100644 index 0000000..bef76be --- /dev/null +++ b/crates/thing-tui/src/paint.rs @@ -0,0 +1,374 @@ +//! Commands into cells. A cell `(c, r)` is covered by a rect exactly when its centre +//! `(c + 0.5, r + 0.5)` lies in `[x, x + w) x [y, y + h)`, so a fractional coordinate needs no +//! rounding policy. Everything a terminal cannot draw is listed in `representation`. + +use thing_contract::Rgba; +use thing_core::layout::{CellStyle, Rect, Run}; +use thing_core::render::RenderCommand; +use thing_core::text::CellText; + +use crate::screen::{Cell, Screen}; + +/// What a frame hands the host beyond cells: the embeds, each the rect, slot kind and slot id of an +/// `Embed` command whose cells were reset to the terminal default. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Painted { + pub embeds: Vec<(Rect, String, String)>, +} + +/// How a command reaches a terminal. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Representation { + Drawn, + /// Drawn as something else, and what. + Approximated(&'static str), +} + +/// The not-representable table: what a terminal cannot draw of each command, and what it draws +/// instead. An exhaustive match, so a new command fails to compile until it has a row. +pub fn representation(command: &RenderCommand) -> Representation { + use Representation::{Approximated, Drawn}; + match command { + RenderCommand::FillRect { radius, .. } if *radius > 0.0 => Approximated("corner radius ignored: a square block of cells"), + RenderCommand::FillRect { .. } => Drawn, + RenderCommand::StrokeRect { width, .. } if *width > 1.0 => Approximated("stroke width ignored: one light line"), + RenderCommand::StrokeRect { .. } => Drawn, + RenderCommand::Text { run: Run::Glyphs { .. }, .. } => Approximated("a shaped glyph run has no cell form: nothing is drawn"), + RenderCommand::Text { .. } => Drawn, + RenderCommand::Image { .. } => Approximated("pixels are not drawn: a shaded block with the alt text on its first row"), + RenderCommand::ClipPush { radius, .. } if *radius > 0.0 => Approximated("clip radius ignored: a rectangle of cells"), + RenderCommand::ClipPush { .. } => Drawn, + RenderCommand::ClipPop => Drawn, + RenderCommand::Polyline { .. } => Approximated("braille dots, two by four to a cell; width ignored"), + RenderCommand::Polygon { .. } => Approximated("the cells whose centre is inside, as background"), + RenderCommand::Embed { .. } => Drawn, + } +} + +/// Paint `commands` in order onto `screen`, which keeps what it held where nothing is drawn. +pub fn paint(commands: &[RenderCommand], screen: &mut Screen) -> Painted { + let whole = Span { c0: 0, c1: screen.cols as i64, r0: 0, r1: screen.rows as i64 }; + let mut canvas = Canvas { screen, clips: vec![whole], painted: Painted::default() }; + for command in commands { + canvas.command(command); + } + canvas.painted +} + +/// A half-open block of cells. +#[derive(Clone, Copy, Debug)] +struct Span { + c0: i64, + c1: i64, + r0: i64, + r1: i64, +} + +impl Span { + fn meet(self, o: Span) -> Span { + let (c0, r0) = (self.c0.max(o.c0), self.r0.max(o.r0)); + Span { c0, c1: self.c1.min(o.c1).max(c0), r0, r1: self.r1.min(o.r1).max(r0) } + } + + fn empty(self) -> bool { + self.c1 <= self.c0 || self.r1 <= self.r0 + } + + fn has(self, c: i64, r: i64) -> bool { + (self.c0..self.c1).contains(&c) && (self.r0..self.r1).contains(&r) + } +} + +/// The cells `[lo, lo + len)` covers along one axis: those whose centre lies inside. +fn cells(lo: f32, len: f32) -> (i64, i64) { + const FAR: f32 = 1.0e6; + if !lo.is_finite() || !len.is_finite() { + return (0, 0); + } + let from = (lo.clamp(-FAR, FAR) - 0.5).ceil() as i64; + let to = ((lo + len).clamp(-FAR, FAR) - 0.5).ceil() as i64; + (from, to.max(from)) +} + +fn span_of(rect: &Rect) -> Span { + let ((c0, c1), (r0, r1)) = (cells(rect.x, rect.w), cells(rect.y, rect.h)); + Span { c0, c1, r0, r1 } +} + +/// `src` over `base` (black where the terminal's own default shows: it is not known). +fn over(src: &Rgba, base: Option<&Rgba>) -> Rgba { + if src.a == 255 { + return src.clone(); + } + let (a, black) = (u32::from(src.a), Rgba { r: 0, g: 0, b: 0, a: 255 }); + let base = base.unwrap_or(&black); + let mix = |s: u8, b: u8| ((u32::from(s) * a + u32::from(b) * (255 - a) + 127) / 255) as u8; + Rgba { r: mix(src.r, base.r), g: mix(src.g, base.g), b: mix(src.b, base.b), a: 255 } +} + +struct Canvas<'a> { + screen: &'a mut Screen, + clips: Vec, + painted: Painted, +} + +impl Canvas<'_> { + fn clip(&self) -> Span { + *self.clips.last().expect("the screen is always a clip") + } + + fn command(&mut self, command: &RenderCommand) { + match command { + RenderCommand::FillRect { rect, color, .. } => self.fill(span_of(rect), color), + RenderCommand::StrokeRect { rect, radius, color, .. } => self.stroke(span_of(rect), *radius > 0.0, color), + RenderCommand::Text { origin, run: Run::Cells { text, style }, color } => { + let (col, row) = (cells(origin.0, 1.0).0, cells(origin.1, 1.0).0); + self.clusters(row, col, text, i64::MAX, Some(color), *style); + } + RenderCommand::Text { .. } => {} + RenderCommand::Image { rect, alt, .. } => self.image(span_of(rect), alt), + RenderCommand::ClipPush { rect, .. } => { + let clip = self.clip().meet(span_of(rect)); + self.clips.push(clip); + } + RenderCommand::ClipPop => { + if self.clips.len() > 1 { + self.clips.pop(); + } + } + RenderCommand::Polyline { points, color, .. } => self.polyline(points, color), + RenderCommand::Polygon { points, color } => self.polygon(points, color), + RenderCommand::Embed { rect, slot_kind, slot_id } => { + let area = span_of(rect).meet(self.clip()); + for r in area.r0..area.r1 { + for c in area.c0..area.c1 { + self.screen.blank_unit(c as usize, r as usize); + *self.screen.at(c as usize, r as usize) = Cell::blank(); + } + } + self.painted.embeds.push((*rect, slot_kind.clone(), slot_id.clone())); + } + } + } + + /// Put one narrow glyph at `(c, r)` if the clip lets it. `fg` composites onto the cell's bg. + fn put(&mut self, c: i64, r: i64, glyph: &str, fg: Option<&Rgba>) { + if !self.clip().has(c, r) { + return; + } + let (c, r) = (c as usize, r as usize); + self.screen.blank_unit(c, r); + let cell = self.screen.at(c, r); + cell.glyph = glyph.to_string(); + cell.fg = fg.map(|color| over(color, cell.bg.as_ref())); + } + + /// Give every wide cluster touched by the `covered` cells of row `r` the colour over its own + /// bg, once. A wide cluster has one background: a terminal cannot colour its halves apart. + fn tint(&mut self, r: i64, covered: impl Fn(i64) -> bool, color: &Rgba) { + if color.a == 0 { + return; + } + let clip = self.clip(); + let row = r as usize; + let mut c = clip.c0; + while c < clip.c1 { + if covered(c) { + let (lead, width) = self.screen.unit(c as usize, row); + let bg = over(color, self.screen.at(lead, row).bg.as_ref()); + for i in lead..lead + width { + self.screen.at(i, row).bg = Some(bg.clone()); + } + c = (lead + width) as i64; + } else { + c += 1; + } + } + } + + fn fill(&mut self, rect: Span, color: &Rgba) { + let area = rect.meet(self.clip()); + if area.empty() { + return; + } + if color.a == 255 { + for r in area.r0..area.r1 { + for c in area.c0..area.c1 { + self.screen.blank_unit(c as usize, r as usize); + self.screen.at(c as usize, r as usize).bg = Some(color.clone()); + } + } + } else { + for r in area.r0..area.r1 { + self.tint(r, |c| (area.c0..area.c1).contains(&c), color); + } + } + } + + fn stroke(&mut self, rect: Span, round: bool, color: &Rgba) { + if rect.empty() { + return; + } + let fg = Some(color); + let (last_c, last_r) = (rect.c1 - 1, rect.r1 - 1); + if rect.r1 - rect.r0 == 1 { + self.put(rect.c0, rect.r0, "[", fg); + if last_c > rect.c0 { + self.put(last_c, rect.r0, "]", fg); + } + return; + } + let area = rect.meet(self.clip()); + if rect.c1 - rect.c0 == 1 { + for r in area.r0..area.r1 { + self.put(rect.c0, r, "\u{2502}", fg); + } + return; + } + let (tl, tr, bl, br) = if round { ("\u{256d}", "\u{256e}", "\u{2570}", "\u{256f}") } else { ("\u{250c}", "\u{2510}", "\u{2514}", "\u{2518}") }; + for c in area.c0..area.c1 { + let (top, bottom) = if c == rect.c0 { + (tl, bl) + } else if c == last_c { + (tr, br) + } else { + ("\u{2500}", "\u{2500}") + }; + self.put(c, rect.r0, top, fg); + self.put(c, last_r, bottom, fg); + } + for r in area.r0.max(rect.r0 + 1)..area.r1.min(last_r) { + self.put(rect.c0, r, "\u{2502}", fg); + self.put(last_c, r, "\u{2502}", fg); + } + } + + /// The clusters of `text` along row `row` from column `col`, within `limit` columns of it. A + /// cluster the clip or the screen does not wholly hold writes spaces in the cells it does. + fn clusters(&mut self, row: i64, col: i64, text: &CellText, limit: i64, fg: Option<&Rgba>, style: CellStyle) { + let clip = self.clip(); + if row < clip.r0 || row >= clip.r1 { + return; + } + let mut at = col; + for (cluster, width) in text.clusters() { + let width = i64::from(width); + if at - col + width > limit || at >= clip.c1 { + break; + } + let r = row as usize; + if at >= clip.c0 && at + width <= clip.c1 { + for i in 0..width { + self.screen.blank_unit((at + i) as usize, r); + } + let bg = self.screen.at(at as usize, r).bg.clone(); + let fg = fg.map(|color| over(color, bg.as_ref())); + for i in 0..width { + let cell = self.screen.at((at + i) as usize, r); + cell.glyph = if i == 0 { cluster.to_string() } else { String::new() }; + cell.width = if i == 0 { width as u8 } else { 0 }; + cell.fg = fg.clone(); + cell.bg = bg.clone(); + cell.style = style; + } + } else { + for c in at.max(clip.c0)..(at + width).min(clip.c1) { + self.put(c, row, " ", None); + } + } + at += width; + } + } + + fn image(&mut self, rect: Span, alt: &str) { + let area = rect.meet(self.clip()); + for r in area.r0..area.r1 { + for c in area.c0..area.c1 { + self.put(c, r, "\u{2591}", None); + } + } + if !rect.empty() { + self.clusters(rect.r0, rect.c0, &CellText::new(alt), rect.c1 - rect.c0, None, CellStyle::default()); + } + } + + /// Light one dot of the braille cell holding dot-space `(x, y)` (2 x 4 dots to a cell). + fn dot(&mut self, x: i64, y: i64, color: &Rgba) { + const BITS: [[u32; 4]; 2] = [[0x01, 0x02, 0x04, 0x40], [0x08, 0x10, 0x20, 0x80]]; + let (c, r) = (x.div_euclid(2), y.div_euclid(4)); + if !self.clip().has(c, r) { + return; + } + let bit = BITS[x.rem_euclid(2) as usize][y.rem_euclid(4) as usize]; + let held = { + let mut chars = self.screen.at(c as usize, r as usize).glyph.chars(); + match (chars.next(), chars.next()) { + (Some(ch), None) if ('\u{2800}'..='\u{28ff}').contains(&ch) => ch as u32 - 0x2800, + _ => 0, + } + }; + let glyph = char::from_u32(0x2800 | held | bit).expect("braille block").to_string(); + self.put(c, r, &glyph, Some(color)); + } + + fn polyline(&mut self, points: &[(f32, f32)], color: &Rgba) { + const FAR: f32 = 1.0e4; + let dots: Vec<(i64, i64)> = points + .iter() + .filter(|(x, y)| x.is_finite() && y.is_finite()) + .map(|&(x, y)| ((x.clamp(-FAR, FAR) * 2.0).floor() as i64, (y.clamp(-FAR, FAR) * 4.0).floor() as i64)) + .collect(); + match dots.as_slice() { + [] => {} + [(x, y)] => self.dot(*x, *y, color), + _ => { + for pair in dots.windows(2) { + self.segment(pair[0], pair[1], color); + } + } + } + } + + /// Bresenham between two dots, both included. + fn segment(&mut self, (mut x, mut y): (i64, i64), (x1, y1): (i64, i64), color: &Rgba) { + let (dx, dy) = ((x1 - x).abs(), -(y1 - y).abs()); + let (sx, sy) = (if x < x1 { 1 } else { -1 }, if y < y1 { 1 } else { -1 }); + let mut error = dx + dy; + loop { + self.dot(x, y, color); + if (x, y) == (x1, y1) { + return; + } + let doubled = 2 * error; + if doubled >= dy { + error += dy; + x += sx; + } + if doubled <= dx { + error += dx; + y += sy; + } + } + } + + /// Even-odd fill of the cells whose centre is inside, as background. + fn polygon(&mut self, points: &[(f32, f32)], color: &Rgba) { + if points.len() < 3 || points.iter().any(|(x, y)| !x.is_finite() || !y.is_finite()) { + return; + } + let clip = self.clip(); + for r in clip.r0..clip.r1 { + let y = r as f32 + 0.5; + let mut crossings: Vec = Vec::new(); + for (i, &(px, py)) in points.iter().enumerate() { + let (qx, qy) = points[(i + 1) % points.len()]; + if (py <= y) != (qy <= y) { + crossings.push(px + (y - py) * (qx - px) / (qy - py)); + } + } + crossings.sort_by(f32::total_cmp); + let spans: Vec<(i64, i64)> = crossings.chunks_exact(2).map(|pair| cells(pair[0], pair[1] - pair[0])).collect(); + self.tint(r, |c| spans.iter().any(|&(from, to)| (from..to).contains(&c)), color); + } + } +} diff --git a/crates/thing-tui/src/screen.rs b/crates/thing-tui/src/screen.rs new file mode 100644 index 0000000..8e5a415 --- /dev/null +++ b/crates/thing-tui/src/screen.rs @@ -0,0 +1,117 @@ +//! The cell buffer: what every terminal cell holds. The headless mode and the live frame buffer +//! are the same type. + +use std::fmt::Write; + +use thing_contract::Rgba; +use thing_core::layout::CellStyle; + +/// One terminal cell. `width` is the columns the cluster in `glyph` takes, written in its lead +/// cell; the cells to its right hold `width` 0 and an empty glyph (the continuation of the wide +/// cluster to their left). `None` colours are the terminal's defaults. `glyph` is never a control +/// character or part of an escape sequence: text reaches it only as a sanitized `CellText`. +#[derive(Clone, Debug, PartialEq)] +pub struct Cell { + pub glyph: String, + pub width: u8, + pub fg: Option, + pub bg: Option, + pub style: CellStyle, +} + +impl Cell { + /// A space in default colours. + pub fn blank() -> Self { + Self { glyph: " ".to_string(), width: 1, fg: None, bg: None, style: CellStyle::default() } + } + + pub fn is_continuation(&self) -> bool { + self.width == 0 + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Screen { + pub cols: usize, + pub rows: usize, + /// Row-major, `cols * rows` cells. + pub cells: Vec, +} + +impl Screen { + pub fn new(cols: usize, rows: usize) -> Self { + Self { cols, rows, cells: vec![Cell::blank(); cols * rows] } + } + + pub fn cell(&self, col: usize, row: usize) -> Option<&Cell> { + (col < self.cols && row < self.rows).then(|| &self.cells[row * self.cols + col]) + } + + pub(crate) fn at(&mut self, col: usize, row: usize) -> &mut Cell { + &mut self.cells[row * self.cols + col] + } + + /// The wide cluster holding `(col, row)`: its lead column and its width in cells (1 for a + /// narrow cell). + pub(crate) fn unit(&self, col: usize, row: usize) -> (usize, usize) { + let mut lead = col; + while lead > 0 && self.cells[row * self.cols + lead].width == 0 { + lead -= 1; + } + let width = usize::from(self.cells[row * self.cols + lead].width).clamp(1, self.cols - lead); + (lead, width) + } + + /// Replace the cluster holding `(col, row)`, both halves of a wide one, with blanks. + pub(crate) fn blank_unit(&mut self, col: usize, row: usize) { + let (lead, width) = self.unit(col, row); + for c in lead..lead + width { + let cell = self.at(c, row); + cell.glyph = " ".to_string(); + cell.width = 1; + cell.fg = None; + cell.style = CellStyle::default(); + } + } + + /// The screen as text: one line per row (continuation cells omitted), then one `style` line per + /// run of equal `(fg, bg, flags)` cells: `row col len fg bg flags`, `-` for a default colour + /// or no flag. + pub fn dump(&self) -> String { + let mut out = String::new(); + for row in 0..self.rows { + for cell in &self.cells[row * self.cols..(row + 1) * self.cols] { + out += &cell.glyph; + } + out.push('\n'); + } + for row in 0..self.rows { + let cells = &self.cells[row * self.cols..(row + 1) * self.cols]; + let mut start = 0; + while start < cells.len() { + let key = |c: &Cell| (c.fg.clone(), c.bg.clone(), c.style); + let mut end = start + 1; + while end < cells.len() && key(&cells[end]) == key(&cells[start]) { + end += 1; + } + let cell = &cells[start]; + let flags = format!( + "{}{}{}", + if cell.style.bold { "b" } else { "" }, + if cell.style.italic { "i" } else { "" }, + if cell.style.underline { "u" } else { "" } + ); + let _ = writeln!(out, "style {row} {start} {} {} {} {}", end - start, hex(&cell.fg), hex(&cell.bg), if flags.is_empty() { "-" } else { &flags }); + start = end; + } + } + out + } +} + +fn hex(color: &Option) -> String { + match color { + Some(c) => format!("#{:02x}{:02x}{:02x}", c.r, c.g, c.b), + None => "-".to_string(), + } +} diff --git a/crates/thing-tui/tests/common/mod.rs b/crates/thing-tui/tests/common/mod.rs new file mode 100644 index 0000000..1155dce --- /dev/null +++ b/crates/thing-tui/tests/common/mod.rs @@ -0,0 +1,62 @@ +//! Shared test helpers: command builders and the screen's well-formedness check. +#![allow(dead_code)] + +use thing_contract::Rgba; +use thing_core::layout::{CellStyle, Rect, Run}; +use thing_core::render::RenderCommand; +use thing_core::text::CellText; +use thing_tui::Screen; + +pub fn rgb(r: u8, g: u8, b: u8) -> Rgba { + Rgba { r, g, b, a: 255 } +} + +pub fn rgba(r: u8, g: u8, b: u8, a: u8) -> Rgba { + Rgba { r, g, b, a } +} + +pub fn rect(x: f32, y: f32, w: f32, h: f32) -> Rect { + Rect { x, y, w, h } +} + +pub fn fill(r: Rect, color: Rgba) -> RenderCommand { + RenderCommand::FillRect { rect: r, radius: 0.0, color } +} + +pub fn stroke(r: Rect, color: Rgba) -> RenderCommand { + RenderCommand::StrokeRect { rect: r, radius: 0.0, width: 1.0, color } +} + +pub fn text(x: f32, y: f32, s: &str, color: Rgba) -> RenderCommand { + RenderCommand::Text { origin: (x, y), run: Run::Cells { text: CellText::new(s), style: CellStyle::default() }, color } +} + +pub fn clip(r: Rect) -> RenderCommand { + RenderCommand::ClipPush { rect: r, radius: 0.0 } +} + +/// The glyph at `(col, row)`. +pub fn glyph(screen: &Screen, col: usize, row: usize) -> &str { + &screen.cell(col, row).expect("on screen").glyph +} + +/// What the screen must always be: no control character in any glyph, every wide lead followed by +/// exactly its width less one continuation cells, no continuation without its lead. +pub fn well_formed(screen: &Screen) { + assert_eq!(screen.cells.len(), screen.cols * screen.rows); + for row in 0..screen.rows { + let mut col = 0; + while col < screen.cols { + let cell = screen.cell(col, row).unwrap(); + assert!(cell.width >= 1, "({col},{row}) is a continuation with no lead"); + assert!(!cell.glyph.is_empty() && !cell.glyph.chars().any(char::is_control), "({col},{row}) holds {:?}", cell.glyph); + let width = usize::from(cell.width); + assert!(col + width <= screen.cols, "({col},{row}) wide cluster leaves the screen"); + for i in 1..width { + let cont = screen.cell(col + i, row).unwrap(); + assert!(cont.width == 0 && cont.glyph.is_empty(), "({},{row}) should continue ({col},{row})", col + i); + } + col += width; + } + } +} diff --git a/crates/thing-tui/tests/diff.rs b/crates/thing-tui/tests/diff.rs new file mode 100644 index 0000000..ac4e1ba --- /dev/null +++ b/crates/thing-tui/tests/diff.rs @@ -0,0 +1,199 @@ +//! Diff: minimal, correct, and resynchronised after non-ASCII text. The model terminal below is +//! the contract the ops are written against. + +mod common; + +use common::*; +use thing_contract::Rgba; +use thing_core::layout::CellStyle; +use thing_core::render::RenderCommand; +use thing_core::text::CellText; +use thing_tui::{Cell, Op, Screen, diff, paint}; + +/// A terminal that obeys `Op`s: a cursor, a pen, wide clusters by the policy's widths, and the +/// rule that writing into half a wide cluster blanks the other half. Returns the cells written. +fn apply(start: &Screen, ops: &[Op]) -> (Screen, Vec<(usize, usize)>) { + let mut screen = start.clone(); + let mut written = Vec::new(); + let mut cursor = (0usize, 0usize); + let mut pen: (Option, Option, CellStyle) = (None, None, CellStyle::default()); + for op in ops { + match op { + Op::MoveTo(c, r) => cursor = (*c, *r), + Op::Style(fg, bg, style) => pen = (fg.clone(), bg.clone(), *style), + Op::Print(s) => { + for (cluster, width) in CellText::new(s).clusters() { + let (c, r) = cursor; + let width = usize::from(width); + assert!(c + width <= screen.cols && r < screen.rows, "print leaves the screen at ({c},{r})"); + for i in 0..width { + // Overwriting half a wide cluster blanks the other half. + let mut lead = c + i; + while lead > 0 && screen.cells[r * screen.cols + lead].width == 0 { + lead -= 1; + } + let span = usize::from(screen.cells[r * screen.cols + lead].width).max(1); + for k in lead..(lead + span).min(screen.cols) { + screen.cells[r * screen.cols + k] = Cell::blank(); + } + } + for i in 0..width { + screen.cells[r * screen.cols + c + i] = Cell { glyph: if i == 0 { cluster.to_string() } else { String::new() }, width: if i == 0 { width as u8 } else { 0 }, fg: pen.0.clone(), bg: pen.1.clone(), style: pen.2 }; + written.push((c + i, r)); + } + cursor = (c + width, r); + } + } + } + } + (screen, written) +} + +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + fn below(&mut self, n: u64) -> u64 { + self.next() % n + } + + fn pick<'a, T>(&mut self, from: &'a [T]) -> &'a T { + &from[self.below(from.len() as u64) as usize] + } +} + +const WORDS: [&str; 10] = ["a", "xyz", "\u{4e2d}", "ab\u{4e2d}\u{6587}", "e\u{301}", "\u{1f600}", "\u{17d8}z", " ", "~", "\u{4e2d}\u{4e2d}\u{4e2d}"]; + +fn commands(rng: &mut Rng, count: usize, cols: u64, rows: u64) -> Vec { + let mut out = Vec::new(); + for _ in 0..count { + let (x, y) = (rng.below(cols + 4) as f32 - 2.0, rng.below(rows + 2) as f32 - 1.0); + let (w, h) = (rng.below(8) as f32, rng.below(4) as f32); + let color = rgba(rng.below(256) as u8, rng.below(256) as u8, rng.below(256) as u8, *rng.pick(&[255, 255, 128, 0])); + out.push(match rng.below(8) { + 0 | 1 => fill(rect(x, y, w, h), color), + 2 => stroke(rect(x, y, w, h), color), + 3 | 4 | 5 => text(x, y, rng.pick(&WORDS), color), + 6 => RenderCommand::Polyline { points: vec![(x, y), (x + w, y + h)], width: 1.0, color }, + _ => RenderCommand::Embed { rect: rect(x, y, w.min(3.0), h.min(2.0)), slot_kind: String::new(), slot_id: String::new() }, + }); + } + out +} + +/// A cell is written only as part of a cluster holding a changed cell. +fn units_touched(old: &Screen, new: &Screen, written: &[(usize, usize)]) { + for &(c, r) in written { + let mut lead = c; + while lead > 0 && new.cells[r * new.cols + lead].width == 0 { + lead -= 1; + } + let span = usize::from(new.cells[r * new.cols + lead].width).max(1); + let changed = (lead..lead + span).any(|k| old.cells[r * old.cols + k] != new.cells[r * new.cols + k]); + assert!(changed, "({c},{r}) was rewritten and nothing in its cluster changed"); + } +} + +#[test] +fn applying_the_diff_gives_the_new_screen() { + let mut rng = Rng(0x9e37_79b9_7f4a_7c15); + for round in 0..400 { + let (cols, rows) = (24, 6); + let mut old = Screen::new(cols, rows); + paint(&commands(&mut rng, 10, 24, 6), &mut old); + let mut new = old.clone(); + paint(&commands(&mut rng, 1 + round % 6, 24, 6), &mut new); + well_formed(&old); + well_formed(&new); + let ops = diff(&old, &new); + let (got, written) = apply(&old, &ops); + assert_eq!(got, new, "round {round}: {ops:?}"); + units_touched(&old, &new, &written); + if old == new { + assert!(ops.is_empty()); + } + } +} + +#[test] +fn a_resize_repaints_every_cell() { + let mut rng = Rng(7); + for _ in 0..40 { + let mut old = Screen::new(10, 4); + paint(&commands(&mut rng, 6, 10, 4), &mut old); + let mut new = Screen::new(14, 5); + paint(&commands(&mut rng, 8, 14, 5), &mut new); + let ops = diff(&old, &new); + // The terminal was cleared by the resize. + let (got, written) = apply(&Screen::new(14, 5), &ops); + assert_eq!(got, new); + assert_eq!(written.len(), 14 * 5); + } +} + +#[test] +fn equal_screens_need_nothing() { + let mut screen = Screen::new(10, 3); + paint(&[text(1.0, 1.0, "\u{4e2d}a", rgb(1, 2, 3))], &mut screen); + assert_eq!(diff(&screen, &screen.clone()), vec![]); +} + +#[test] +fn one_changed_cell_is_move_style_print() { + let old = Screen::new(10, 3); + let mut new = old.clone(); + paint(&[text(4.0, 1.0, "q", rgb(1, 2, 3))], &mut new); + assert_eq!(diff(&old, &new), vec![Op::MoveTo(4, 1), Op::Style(Some(rgb(1, 2, 3)), None, CellStyle::default()), Op::Print("q".to_string())]); +} + +#[test] +fn a_contiguous_run_is_one_move_and_one_print() { + let old = Screen::new(10, 3); + let mut new = old.clone(); + paint(&[text(2.0, 0.0, "abc", rgb(1, 2, 3))], &mut new); + let ops = diff(&old, &new); + assert_eq!(ops, vec![Op::MoveTo(2, 0), Op::Style(Some(rgb(1, 2, 3)), None, CellStyle::default()), Op::Print("abc".to_string())]); + // A new style mid-run is a Style, not a move. + let mut new = old.clone(); + paint(&[text(2.0, 0.0, "a", rgb(1, 2, 3)), text(3.0, 0.0, "b", rgb(4, 5, 6))], &mut new); + let ops = diff(&old, &new); + assert_eq!(ops.iter().filter(|op| matches!(op, Op::MoveTo(..))).count(), 1); + assert_eq!(ops.iter().filter(|op| matches!(op, Op::Style(..))).count(), 2); +} + +#[test] +fn ascii_after_a_wide_cluster_resynchronises() { + let old = Screen::new(20, 2); + let mut new = old.clone(); + paint(&[text(5.0, 0.0, "\u{4e2d}", rgb(1, 2, 3)), text(7.0, 0.0, "a", rgb(1, 2, 3))], &mut new); + let pen = Op::Style(Some(rgb(1, 2, 3)), None, CellStyle::default()); + assert_eq!(diff(&old, &new), vec![Op::MoveTo(5, 0), pen, Op::Print("\u{4e2d}".to_string()), Op::MoveTo(7, 0), Op::Print("a".to_string())]); +} + +#[test] +fn a_changed_half_repaints_the_whole_cluster() { + let mut old = Screen::new(20, 2); + paint(&[text(5.0, 0.0, "\u{4e2d}", rgb(1, 2, 3))], &mut old); + let mut new = old.clone(); + // Only the right half's cell differs: its background. + new.cells[6].bg = Some(rgb(9, 9, 9)); + new.cells[5].bg = Some(rgb(9, 9, 9)); + let ops = diff(&old, &new); + assert!(ops.contains(&Op::Print("\u{4e2d}".to_string())), "{ops:?}"); + let (got, _) = apply(&old, &ops); + assert_eq!(got, new); +} + +#[test] +fn a_resize_prints_every_cell() { + let old = Screen::new(4, 2); + let new = Screen::new(6, 3); + let printed: usize = diff(&old, &new).iter().map(|op| if let Op::Print(s) = op { s.chars().count() } else { 0 }).sum(); + assert_eq!(printed, 18); +} diff --git a/crates/thing-tui/tests/paint.rs b/crates/thing-tui/tests/paint.rs new file mode 100644 index 0000000..aa938f3 --- /dev/null +++ b/crates/thing-tui/tests/paint.rs @@ -0,0 +1,260 @@ +//! Paint: the table, the clip stack, wide clusters, colour, braille and polygon coverage. + +mod common; + +use common::*; +use thing_core::layout::{CellStyle, Run}; +use thing_core::render::RenderCommand; +use thing_core::text::CellText; +use thing_tui::{Representation, Screen, paint, representation}; + +fn blank() -> Screen { + Screen::new(20, 6) +} + +fn one(command: RenderCommand) -> Screen { + let mut screen = blank(); + paint(&[command], &mut screen); + well_formed(&screen); + screen +} + +#[test] +fn every_variant_changes_a_cell() { + let red = rgb(255, 0, 0); + let a = rect(2.0, 1.0, 6.0, 3.0); + let commands = [ + fill(a, red.clone()), + stroke(a, red.clone()), + text(1.0, 1.0, "hi", red.clone()), + RenderCommand::Image { rect: a, uri: "u".into(), alt: "alt".into() }, + RenderCommand::Polyline { points: vec![(1.0, 1.0), (5.0, 3.0)], width: 1.0, color: red.clone() }, + RenderCommand::Polygon { points: vec![(0.0, 0.0), (6.0, 0.0), (0.0, 4.0)], color: red.clone() }, + RenderCommand::Embed { rect: a, slot_kind: "k".into(), slot_id: "i".into() }, + ]; + for command in commands { + let mut screen = blank(); + // An embed resets cells to the default: give it something to reset. + if matches!(command, RenderCommand::Embed { .. }) { + paint(&[fill(a, red.clone())], &mut screen); + } + let before = screen.clone(); + paint(std::slice::from_ref(&command), &mut screen); + assert_ne!(screen, before, "{command:?} changed nothing"); + let _ = representation(&command); + } + assert_eq!(representation(&RenderCommand::ClipPop), Representation::Drawn); + assert!(matches!(representation(&RenderCommand::Polyline { points: vec![], width: 1.0, color: red }), Representation::Approximated(_))); +} + +#[test] +fn a_cell_is_covered_by_its_centre() { + // x 0.4..2.6 covers the centres 0.5, 1.5 and 2.5: cells 0, 1, 2. + let screen = one(fill(rect(0.4, 0.0, 2.2, 1.0), rgb(1, 2, 3))); + let painted: Vec = (0..6).filter(|&c| screen.cell(c, 0).unwrap().bg.is_some()).collect(); + assert_eq!(painted, vec![0, 1, 2]); + // x 0.6 starts past the first centre. + let screen = one(fill(rect(0.6, 0.0, 1.0, 1.0), rgb(1, 2, 3))); + let painted: Vec = (0..6).filter(|&c| screen.cell(c, 0).unwrap().bg.is_some()).collect(); + assert_eq!(painted, vec![1]); +} + +#[test] +fn clip_bounds_writes_and_pop_restores() { + let red = rgb(255, 0, 0); + let mut screen = blank(); + let commands = [ + clip(rect(2.0, 1.0, 4.0, 2.0)), + fill(rect(0.0, 0.0, 20.0, 6.0), red.clone()), + text(0.0, 1.0, "abcdefghij", rgb(0, 255, 0)), + text(0.0, 0.0, "outside", rgb(0, 255, 0)), + RenderCommand::ClipPop, + fill(rect(10.0, 4.0, 2.0, 1.0), rgb(0, 0, 255)), + RenderCommand::ClipPop, + ]; + paint(&commands, &mut screen); + well_formed(&screen); + for row in 0..6 { + for col in 0..20 { + let inside = (2..6).contains(&col) && (1..3).contains(&row); + let cell = screen.cell(col, row).unwrap(); + let outer = (10..12).contains(&col) && row == 4; + assert_eq!(cell.bg.is_some(), inside || outer, "bg at ({col},{row})"); + if !inside && !(row == 1 && col == 6) { + assert_eq!(cell.glyph, " ", "glyph at ({col},{row})"); + } + } + } + assert_eq!((glyph(&screen, 2, 1), glyph(&screen, 5, 1), glyph(&screen, 6, 1)), ("c", "f", " ")); + // Nested clips intersect. + let mut screen = blank(); + paint(&[clip(rect(0.0, 0.0, 4.0, 4.0)), clip(rect(2.0, 2.0, 10.0, 10.0)), fill(rect(0.0, 0.0, 20.0, 6.0), red)], &mut screen); + let lit: Vec<(usize, usize)> = (0..6).flat_map(|r| (0..20).map(move |c| (c, r))).filter(|&(c, r)| screen.cell(c, r).unwrap().bg.is_some()).collect(); + assert_eq!(lit, vec![(2, 2), (3, 2), (2, 3), (3, 3)]); +} + +#[test] +fn wide_clusters_take_their_width() { + let white = rgb(255, 255, 255); + let mut screen = blank(); + paint(&[text(5.0, 0.0, "\u{4e2d}", white.clone())], &mut screen); + well_formed(&screen); + assert_eq!((glyph(&screen, 5, 0), screen.cell(5, 0).unwrap().width), ("\u{4e2d}", 2)); + assert_eq!((glyph(&screen, 6, 0), screen.cell(6, 0).unwrap().width), ("", 0)); + // Writing into the right half blanks the left. + paint(&[text(6.0, 0.0, "a", white.clone())], &mut screen); + well_formed(&screen); + assert_eq!((glyph(&screen, 5, 0), glyph(&screen, 6, 0)), (" ", "a")); + // Writing into the left half blanks the right. + let mut screen = blank(); + paint(&[text(5.0, 0.0, "\u{4e2d}", white.clone()), text(5.0, 0.0, "a", white.clone())], &mut screen); + well_formed(&screen); + assert_eq!((glyph(&screen, 5, 0), glyph(&screen, 6, 0)), ("a", " ")); + // A cluster straddling the clip edge writes a space in its visible cell. + let mut screen = blank(); + paint(&[clip(rect(0.0, 0.0, 6.0, 6.0)), text(5.0, 0.0, "\u{4e2d}", white.clone())], &mut screen); + well_formed(&screen); + assert_eq!((glyph(&screen, 5, 0), glyph(&screen, 6, 0)), (" ", " ")); + // Off the screen's right edge likewise. + let mut screen = blank(); + paint(&[text(19.0, 0.0, "\u{4e2d}x", white.clone())], &mut screen); + well_formed(&screen); + assert_eq!(glyph(&screen, 19, 0), " "); + // A 3-wide cluster marks two continuations, and the next cluster starts after them. + let khmer = "\u{17d8}"; + assert_eq!(CellText::new(khmer).width(), 3); + let mut screen = blank(); + paint(&[text(2.0, 0.0, &format!("{khmer}z"), white)], &mut screen); + well_formed(&screen); + assert_eq!(screen.cell(2, 0).unwrap().width, 3); + assert_eq!((screen.cell(3, 0).unwrap().width, screen.cell(4, 0).unwrap().width), (0, 0)); + assert_eq!(glyph(&screen, 5, 0), "z"); +} + +#[test] +fn colour_composites_over_the_cell() { + let red = rgb(255, 0, 0); + let mut screen = blank(); + paint(&[fill(rect(0.0, 0.0, 3.0, 1.0), red.clone()), fill(rect(0.0, 0.0, 3.0, 1.0), rgba(0, 0, 255, 51))], &mut screen); + assert_eq!(screen.cell(1, 0).unwrap().bg, Some(rgb(204, 0, 51))); + // A translucent fill keeps the glyph; an opaque one clears it. + let mut screen = blank(); + paint(&[text(0.0, 0.0, "hi", rgb(9, 9, 9)), fill(rect(0.0, 0.0, 1.0, 1.0), rgba(0, 0, 255, 51)), fill(rect(1.0, 0.0, 1.0, 1.0), red.clone())], &mut screen); + assert_eq!((glyph(&screen, 0, 0), glyph(&screen, 1, 0)), ("h", " ")); + // Text colour reaches fg, and its alpha composites onto the bg. + let mut screen = blank(); + paint(&[fill(rect(0.0, 0.0, 2.0, 1.0), red.clone()), text(0.0, 0.0, "a", rgb(10, 20, 30)), text(1.0, 0.0, "b", rgba(0, 0, 255, 51))], &mut screen); + assert_eq!(screen.cell(0, 0).unwrap().fg, Some(rgb(10, 20, 30))); + assert_eq!(screen.cell(1, 0).unwrap().fg, Some(rgb(204, 0, 51))); + assert_eq!(screen.cell(0, 0).unwrap().bg, Some(red)); + // A run's style lands in the cell. + let style = CellStyle { bold: true, italic: false, underline: true }; + let styled = RenderCommand::Text { origin: (0.0, 0.0), run: Run::Cells { text: CellText::new("x"), style }, color: rgb(1, 1, 1) }; + assert_eq!(one(styled).cell(0, 0).unwrap().style, style); +} + +#[test] +fn a_wide_cluster_has_one_background() { + let mut screen = blank(); + paint(&[text(2.0, 0.0, "\u{4e2d}", rgb(1, 1, 1)), fill(rect(3.0, 0.0, 1.0, 1.0), rgba(255, 0, 0, 128))], &mut screen); + well_formed(&screen); + assert_eq!(screen.cell(2, 0).unwrap().bg, screen.cell(3, 0).unwrap().bg); + assert!(screen.cell(2, 0).unwrap().bg.is_some()); +} + +#[test] +fn strokes_draw_boxes_brackets_and_columns() { + let white = rgb(255, 255, 255); + let screen = one(stroke(rect(1.0, 1.0, 4.0, 3.0), white.clone())); + let row = |r: usize| (0..6).map(|c| glyph(&screen, c, r)).collect::(); + assert_eq!((row(1), row(2), row(3)), (" \u{250c}\u{2500}\u{2500}\u{2510} ".to_string(), " \u{2502} \u{2502} ".to_string(), " \u{2514}\u{2500}\u{2500}\u{2518} ".to_string())); + let round = one(RenderCommand::StrokeRect { rect: rect(1.0, 1.0, 4.0, 3.0), radius: 2.0, width: 1.0, color: white.clone() }); + assert_eq!((glyph(&round, 1, 1), glyph(&round, 4, 3)), ("\u{256d}", "\u{256f}")); + let bracket = one(stroke(rect(2.0, 1.0, 5.0, 1.0), white.clone())); + assert_eq!((glyph(&bracket, 2, 1), glyph(&bracket, 3, 1), glyph(&bracket, 6, 1)), ("[", " ", "]")); + let column = one(stroke(rect(2.0, 1.0, 1.0, 3.0), white)); + assert_eq!((glyph(&column, 2, 1), glyph(&column, 2, 3), glyph(&column, 2, 4)), ("\u{2502}", "\u{2502}", " ")); +} + +#[test] +fn braille_dots() { + let white = rgb(255, 255, 255); + // Across two cells on dot row 2: bits 0x04 and 0x20 in each. + let screen = one(RenderCommand::Polyline { points: vec![(0.25, 0.5), (1.75, 0.5)], width: 3.0, color: white.clone() }); + assert_eq!((glyph(&screen, 0, 0), glyph(&screen, 1, 0), glyph(&screen, 2, 0)), ("\u{2824}", "\u{2824}", " ")); + // Two polylines in one cell OR their dots. + let mut screen = blank(); + paint( + &[ + RenderCommand::Polyline { points: vec![(0.1, 0.1)], width: 1.0, color: white.clone() }, + RenderCommand::Polyline { points: vec![(0.6, 0.9)], width: 1.0, color: white.clone() }, + ], + &mut screen, + ); + assert_eq!(glyph(&screen, 0, 0), "\u{2881}"); + assert_eq!(screen.cell(0, 0).unwrap().fg, Some(white.clone())); + // A vertical line down one dot column fills it. + let screen = one(RenderCommand::Polyline { points: vec![(0.1, 0.0), (0.1, 0.99)], width: 1.0, color: white }); + assert_eq!(glyph(&screen, 0, 0), "\u{2847}"); +} + +#[test] +fn polygon_covers_cells_whose_centre_is_inside() { + let screen = one(RenderCommand::Polygon { points: vec![(0.0, 0.0), (4.0, 0.0), (0.0, 4.0)], color: rgb(5, 6, 7) }); + let row = |r: usize| (0..6).filter(|&c| screen.cell(c, r).unwrap().bg.is_some()).collect::>(); + assert_eq!((row(0), row(1), row(2), row(3)), (vec![0, 1, 2], vec![0, 1], vec![0], vec![])); + // Even-odd: a square with a square traced inside it leaves a hole. + let ring = vec![(0.0, 0.0), (6.0, 0.0), (6.0, 6.0), (0.0, 6.0), (0.0, 0.0), (2.0, 2.0), (2.0, 4.0), (4.0, 4.0), (4.0, 2.0), (2.0, 2.0)]; + let screen = one(RenderCommand::Polygon { points: ring, color: rgb(5, 6, 7) }); + assert!(screen.cell(0, 0).unwrap().bg.is_some() && screen.cell(2, 2).unwrap().bg.is_none() && screen.cell(5, 5).unwrap().bg.is_some()); +} + +#[test] +fn image_shades_and_labels() { + let screen = one(RenderCommand::Image { rect: rect(1.0, 1.0, 5.0, 2.0), uri: "u".into(), alt: "ab\u{4e2d}cd".into() }); + let row = |r: usize| (0..8).filter(|&c| screen.cell(c, r).unwrap().width > 0).map(|c| glyph(&screen, c, r)).collect::(); + // The 5 columns hold a, b, the wide cluster and c; d is cut. + assert_eq!(row(1), " ab\u{4e2d}c "); + assert_eq!(row(2), " \u{2591}\u{2591}\u{2591}\u{2591}\u{2591} "); + assert!(screen.cell(1, 1).unwrap().fg.is_none()); +} + +#[test] +fn embed_resets_cells_and_reports() { + let mut screen = blank(); + let target = rect(2.0, 1.0, 3.0, 2.0); + let painted = paint( + &[fill(rect(0.0, 0.0, 20.0, 6.0), rgb(1, 2, 3)), text(2.0, 1.0, "xyz", rgb(9, 9, 9)), RenderCommand::Embed { rect: target, slot_kind: "kind".into(), slot_id: "id".into() }], + &mut screen, + ); + assert_eq!(painted.embeds, vec![(target, "kind".to_string(), "id".to_string())]); + assert_eq!(*screen.cell(3, 2).unwrap(), thing_tui::Cell::blank()); + assert_eq!(screen.cell(5, 2).unwrap().bg, Some(rgb(1, 2, 3))); +} + +#[test] +fn no_control_character_reaches_the_screen() { + let mut screen = blank(); + let alt = RenderCommand::Image { rect: rect(0.0, 2.0, 12.0, 1.0), uri: String::new(), alt: "\u{1b}]0;x\u{7}".into() }; + paint(&[text(0.0, 0.0, "a\u{1b}[31mb\tc\u{7f}\r\n", rgb(1, 1, 1)), alt], &mut screen); + well_formed(&screen); + assert!(screen.dump().chars().all(|c| c == '\n' || !c.is_control())); +} + +#[test] +fn hostile_geometry_is_inert() { + let nan = f32::NAN; + let mut screen = blank(); + let commands = [ + fill(rect(nan, 0.0, 5.0, 5.0), rgb(1, 1, 1)), + fill(rect(-1.0e30, -1.0e30, 2.0e30, 2.0e30), rgb(1, 1, 1)), + stroke(rect(0.0, 0.0, f32::INFINITY, 2.0), rgb(1, 1, 1)), + text(f32::NEG_INFINITY, 0.0, "x", rgb(1, 1, 1)), + text(-50.0, 1.0, "wide \u{4e2d} text running far left", rgb(1, 1, 1)), + RenderCommand::Polyline { points: vec![(nan, 0.0), (1.0e30, -1.0e30), (3.0, 3.0)], width: 1.0, color: rgb(1, 1, 1) }, + RenderCommand::Polygon { points: vec![(0.0, 0.0), (nan, 3.0), (3.0, 3.0)], color: rgb(1, 1, 1) }, + RenderCommand::ClipPop, + ]; + paint(&commands, &mut screen); + well_formed(&screen); +} diff --git a/crates/thing-tui/tests/screen.rs b/crates/thing-tui/tests/screen.rs new file mode 100644 index 0000000..297ef93 --- /dev/null +++ b/crates/thing-tui/tests/screen.rs @@ -0,0 +1,78 @@ +//! Screen goldens: every fixture through resolve, bind, layout and render in Cells, painted onto a +//! 100x37 screen. The composition is test-only: the shipped crate composes nothing. +//! `THING_BLESS=1` rewrites the goldens through the testkit's one door. + +mod common; + +use std::path::PathBuf; + +use common::well_formed; +use thing_contract::SurfaceDocument; +use thing_core::bind::Binder; +use thing_core::diagnostic::Code; +use thing_core::layout::{LayoutFrame, Metrics, layout}; +use thing_core::port::Ledger; +use thing_core::render::{RenderInput, ScrollOffsets, render}; +use thing_core::resolve::{Limits, resolve}; +use thing_core::text::CellMeasure; +use thing_core::theme::Theme; +use thing_testkit::fixture::Fixture; +use thing_testkit::golden; +use thing_testkit::mem_state::MemState; +use thing_testkit::state; +use thing_tui::{Screen, paint}; + +const COLS: usize = 100; +const ROWS: usize = 37; + +fn golden_dir() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens") +} + +fn screen_of(state: &mut MemState, document: &SurfaceDocument) -> Result { + let limits = Limits::default(); + let resolution = resolve(document, state, &limits); + let Some(tree) = resolution.tree else { + return Err(resolution.diagnostics.iter().find(|d| d.code.refuses_document()).map(|d| d.code).expect("a refusal")); + }; + let mut binder = Binder::new(limits); + binder.bind(tree, state, &mut Ledger::new()); + let tree = binder.tree(&document.record_key()).expect("bound").clone(); + let frame = LayoutFrame { viewport: (COLS as f32, ROWS as f32), scale: 1.0, metrics: Metrics::Cells }; + let laid = layout(&tree, &frame, &mut CellMeasure).unwrap(); + let scroll = ScrollOffsets::default(); + let theme = Theme::std(); + let input = RenderInput { scale: 1.0, metrics: Metrics::Cells, viewport: frame.viewport, scroll: &scroll, theme: &theme }; + let rendered = render(&tree, &laid, &input, &mut CellMeasure); + let mut screen = Screen::new(COLS, ROWS); + paint(&rendered.commands, &mut screen); + Ok(screen) +} + +fn stem(fixture: Fixture) -> String { + fixture.file_name().trim_end_matches(".surface.cc").to_string() +} + +fn golden_text(fixture: Fixture) -> String { + let set = fixture.load(); + let mut state = MemState::from_fixture(fixture); + state::script(fixture, &mut state); + let mut out = String::new(); + for document in &set.surfaces { + match screen_of(&mut state, document) { + Ok(screen) => { + well_formed(&screen); + out += &format!("surface {} {COLS}x{ROWS}\n{}", document.record_key(), screen.dump()); + } + Err(code) => out += &format!("surface {} refused {code:?}\n", document.record_key()), + } + } + out +} + +#[test] +fn goldens() { + for fixture in Fixture::ALL { + golden::check(&golden_dir(), &format!("screen-{}-cells.txt", stem(fixture)), golden_text(fixture).as_bytes()); + } +}