From 738898445002ebcc2795675c7b8103a749cd3866 Mon Sep 17 00:00:00 2001 From: Eureka Date: Sat, 28 Nov 2026 19:38:59 +0000 Subject: [PATCH] thing-tui: paint Cells frames to a terminal screen (cut 8a) (#24) --- Cargo.lock | 9 + crates/thing-core/src/layout/measure.rs | 80 +++- crates/thing-core/src/layout/mod.rs | 86 +++- crates/thing-core/src/layout/overlay.rs | 5 +- crates/thing-core/src/layout/style.rs | 90 ++-- crates/thing-core/src/layout/tree.rs | 120 +++++- crates/thing-core/src/render/leaf.rs | 47 ++- crates/thing-core/src/render/mod.rs | 45 +- crates/thing-core/src/text/cells.rs | 4 +- .../layout-f01-swarm-dashboard-cells.txt | 14 +- .../render-f01-swarm-dashboard-cells.txt | 16 +- .../goldens/render-f12-text-edge-cells.txt | 57 ++- crates/thing-core/tests/layout.rs | 395 +++++++++++++++++- crates/thing-core/tests/render.rs | 237 ++++++++++- 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 | 395 ++++++++++++++++++ crates/thing-tui/src/screen.rs | 117 ++++++ crates/thing-tui/tests/common/mod.rs | 62 +++ crates/thing-tui/tests/diff.rs | 205 +++++++++ crates/thing-tui/tests/goldens/README.md | 5 + .../screen-f01-swarm-dashboard-cells.txt | 87 ++++ .../goldens/screen-f02-login-effect-cells.txt | 81 ++++ .../goldens/screen-f03-input-target-cells.txt | 77 ++++ .../tests/goldens/screen-f04-form-cells.txt | 85 ++++ .../screen-f05-modal-overlay-cells.txt | 83 ++++ .../goldens/screen-f06-scroll-list-cells.txt | 103 +++++ .../tests/goldens/screen-f07-plot-cells.txt | 127 ++++++ .../screen-f08-embed-viewport-cells.txt | 78 ++++ .../screen-f09-composition-stack-cells.txt | 97 +++++ .../goldens/screen-f10-hostile-cells.txt | 156 +++++++ .../goldens/screen-f12-text-edge-cells.txt | 86 ++++ crates/thing-tui/tests/paint.rs | 294 +++++++++++++ crates/thing-tui/tests/screen.rs | 94 +++++ 35 files changed, 3383 insertions(+), 163 deletions(-) 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/goldens/README.md create mode 100644 crates/thing-tui/tests/goldens/screen-f01-swarm-dashboard-cells.txt create mode 100644 crates/thing-tui/tests/goldens/screen-f02-login-effect-cells.txt create mode 100644 crates/thing-tui/tests/goldens/screen-f03-input-target-cells.txt create mode 100644 crates/thing-tui/tests/goldens/screen-f04-form-cells.txt create mode 100644 crates/thing-tui/tests/goldens/screen-f05-modal-overlay-cells.txt create mode 100644 crates/thing-tui/tests/goldens/screen-f06-scroll-list-cells.txt create mode 100644 crates/thing-tui/tests/goldens/screen-f07-plot-cells.txt create mode 100644 crates/thing-tui/tests/goldens/screen-f08-embed-viewport-cells.txt create mode 100644 crates/thing-tui/tests/goldens/screen-f09-composition-stack-cells.txt create mode 100644 crates/thing-tui/tests/goldens/screen-f10-hostile-cells.txt create mode 100644 crates/thing-tui/tests/goldens/screen-f12-text-edge-cells.txt 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..c45167d 100644 --- a/crates/thing-core/src/layout/measure.rs +++ b/crates/thing-core/src/layout/measure.rs @@ -6,6 +6,7 @@ use taffy::{AvailableSpace, Size}; use thing_contract::NodeId; use crate::bind::Bound; +use super::ControlForm; use crate::text::CellText; /// The room a leaf is offered on one axis. @@ -105,8 +106,24 @@ pub(crate) const MAX_DEVICE: f32 = 2_097_152.0; /// leaves. A smaller side is below the resolution layout keeps. pub(super) const MIN_SIDE: f32 = 0.125; +/// The fewest rows a Cells control needs to be `Bordered`: a border row above and below a content row. +pub(super) const BORDERED_ROWS: f32 = 3.0; + +/// Device px per cell, `(across, down)`: the metric a terminal cell stands for. In Cells mode a Px +/// length converts at it (8 wide, 16 tall), and an Image's pixel extent is read in cells at it. +pub(crate) const CELL_PX: (f32, f32) = (8.0, 16.0); + +/// The axis a Px length runs along: across (width, left and right, columns) or down (height, top +/// and bottom, rows). A cell is not square, so a Px length converts per axis in Cells. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Axis { + X, + Y, +} + /// The one place logical units become device units and back: `k` device px per logical px -/// (1 in Cells). Everything past this adapter, the style map and the solver included, is device. +/// (1 in Cells, where `length` divides a Px length by the cell metric instead). Everything past +/// this adapter, the style map and the solver included, is device. #[derive(Clone, Copy, Debug)] pub(super) struct Device { k: f32, @@ -118,21 +135,70 @@ impl Device { Self { k, cells } } - /// The least a Use placeholder takes, so its error is visible: 16 logical px, one cell. - pub(super) fn placeholder(self) -> f32 { - if self.cells { 1.0 } else { self.px(16.0) } + /// The least a Use placeholder takes, so its error is visible: 16 logical px each way. + pub(super) fn placeholder(self) -> (f32, f32) { + (self.length(16.0, Axis::X), self.length(16.0, Axis::Y)) } - /// A Plot's size: the CSS default object size, 300x150 logical px, or 38x10 cells. A plot is - /// sized by layout, never measured. + /// Whether this is a cell grid. + pub(super) fn cells(self) -> bool { + self.cells + } + + /// A Plot's size: the CSS default object size, 300x150 logical px. A plot is sized by layout, + /// never measured. pub(super) fn plot(self) -> (f32, f32) { - if self.cells { (38.0, 10.0) } else { (self.px(300.0), self.px(150.0)) } + (self.length(300.0, Axis::X), self.length(150.0, Axis::Y)) } + /// A viewport side or a measured size in device units: logical px times the scale, or cells + /// as they are (a Measure answers in cells in Cells). pub(super) fn px(self, logical: f32) -> f32 { logical * self.k } + /// A Px length of the document in device units along `axis`: times the scale in Pixels, divided + /// by the cell metric in Cells. Taffy's rounding then lands it on a device pixel or a cell. + pub(super) fn length(self, px: f32, axis: Axis) -> f32 { + if self.cells { + px / match axis { + Axis::X => CELL_PX.0, + Axis::Y => CELL_PX.1, + } + } else { + px * self.k + } + } + + /// A border side of `px` along `axis`: its Px length, and in Cells at least one cell when it is + /// nonzero, so the terminal shows the border and content never sits under it. Zero stays zero. + pub(super) fn border(self, px: f32, axis: Axis) -> f32 { + let length = self.length(px, axis); + if self.cells && px > 0.0 { length.max(1.0) } else { length } + } + + /// A control's form, read off its laid border-box height `h` and the laid height `row` of its + /// content node, never fed back to the solve: in Pixels always `Bordered`; in Cells `Bordered` + /// from `BORDERED_ROWS` rows and only when the content row fits between the border rows, else + /// `Compact` (ruling cells-bordered-needs-content-fit). + pub(super) fn form(self, h: f32, row: f32) -> ControlForm { + let (_, edge) = self.inset(ControlForm::Bordered, f32::INFINITY, f32::INFINITY); + if !self.cells || (h >= BORDERED_ROWS && row + 2.0 * edge <= h) { ControlForm::Bordered } else { ControlForm::Compact } + } + + /// The inset of a laid control's content from its border box, `(x, y)`, in device units: the one + /// rule, owned here. In Pixels: the 2 px of chrome. In Cells a `Bordered` control keeps one cell + /// clear on every side, a `Compact` one a cell on each side across and none down. Never more than + /// half a side. + pub(super) fn inset(self, form: ControlForm, w: f32, h: f32) -> (f32, f32) { + let (x, y) = match (self.cells, form) { + (false, _) => (self.px(2.0), self.px(2.0)), + (true, ControlForm::Bordered) => (1.0, 1.0), + (true, ControlForm::Compact) => (1.0, 0.0), + }; + (x.min(w / 2.0).max(0.0), y.min(h / 2.0).max(0.0)) + } + fn logical(self, device: f32) -> f32 { device / self.k } diff --git a/crates/thing-core/src/layout/mod.rs b/crates/thing-core/src/layout/mod.rs index e23b407..169c1d1 100644 --- a/crates/thing-core/src/layout/mod.rs +++ b/crates/thing-core/src/layout/mod.rs @@ -4,7 +4,7 @@ //! //! Pixels mode runs the solver in device pixels (every Px length and every measured size is //! multiplied by the scale factor at the one adapter) with Taffy's cumulative rounding, so every -//! edge lands on a device pixel and adjacent boxes share it. Cells mode ignores the scale. The +//! edge lands on a device pixel and adjacent boxes share it. Cells mode ignores the scale and converts a Px length at the cell metric (8x16 device px per cell). The //! viewport is a block container the document root flows in, and is not itself in the output. //! Overlays are out of flow: after the main pass each is laid out as its own root against its anchor //! and appended after every main-tree node. @@ -19,7 +19,7 @@ use measure::Device; use thing_contract::{NodeId, OverlayNode}; pub use measure::{Avail, CellStyle, Constraint, FontId, Glyph, Leaf, Measure, Run, TextLayout, TextLine, TextRequest}; -pub(crate) use measure::MAX_DEVICE; +pub(crate) use measure::{CELL_PX, MAX_DEVICE}; use crate::bind::BoundTree; use crate::diagnostic::{Code, Diagnostic}; @@ -69,6 +69,34 @@ pub struct LaidNode { /// it. Layout never sees a scroll position, so a scroll never re-runs layout. pub max_scroll: Option<(f32, f32)>, pub clip: Option, + /// A control's (Button, TextInput, Select, Toggle) form and content box, stated by layout; render + /// draws what this says and infers nothing from geometry. `None` for every other node. + pub control: Option, +} + +/// The two forms of a control. In Pixels every control is `Bordered` (render draws chrome behind its +/// content). In Cells a control laid 3 rows or taller is `Bordered`: its border stands in the edge +/// cells and its content keeps one cell clear on every side. A control laid shorter is `Compact`: its +/// one-row affordance on the first row, one cell each side. +/// +/// The form is a function of the laid border-box height alone (`Device::form`), read after the one +/// solve. A content-sized control is at least 3 rows because its border rows are in its max-content +/// height, not its min-content height: a short container still squeezes it to one compact row. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ControlForm { + Bordered, + Compact, +} + +/// A laid control: the form layout chose and the box its content is laid or drawn in, in device px +/// (Pixels) or cells: the border box less the form's inset. A Pixels Button's content is laid +/// without an inset, so its content box is its border box. `Compact` is the form of a control whose +/// content row does not fit between the border rows: its content stands from the first row and runs +/// past the last, so a painter clips a `Compact` control to its rect. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct LaidControl { + pub form: ControlForm, + pub content: Rect, } /// Every laid node in paint order (document order, Repeat instances spliced), and the style @@ -121,26 +149,14 @@ pub fn layout(tree: &BoundTree, frame: &LayoutFrame, measure: &mut dyn Measure) }; let mut nodes = Vec::new(); let mut diagnostics = Vec::new(); - let main = tree::build(tree, dev, tree::Top::Document, (vw, vh), measure); - let overlays = solve(tree, main, dev, (vw, vh), (0.0, 0.0), measure, &mut nodes, &mut diagnostics)?; + let overlays = solve(tree, tree::Top::Document, dev, (vw, vh), (0.0, 0.0), measure, &mut nodes, &mut diagnostics)?; overlay::place_all(tree, dev, (vw, vh), overlays, measure, &mut nodes, &mut diagnostics)?; Ok(LaidTree { nodes, diagnostics }) } -/// Solve one built Taffy tree in `size` device px, its origin at `origin`, and append its laid -/// nodes (absolute, in entry order) and its diagnostics. Returns the Overlays the tree met in flow. -#[allow(clippy::too_many_arguments)] -fn solve<'a>( - tree: &BoundTree, - mut built: tree::Built<'a>, - dev: Device, - size: (f32, f32), - origin: (f32, f32), - measure: &mut dyn Measure, - nodes: &mut Vec, - diagnostics: &mut Vec, -) -> Result, LayoutError> { - let tree::Built { taffy, root, entries, leaves, diagnostics: own, overlays } = &mut built; +/// Run the one solve over a built tree in `size` device px. +fn compute(built: &mut tree::Built, dev: Device, size: (f32, f32), measure: &mut dyn Measure) { + let tree::Built { taffy, root, entries, leaves, .. } = built; let space = Size { width: AvailableSpace::Definite(size.0), height: AvailableSpace::Definite(size.1) }; // Entries come parent first, so one pass finds the deepest; the viewport and a spare few add. let mut depth = vec![1usize; entries.len()]; @@ -164,14 +180,41 @@ fn solve<'a>( }) .expect("taffy: the root is in the tree") }); +} + +/// Build and solve one Taffy tree in `size` device px, its origin at `origin`, and append its laid +/// nodes (absolute, in entry order) and its diagnostics. Returns the Overlays the tree met in flow. +/// +/// One build, one solve: a control's form is read off the height Taffy laid it, never fed back. +#[allow(clippy::too_many_arguments)] +fn solve<'a>( + tree: &'a BoundTree, + top: tree::Top<'a>, + dev: Device, + size: (f32, f32), + origin: (f32, f32), + measure: &mut dyn Measure, + nodes: &mut Vec, + diagnostics: &mut Vec, +) -> Result, LayoutError> { + let mut built = tree::build(tree, dev, top, size, measure); + compute(&mut built, dev, size, measure); + let tree::Built { taffy, entries, diagnostics: own, overlays, .. } = &mut built; let base = nodes.len(); let mut absolute: Vec<(f32, f32)> = Vec::with_capacity(entries.len()); for entry in entries.iter() { let laid = taffy.layout(entry.node).expect("taffy: node is in the tree"); let (px, py) = entry.parent.map_or(origin, |parent| absolute[parent]); let (x, y) = (px + laid.location.x, py + laid.location.y); - absolute.push((x, y)); let (w, h) = (laid.size.width, laid.size.height); + // The content row's laid height. A control without a content node (a Pixels Button, a + // non-control) passes `h`, which the form never reads. + let row = entry.control.and_then(|c| c.inner).map_or(h, |inner| taffy.layout(inner).expect("taffy: node is in the tree").size.height); + let form = dev.form(h, row); + let (ix, iy) = entry.control.filter(|c| c.inset).map_or((0.0, 0.0), |_| dev.inset(form, w, h)); + // The origin the children are placed from: a control's content node sits where the inset + // says, not where Taffy put it. + absolute.push(if entry.control.is_some_and(|c| c.inner.is_some()) { (x + ix, y + iy) } else { (x, y) }); // Taffy's content extent is measured from the padding box. `content` is never smaller than // the border box; `max_scroll` is what the content reaches past the padding box. let reached = entry.scroll.then(|| { @@ -202,6 +245,10 @@ fn solve<'a>( w: clean(w - laid.border.left - laid.border.right), h: clean(h - laid.border.top - laid.border.bottom), }); + let control = entry.control.map(|_| LaidControl { + form, + content: Rect { x: clean(x + ix), y: clean(y + iy), w: clean(w - 2.0 * ix), h: clean(h - 2.0 * iy) }, + }); nodes.push(LaidNode { id: entry.id.clone(), parent: entry.parent.map(|parent| (base + parent) as u32), @@ -209,6 +256,7 @@ fn solve<'a>( content, max_scroll, clip, + control, }); } diagnostics.append(own); diff --git a/crates/thing-core/src/layout/overlay.rs b/crates/thing-core/src/layout/overlay.rs index 9a594d3..71f7dbe 100644 --- a/crates/thing-core/src/layout/overlay.rs +++ b/crates/thing-core/src/layout/overlay.rs @@ -8,7 +8,7 @@ use std::collections::HashMap; use thing_contract::{Anchor, NodeId, OverlayNode}; use super::measure::Device; -use super::tree::{self, Top}; +use super::tree::Top; use super::{LaidNode, LayoutError, Measure, Rect, solve}; use crate::bind::BoundTree; use crate::diagnostic::{Code, Diagnostic}; @@ -44,9 +44,8 @@ pub(super) fn place_all<'a>( } }, }; - let built = tree::build(tree, dev, Top::Overlay(overlay), (anchor.w, anchor.h), measure); let start = nodes.len(); - let nested = solve(tree, built, dev, (anchor.w, anchor.h), (anchor.x, anchor.y), measure, nodes, diagnostics)?; + let nested = solve(tree, Top::Overlay(overlay), dev, (anchor.w, anchor.h), (anchor.x, anchor.y), measure, nodes, diagnostics)?; for node in &nodes[start..] { rects.entry(node.id.clone()).or_insert(node.rect); } diff --git a/crates/thing-core/src/layout/style.rs b/crates/thing-core/src/layout/style.rs index 6816c35..6f6f4dc 100644 --- a/crates/thing-core/src/layout/style.rs +++ b/crates/thing-core/src/layout/style.rs @@ -13,7 +13,7 @@ use taffy::{ }; use thing_contract as c; -use super::measure::{Device, MAX_DEVICE}; +use super::measure::{Axis, Device, MAX_DEVICE}; /// Field names of the slots that took their initial value. pub(super) type Invalid = Vec<&'static str>; @@ -23,34 +23,34 @@ fn number(value: f64, negative: bool) -> Option { fits.then_some(value as f32) } -fn length(scalar: &c::Scalar, dev: Device, negative: bool) -> Option { - number(scalar.value, negative).map(|v| dev.px(v)).filter(|v| v.abs() <= MAX_DEVICE) +fn length(scalar: &c::Scalar, dev: Device, axis: Axis, negative: bool) -> Option { + number(scalar.value, negative).map(|v| dev.length(v, axis)).filter(|v| v.abs() <= MAX_DEVICE) } fn percent(scalar: &c::Scalar, negative: bool) -> Option { number(scalar.value, negative).map(|v| v / 100.0) } -fn lp(d: &c::Dimension, dev: Device) -> Option { +fn lp(d: &c::Dimension, dev: Device, axis: Axis) -> Option { match d { - c::Dimension::Px(s) => length(s, dev, false).map(LengthPercentage::length), + c::Dimension::Px(s) => length(s, dev, axis, false).map(LengthPercentage::length), c::Dimension::Percent(s) => percent(s, false).map(LengthPercentage::percent), _ => None, } } -fn lpa(d: &c::Dimension, dev: Device, negative: bool) -> Option { +fn lpa(d: &c::Dimension, dev: Device, axis: Axis, negative: bool) -> Option { match d { - c::Dimension::Px(s) => length(s, dev, negative).map(LengthPercentageAuto::length), + c::Dimension::Px(s) => length(s, dev, axis, negative).map(LengthPercentageAuto::length), c::Dimension::Percent(s) => percent(s, negative).map(LengthPercentageAuto::percent), c::Dimension::Auto => Some(LengthPercentageAuto::auto()), _ => None, } } -fn size_dim(d: &c::Dimension, dev: Device) -> Option { +fn size_dim(d: &c::Dimension, dev: Device, axis: Axis) -> Option { match d { - c::Dimension::Px(s) => length(s, dev, false).map(Dimension::length), + c::Dimension::Px(s) => length(s, dev, axis, false).map(Dimension::length), c::Dimension::Percent(s) => percent(s, false).map(Dimension::percent), c::Dimension::Auto => Some(Dimension::auto()), c::Dimension::Content => Some(Dimension::fit_content()), @@ -58,20 +58,20 @@ fn size_dim(d: &c::Dimension, dev: Device) -> Option { } } -fn basis_dim(d: &c::Dimension, dev: Device) -> Option { +fn basis_dim(d: &c::Dimension, dev: Device, axis: Axis) -> Option { match d { c::Dimension::Content => Some(Dimension::content()), c::Dimension::Fr(_) => None, - other => size_dim(other, dev), + other => size_dim(other, dev, axis), } } -fn track(d: &c::Dimension, dev: Device) -> Option> { +fn track(d: &c::Dimension, dev: Device, axis: Axis) -> Option> { use MaxTrackSizingFunction as Max; use MinTrackSizingFunction as Min; let (min, max) = match d { c::Dimension::Px(s) => { - let v = length(s, dev, false)?; + let v = length(s, dev, axis, false)?; (Min::length(v), Max::length(v)) } c::Dimension::Percent(s) => { @@ -103,16 +103,16 @@ impl Slots { fn size2(&mut self, field: &'static str, s: &c::Size2) -> Size { let dev = self.dev; Size { - width: self.take(field, size_dim(&s.width, dev), Dimension::auto()), - height: self.take(field, size_dim(&s.height, dev), Dimension::auto()), + width: self.take(field, size_dim(&s.width, dev, Axis::X), Dimension::auto()), + height: self.take(field, size_dim(&s.height, dev, Axis::Y), Dimension::auto()), } } fn size2_lpa(&mut self, field: &'static str, s: &c::Size2) -> Size { let dev = self.dev; Size { - width: self.take(field, lpa(&s.width, dev, false), LengthPercentageAuto::auto()), - height: self.take(field, lpa(&s.height, dev, false), LengthPercentageAuto::auto()), + width: self.take(field, lpa(&s.width, dev, Axis::X, false), LengthPercentageAuto::auto()), + height: self.take(field, lpa(&s.height, dev, Axis::Y, false), LengthPercentageAuto::auto()), } } @@ -125,10 +125,10 @@ impl Slots { ) -> Rect { let dev = self.dev; Rect { - left: self.take(field, lpa(&e.left, dev, negative), initial), - right: self.take(field, lpa(&e.right, dev, negative), initial), - top: self.take(field, lpa(&e.top, dev, negative), initial), - bottom: self.take(field, lpa(&e.bottom, dev, negative), initial), + left: self.take(field, lpa(&e.left, dev, Axis::X, negative), initial), + right: self.take(field, lpa(&e.right, dev, Axis::X, negative), initial), + top: self.take(field, lpa(&e.top, dev, Axis::Y, negative), initial), + bottom: self.take(field, lpa(&e.bottom, dev, Axis::Y, negative), initial), } } @@ -136,16 +136,16 @@ impl Slots { let dev = self.dev; let zero = LengthPercentage::ZERO; Rect { - left: self.take(field, lp(&e.left, dev), zero), - right: self.take(field, lp(&e.right, dev), zero), - top: self.take(field, lp(&e.top, dev), zero), - bottom: self.take(field, lp(&e.bottom, dev), zero), + left: self.take(field, lp(&e.left, dev, Axis::X), zero), + right: self.take(field, lp(&e.right, dev, Axis::X), zero), + top: self.take(field, lp(&e.top, dev, Axis::Y), zero), + bottom: self.take(field, lp(&e.bottom, dev, Axis::Y), zero), } } - fn tracks(&mut self, field: &'static str, dims: &[c::Dimension]) -> Vec> { + fn tracks(&mut self, field: &'static str, axis: Axis, dims: &[c::Dimension]) -> Vec> { let dev = self.dev; - let tracks: Option> = dims.iter().map(|d| track(d, dev)).collect(); + let tracks: Option> = dims.iter().map(|d| track(d, dev, axis)).collect(); self.take(field, tracks, Vec::new()) } @@ -179,7 +179,9 @@ fn content(align: &c::ContentAlign, auto: AlignContent) -> AlignContent { } /// The Taffy style of a Box. `dev` converts Px lengths to the solver's device units; the slots that were not legal are named in the second value. -pub(super) fn box_style(s: &c::BoxStyle, paint: &c::Paint, dev: Device) -> (Style, Invalid) { +/// `main` is the main axis of the flex container this box is a child of: a flex basis runs along +/// its parent's main axis, not the box's own. +pub(super) fn box_style(s: &c::BoxStyle, paint: &c::Paint, dev: Device, main: Axis) -> (Style, Invalid) { let c::BoxStyle { display, direction, @@ -204,11 +206,15 @@ pub(super) fn box_style(s: &c::BoxStyle, paint: &c::Paint, dev: Device) -> (Styl grid_rows, } = s; let mut slots = Slots { dev, invalid: Vec::new() }; - let border = match &paint.border { - None => LengthPercentage::ZERO, + // A border is one width on four sides: across (left, right) and down (top, bottom) it + // converts at its own axis. + let (border_x, border_y) = match &paint.border { + None => (LengthPercentage::ZERO, LengthPercentage::ZERO), Some(b) => { - let width = slots.take("border", length(&c::Scalar { value: b.width }, dev, false), 0.0); - LengthPercentage::length(width) + let side = |axis| number(b.width, false).map(|v| dev.border(v, axis)).filter(|v| v.abs() <= MAX_DEVICE); + let across = slots.take("border", side(Axis::X), 0.0); + let down = side(Axis::Y).unwrap_or(0.0); + (LengthPercentage::length(across), LengthPercentage::length(down)) } }; let overflow = match overflow { @@ -217,8 +223,8 @@ pub(super) fn box_style(s: &c::BoxStyle, paint: &c::Paint, dev: Device) -> (Styl c::Overflow::Scroll => TOverflow::Scroll, }; let gap = { - let width = slots.take("gap", lp(&gap.width, dev), LengthPercentage::ZERO); - let height = slots.take("gap", lp(&gap.height, dev), LengthPercentage::ZERO); + let width = slots.take("gap", lp(&gap.width, dev, Axis::X), LengthPercentage::ZERO); + let height = slots.take("gap", lp(&gap.height, dev, Axis::Y), LengthPercentage::ZERO); Size { width, height } }; let style = Style { @@ -240,7 +246,7 @@ pub(super) fn box_style(s: &c::BoxStyle, paint: &c::Paint, dev: Device) -> (Styl }, gap, padding: slots.edges_lp("padding", padding), - border: Rect { left: border, right: border, top: border, bottom: border }, + border: Rect { left: border_x, right: border_x, top: border_y, bottom: border_y }, margin: slots.edges_lpa("margin", margin, true, LengthPercentageAuto::ZERO), size: slots.size2("size", size), min_size: slots.size2_lpa("min_size", min_size), @@ -259,11 +265,11 @@ pub(super) fn box_style(s: &c::BoxStyle, paint: &c::Paint, dev: Device) -> (Styl flex_grow: slots.weight("grow", *grow, 0.0), flex_shrink: slots.weight("shrink", *shrink, 1.0), flex_basis: { - let basis = basis_dim(basis, dev); + let basis = basis_dim(basis, dev, main); slots.take("basis", basis, Dimension::auto()) }, - grid_template_columns: slots.tracks("grid_columns", grid_columns).into_iter().collect(), - grid_template_rows: slots.tracks("grid_rows", grid_rows).into_iter().collect(), + grid_template_columns: slots.tracks("grid_columns", Axis::X, grid_columns).into_iter().collect(), + grid_template_rows: slots.tracks("grid_rows", Axis::Y, grid_rows).into_iter().collect(), ..Style::default() }; (style, slots.invalid) @@ -272,12 +278,12 @@ pub(super) fn box_style(s: &c::BoxStyle, paint: &c::Paint, dev: Device) -> (Styl /// An Embed's style: exactly its declared size, never shrunk. pub(super) fn embed_style(width: f64, height: f64, dev: Device) -> (Style, Invalid) { let mut slots = Slots { dev, invalid: Vec::new() }; - let side = |slots: &mut Slots, value: f64| { - let v = slots.take("size", length(&c::Scalar { value }, dev, false), 0.0); + let side = |slots: &mut Slots, value: f64, axis: Axis| { + let v = slots.take("size", length(&c::Scalar { value }, dev, axis, false), 0.0); (Dimension::length(v), LengthPercentageAuto::length(v)) }; - let (w, wa) = side(&mut slots, width); - let (h, ha) = side(&mut slots, height); + let (w, wa) = side(&mut slots, width, Axis::X); + let (h, ha) = side(&mut slots, height, Axis::Y); let style = Style { size: Size { width: w, height: h }, min_size: Size { width: wa, height: ha }, diff --git a/crates/thing-core/src/layout/tree.rs b/crates/thing-core/src/layout/tree.rs index a5f049f..6e7071c 100644 --- a/crates/thing-core/src/layout/tree.rs +++ b/crates/thing-core/src/layout/tree.rs @@ -1,9 +1,10 @@ //! The walk: a `BoundTree` becomes a Taffy tree, one Taffy node per laid node, Repeats spliced. use taffy::{Style, TaffyTree}; -use thing_contract::{Node, NodeId, Overflow, OverlayNode}; +use thing_contract::{Direction, Node, NodeId, Overflow, OverlayNode}; -use super::measure::{Device, Leaf, MAX_DEVICE, intrinsic_ratio}; +use super::ControlForm; +use super::measure::{Axis, Device, Leaf, MAX_DEVICE, intrinsic_ratio}; use super::style::{Invalid, box_style, embed_style}; use crate::bind::{Bound, BoundTree, Field}; use crate::diagnostic::{Code, Diagnostic}; @@ -18,6 +19,17 @@ pub(super) struct Entry<'a> { pub(super) parent: Option, pub(super) clip: bool, pub(super) scroll: bool, + /// A control (Button, TextInput, Select, Toggle): its form and content box are published. + pub(super) control: Option, +} + +/// What `solve` needs to state a control: whether layout reserves it an inset (every control but a +/// Pixels Button) and, in Cells, the content node inside its shell whose children are placed from +/// the inset origin. +#[derive(Clone, Copy)] +pub(super) struct Control { + pub(super) inner: Option, + pub(super) inset: bool, } pub(super) struct Built<'a> { @@ -41,9 +53,13 @@ struct Builder<'a, 'm> { leaves: Vec>, diagnostics: Vec, overlays: Vec<&'a OverlayNode>, + /// The main axis of the container whose children are being visited: the axis a child's flex + /// basis runs along. The viewport is a block, whose children take no basis; across stands. + main: Axis, } /// What the Taffy tree is rooted at: the viewport holding the document root, or one Overlay. +#[derive(Clone, Copy)] pub(super) enum Top<'a> { Document, Overlay(&'a OverlayNode), @@ -71,6 +87,7 @@ pub(super) fn build<'a>( leaves: Vec::new(), diagnostics: Vec::new(), overlays: Vec::new(), + main: Axis::X, }; let mut kids = Vec::new(); let mut style = Style { @@ -107,6 +124,38 @@ pub(super) fn build<'a>( } impl<'a> Builder<'a, '_> { + /// The shell of a Cells control: a grid of three rows (an edge row of up to one row above and + /// below, the content row between) one cell in on each side, the inset rule's numbers + /// (`Device::inset`). The content node takes the middle row, at least its children's height of it (one row if it has none). The edge + /// rows give way first, so the shell lays anywhere from one row up and the form is read off the + /// height it ends with (`Device::form`). + fn shell(&mut self, content: taffy::NodeId) -> taffy::NodeId { + use taffy::style_helpers::{auto, length, line, minmax}; + let (across, down) = self.dev.inset(ControlForm::Bordered, f32::INFINITY, f32::INFINITY); + let mut seat = self.taffy.style(content).expect("taffy: node is in the tree").clone(); + // A content node with children is never laid shorter than they are (its automatic minimum), + // so the row the form reads is the content's own height; a leaf or an empty Button holds one row. + if self.taffy.children(content).expect("taffy: node is in the tree").is_empty() { + seat.min_size.height = taffy::LengthPercentageAuto::length(1.0); + } + seat.grid_row = taffy::Line { start: line(2), end: auto() }; + self.taffy.set_style(content, seat).expect("taffy: style"); + let edge = || -> taffy::GridTemplateComponent { minmax::(length(0.0), length(down)).into() }; + let content_row: taffy::GridTemplateComponent = minmax::(auto(), auto()).into(); + let style = Style { + display: taffy::Display::Grid, + grid_template_rows: vec![edge(), content_row, edge()], + padding: taffy::Rect { + left: taffy::LengthPercentage::length(across), + right: taffy::LengthPercentage::length(across), + top: taffy::LengthPercentage::length(0.0), + bottom: taffy::LengthPercentage::length(0.0), + }, + ..Style::default() + }; + self.taffy.new_with_children(style, &[content]).expect("taffy: insert") + } + fn hidden(&self, id: &NodeId) -> bool { matches!(self.tree.value(id, Field::Visible), Some(Bound::Bool(false))) } @@ -129,7 +178,7 @@ impl<'a> Builder<'a, '_> { fn entry(&mut self, id: &'a NodeId, parent: Option, overflow: &Overflow) -> usize { let clip = !matches!(overflow, Overflow::Visible); let scroll = matches!(overflow, Overflow::Scroll); - self.entries.push(Entry { id, node: taffy::NodeId::from(0u64), parent, clip, scroll }); + self.entries.push(Entry { id, node: taffy::NodeId::from(0u64), parent, clip, scroll, control: None }); self.entries.len() - 1 } @@ -149,10 +198,19 @@ impl<'a> Builder<'a, '_> { Err(()) => self.report(id, vec!["measure"]), } } + let control = matches!(leaf, Leaf::TextInput { .. } | Leaf::Toggle { .. } | Leaf::Select { .. }); let index = self.entry(id, parent, &Overflow::Visible); let context = self.leaves.len(); self.leaves.push(leaf); - let node = self.taffy.new_leaf_with_context(style, context).expect("taffy: insert"); + let mut node = self.taffy.new_leaf_with_context(style, context).expect("taffy: insert"); + if control { + // In Cells the leaf sits in its shell, which is the control's laid node. + let inner = self.dev.cells().then_some(node); + if inner.is_some() { + node = self.shell(node); + } + self.entries[index].control = Some(Control { inner, inset: true }); + } self.entries[index].node = node; out.push(node); } @@ -161,20 +219,36 @@ impl<'a> Builder<'a, '_> { &mut self, id: &'a NodeId, parent: Option, - (style, invalid): (Style, Invalid), + style: (Style, Invalid), overflow: &Overflow, + main: Axis, children: &'a [Node], out: &mut Vec, ) { + let (index, node) = self.contain(id, parent, style, overflow, main, children); + self.entries[index].node = node; + out.push(node); + } + + /// The entry and Taffy node of a container, its children visited; the caller seats the node. + fn contain( + &mut self, + id: &'a NodeId, + parent: Option, + (style, invalid): (Style, Invalid), + overflow: &Overflow, + main: Axis, + children: &'a [Node], + ) -> (usize, taffy::NodeId) { self.report(id, invalid); let index = self.entry(id, parent, overflow); let mut kids = Vec::new(); + let outer = std::mem::replace(&mut self.main, main); for child in children { self.visit(child, Some(index), &mut kids); } - let node = self.taffy.new_with_children(style, &kids).expect("taffy: insert"); - self.entries[index].node = node; - out.push(node); + self.main = outer; + (index, self.taffy.new_with_children(style, &kids).expect("taffy: insert")) } /// Append the Taffy nodes `node` contributes to its parent's children: one, none (hidden, @@ -183,13 +257,32 @@ impl<'a> Builder<'a, '_> { grow(|| match node { Node::Box(b) => { if !self.hidden(&b.common.id) { - let style = box_style(&b.style, &b.paint, self.dev); - self.container(&b.common.id, parent, style, &b.style.overflow, &b.children, out); + let style = box_style(&b.style, &b.paint, self.dev, self.main); + let main = match b.style.direction { + Direction::Row | Direction::RowReverse => Axis::X, + Direction::Column | Direction::ColumnReverse => Axis::Y, + }; + self.container(&b.common.id, parent, style, &b.style.overflow, main, &b.children, out); } } Node::Button(b) => { if !self.hidden(&b.common.id) { - self.container(&b.common.id, parent, (Style::default(), Vec::new()), &Overflow::Visible, &b.content, out); + // In Cells the Button is a shell (`Builder::shell`) around a row of its content, the + // items centred in it, so a content-sized Button's box includes its border rows and + // a short one squeezes to one compact row. Pixels: render draws the chrome behind + // the content and no inset applies. + if self.dev.cells() { + let row = Style { align_items: taffy::AlignItems::CENTER, ..Style::default() }; + let (index, inner) = self.contain(&b.common.id, parent, (row, Vec::new()), &Overflow::Visible, Axis::X, &b.content); + let shell = self.shell(inner); + self.entries[index].node = shell; + self.entries[index].control = Some(Control { inner: Some(inner), inset: true }); + out.push(shell); + } else { + let index = self.entries.len(); + self.container(&b.common.id, parent, (Style::default(), Vec::new()), &Overflow::Visible, Axis::X, &b.content, out); + self.entries[index].control = Some(Control { inner: None, inset: false }); + } } } // A Repeat has no box: its instances are its parent's children, in instance order. @@ -211,8 +304,9 @@ impl<'a> Builder<'a, '_> { Node::Use(u) => { if !self.hidden(&u.common.id) { let index = self.entry(&u.common.id, parent, &Overflow::Visible); - let least = taffy::LengthPercentageAuto::length(self.dev.placeholder()); - let style = Style { min_size: taffy::Size { width: least, height: least }, ..Style::default() }; + let (width, height) = self.dev.placeholder(); + let least = taffy::Size { width: taffy::LengthPercentageAuto::length(width), height: taffy::LengthPercentageAuto::length(height) }; + let style = Style { min_size: least, ..Style::default() }; let id = self.taffy.new_leaf(style).expect("taffy: insert"); self.entries[index].node = id; out.push(id); diff --git a/crates/thing-core/src/render/leaf.rs b/crates/thing-core/src/render/leaf.rs index 611b99b..5006af8 100644 --- a/crates/thing-core/src/render/leaf.rs +++ b/crates/thing-core/src/render/leaf.rs @@ -8,7 +8,7 @@ use super::Painter; use super::command::RenderCommand; use crate::bind::{Bound, Field}; use crate::diagnostic::{Code, Diagnostic}; -use crate::layout::{Measure, Metrics, Rect, TextRequest}; +use crate::layout::{ControlForm, LaidControl, Measure, Metrics, Rect, TextRequest}; /// Where an Image lands inside `rect` for an extent of `(w, h)` asset px (1 asset px = 1 logical /// px), and whether it must be clipped to `rect`. @@ -40,11 +40,6 @@ impl<'a> Painter<'a> { } } - /// The inset of a control's content from its border: 2 logical px, none in a cell grid. - fn inset(&self) -> f32 { - if self.input.metrics == Metrics::Cells { 0.0 } else { 2.0 } - } - fn stroke(&mut self, id: &NodeId, rect: Rect) { let color = self.named(id, "thing.control.border"); self.out.commands.push(RenderCommand::StrokeRect { rect, radius: 0.0, width: 1.0, color }); @@ -75,23 +70,33 @@ impl<'a> Painter<'a> { self.out.commands.push(RenderCommand::StrokeRect { rect, radius: 0.0, width: 1.0, color }); } - /// The content box of a control: `rect` less the inset all round. - fn content_box(&self, rect: Rect) -> Rect { - let pad = self.inset().min(rect.w / 2.0).min(rect.h / 2.0).max(0.0); - Rect { x: rect.x + pad, y: rect.y + pad, w: rect.w - 2.0 * pad, h: rect.h - 2.0 * pad } + /// A control's chrome as layout chose its form: `Bordered` is the box stroke; `Compact` is the + /// one-row affordance on the first row, whose stroke is the brackets of a one-row stroke. + fn chrome(&mut self, id: &NodeId, rect: Rect, form: ControlForm) { + match form { + ControlForm::Bordered => self.stroke(id, rect), + ControlForm::Compact => self.stroke(id, Rect { h: rect.h.min(1.0), ..rect }), + } } - pub(super) fn button(&mut self, n: &ButtonNode, rect: Rect) { + pub(super) fn button(&mut self, n: &ButtonNode, rect: Rect, control: LaidControl) { let id = &n.common.id; let enabled = self.flag(id, Field::Enabled) != Some(false); self.fill(id, rect, if enabled { "thing.control.fill" } else { "thing.control.disabled" }); - self.stroke(id, rect); + self.chrome(id, rect, control.form); } - pub(super) fn toggle(&mut self, n: &ToggleNode, rect: Rect) { + pub(super) fn toggle(&mut self, n: &ToggleNode, rect: Rect, control: LaidControl) { let id = &n.common.id; - self.stroke(id, rect); - let inner = self.content_box(rect); + let LaidControl { form, content } = control; + // A compact toggle is its glyph alone, on the one row its form keeps. + let inner = match form { + ControlForm::Bordered => content, + ControlForm::Compact => Rect { h: content.h.min(1.0), ..content }, + }; + if form == ControlForm::Bordered { + self.chrome(id, rect, form); + } let side = inner.h.min(inner.w / 2.0).max(0.0); let checked = self.flag(id, Field::Checked) == Some(true); let x = if checked { inner.x + inner.w - side } else { inner.x }; @@ -121,22 +126,23 @@ impl<'a> Painter<'a> { self.fill(id, Rect { x, y: rect.y, w: side, h: side }, "thing.control.accent"); } - pub(super) fn select(&mut self, n: &SelectNode, rect: Rect, text: &mut dyn Measure) { + pub(super) fn select(&mut self, n: &SelectNode, rect: Rect, control: LaidControl, text: &mut dyn Measure) { let id = &n.common.id; - self.stroke(id, rect); + let inner = control.content; + self.chrome(id, rect, control.form); let Some(value) = self.bound_text(id, Field::Selected) else { return }; let tree = self.tree; let label = match tree.value(id, Field::Options) { Some(Bound::Options(options)) => options.iter().find(|o| o.value == value).map_or(value, |o| o.label.as_str()), _ => value, }; - let inner = self.content_box(rect); self.draw_text(id, label, "thing.text", false, Some(1), inner, inner.h, text); } - pub(super) fn text_input(&mut self, n: &TextInputNode, rect: Rect, text: &mut dyn Measure) { + pub(super) fn text_input(&mut self, n: &TextInputNode, rect: Rect, control: LaidControl, text: &mut dyn Measure) { let id = &n.common.id; - self.stroke(id, rect); + let inner = control.content; + self.chrome(id, rect, control.form); let (content, token) = match self.bound_text(id, Field::Initial).filter(|t| !t.is_empty()) { Some(initial) => (initial, "thing.text"), None => match self.bound_text(id, Field::Placeholder) { @@ -144,7 +150,6 @@ impl<'a> Painter<'a> { None => return, }, }; - let inner = self.content_box(rect); self.draw_text(id, content, token, n.multiline, if n.multiline { None } else { Some(1) }, inner, inner.h, text); } diff --git a/crates/thing-core/src/render/mod.rs b/crates/thing-core/src/render/mod.rs index e24b0eb..847e57b 100644 --- a/crates/thing-core/src/render/mod.rs +++ b/crates/thing-core/src/render/mod.rs @@ -19,7 +19,7 @@ pub use scroll::{ScrollOffsets, clamp}; use crate::bind::{Bound, BoundTree, Field}; use crate::diagnostic::{Code, Diagnostic}; -use crate::layout::{LaidTree, MAX_DEVICE, Measure, Metrics, Rect}; +use crate::layout::{ControlForm, LaidControl, LaidNode, LaidTree, MAX_DEVICE, Measure, Metrics, Rect}; use crate::resolve::grow; use crate::theme::{Theme, fallback}; @@ -138,6 +138,11 @@ fn meet(a: Rect, b: Rect) -> Option { (x1 >= x0 && y1 >= y0).then_some(Rect { x: x0, y: y0, w: x1 - x0, h: y1 - y0 }) } +/// Whether layout states the node a `Compact` control, whose content is clipped to its rect. +fn is_compact(node: &LaidNode) -> bool { + node.control.is_some_and(|c| c.form == ControlForm::Compact) +} + fn radius(value: f64) -> f32 { let value = value as f32; if value.is_finite() && value > 0.0 { value } else { 0.0 } @@ -221,16 +226,21 @@ impl<'a> Painter<'a> { self.out.placed.push(Placed { id: laid.id.clone(), rect, visible }); self.stack.push(i); let Some(node) = node else { return }; - self.paint(node, rect, text); + let control = laid.control.map(|c| LaidControl { content: self.logical(c.content, shift), ..c }); + self.paint(node, rect, control, text); if let (Some(padding), Node::Box(b)) = (laid.clip, node) { let clip = self.logical(padding, shift); let border = self.border(b).map_or(0.0, |(_, width)| width); self.out.commands.push(RenderCommand::ClipPush { rect: clip, radius: (radius(b.paint.radius) - border).max(0.0) }); self.clips.push(clip); + } else if is_compact(laid) { + // A Compact control's content may run past its last row: cut it to the rect the form states. + self.out.commands.push(RenderCommand::ClipPush { rect, radius: 0.0 }); + self.clips.push(rect); } } - fn paint(&mut self, node: &'a Node, rect: Rect, text: &mut dyn Measure) { + fn paint(&mut self, node: &'a Node, rect: Rect, control: Option, text: &mut dyn Measure) { match node { Node::Box(b) => { let id = &b.common.id; @@ -267,11 +277,24 @@ impl<'a> Painter<'a> { _ => {} } } - Node::Button(n) => self.button(n, rect), - Node::Toggle(n) => self.toggle(n, rect), + // A control layout states no form for has nothing to draw as. + Node::Button(n) => match control { + Some(c) => self.button(n, rect, c), + None => self.placeholder(&n.common.id, rect), + }, + Node::Toggle(n) => match control { + Some(c) => self.toggle(n, rect, c), + None => self.placeholder(&n.common.id, rect), + }, Node::Slider(n) => self.slider(n, rect), - Node::Select(n) => self.select(n, rect, text), - Node::TextInput(n) => self.text_input(n, rect, text), + Node::Select(n) => match control { + Some(c) => self.select(n, rect, c, text), + None => self.placeholder(&n.common.id, rect), + }, + Node::TextInput(n) => match control { + Some(c) => self.text_input(n, rect, c, text), + None => self.placeholder(&n.common.id, rect), + }, Node::Image(n) => self.image(n, rect, text), Node::Plot(n) => self.plot(n, rect), Node::Overlay(_) | Node::Repeat(_) | Node::Slot(_) => {} @@ -282,7 +305,13 @@ impl<'a> Painter<'a> { fn close(&mut self, i: usize) { let laid = self.laid; let node = &laid.nodes[i]; - let Some(padding) = node.clip else { return }; + let Some(padding) = node.clip else { + if is_compact(node) { + self.clips.pop(); + self.out.commands.push(RenderCommand::ClipPop); + } + return; + }; self.clips.pop(); self.out.commands.push(RenderCommand::ClipPop); let Some(max) = node.max_scroll else { return }; diff --git a/crates/thing-core/src/text/cells.rs b/crates/thing-core/src/text/cells.rs index 500b73b..b527025 100644 --- a/crates/thing-core/src/text/cells.rs +++ b/crates/thing-core/src/text/cells.rs @@ -17,7 +17,7 @@ use unicode_segmentation::UnicodeSegmentation; use unicode_width::UnicodeWidthStr; use crate::bind::Bound; -use crate::layout::{Avail, CellStyle, Constraint, Leaf, Measure, Run, TextLayout, TextLine, TextRequest}; +use crate::layout::{Avail, CELL_PX, CellStyle, Constraint, Leaf, Measure, Run, TextLayout, TextLine, TextRequest}; /// The tab stop, in columns (CSS `tab-size: 8`). const TAB: u32 = 8; @@ -298,7 +298,7 @@ impl Measure for CellMeasure { Leaf::Slider { .. } => (20.0, 1.0), Leaf::Select { .. } => (20.0, 1.0), Leaf::Image { asset, .. } => match asset { - Bound::Asset(entry) => ((entry.width.get() as f32 / 8.0).ceil(), (entry.height.get() as f32 / 16.0).ceil()), + Bound::Asset(entry) => ((entry.width.get() as f32 / CELL_PX.0).ceil(), (entry.height.get() as f32 / CELL_PX.1).ceil()), _ => (0.0, 0.0), }, } diff --git a/crates/thing-core/tests/goldens/layout-f01-swarm-dashboard-cells.txt b/crates/thing-core/tests/goldens/layout-f01-swarm-dashboard-cells.txt index 6432dc9..5a28c2d 100644 --- a/crates/thing-core/tests/goldens/layout-f01-swarm-dashboard-cells.txt +++ b/crates/thing-core/tests/goldens/layout-f01-swarm-dashboard-cells.txt @@ -1,8 +1,8 @@ surface thing:surface:provider.swarm.dashboard viewport 100x37 scale 1 cells -root 0 0 100 23 -load 2 2 48 1 -minds#6:mind-1/mind-name 54 2 48 1 -minds#6:mind-2/mind-name 2 11 48 1 -minds#6:mind-3/mind-name 54 11 48 1 -restart 2 20 48 1 -restart-label 2 20 7 1 +root 0 0 100 6 +load 0 0 50 1 +minds#6:mind-1/mind-name 51 0 49 1 +minds#6:mind-2/mind-name 0 2 50 1 +minds#6:mind-3/mind-name 51 2 49 1 +restart 0 3 50 3 +restart-label 1 4 7 1 diff --git a/crates/thing-core/tests/goldens/render-f01-swarm-dashboard-cells.txt b/crates/thing-core/tests/goldens/render-f01-swarm-dashboard-cells.txt index 01ca3e3..f847bf7 100644 --- a/crates/thing-core/tests/goldens/render-f01-swarm-dashboard-cells.txt +++ b/crates/thing-core/tests/goldens/render-f01-swarm-dashboard-cells.txt @@ -1,9 +1,9 @@ surface thing:surface:provider.swarm.dashboard viewport 100x37 scale 1 cells -fill 0 0 100 23 r8 #1e1e2eff -text 2 2 #ffffffff cells "42.0%" bold=false italic=false underline=false -text 54 2 #eeeef4ff cells "Eureka" bold=false italic=false underline=false -text 2 11 #eeeef4ff cells "Libby" bold=false italic=false underline=false -text 54 11 #eeeef4ff cells "Kiko" bold=false italic=false underline=false -fill 2 20 48 1 r0 #2c2c3eff -stroke 2 20 48 1 r0 w1 #4a4a60ff -text 2 20 #eeeef4ff cells "Restart" bold=false italic=false underline=false +fill 0 0 100 6 r8 #1e1e2eff +text 0 0 #ffffffff cells "42.0%" bold=false italic=false underline=false +text 51 0 #eeeef4ff cells "Eureka" bold=false italic=false underline=false +text 0 2 #eeeef4ff cells "Libby" bold=false italic=false underline=false +text 51 2 #eeeef4ff cells "Kiko" bold=false italic=false underline=false +fill 0 3 50 3 r0 #2c2c3eff +stroke 0 3 50 3 r0 w1 #4a4a60ff +text 1 4 #eeeef4ff cells "Restart" bold=false italic=false underline=false diff --git a/crates/thing-core/tests/goldens/render-f12-text-edge-cells.txt b/crates/thing-core/tests/goldens/render-f12-text-edge-cells.txt index 1fdbefa..875c195 100644 --- a/crates/thing-core/tests/goldens/render-f12-text-edge-cells.txt +++ b/crates/thing-core/tests/goldens/render-f12-text-edge-cells.txt @@ -1,31 +1,28 @@ surface thing:surface:provider.text.text-edge viewport 40x60 scale 1 cells -text 2 2 #eeeef4ff cells "Hello שלום עולם and مرحبا بالعالم" bold=false italic=false underline=false -text 2 3 #eeeef4ff cells "then 123 end." bold=false italic=false underline=false -text 2 12 #eeeef4ff cells "日本語テスト 你好世界 한국어 ABC" bold=false italic=false underline=false widths=2,2,2,2,2,2,1,2,2,2,2,1,2,2,2,1,2,2,2 -text 2 13 #eeeef4ff cells "123" bold=false italic=false underline=false widths=2,2,2 -text 2 22 #eeeef4ff cells "e\u{301} a\u{308} n\u{303} o\u{302}\u{323} z\u{35b}\u{34f}\u{300}" bold=false italic=false underline=false -text 2 31 #eeeef4ff cells "👩\u{200d}👩\u{200d}👧\u{200d}👦 👨🏽\u{200d}💻 🏳\u{fe0f}\u{200d}🌈" bold=false italic=false underline=false widths=2,1,2,1,2 -text 2 40 #eeeef4ff cells "The quick brown fox jumps over the" bold=false italic=false underline=false -text 2 41 #eeeef4ff cells "lazy dog while the evening light" bold=false italic=false underline=false -text 2 42 #eeeef4ff cells "slides across the valley, and the" bold=false italic=false underline=false -text 2 43 #eeeef4ff cells "long paragraph keeps going so that" bold=false italic=false underline=false -text 2 44 #eeeef4ff cells "any reasonable column must break it" bold=false italic=false underline=false -text 2 45 #eeeef4ff cells "across several lines. The quick" bold=false italic=false underline=false -text 2 46 #eeeef4ff cells "brown fox jumps over the lazy dog" bold=false italic=false underline=false -text 2 47 #eeeef4ff cells "while the evening light slides" bold=false italic=false underline=false -text 2 48 #eeeef4ff cells "across the valley, and the long" bold=false italic=false underline=false -text 2 49 #eeeef4ff cells "paragraph keeps going so that any" bold=false italic=false underline=false -text 2 50 #eeeef4ff cells "reasonable column must break it" bold=false italic=false underline=false -text 2 51 #eeeef4ff cells "across several lines. The quick" bold=false italic=false underline=false -text 2 52 #eeeef4ff cells "brown fox jumps over the lazy dog" bold=false italic=false underline=false -text 2 53 #eeeef4ff cells "while the evening light slides" bold=false italic=false underline=false -text 2 54 #eeeef4ff cells "across the valley, and the long" bold=false italic=false underline=false -text 2 55 #eeeef4ff cells "paragraph keeps going so that any" bold=false italic=false underline=false -text 2 56 #eeeef4ff cells "reasonable column must break it" bold=false italic=false underline=false -text 2 57 #eeeef4ff cells "across several lines. The quick" bold=false italic=false underline=false -text 2 58 #eeeef4ff cells "brown fox jumps over the lazy dog" bold=false italic=false underline=false -text 2 59 #eeeef4ff cells "while the evening light slides" bold=false italic=false underline=false -text 2 60 #eeeef4ff cells "across the valley, and the long" bold=false italic=false underline=false -text 2 61 #eeeef4ff cells "paragraph keeps going so that any" bold=false italic=false underline=false -text 2 62 #eeeef4ff cells "reasonable column must break it" bold=false italic=false underline=false -text 2 63 #eeeef4ff cells "across several lines. " bold=false italic=false underline=false +text 0 0 #eeeef4ff cells "Hello שלום עולם and مرحبا بالعالم then" bold=false italic=false underline=false +text 0 1 #eeeef4ff cells "123 end." bold=false italic=false underline=false +text 0 3 #eeeef4ff cells "日本語テスト 你好世界 한국어 ABC12" bold=false italic=false underline=false widths=2,2,2,2,2,2,1,2,2,2,2,1,2,2,2,1,2,2,2,2,2 +text 0 4 #eeeef4ff cells "3" bold=false italic=false underline=false widths=2 +text 0 5 #eeeef4ff cells "e\u{301} a\u{308} n\u{303} o\u{302}\u{323} z\u{35b}\u{34f}\u{300}" bold=false italic=false underline=false +text 0 7 #eeeef4ff cells "👩\u{200d}👩\u{200d}👧\u{200d}👦 👨🏽\u{200d}💻 🏳\u{fe0f}\u{200d}🌈" bold=false italic=false underline=false widths=2,1,2,1,2 +text 0 8 #eeeef4ff cells "The quick brown fox jumps over the lazy" bold=false italic=false underline=false +text 0 9 #eeeef4ff cells "dog while the evening light slides" bold=false italic=false underline=false +text 0 10 #eeeef4ff cells "across the valley, and the long" bold=false italic=false underline=false +text 0 11 #eeeef4ff cells "paragraph keeps going so that any" bold=false italic=false underline=false +text 0 12 #eeeef4ff cells "reasonable column must break it across" bold=false italic=false underline=false +text 0 13 #eeeef4ff cells "several lines. The quick brown fox jumps" bold=false italic=false underline=false +text 0 14 #eeeef4ff cells "over the lazy dog while the evening" bold=false italic=false underline=false +text 0 15 #eeeef4ff cells "light slides across the valley, and the" bold=false italic=false underline=false +text 0 16 #eeeef4ff cells "long paragraph keeps going so that any" bold=false italic=false underline=false +text 0 17 #eeeef4ff cells "reasonable column must break it across" bold=false italic=false underline=false +text 0 18 #eeeef4ff cells "several lines. The quick brown fox jumps" bold=false italic=false underline=false +text 0 19 #eeeef4ff cells "over the lazy dog while the evening" bold=false italic=false underline=false +text 0 20 #eeeef4ff cells "light slides across the valley, and the" bold=false italic=false underline=false +text 0 21 #eeeef4ff cells "long paragraph keeps going so that any" bold=false italic=false underline=false +text 0 22 #eeeef4ff cells "reasonable column must break it across" bold=false italic=false underline=false +text 0 23 #eeeef4ff cells "several lines. The quick brown fox jumps" bold=false italic=false underline=false +text 0 24 #eeeef4ff cells "over the lazy dog while the evening" bold=false italic=false underline=false +text 0 25 #eeeef4ff cells "light slides across the valley, and the" bold=false italic=false underline=false +text 0 26 #eeeef4ff cells "long paragraph keeps going so that any" bold=false italic=false underline=false +text 0 27 #eeeef4ff cells "reasonable column must break it across" bold=false italic=false underline=false +text 0 28 #eeeef4ff cells "several lines. " bold=false italic=false underline=false diff --git a/crates/thing-core/tests/layout.rs b/crates/thing-core/tests/layout.rs index aba42b1..ba09f15 100644 --- a/crates/thing-core/tests/layout.rs +++ b/crates/thing-core/tests/layout.rs @@ -8,7 +8,7 @@ use taffy::{AlignContent, AlignItems, AvailableSpace, FlexDirection, Style, Taff use thing_contract::*; use thing_core::bind::{Binder, BoundTree}; use thing_core::diagnostic::Code; -use thing_core::layout::{Constraint, FrameError, LaidNode, LayoutError, LaidTree, LayoutFrame, Leaf, Measure, Metrics, TextLayout, TextRequest, layout}; +use thing_core::layout::{Constraint, ControlForm, FrameError, LaidNode, LayoutError, LaidTree, LayoutFrame, Leaf, Measure, Metrics, TextLayout, TextRequest, layout}; use thing_core::port::Ledger; use thing_core::resolve::{Limits, resolve}; use thing_testkit::build::*; @@ -1227,3 +1227,396 @@ fn overlays_hold_the_bound() { other => panic!("{other:?}"), } } + +#[test] +fn a_px_length_in_cells_is_cells_at_the_cell_metric_per_axis() { + // 8 px across and 16 px down are one cell: a width, margin or border across divides by 8, a + // height or one down by 16, and an item's basis by the axis it runs along. + let mut style = sized(80.0, 32.0); + style.padding = Edges { left: px(8.0), top: px(16.0), right: px(8.0), bottom: px(16.0) }; + let child = bx("child", sized(24.0, 16.0), vec![]); + let root = bx("root", style, vec![child]); + let laid = lay_with(&mut MemState::new(), root, &cells(100.0, 37.0)); + assert_eq!(rect(&laid, "root"), (0.0, 0.0, 10.0, 2.0)); + assert_eq!(rect(&laid, "child"), (1.0, 1.0, 3.0, 1.0)); + + let border = Paint { background: None, border: Some(Border { color: ColorRef::Rgba(Rgba { r: 0, g: 0, b: 0, a: 255 }), width: 16.0 }), radius: 0.0 }; + let framed = bx_paint("framed", sized(80.0, 48.0), border, vec![bx("inner", BoxStyle { grow: 1.0, ..plain() }, vec![])]); + let laid = lay_with(&mut MemState::new(), framed, &cells(100.0, 37.0)); + assert_eq!(rect(&laid, "inner"), (2.0, 1.0, 6.0, 1.0), "a 16 px border is 2 cells across and 1 down"); + + let along = |direction: Direction| { + let style = BoxStyle { direction, ..sized(80.0, 80.0) }; + let item = bx("item", BoxStyle { basis: px(32.0), ..plain() }, vec![]); + let laid = lay_with(&mut MemState::new(), bx("root", style, vec![item]), &cells(100.0, 37.0)); + rect(&laid, "item") + }; + assert_eq!(along(Direction::Row).2, 4.0, "a row's basis runs across: 32 px is 4 cells"); + assert_eq!(along(Direction::Column).3, 2.0, "a column's basis runs down: 32 px is 2 rows"); + + let grid = BoxStyle { + display: Display::Grid, + grid_columns: vec![px(24.0), Dimension::Fr(Scalar { value: 1.0 })], + grid_rows: vec![px(32.0)], + gap: size2(px(16.0), px(16.0)), + ..sized(80.0, 80.0) + }; + let laid = lay_with(&mut MemState::new(), bx("grid", grid, vec![bx("a", plain(), vec![]), bx("b", plain(), vec![])]), &cells(100.0, 37.0)); + assert_eq!((rect(&laid, "a").2, rect(&laid, "a").3), (3.0, 2.0), "tracks: 24 px across, 32 px down"); + assert_eq!(rect(&laid, "b").0, 5.0, "the gap across is 16 px: 2 cells"); +} + +/// A Button of `label` Text children inside a root of `size` (None: the root hugs it), laid in +/// `frame` with the engine the frame names. +fn laid_button(labels: &[(&str, &str)], size: Option<(f64, f64)>, frame: &LayoutFrame) -> LaidTree { + let content = labels.iter().map(|(id, content)| text(id, content)).collect(); + let button = Node::Button(ButtonNode { common: common("btn"), content, on_activate: command("dismiss"), enabled: lit_bool(true) }); + let style = size.map_or_else(plain, |(w, h)| sized(w, h)); + let tree = bind(&mut MemState::new(), &surface_of(bx("root", style, vec![button]))).expect("resolves"); + let mut measure: Box = match frame.metrics { + Metrics::Cells => Box::new(FixedMeasure::cells()), + Metrics::Pixels => Box::new(FixedMeasure::pixels()), + }; + layout(&tree, frame, &mut *measure).unwrap() +} + +#[test] +fn a_buttons_content_runs_in_a_row_in_both_metrics_and_is_centred_by_alignment() { + // Two items side by side, as in Pixels; the label is one item, so a tall Button centres it + // between the borders by alignment, never by changing the axis. + for frame in [cells(40.0, 10.0), pixels(640.0, 160.0, 1.0)] { + let laid = laid_button(&[("ab", "ab"), ("cd", "cd")], None, &frame); + let (ab, cd) = (rect(&laid, "ab"), rect(&laid, "cd")); + assert_eq!(ab.1, cd.1, "{:?}: one row", frame.metrics); + assert_eq!(cd.0, ab.0 + ab.2, "{:?}: cd follows ab across", frame.metrics); + } + let tall = laid_button(&[("go", "Go")], Some((160.0, 80.0)), &cells(40.0, 10.0)); + assert_eq!(rect(&tall, "btn").3, 5.0); + assert_eq!(rect(&tall, "go").1, 2.0, "the label is centred between the borders of a 5-row Button"); +} + +/// One bordered control of each kind, by name. +fn bordered(kind: &str) -> Node { + match kind { + "button" => Node::Button(ButtonNode { common: common(kind), content: vec![text("label", "Go")], on_activate: command("dismiss"), enabled: lit_bool(true) }), + "toggle" => Node::Toggle(ToggleNode { common: common(kind), checked: lit_bool(true), on_change: command("dismiss") }), + "input" => Node::TextInput(TextInputNode { + common: common(kind), + multiline: false, + input_kind: InputKind::Text, + placeholder: lit_text("type"), + initial: lit_text("hi"), + submit: command("dismiss"), + }), + "select" => { + let options = OptionList::Literal(LiteralOptions { options: vec![SelectOption { value: "a".into(), label: "Alpha".into() }] }); + let value = Bind { source: StateSource::Record(StateRef { provider: Some(ProviderId::new("provider.layout")), schema: SchemaId::new("gamecult.thing.test.swarm.v1"), key: RecordKey::new("row") }), member: path(&["Name"]), format: None }; + Node::Select(SelectNode { common: common(kind), options, value, on_change: command("dismiss") }) + } + other => panic!("no control {other}"), + } +} + +const BORDERED: [&str; 4] = ["button", "toggle", "input", "select"]; + +fn lay_control(kind: &str, size: Option<(f64, f64)>, frame: &LayoutFrame) -> LaidTree { + let style = size.map_or_else(plain, |(w, h)| sized(w, h)); + let tree = bind(&mut MemState::new(), &surface_of(bx("root", style, vec![bordered(kind)]))).expect("resolves"); + let mut measure: Box = match frame.metrics { + Metrics::Cells => Box::new(FixedMeasure::cells()), + Metrics::Pixels => Box::new(FixedMeasure::pixels()), + }; + layout(&tree, frame, &mut *measure).unwrap() +} + +/// A control's stated form and content box. +fn control(laid: &LaidTree, id: &str) -> (ControlForm, (f32, f32, f32, f32)) { + let node = laid.nodes.iter().find(|n| n.id.as_str() == id).unwrap_or_else(|| panic!("no node {id}")); + let c = node.control.unwrap_or_else(|| panic!("{id} is no control")); + (c.form, (c.content.x, c.content.y, c.content.w, c.content.h)) +} + +/// A cell row in Px. +const ROW: f64 = 16.0; + +#[test] +fn a_control_declared_under_three_rows_keeps_that_height_in_the_compact_form() { + // The author asked for 1 or 2 rows: exactly that, never floored by chrome. One cell each side + // (the brackets, the toggle glyph), no vertical inset: content on the first row. + for kind in BORDERED { + for rows in [1.0_f32, 2.0] { + let laid = lay_control(kind, Some((20.0 * 8.0, f64::from(rows) * ROW)), &cells(40.0, 10.0)); + let (x, y, w, h) = rect(&laid, kind); + assert_eq!(h, rows, "{kind}: declared {rows} rows is {rows} rows"); + assert_eq!(control(&laid, kind), (ControlForm::Compact, (x + 1.0, y, w - 2.0, h)), "{kind} at {rows} rows"); + } + } +} + +#[test] +fn a_control_of_three_rows_or_more_is_bordered_with_its_content_one_cell_in() { + for kind in BORDERED { + for rows in [3.0_f32, 4.0, 7.0] { + let laid = lay_control(kind, Some((20.0 * 8.0, f64::from(rows) * ROW)), &cells(40.0, 10.0)); + let (x, y, w, h) = rect(&laid, kind); + assert_eq!(h, rows, "{kind}: stretched to the root's {rows} rows"); + assert_eq!(control(&laid, kind), (ControlForm::Bordered, (x + 1.0, y + 1.0, w - 2.0, h - 2.0)), "{kind} at {rows} rows"); + } + } +} + +#[test] +fn a_content_sized_cells_control_is_bordered_and_includes_its_border_rows() { + for kind in BORDERED { + let laid = lay_control(kind, None, &cells(40.0, 10.0)); + let (x, y, w, h) = rect(&laid, kind); + assert!(h >= 3.0, "{kind}: a border row above and below at least one content row"); + assert_eq!(control(&laid, kind), (ControlForm::Bordered, (x + 1.0, y + 1.0, w - 2.0, h - 2.0)), "{kind}"); + } + // A label that wraps to three lines in a Button 8 cells wide: 3 rows of label between 2 of border. + let hugging = laid_button(&[("label", "abcd efgh ijkl")], None, &cells(8.0, 10.0)); + let (button, label) = (rect(&hugging, "btn"), rect(&hugging, "label")); + assert_eq!((button.3, label.3), (label.3 + 2.0, 3.0), "3 label rows and 2 border rows"); + assert_eq!((label.0, label.1), (button.0 + 1.0, button.1 + 1.0), "the label starts inside the border"); +} + +#[test] +fn a_compact_buttons_label_stands_on_its_first_row_inside_the_brackets() { + for rows in [1.0_f64, 2.0] { + let laid = laid_button(&[("go", "Go")], Some((160.0, rows * ROW)), &cells(40.0, 10.0)); + let (button, label) = (rect(&laid, "btn"), rect(&laid, "go")); + assert_eq!(button.3, rows as f32); + assert_eq!((label.0, label.1), (button.0 + 1.0, button.1), "{rows} rows: one cell in, on the first row"); + } +} + +/// `root` laid in a Cells frame, text measured in cells. +fn lay_in_cells(root: Node, w: f32, h: f32) -> LaidTree { + let tree = bind(&mut MemState::new(), &surface_of(root)).expect("resolves"); + layout(&tree, &cells(w, h), &mut FixedMeasure::cells()).unwrap() +} + +/// A column of `rows` rows holding each of `children` in a box of its own that may shrink to nothing. +fn column_of(rows: f64, children: Vec<(f64, Node)>) -> Node { + let boxes = children + .into_iter() + .enumerate() + .map(|(i, (grow, node))| { + let shrinkable = BoxStyle { grow, min_size: size2(Dimension::Auto, px(0.0)), ..plain() }; + bx(&format!("holder{i}"), shrinkable, vec![node]) + }) + .collect(); + bx("root", BoxStyle { direction: Direction::Column, size: size2(px(160.0), px(rows * ROW)), ..plain() }, boxes) +} + +fn a_button(id: &str, label: &str) -> Node { + Node::Button(ButtonNode { common: common(id), content: vec![text(&format!("{id}-label"), label)], on_activate: command("dismiss"), enabled: lit_bool(true) }) +} + +#[test] +fn the_form_is_read_off_the_final_height_whatever_a_sibling_does() { + // Soul's sticky probe: X grows and Y does not, each a min-height-0 box around a control. Whatever + // heights the one solve leaves, every control's form is Compact iff it is under 3 rows and its + // content box is its rect less that form's inset. + for kind in BORDERED { + for rows in [4.0_f64, 5.0, 6.0, 9.0] { + let root = column_of(rows, vec![(1.0, bordered(kind)), (0.0, a_button("other", "Go"))]); + let laid = lay_in_cells(root, 40.0, 20.0); + for id in [kind, "other"] { + let (x, y, w, h) = rect(&laid, id); + let expected = if h < 3.0 { + (ControlForm::Compact, (x + 1.0, y, w - 2.0, h)) + } else { + (ControlForm::Bordered, (x + 1.0, y + 1.0, w - 2.0, h - 2.0)) + }; + assert_eq!(control(&laid, id), expected, "{kind} beside a button in {rows} rows: {id} is {h} rows"); + } + } + } +} + +#[test] +fn an_empty_content_sized_button_is_three_bordered_rows() { + let button = Node::Button(ButtonNode { common: common("btn"), content: vec![], on_activate: command("dismiss"), enabled: lit_bool(true) }); + let laid = lay_in_cells(bx("root", plain(), vec![button]), 40.0, 10.0); + let (x, y, w, h) = rect(&laid, "btn"); + assert_eq!(h, 3.0, "a border row above and below one content row"); + assert_eq!(control(&laid, "btn"), (ControlForm::Bordered, (x + 1.0, y + 1.0, w - 2.0, 1.0))); +} + +#[test] +fn a_content_sized_control_shrinks_to_one_compact_row_in_a_short_column() { + // Directly in the column: no wrapper that may shrink, only the shell's edge rows giving way. + for kind in BORDERED { + for rows in [1.0_f64, 2.0] { + let root = bx("root", BoxStyle { direction: Direction::Column, size: size2(px(160.0), px(rows * ROW)), ..plain() }, vec![bordered(kind)]); + let laid = lay_in_cells(root, 40.0, 10.0); + let (x, y, w, h) = rect(&laid, kind); + assert_eq!(h, rows as f32, "{kind} in {rows} rows"); + assert_eq!(control(&laid, kind), (ControlForm::Compact, (x + 1.0, y, w - 2.0, h)), "{kind} in {rows} rows"); + } + } + let root = bx("root", BoxStyle { direction: Direction::Column, size: size2(px(160.0), px(2.0 * ROW)), ..plain() }, vec![a_button("btn", "Go")]); + let laid = lay_in_cells(root, 40.0, 10.0); + let (button, label) = (rect(&laid, "btn"), rect(&laid, "btn-label")); + assert_eq!((label.0, label.1, label.3), (button.0 + 1.0, button.1, 1.0), "a 1-row label on the first row of the 2-row Button"); +} + +/// A Button holding a block 8 cells wide and `lines` rows tall (its content row is that tall, whatever +/// the grid leaves it), alone in a root `rows` rows tall: a `column` the Button may only shrink in, or a +/// row that stretches it to the root's height. +fn button_of_lines_in(rows: f64, column: bool, lines: f64) -> LaidTree { + let content = vec![bx("blk", sized(64.0, lines * ROW), vec![])]; + let button = Node::Button(ButtonNode { common: common("btn"), content, on_activate: command("dismiss"), enabled: lit_bool(true) }); + let direction = if column { Direction::Column } else { Direction::Row }; + lay_in_cells(bx("root", BoxStyle { direction, size: size2(px(80.0), px(rows * ROW)), ..plain() }, vec![button]), 40.0, 20.0) +} + +#[test] +fn a_squeezed_control_whose_content_does_not_fit_the_border_is_compact() { + // Soul's case: 3 rows of content directly in a 4-row column. The Button lays 4 rows around a + // content row that does not fit between two border rows: Compact, content from the first row, + // clipped to the rect (render pins the clip). + let laid = button_of_lines_in(4.0, true, 3.0); + let (x, y, w, h) = rect(&laid, "btn"); + assert_eq!(h, 4.0); + assert_eq!(control(&laid, "btn"), (ControlForm::Compact, (x + 1.0, y, w - 2.0, 4.0))); + assert_eq!(rect(&laid, "blk"), (x + 1.0, y, 8.0, 3.0), "the content on the first row, three rows tall"); +} + +#[test] +fn a_control_exactly_its_content_rows_tall_is_compact() { + let laid = button_of_lines_in(3.0, true, 3.0); + let (x, y, w, h) = rect(&laid, "btn"); + assert_eq!(h, 3.0); + assert_eq!(control(&laid, "btn"), (ControlForm::Compact, (x + 1.0, y, w - 2.0, 3.0))); + assert_eq!(rect(&laid, "blk"), (x + 1.0, y, 8.0, 3.0)); +} + +#[test] +fn a_two_row_label_at_four_rows_stays_bordered() { + let laid = button_of_lines_in(4.0, false, 2.0); + let (x, y, w, h) = rect(&laid, "btn"); + assert_eq!(h, 4.0); + assert_eq!(control(&laid, "btn"), (ControlForm::Bordered, (x + 1.0, y + 1.0, w - 2.0, 2.0))); + assert_eq!(rect(&laid, "blk"), (x + 1.0, y + 1.0, 8.0, 2.0)); +} + +#[test] +fn a_control_under_three_rows_is_compact_even_when_its_content_row_is_empty() { + // Content with no height: row 0 plus two border rows is 2, which fits, but under 3 rows is Compact. + let laid = button_of_lines_in(8.0, true, 0.0); + let (x, y, w, h) = rect(&laid, "btn"); + assert_eq!(h, 2.0); + assert_eq!(control(&laid, "btn"), (ControlForm::Compact, (x + 1.0, y, w - 2.0, 2.0))); +} + +#[test] +fn a_control_whose_content_plus_its_border_is_its_height_is_bordered() { + let laid = button_of_lines_in(5.0, false, 3.0); + let (x, y, w, h) = rect(&laid, "btn"); + assert_eq!(h, 5.0); + assert_eq!(control(&laid, "btn"), (ControlForm::Bordered, (x + 1.0, y + 1.0, w - 2.0, 3.0))); + assert_eq!(rect(&laid, "blk"), (x + 1.0, y + 1.0, 8.0, 3.0)); +} + +#[test] +fn a_pixels_control_is_always_bordered_with_a_two_px_inset_and_a_pixels_button_has_none() { + // The compact form is a Cells form: a short Pixels control keeps its chrome. + for px_height in [16.0, 32.0, 100.0] { + let laid = lay_control("input", Some((200.0, px_height)), &pixels(800.0, 600.0, 2.0)); + let (x, y, w, h) = rect(&laid, "input"); + let inset = 4.0_f32.min(h / 2.0); + assert_eq!(control(&laid, "input"), (ControlForm::Bordered, (x + 4.0, y + inset, w - 8.0, h - 2.0 * inset)), "2 logical px is 4 device px at scale 2, never more than half a side"); + } + let button = lay_control("button", None, &pixels(800.0, 600.0, 2.0)); + let (x, y, w, h) = rect(&button, "button"); + assert_eq!(control(&button, "button"), (ControlForm::Bordered, (x, y, w, h)), "Pixels lays a Button's content without an inset"); + assert!(laid_node(&button, "label").control.is_none(), "a node that is no control states none"); +} + +fn laid_node<'a>(laid: &'a LaidTree, id: &str) -> &'a LaidNode { + laid.nodes.iter().find(|n| n.id.as_str() == id).unwrap_or_else(|| panic!("no node {id}")) +} + +#[test] +fn a_control_smaller_than_its_inset_gives_up_half_of_each_side_at_most() { + // A 2x2 px grid track holds an input whose 2 px chrome on each side would eat the box twice: + // the inset is capped at half a side, so the content box is empty and in the middle. + let grid = BoxStyle { display: Display::Grid, grid_columns: vec![px(2.0)], grid_rows: vec![px(2.0)], ..sized(10.0, 10.0) }; + let tree = bind(&mut MemState::new(), &surface_of(bx("root", grid, vec![bordered("input")]))).expect("resolves"); + let laid = layout(&tree, &pixels(100.0, 100.0, 1.0), &mut FixedMeasure::pixels()).unwrap(); + assert_eq!(rect(&laid, "input"), (0.0, 0.0, 2.0, 2.0)); + assert_eq!(control(&laid, "input"), (ControlForm::Bordered, (1.0, 1.0, 0.0, 0.0))); +} + +#[test] +fn a_nonzero_border_side_is_at_least_one_cell_in_cells_so_content_never_sits_under_the_stroke() { + // A 20x4-cell Box holding four text lines: whatever the hairline's width, the stroke is one cell + // wide on the perimeter and the first line starts inside it. Zero stays zero. + let framed = |width: f64| { + let border = Paint { background: None, border: Some(Border { color: ColorRef::Rgba(Rgba { r: 0, g: 0, b: 0, a: 255 }), width }), radius: 0.0 }; + let lines = ["one", "two", "three", "four"].map(|id| text(id, id)).to_vec(); + let root = bx_paint("framed", BoxStyle { direction: Direction::Column, ..sized(160.0, 64.0) }, border, lines); + lay_with(&mut MemState::new(), root, &cells(40.0, 10.0)) + }; + for (width, across, down) in [(0.0, 0.0, 0.0), (1.0, 1.0, 1.0), (4.0, 1.0, 1.0), (8.0, 1.0, 1.0), (16.0, 2.0, 1.0)] { + let laid = framed(width); + assert_eq!(rect(&laid, "framed"), (0.0, 0.0, 20.0, 4.0)); + let one = rect(&laid, "one"); + assert_eq!((one.0, one.1), (across, down), "a {width} px border: content starts at ({across}, {down})"); + } +} + +#[test] +fn a_margin_and_a_min_size_convert_each_side_at_its_own_axis_in_cells() { + // Every side of the two slots with a different Px length down than across, so an axis swap on + // any one moves a rect: margin-bottom 32 px is 2 rows (not 4), min-height 48 px is 3 rows (not 6). + let column = BoxStyle { direction: Direction::Column, align_items: ItemAlign::Start, ..sized(160.0, 160.0) }; + let a_style = BoxStyle { + size: size2(px(8.0), px(16.0)), + margin: Edges { top: px(16.0), right: px(24.0), bottom: px(32.0), left: px(8.0) }, + ..plain() + }; + let b_style = BoxStyle { min_size: size2(px(24.0), px(48.0)), ..plain() }; + let laid = lay_with(&mut MemState::new(), bx("root", column, vec![bx("a", a_style, vec![]), bx("b", b_style, vec![])]), &cells(40.0, 20.0)); + assert_eq!(rect(&laid, "a"), (1.0, 1.0, 1.0, 1.0), "margin left 8 px is 1 cell across, top 16 px is 1 row down"); + assert_eq!(rect(&laid, "b").1, 1.0 + 1.0 + 2.0, "a's top margin, a, then its 32 px bottom margin: 2 rows"); + assert_eq!((rect(&laid, "b").2, rect(&laid, "b").3), (3.0, 3.0), "min size 24 px across is 3 cells, 48 px down is 3 rows"); + let row = BoxStyle { align_items: ItemAlign::Start, ..sized(160.0, 160.0) }; + let right = lay_with(&mut MemState::new(), bx("root", row, vec![bx("a", a_style_with_margin_right(), vec![]), bx("b", plain(), vec![])]), &cells(40.0, 20.0)); + assert_eq!(rect(&right, "b").0, 1.0 + 1.0 + 3.0, "a's 8 px left margin, a (1 cell), then its 24 px right margin: 3 cells"); +} + +fn a_style_with_margin_right() -> BoxStyle { + BoxStyle { size: size2(px(8.0), px(16.0)), margin: Edges { top: px(0.0), right: px(24.0), bottom: px(0.0), left: px(8.0) }, ..plain() } +} + +#[test] +fn f11_lays_out_its_whole_nest_in_cells_at_the_cell_metric_of_its_pixels_layout() { + // f11 paints nothing in any mode, so its nesting is a layout fact. In Cells the chain is the + // same nest at the metric: each level inside the last, every rect within a cell of the Pixels + // rect divided by 8 across and 16 down (its 2 px padding per side compounds over the levels). + let document = Fixture::F11Deep.load().surfaces.remove(0); + let tree = bind(&mut MemState::from_fixture(Fixture::F11Deep), &document).unwrap(); + let device = layout(&tree, &pixels(800.0, 600.0, 1.0), &mut FixedMeasure::pixels()).unwrap(); + let laid = layout(&tree, &cells(100.0, 37.0), &mut FixedMeasure::cells()).unwrap(); + assert_eq!(laid.nodes.len(), device.nodes.len()); + assert!(laid.nodes.len() > 20); + for (i, (cell, px)) in laid.nodes.iter().zip(&device.nodes).enumerate() { + assert_eq!((&cell.id, cell.parent), (&px.id, px.parent), "level {i}"); + assert_eq!(cell.parent, i.checked_sub(1).map(|p| p as u32), "level {i} is the only child of the last"); + for (cells, device, per) in [(cell.rect.x, px.rect.x, 8.0), (cell.rect.y, px.rect.y, 16.0), (cell.rect.w, px.rect.w, 8.0), (cell.rect.h, px.rect.h, 16.0)] { + assert!((cells - device / per).abs() <= 1.0, "level {i}: {cells} cells vs {device} px / {per}"); + } + if let Some(parent) = cell.parent { + let outer = laid.nodes[parent as usize].rect; + let inner = cell.rect; + assert!(inner.x >= outer.x && inner.y >= outer.y && inner.x + inner.w <= outer.x + outer.w && inner.y + inner.h <= outer.y + outer.h, "level {i} lies inside level {}", i - 1); + } + } + let root = laid.nodes[0].rect; + let innermost = laid.nodes.last().expect("a nest").rect; + assert_eq!((root.x, root.y, root.w), (0.0, 0.0, 100.0), "the root fills the viewport across"); + assert!(innermost.w > 0.0 && innermost.x > root.x, "the padding of every level narrows the nest to the innermost"); +} diff --git a/crates/thing-core/tests/render.rs b/crates/thing-core/tests/render.rs index e2dcd66..1ab0153 100644 --- a/crates/thing-core/tests/render.rs +++ b/crates/thing-core/tests/render.rs @@ -558,7 +558,7 @@ fn wrapping_text_is_one_command_per_engine_line_at_the_node_origin() { assert_eq!(t.3, 64.0, "layout sized the leaf for the lines the engine returns"); // Cells: the line's characters, one row each. let cells = frame(20.0, 10.0, 1.0, Metrics::Cells); - let root = if let Node::Box(mut b) = root { b.style.size = size2(px(5.0), Dimension::Auto); b.style.padding = edges(px(0.0)); Node::Box(b) } else { unreachable!() }; + let root = if let Node::Box(mut b) = root { b.style.size = size2(px(40.0), Dimension::Auto); b.style.padding = edges(px(0.0)); Node::Box(b) } else { unreachable!() }; let (_, rendered) = inline(root, &cells, &ScrollOffsets::default()); let texts: Vec<(f32, f32, String)> = rendered .commands @@ -591,6 +591,64 @@ fn leaves_draw_what_this_cut_owns() { assert_eq!(rendered.placed.len(), laid.nodes.len()); } +#[test] +fn a_control_layout_states_no_form_for_paints_the_placeholder() { + // Render invents no form: a Button and a TextInput whose laid node carries no control are the + // placeholder and nothing else, not chrome as a bordered control. + let button = Node::Button(ButtonNode { common: common("btn"), content: vec![], on_activate: command("dismiss"), enabled: lit_bool(true) }); + let field = Node::TextInput(TextInputNode { + common: common("field"), + multiline: false, + input_kind: InputKind::Text, + placeholder: lit_text("type"), + initial: lit_text("hi"), + submit: command("dismiss"), + }); + let root = flat("root", BoxStyle { direction: Direction::Column, size: size2(px(160.0), px(160.0)), ..plain() }, vec![button, field]); + let tree = bind(&mut MemState::new(), &surface_of(root)).expect("resolves"); + let frame = frame(20.0, 10.0, 1.0, Metrics::Cells); + let mut laid = layout(&tree, &frame, &mut *measure(&frame)).unwrap(); + for node in laid.nodes.iter_mut().filter(|n| matches!(n.id.as_str(), "btn" | "field")) { + assert!(node.control.take().is_some(), "{} is a laid control", node.id.as_str()); + } + let scroll = ScrollOffsets::default(); + let theme = Theme::std(); + let rendered = render(&tree, &laid, &input(&frame, &scroll, &theme), &mut *measure(&frame)); + let (btn, field) = (placed(&rendered, "btn").rect, placed(&rendered, "field").rect); + let placeholder = |r: thing_core::layout::Rect| { + [ + RenderCommand::FillRect { rect: r, radius: 0.0, color: color("thing.placeholder") }, + RenderCommand::StrokeRect { rect: r, radius: 0.0, width: 1.0, color: color("thing.error") }, + ] + }; + let expected: Vec<_> = placeholder(btn).into_iter().chain(placeholder(field)).collect(); + assert_eq!(rendered.commands, expected); +} + +#[test] +fn a_compact_buttons_overflowing_content_is_clipped_to_its_rect() { + // A 3-row label in a Button stretched to 2 rows: Compact, so its label runs past the last row and + // render cuts it to the Button's rect. Bordered controls, whose content fits, push no clip. + let button = Node::Button(ButtonNode { + common: common("btn"), + content: vec![text("label", "abcd efgh ijkl")], + on_activate: command("dismiss"), + enabled: lit_bool(true), + }); + let root = flat("root", BoxStyle { size: size2(px(80.0), px(32.0)), ..plain() }, vec![button]); + let (laid, out) = inline(root, &frame(20.0, 10.0, 1.0, Metrics::Cells), &ScrollOffsets::default()); + let node = laid.nodes.iter().find(|n| n.id.as_str() == "btn").unwrap(); + assert_eq!((node.rect.h, node.control.map(|c| c.form)), (2.0, Some(thing_core::layout::ControlForm::Compact))); + let rect = placed(&out, "btn").rect; + let at = |want: fn(&RenderCommand) -> bool| out.commands.iter().position(want).expect("a command"); + let (push, pop) = (at(|c| matches!(c, RenderCommand::ClipPush { .. })), at(|c| matches!(c, RenderCommand::ClipPop))); + assert_eq!(out.commands[push], RenderCommand::ClipPush { rect, radius: 0.0 }); + let texts: Vec = (0..out.commands.len()).filter(|&i| matches!(out.commands[i], RenderCommand::Text { .. })).collect(); + assert!(!texts.is_empty() && texts.iter().all(|&i| push < i && i < pop), "every label line between the push and the pop: {:?}", out.commands); + assert_eq!(out.commands.iter().filter(|c| matches!(c, RenderCommand::ClipPush { .. })).count(), 1); + assert!(balanced(&out.commands)); +} + #[test] fn an_oversize_asset_extent_through_bind_is_an_invalid_measure_and_renders() { let provider = ProviderId::new("provider.render"); @@ -1022,7 +1080,7 @@ fn a_plot_is_sized_by_layout_to_the_default_object_size() { let scaled = with_state(&mut MemState::new(), plot(), &pixels(2.0)); assert_eq!(placed(&scaled, "p").rect, rect(0.0, 0.0, 300.0, 150.0), "logical, whatever the scale"); let cells = with_state(&mut MemState::new(), plot(), &frame(80.0, 30.0, 1.0, Metrics::Cells)); - assert_eq!(placed(&cells, "p").rect, rect(0.0, 0.0, 38.0, 10.0)); + assert_eq!(placed(&cells, "p").rect, rect(0.0, 0.0, 38.0, 9.0), "300x150 px at 8x16 is 37.5x9.375 cells, rounded"); } fn knob(rendered: &Rendered) -> Rect { @@ -1179,3 +1237,178 @@ fn the_alt_line_of_a_placeholder_draws_only_when_it_fits() { assert_eq!(lines_of(&in_grid(40.0)), ["alt"]); assert_eq!(lines_of(&in_grid(10.0)), Vec::::new(), "a 16 high line does not fit 10"); } + +/// The `(x, y)` of every Cells text origin in `root` at 30x12 cells. +fn cells_text_origins(root: Node) -> Vec<(f32, f32)> { + let (_, rendered) = inline(root, &frame(30.0, 12.0, 1.0, Metrics::Cells), &ScrollOffsets::default()); + rendered + .commands + .iter() + .filter_map(|c| match c { + RenderCommand::Text { origin, .. } => Some(*origin), + _ => None, + }) + .collect() +} + +#[test] +fn cells_content_keeps_clear_of_every_bordered_controls_border() { + // A content-sized control is a box with its border rows: one cell in on every side. A + // TextInput's text starts at (1, 1) of its box, never on the border. + let input = Node::TextInput(TextInputNode { + common: common("i"), + multiline: false, + input_kind: InputKind::Text, + placeholder: lit_text("type"), + initial: lit_text("hi"), + submit: command("dismiss"), + }); + assert_eq!(cells_text_origins(flat("root", plain(), vec![input])), [(1.0, 1.0)]); + // A Button's content likewise, with the label centred between the borders of a tall Button. + let button = |height: f64| { + let mut style = plain(); + style.size = size2(px(20.0 * 8.0), px(height * 16.0)); + let node = Node::Button(ButtonNode { common: common("b"), content: vec![text("label", "Go")], on_activate: command("dismiss"), enabled: lit_bool(true) }); + flat("root", style, vec![node]) + }; + assert_eq!(cells_text_origins(button(3.0)), [(1.0, 1.0)]); + assert_eq!(cells_text_origins(button(5.0)), [(1.0, 2.0)]); + // Pixels are unchanged: content sits on the content box, 2 px in. + let pixels_input = Node::TextInput(TextInputNode { + common: common("i"), + multiline: false, + input_kind: InputKind::Text, + placeholder: lit_text("type"), + initial: lit_text("hi"), + submit: command("dismiss"), + }); + let r = rendered(flat("root", plain(), vec![pixels_input])); + assert!(matches!(r.commands.last(), Some(RenderCommand::Text { origin, .. }) if origin.0 == 2.0)); +} + +#[test] +fn an_image_extent_and_a_px_box_of_the_same_size_are_the_same_cells() { + // One cell is 8x16 device px for both: the Image's pixel extent and a Box's Px size. + let provider = ProviderId::new(PROVIDER); + let mut state = MemState::new(); + state.put(&provider, &catalog(&[("pic", 64, 32)])); + let root = flat("root", plain(), vec![image("pic", "pic", ImageFit::Fill), flat("twin", sized(64.0, 32.0), vec![])]); + let tree = bind(&mut state, &surface_of(root)).expect("resolves"); + let frame = frame(30.0, 12.0, 1.0, Metrics::Cells); + let (_, rendered) = draw_with(Engine::Real, &tree, &frame, &ScrollOffsets::default()); + assert_eq!(xywh(placed(&rendered, "pic")), (0.0, 0.0, 8.0, 2.0)); + assert_eq!(xywh(placed(&rendered, "twin")), (8.0, 0.0, 8.0, 2.0)); +} + +#[test] +fn render_paints_the_form_layout_stated_for_a_cells_control() { + // Bordered (3 rows or more): the box stroke. Compact (under 3): the brackets, a one-row stroke + // on the first row; a toggle is its glyph alone, no stroke. Layout chose; render drew that. + let strokes = |kind: &str, rows: f64| { + let mut style = plain(); + style.size = size2(px(20.0 * 8.0), px(rows * 16.0)); + let node = match kind { + "input" => Node::TextInput(TextInputNode { + common: common("c"), + multiline: false, + input_kind: InputKind::Text, + placeholder: lit_text("type"), + initial: lit_text("hi"), + submit: command("dismiss"), + }), + "select" => { + let options = OptionList::Literal(LiteralOptions { options: vec![SelectOption { value: "a".into(), label: "Alpha".into() }] }); + let value = Bind { source: StateSource::Record(StateRef { provider: Some(ProviderId::new(PROVIDER)), schema: SchemaId::new("gamecult.thing.test.series.v1"), key: RecordKey::new("row") }), member: path(&["Name"]), format: None }; + Node::Select(SelectNode { common: common("c"), options, value, on_change: command("dismiss") }) + } + "toggle" => Node::Toggle(ToggleNode { common: common("c"), checked: lit_bool(true), on_change: command("dismiss") }), + _ => Node::Button(ButtonNode { common: common("c"), content: vec![text("label", "Go")], on_activate: command("dismiss"), enabled: lit_bool(true) }), + }; + let (_, rendered) = inline(flat("root", style, vec![node]), &frame(30.0, 12.0, 1.0, Metrics::Cells), &ScrollOffsets::default()); + let rects: Vec<(f32, f32)> = rendered + .commands + .iter() + .filter_map(|c| match c { + RenderCommand::StrokeRect { rect, .. } => Some((rect.y, rect.h)), + _ => None, + }) + .collect(); + rects + }; + for kind in ["input", "select", "button"] { + assert_eq!(strokes(kind, 1.0), [(0.0, 1.0)], "{kind} at 1 row: brackets"); + assert_eq!(strokes(kind, 2.0), [(0.0, 1.0)], "{kind} at 2 rows: brackets on the first row"); + assert_eq!(strokes(kind, 3.0), [(0.0, 3.0)], "{kind} at 3 rows: the box"); + assert_eq!(strokes(kind, 6.0), [(0.0, 6.0)], "{kind} at 6 rows: the box"); + } + assert!(strokes("toggle", 1.0).is_empty() && strokes("toggle", 2.0).is_empty(), "a compact toggle is its glyph"); + assert_eq!(strokes("toggle", 3.0), [(0.0, 3.0)]); +} + +#[test] +fn a_compact_controls_text_stands_one_cell_in_on_its_first_row() { + let input = |rows: f64| { + let mut style = plain(); + style.size = size2(px(20.0 * 8.0), px(rows * 16.0)); + let node = Node::TextInput(TextInputNode { + common: common("i"), + multiline: false, + input_kind: InputKind::Text, + placeholder: lit_text("type"), + initial: lit_text("hi"), + submit: command("dismiss"), + }); + cells_text_origins(flat("root", style, vec![node])) + }; + assert_eq!(input(1.0), [(1.0, 0.0)]); + assert_eq!(input(2.0), [(1.0, 0.0)]); + assert_eq!(input(3.0), [(1.0, 1.0)]); +} + +#[test] +fn a_use_placeholder_is_16_px_at_the_cell_metric_in_cells() { + // The least a Use placeholder takes is 16 logical px: 2 cells across and 1 down at 8x16, the + // same Px length a Box states, not a cell count of its own. + let use_node = || { + Node::Use(UseNode { + common: common("u"), + composition: CompositionRef { publisher: "nobody".into(), name: seg("missing"), version: ver(1) }, + args: vec![], + }) + }; + let (_, cells) = inline(flat("root", BoxStyle { direction: Direction::Column, align_items: ItemAlign::Start, ..plain() }, vec![use_node()]), &frame(40.0, 10.0, 1.0, Metrics::Cells), &ScrollOffsets::default()); + assert_eq!(placed(&cells, "u").rect, rect(0.0, 0.0, 2.0, 1.0)); + let twin = flat("root", BoxStyle { direction: Direction::Column, align_items: ItemAlign::Start, ..plain() }, vec![flat("twin", sized(16.0, 16.0), vec![])]); + let (_, boxed) = inline(twin, &frame(40.0, 10.0, 1.0, Metrics::Cells), &ScrollOffsets::default()); + assert_eq!(placed(&boxed, "twin").rect, placed(&cells, "u").rect, "a 16 px Box and a Use placeholder are the same cells"); +} + +#[test] +fn a_compact_toggles_glyph_is_one_cell_on_its_first_row_whatever_its_declared_height() { + for rows in [1.0_f64, 2.0] { + for checked in [false, true] { + let mut style = plain(); + style.size = size2(px(20.0 * 8.0), px(rows * 16.0)); + let toggle = Node::Toggle(ToggleNode { common: common("t"), checked: lit_bool(checked), on_change: command("dismiss") }); + let (_, out) = inline(flat("root", style, vec![toggle]), &frame(30.0, 12.0, 1.0, Metrics::Cells), &ScrollOffsets::default()); + let whole = placed(&out, "t").rect; + let x = if checked { whole.x + whole.w - 2.0 } else { whole.x + 1.0 }; + assert_eq!(knob(&out), rect(x, 0.0, 1.0, 1.0), "{rows} rows, checked {checked}: one cell, one cell in from its side"); + } + } +} + +#[test] +fn a_pixels_control_draws_its_content_in_logical_px_at_any_scale() { + // The content box layout states is device px; render divides it by the scale: 2 logical px in. + let input = Node::TextInput(TextInputNode { + common: common("i"), + multiline: false, + input_kind: InputKind::Text, + placeholder: lit_text("type"), + initial: lit_text("hi"), + submit: command("dismiss"), + }); + let out = with_state(&mut MemState::new(), flat("root", plain(), vec![input]), &pixels(2.0)); + assert!(matches!(out.commands.last(), Some(RenderCommand::Text { origin, .. }) if origin.0 == 2.0), "{:?}", out.commands.last()); +} 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..c4e3cad --- /dev/null +++ b/crates/thing-tui/src/paint.rs @@ -0,0 +1,395 @@ +//! 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") + } + + /// Whether `(c, r)` may be written: inside the clip, and not half of a wide cluster whose other + /// half the clip does not hold (that half would be corrupted, so the cluster is left whole). + fn free(&self, c: i64, r: i64) -> bool { + let clip = self.clip(); + if !clip.has(c, r) { + return false; + } + let (lead, width) = self.screen.unit(c as usize, r as usize); + lead as i64 >= clip.c0 && (lead + width) as i64 <= clip.c1 + } + + 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 { + if !self.free(c, r) { + continue; + } + 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.free(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); + if (lead as i64) < clip.c0 || (lead + width) as i64 > clip.c1 { + c = (lead + width) as i64; + continue; + } + 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 { + if !self.free(c, r) { + continue; + } + 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 && (at..at + width).all(|c| self.free(c, row)) { + 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.free(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..50affdd --- /dev/null +++ b/crates/thing-tui/tests/diff.rs @@ -0,0 +1,205 @@ +//! 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); +} + +#[test] +fn a_change_of_rows_alone_prints_every_cell() { + let printed = |ops: Vec| ops.iter().map(|op| if let Op::Print(s) = op { s.chars().count() } else { 0 }).sum::(); + assert_eq!(printed(diff(&Screen::new(4, 2), &Screen::new(4, 3))), 12); +} diff --git a/crates/thing-tui/tests/goldens/README.md b/crates/thing-tui/tests/goldens/README.md new file mode 100644 index 0000000..0fb26aa --- /dev/null +++ b/crates/thing-tui/tests/goldens/README.md @@ -0,0 +1,5 @@ +# thing-tui goldens + +`screen--cells.txt` is `Screen::dump` of each fixture surface (f11, which paints nothing, is a layout fact and has none) painted from its Cells render at +100x37 (CellMeasure, the standard theme). `THING_BLESS=1` through `thing_testkit::golden::check` is the +only way one changes. diff --git a/crates/thing-tui/tests/goldens/screen-f01-swarm-dashboard-cells.txt b/crates/thing-tui/tests/goldens/screen-f01-swarm-dashboard-cells.txt new file mode 100644 index 0000000..c5ed2fd --- /dev/null +++ b/crates/thing-tui/tests/goldens/screen-f01-swarm-dashboard-cells.txt @@ -0,0 +1,87 @@ +surface thing:surface:provider.swarm.dashboard 100x37 +42.0% Eureka + +Libby Kiko +┌────────────────────────────────────────────────┐ +│Restart │ +└────────────────────────────────────────────────┘ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +style 0 0 5 #ffffff #1e1e2e - +style 0 5 46 - #1e1e2e - +style 0 51 6 #eeeef4 #1e1e2e - +style 0 57 43 - #1e1e2e - +style 1 0 100 - #1e1e2e - +style 2 0 5 #eeeef4 #1e1e2e - +style 2 5 46 - #1e1e2e - +style 2 51 4 #eeeef4 #1e1e2e - +style 2 55 45 - #1e1e2e - +style 3 0 50 #4a4a60 #2c2c3e - +style 3 50 50 - #1e1e2e - +style 4 0 1 #4a4a60 #2c2c3e - +style 4 1 7 #eeeef4 #2c2c3e - +style 4 8 41 - #2c2c3e - +style 4 49 1 #4a4a60 #2c2c3e - +style 4 50 50 - #1e1e2e - +style 5 0 50 #4a4a60 #2c2c3e - +style 5 50 50 - #1e1e2e - +style 6 0 100 - - - +style 7 0 100 - - - +style 8 0 100 - - - +style 9 0 100 - - - +style 10 0 100 - - - +style 11 0 100 - - - +style 12 0 100 - - - +style 13 0 100 - - - +style 14 0 100 - - - +style 15 0 100 - - - +style 16 0 100 - - - +style 17 0 100 - - - +style 18 0 100 - - - +style 19 0 100 - - - +style 20 0 100 - - - +style 21 0 100 - - - +style 22 0 100 - - - +style 23 0 100 - - - +style 24 0 100 - - - +style 25 0 100 - - - +style 26 0 100 - - - +style 27 0 100 - - - +style 28 0 100 - - - +style 29 0 100 - - - +style 30 0 100 - - - +style 31 0 100 - - - +style 32 0 100 - - - +style 33 0 100 - - - +style 34 0 100 - - - +style 35 0 100 - - - +style 36 0 100 - - - diff --git a/crates/thing-tui/tests/goldens/screen-f02-login-effect-cells.txt b/crates/thing-tui/tests/goldens/screen-f02-login-effect-cells.txt new file mode 100644 index 0000000..04ef29a --- /dev/null +++ b/crates/thing-tui/tests/goldens/screen-f02-login-effect-cells.txt @@ -0,0 +1,81 @@ +surface thing:surface:provider.login.login 100x37 +┌──────────────────────────────────────────────────────────────────────────────────────────────────┐ +│username │ +└──────────────────────────────────────────────────────────────────────────────────────────────────┘ + +┌──────────────────────────────────────────────────────────────────────────────────────────────────┐ +│Sign in │ +└──────────────────────────────────────────────────────────────────────────────────────────────────┘ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +style 0 0 100 #4a4a60 - - +style 1 0 1 #4a4a60 - - +style 1 1 8 #6e6e80 - - +style 1 9 90 - - - +style 1 99 1 #4a4a60 - - +style 2 0 100 #4a4a60 - - +style 3 0 100 - - - +style 4 0 100 #4a4a60 #2c2c3e - +style 5 0 1 #4a4a60 #2c2c3e - +style 5 1 7 #eeeef4 #2c2c3e - +style 5 8 91 - #2c2c3e - +style 5 99 1 #4a4a60 #2c2c3e - +style 6 0 100 #4a4a60 #2c2c3e - +style 7 0 100 - - - +style 8 0 100 - - - +style 9 0 100 - - - +style 10 0 100 - - - +style 11 0 100 - - - +style 12 0 100 - - - +style 13 0 100 - - - +style 14 0 100 - - - +style 15 0 100 - - - +style 16 0 100 - - - +style 17 0 100 - - - +style 18 0 100 - - - +style 19 0 100 - - - +style 20 0 100 - - - +style 21 0 100 - - - +style 22 0 100 - - - +style 23 0 100 - - - +style 24 0 100 - - - +style 25 0 100 - - - +style 26 0 100 - - - +style 27 0 100 - - - +style 28 0 100 - - - +style 29 0 100 - - - +style 30 0 100 - - - +style 31 0 100 - - - +style 32 0 100 - - - +style 33 0 100 - - - +style 34 0 100 - - - +style 35 0 100 - - - +style 36 0 100 - - - diff --git a/crates/thing-tui/tests/goldens/screen-f03-input-target-cells.txt b/crates/thing-tui/tests/goldens/screen-f03-input-target-cells.txt new file mode 100644 index 0000000..d8591de --- /dev/null +++ b/crates/thing-tui/tests/goldens/screen-f03-input-target-cells.txt @@ -0,0 +1,77 @@ +surface thing:surface:provider.muninn.input-target 100x37 + The board the target sits on░░░░░░░░░░░░ + ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ + ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ + ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ + ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ + ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ + ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ + ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ + ░░░░░Ready░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ + ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ + ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ + ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ + ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ + ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ + ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ + ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ + ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ + ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ + ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ + ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ + ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ + ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ + ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ + + + + + + + + + + + + + + +style 0 0 100 - - - +style 1 0 100 - - - +style 2 0 100 - - - +style 3 0 100 - - - +style 4 0 100 - - - +style 5 0 100 - - - +style 6 0 100 - - - +style 7 0 100 - - - +style 8 0 35 - - - +style 8 35 5 #eeeef4 - - +style 8 40 60 - - - +style 9 0 100 - - - +style 10 0 100 - - - +style 11 0 100 - - - +style 12 0 100 - - - +style 13 0 100 - - - +style 14 0 100 - - - +style 15 0 100 - - - +style 16 0 100 - - - +style 17 0 100 - - - +style 18 0 100 - - - +style 19 0 100 - - - +style 20 0 100 - - - +style 21 0 100 - - - +style 22 0 100 - - - +style 23 0 100 - - - +style 24 0 100 - - - +style 25 0 100 - - - +style 26 0 100 - - - +style 27 0 100 - - - +style 28 0 100 - - - +style 29 0 100 - - - +style 30 0 100 - - - +style 31 0 100 - - - +style 32 0 100 - - - +style 33 0 100 - - - +style 34 0 100 - - - +style 35 0 100 - - - +style 36 0 100 - - - diff --git a/crates/thing-tui/tests/goldens/screen-f04-form-cells.txt b/crates/thing-tui/tests/goldens/screen-f04-form-cells.txt new file mode 100644 index 0000000..e8051e7 --- /dev/null +++ b/crates/thing-tui/tests/goldens/screen-f04-form-cells.txt @@ -0,0 +1,85 @@ +surface thing:surface:provider.settings.form 100x37 +┌──────────────────────────────────────────────────────────────────────────────────────────────────┐ +│ │ +└──────────────────────────────────────────────────────────────────────────────────────────────────┘ + + +┌──────────────────────────────────────────────────────────────────────────────────────────────────┐ +│Dark │ +└──────────────────────────────────────────────────────────────────────────────────────────────────┘ + +┌──────────────────────────────────────────────────────────────────────────────────────────────────┐ +│8080 │ +└──────────────────────────────────────────────────────────────────────────────────────────────────┘ + + + + + + + + + + + + + + + + + + + + + + + + + +style 0 0 100 #4a4a60 - - +style 1 0 1 #4a4a60 - - +style 1 1 97 - - - +style 1 98 1 - #7c9cff - +style 1 99 1 #4a4a60 - - +style 2 0 100 #4a4a60 - - +style 3 0 100 - - - +style 4 0 99 - #4a4a60 - +style 4 99 1 - #7c9cff - +style 5 0 100 #4a4a60 - - +style 6 0 1 #4a4a60 - - +style 6 1 4 #eeeef4 - - +style 6 5 94 - - - +style 6 99 1 #4a4a60 - - +style 7 0 100 #4a4a60 - - +style 8 0 100 - - - +style 9 0 100 #4a4a60 - - +style 10 0 1 #4a4a60 - - +style 10 1 4 #eeeef4 - - +style 10 5 94 - - - +style 10 99 1 #4a4a60 - - +style 11 0 100 #4a4a60 - - +style 12 0 100 - - - +style 13 0 100 - - - +style 14 0 100 - - - +style 15 0 100 - - - +style 16 0 100 - - - +style 17 0 100 - - - +style 18 0 100 - - - +style 19 0 100 - - - +style 20 0 100 - - - +style 21 0 100 - - - +style 22 0 100 - - - +style 23 0 100 - - - +style 24 0 100 - - - +style 25 0 100 - - - +style 26 0 100 - - - +style 27 0 100 - - - +style 28 0 100 - - - +style 29 0 100 - - - +style 30 0 100 - - - +style 31 0 100 - - - +style 32 0 100 - - - +style 33 0 100 - - - +style 34 0 100 - - - +style 35 0 100 - - - +style 36 0 100 - - - diff --git a/crates/thing-tui/tests/goldens/screen-f05-modal-overlay-cells.txt b/crates/thing-tui/tests/goldens/screen-f05-modal-overlay-cells.txt new file mode 100644 index 0000000..beeccbf --- /dev/null +++ b/crates/thing-tui/tests/goldens/screen-f05-modal-overlay-cells.txt @@ -0,0 +1,83 @@ +surface thing:surface:provider.dialog.modal 100x37 +The archive holds 12 items. + + + + + + + + + + + + + + +Delete the archive? +┌──────────────────────────────────────────────────────────────────────────────────────────────────┐ +│Delete │ +└──────────────────────────────────────────────────────────────────────────────────────────────────┘ + +┌──────────────────────────────────────────────────────────────────────────────────────────────────┐ +│Cancel │ +└──────────────────────────────────────────────────────────────────────────────────────────────────┘ + + + + + + + + + + + + + + +style 0 0 27 #eeeef4 #000000 - +style 0 27 73 - #000000 - +style 1 0 100 - #000000 - +style 2 0 100 - #000000 - +style 3 0 100 - #000000 - +style 4 0 100 - #000000 - +style 5 0 100 - #000000 - +style 6 0 100 - #000000 - +style 7 0 100 - #000000 - +style 8 0 100 - #000000 - +style 9 0 100 - #000000 - +style 10 0 100 - #000000 - +style 11 0 100 - #000000 - +style 12 0 100 - #000000 - +style 13 0 100 - #000000 - +style 14 0 100 - #2c2c3e - +style 15 0 19 #eeeef4 #2c2c3e - +style 15 19 81 - #2c2c3e - +style 16 0 100 #4a4a60 #2c2c3e - +style 17 0 1 #4a4a60 #2c2c3e - +style 17 1 6 #eeeef4 #2c2c3e - +style 17 7 92 - #2c2c3e - +style 17 99 1 #4a4a60 #2c2c3e - +style 18 0 100 #4a4a60 #2c2c3e - +style 19 0 100 - #2c2c3e - +style 20 0 100 #4a4a60 #2c2c3e - +style 21 0 1 #4a4a60 #2c2c3e - +style 21 1 6 #eeeef4 #2c2c3e - +style 21 7 92 - #2c2c3e - +style 21 99 1 #4a4a60 #2c2c3e - +style 22 0 100 #4a4a60 #2c2c3e - +style 23 0 100 - #000000 - +style 24 0 100 - #000000 - +style 25 0 100 - #000000 - +style 26 0 100 - #000000 - +style 27 0 100 - #000000 - +style 28 0 100 - #000000 - +style 29 0 100 - #000000 - +style 30 0 100 - #000000 - +style 31 0 100 - #000000 - +style 32 0 100 - #000000 - +style 33 0 100 - #000000 - +style 34 0 100 - #000000 - +style 35 0 100 - #000000 - +style 36 0 100 - #000000 - diff --git a/crates/thing-tui/tests/goldens/screen-f06-scroll-list-cells.txt b/crates/thing-tui/tests/goldens/screen-f06-scroll-list-cells.txt new file mode 100644 index 0000000..4f6aaa4 --- /dev/null +++ b/crates/thing-tui/tests/goldens/screen-f06-scroll-list-cells.txt @@ -0,0 +1,103 @@ +surface thing:surface:provider.feed.scroll-list 100x37 + Item 0 + + Item 1 + + Item 2 + + Item 3 + Item 4 + + Item 5 + + Item 6 + + Item 7 + Item 8 + + Item 9 + + Item 10 + + Item 11 + Item 12 + + Item 13 + + + + + + + + + + + + + +style 0 0 1 - - - +style 0 1 6 #eeeef4 - - +style 0 7 93 - - - +style 1 0 100 - - - +style 2 0 1 - - - +style 2 1 6 #eeeef4 - - +style 2 7 93 - - - +style 3 0 100 - - - +style 4 0 1 - - - +style 4 1 6 #eeeef4 - - +style 4 7 93 - - - +style 5 0 100 - - - +style 6 0 1 - - - +style 6 1 6 #eeeef4 - - +style 6 7 93 - - - +style 7 0 1 - - - +style 7 1 6 #eeeef4 - - +style 7 7 93 - - - +style 8 0 100 - - - +style 9 0 1 - - - +style 9 1 6 #eeeef4 - - +style 9 7 93 - - - +style 10 0 100 - - - +style 11 0 1 - - - +style 11 1 6 #eeeef4 - - +style 11 7 93 - - - +style 12 0 100 - - - +style 13 0 1 - - - +style 13 1 6 #eeeef4 - - +style 13 7 93 - - - +style 14 0 1 - - - +style 14 1 6 #eeeef4 - - +style 14 7 93 - - - +style 15 0 100 - - - +style 16 0 1 - - - +style 16 1 6 #eeeef4 - - +style 16 7 93 - - - +style 17 0 100 - - - +style 18 0 1 - - - +style 18 1 7 #eeeef4 - - +style 18 8 92 - - - +style 19 0 100 - - - +style 20 0 1 - - - +style 20 1 7 #eeeef4 - - +style 20 8 92 - - - +style 21 0 1 - - - +style 21 1 7 #eeeef4 - - +style 21 8 92 - - - +style 22 0 100 - - - +style 23 0 1 - - - +style 23 1 7 #eeeef4 - - +style 23 8 92 - - - +style 24 0 100 - - - +style 25 0 100 - - - +style 26 0 100 - - - +style 27 0 100 - - - +style 28 0 100 - - - +style 29 0 100 - - - +style 30 0 100 - - - +style 31 0 100 - - - +style 32 0 100 - - - +style 33 0 100 - - - +style 34 0 100 - - - +style 35 0 100 - - - +style 36 0 100 - - - diff --git a/crates/thing-tui/tests/goldens/screen-f07-plot-cells.txt b/crates/thing-tui/tests/goldens/screen-f07-plot-cells.txt new file mode 100644 index 0000000..606fb16 --- /dev/null +++ b/crates/thing-tui/tests/goldens/screen-f07-plot-cells.txt @@ -0,0 +1,127 @@ +surface thing:surface:provider.market.plot 100x37 + ⢀⠎⠒⢄⡀ + ⢠⠃ ⠈⠑⠤⡀ + ⡰⠁ ⠈⠑⠢⣀ + ⡜ + ⢀⠎ + ⡠⠊⠒⠤⣀ ⡠⠃ + ⡠⠊ ⠉⠒⠤⣀ ⡰⠁ + ⢀⠎ ⠉⠒⠜ + ⢀⠔⠁ +⢀⠔⠁ + + + + + + + + + + + + + + + + + + + + + + + + + + + +style 0 0 27 - - - +style 0 27 5 #7c9cff - - +style 0 32 68 - - - +style 1 0 26 - - - +style 1 26 2 #7c9cff - - +style 1 28 3 - - - +style 1 31 4 #7c9cff - - +style 1 35 65 - - - +style 2 0 25 - - - +style 2 25 2 #7c9cff - - +style 2 27 7 - - - +style 2 34 4 #7c9cff - - +style 2 38 62 - - - +style 3 0 24 - - - +style 3 24 1 #7c9cff - - +style 3 25 75 - - - +style 4 0 22 - - - +style 4 22 2 #7c9cff - - +style 4 24 76 - - - +style 5 0 8 - - - +style 5 8 5 #7c9cff - - +style 5 13 8 - - - +style 5 21 2 #7c9cff - - +style 5 23 77 - - - +style 6 0 6 - - - +style 6 6 2 #7c9cff - - +style 6 8 5 - - - +style 6 13 4 #7c9cff - - +style 6 17 3 - - - +style 6 20 2 #7c9cff - - +style 6 22 78 - - - +style 7 0 4 - - - +style 7 4 2 #7c9cff - - +style 7 6 11 - - - +style 7 17 3 #7c9cff - - +style 7 20 80 - - - +style 8 0 2 - - - +style 8 2 3 #7c9cff - - +style 8 5 95 - - - +style 9 0 3 #7c9cff - - +style 9 3 97 - - - +style 10 0 23 - - - +style 10 23 7 - #7c9cff - +style 10 30 70 - - - +style 11 0 23 - - - +style 11 23 7 - #7c9cff - +style 11 30 70 - - - +style 12 0 23 - - - +style 12 23 15 - #7c9cff - +style 12 38 62 - - - +style 13 0 8 - - - +style 13 8 7 - #7c9cff - +style 13 15 8 - - - +style 13 23 15 - #7c9cff - +style 13 38 62 - - - +style 14 0 8 - - - +style 14 8 30 - #7c9cff - +style 14 38 62 - - - +style 15 0 8 - - - +style 15 8 30 - #7c9cff - +style 15 38 62 - - - +style 16 0 38 - #7c9cff - +style 16 38 62 - - - +style 17 0 38 - #7c9cff - +style 17 38 62 - - - +style 18 0 38 - #7c9cff - +style 18 38 62 - - - +style 19 0 100 - - - +style 20 0 2 - #7c9cff - +style 20 2 98 - - - +style 21 0 2 - #7c9cff - +style 21 2 98 - - - +style 22 0 2 - #7c9cff - +style 22 2 98 - - - +style 23 0 2 - #7c9cff - +style 23 2 98 - - - +style 24 0 100 - - - +style 25 0 100 - - - +style 26 0 100 - - - +style 27 0 100 - - - +style 28 0 100 - - - +style 29 0 100 - - - +style 30 0 100 - - - +style 31 0 100 - - - +style 32 0 100 - - - +style 33 0 100 - - - +style 34 0 100 - - - +style 35 0 100 - - - +style 36 0 100 - - - diff --git a/crates/thing-tui/tests/goldens/screen-f08-embed-viewport-cells.txt b/crates/thing-tui/tests/goldens/screen-f08-embed-viewport-cells.txt new file mode 100644 index 0000000..7041ff3 --- /dev/null +++ b/crates/thing-tui/tests/goldens/screen-f08-embed-viewport-cells.txt @@ -0,0 +1,78 @@ +surface thing:surface:provider.viewport.embed-viewport 100x37 +before after + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +style 0 0 6 #eeeef4 - - +style 0 6 89 - - - +style 0 95 5 #eeeef4 - - +style 1 0 100 - - - +style 2 0 100 - - - +style 3 0 100 - - - +style 4 0 100 - - - +style 5 0 100 - - - +style 6 0 100 - - - +style 7 0 100 - - - +style 8 0 100 - - - +style 9 0 100 - - - +style 10 0 100 - - - +style 11 0 100 - - - +style 12 0 100 - - - +style 13 0 100 - - - +style 14 0 100 - - - +style 15 0 100 - - - +style 16 0 100 - - - +style 17 0 100 - - - +style 18 0 100 - - - +style 19 0 100 - - - +style 20 0 100 - - - +style 21 0 100 - - - +style 22 0 100 - - - +style 23 0 100 - - - +style 24 0 100 - - - +style 25 0 100 - - - +style 26 0 100 - - - +style 27 0 100 - - - +style 28 0 100 - - - +style 29 0 100 - - - +style 30 0 100 - - - +style 31 0 100 - - - +style 32 0 100 - - - +style 33 0 100 - - - +style 34 0 100 - - - +style 35 0 100 - - - +style 36 0 100 - - - +embed 31 0 40 11 "viewport.world" "main" diff --git a/crates/thing-tui/tests/goldens/screen-f09-composition-stack-cells.txt b/crates/thing-tui/tests/goldens/screen-f09-composition-stack-cells.txt new file mode 100644 index 0000000..a13fa87 --- /dev/null +++ b/crates/thing-tui/tests/goldens/screen-f09-composition-stack-cells.txt @@ -0,0 +1,97 @@ +surface thing:surface:provider.stack.stack 100x37 +Load + + + Card + + ┌─────────────────────────────────────────────────────────────────────────────────────────────────┐ + │Open │ + └─────────────────────────────────────────────────────────────────────────────────────────────────┘ + Card + + ┌────────────────────────────────────────────────────────────────────────────────────────────────┐ + │Open │ + └────────────────────────────────────────────────────────────────────────────────────────────────┘ + nested + + + + + + + + + + + + + + + + + + + + + + + +style 0 0 4 #ff00ff - - +style 0 4 96 - - - +style 1 0 100 - - - +style 2 0 100 - - - +style 3 0 1 - - - +style 3 1 4 #ffffff - - +style 3 5 95 - - - +style 4 0 100 - - - +style 5 0 1 - - - +style 5 1 99 #4a4a60 #2c2c3e - +style 6 0 1 - - - +style 6 1 1 #4a4a60 #2c2c3e - +style 6 2 4 #eeeef4 #2c2c3e - +style 6 6 93 - #2c2c3e - +style 6 99 1 #4a4a60 #2c2c3e - +style 7 0 1 - - - +style 7 1 99 #4a4a60 #2c2c3e - +style 8 0 1 - - - +style 8 1 4 #ffffff - - +style 8 5 95 - - - +style 9 0 100 - - - +style 10 0 1 - - - +style 10 1 98 #4a4a60 #2c2c3e - +style 10 99 1 - - - +style 11 0 1 - - - +style 11 1 1 #4a4a60 #2c2c3e - +style 11 2 4 #eeeef4 #2c2c3e - +style 11 6 92 - #2c2c3e - +style 11 98 1 #4a4a60 #2c2c3e - +style 11 99 1 - - - +style 12 0 1 - - - +style 12 1 98 #4a4a60 #2c2c3e - +style 12 99 1 - - - +style 13 0 1 - - - +style 13 1 6 #eeeef4 - - +style 13 7 93 - - - +style 14 0 100 - - - +style 15 0 100 - - - +style 16 0 100 - - - +style 17 0 100 - - - +style 18 0 100 - - - +style 19 0 100 - - - +style 20 0 100 - - - +style 21 0 100 - - - +style 22 0 100 - - - +style 23 0 100 - - - +style 24 0 100 - - - +style 25 0 100 - - - +style 26 0 100 - - - +style 27 0 100 - - - +style 28 0 100 - - - +style 29 0 100 - - - +style 30 0 100 - - - +style 31 0 100 - - - +style 32 0 100 - - - +style 33 0 100 - - - +style 34 0 100 - - - +style 35 0 100 - - - +style 36 0 100 - - - diff --git a/crates/thing-tui/tests/goldens/screen-f10-hostile-cells.txt b/crates/thing-tui/tests/goldens/screen-f10-hostile-cells.txt new file mode 100644 index 0000000..620f366 --- /dev/null +++ b/crates/thing-tui/tests/goldens/screen-f10-hostile-cells.txt @@ -0,0 +1,156 @@ +surface thing:surface:provider.hostile.duplicate-id refused DuplicateNodeId +surface thing:surface:provider.hostile.schema-mismatch 100x37 +[ ] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +style 0 0 1 #e5484d - - +style 0 1 98 - - - +style 0 99 1 #e5484d - - +style 1 0 100 - - - +style 2 0 100 - - - +style 3 0 100 - - - +style 4 0 100 - - - +style 5 0 100 - - - +style 6 0 100 - - - +style 7 0 100 - - - +style 8 0 100 - - - +style 9 0 100 - - - +style 10 0 100 - - - +style 11 0 100 - - - +style 12 0 100 - - - +style 13 0 100 - - - +style 14 0 100 - - - +style 15 0 100 - - - +style 16 0 100 - - - +style 17 0 100 - - - +style 18 0 100 - - - +style 19 0 100 - - - +style 20 0 100 - - - +style 21 0 100 - - - +style 22 0 100 - - - +style 23 0 100 - - - +style 24 0 100 - - - +style 25 0 100 - - - +style 26 0 100 - - - +style 27 0 100 - - - +style 28 0 100 - - - +style 29 0 100 - - - +style 30 0 100 - - - +style 31 0 100 - - - +style 32 0 100 - - - +style 33 0 100 - - - +style 34 0 100 - - - +style 35 0 100 - - - +style 36 0 100 - - - +surface thing:surface:provider.hostile.undeclared-command refused UndeclaredCommand +surface thing:surface:provider.hostile.unresolved-use 100x37 +[ ] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +style 0 0 1 #e5484d #6e6e80 - +style 0 1 98 - #6e6e80 - +style 0 99 1 #e5484d #6e6e80 - +style 1 0 100 - - - +style 2 0 100 - - - +style 3 0 100 - - - +style 4 0 100 - - - +style 5 0 100 - - - +style 6 0 100 - - - +style 7 0 100 - - - +style 8 0 100 - - - +style 9 0 100 - - - +style 10 0 100 - - - +style 11 0 100 - - - +style 12 0 100 - - - +style 13 0 100 - - - +style 14 0 100 - - - +style 15 0 100 - - - +style 16 0 100 - - - +style 17 0 100 - - - +style 18 0 100 - - - +style 19 0 100 - - - +style 20 0 100 - - - +style 21 0 100 - - - +style 22 0 100 - - - +style 23 0 100 - - - +style 24 0 100 - - - +style 25 0 100 - - - +style 26 0 100 - - - +style 27 0 100 - - - +style 28 0 100 - - - +style 29 0 100 - - - +style 30 0 100 - - - +style 31 0 100 - - - +style 32 0 100 - - - +style 33 0 100 - - - +style 34 0 100 - - - +style 35 0 100 - - - +style 36 0 100 - - - diff --git a/crates/thing-tui/tests/goldens/screen-f12-text-edge-cells.txt b/crates/thing-tui/tests/goldens/screen-f12-text-edge-cells.txt new file mode 100644 index 0000000..46a8211 --- /dev/null +++ b/crates/thing-tui/tests/goldens/screen-f12-text-edge-cells.txt @@ -0,0 +1,86 @@ +surface thing:surface:provider.text.text-edge 100x37 +Hello שלום עולם and مرحبا بالعالم then 123 end. + +日本語テスト 你好世界 한국어 ABC123 +é ä ñ ộ z͛͏̀ + +👩‍👩‍👧‍👦 👨🏽‍💻 🏳️‍🌈 +The quick brown fox jumps over the lazy dog while the evening light slides across the valley, and +the long paragraph keeps going so that any reasonable column must break it across several lines. The +quick brown fox jumps over the lazy dog while the evening light slides across the valley, and the +long paragraph keeps going so that any reasonable column must break it across several lines. The +quick brown fox jumps over the lazy dog while the evening light slides across the valley, and the +long paragraph keeps going so that any reasonable column must break it across several lines. The +quick brown fox jumps over the lazy dog while the evening light slides across the valley, and the +long paragraph keeps going so that any reasonable column must break it across several lines. + + + + + + + + + + + + + + + + + + + + + + + +style 0 0 47 #eeeef4 - - +style 0 47 53 - - - +style 1 0 100 - - - +style 2 0 41 #eeeef4 - - +style 2 41 59 - - - +style 3 0 9 #eeeef4 - - +style 3 9 91 - - - +style 4 0 100 - - - +style 5 0 8 #eeeef4 - - +style 5 8 92 - - - +style 6 0 97 #eeeef4 - - +style 6 97 3 - - - +style 7 0 100 #eeeef4 - - +style 8 0 97 #eeeef4 - - +style 8 97 3 - - - +style 9 0 96 #eeeef4 - - +style 9 96 4 - - - +style 10 0 97 #eeeef4 - - +style 10 97 3 - - - +style 11 0 96 #eeeef4 - - +style 11 96 4 - - - +style 12 0 97 #eeeef4 - - +style 12 97 3 - - - +style 13 0 93 #eeeef4 - - +style 13 93 7 - - - +style 14 0 100 - - - +style 15 0 100 - - - +style 16 0 100 - - - +style 17 0 100 - - - +style 18 0 100 - - - +style 19 0 100 - - - +style 20 0 100 - - - +style 21 0 100 - - - +style 22 0 100 - - - +style 23 0 100 - - - +style 24 0 100 - - - +style 25 0 100 - - - +style 26 0 100 - - - +style 27 0 100 - - - +style 28 0 100 - - - +style 29 0 100 - - - +style 30 0 100 - - - +style 31 0 100 - - - +style 32 0 100 - - - +style 33 0 100 - - - +style 34 0 100 - - - +style 35 0 100 - - - +style 36 0 100 - - - diff --git a/crates/thing-tui/tests/paint.rs b/crates/thing-tui/tests/paint.rs new file mode 100644 index 0000000..4e3a9d1 --- /dev/null +++ b/crates/thing-tui/tests/paint.rs @@ -0,0 +1,294 @@ +//! 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); +} + +#[test] +fn a_clip_never_corrupts_a_wide_cluster_it_cuts() { + let white = rgb(255, 255, 255); + let wide = || { + let mut screen = blank(); + paint(&[fill(rect(5.0, 0.0, 2.0, 1.0), rgb(1, 2, 3)), text(5.0, 0.0, "\u{4e2d}", white.clone())], &mut screen); + screen + }; + let before = wide(); + // Each write kind, clipped between the two halves, leaves the whole screen as it was. + let writes = [ + text(5.0, 0.0, "a", white.clone()), + text(4.0, 0.0, "ab", white.clone()), + fill(rect(0.0, 0.0, 20.0, 1.0), rgb(9, 9, 9)), + fill(rect(0.0, 0.0, 20.0, 1.0), rgba(9, 9, 9, 128)), + stroke(rect(5.0, 0.0, 1.0, 1.0), white.clone()), + RenderCommand::Embed { rect: rect(0.0, 0.0, 20.0, 1.0), slot_kind: String::new(), slot_id: String::new() }, + RenderCommand::Polyline { points: vec![(5.1, 0.1), (6.9, 0.9)], width: 1.0, color: white.clone() }, + RenderCommand::Polygon { points: vec![(0.0, 0.0), (20.0, 0.0), (20.0, 1.0), (0.0, 1.0)], color: rgba(9, 9, 9, 128) }, + ]; + for write in writes { + for (left, width) in [(0.0, 6.0), (6.0, 14.0)] { + let mut screen = before.clone(); + paint(&[clip(rect(left, 0.0, width, 6.0)), write.clone()], &mut screen); + well_formed(&screen); + assert_eq!((screen.cell(5, 0), screen.cell(6, 0)), (before.cell(5, 0), before.cell(6, 0)), "{write:?} clipped from {left}"); + } + } + // Cells wholly inside the clip are still written. + let mut screen = before.clone(); + paint(&[clip(rect(0.0, 0.0, 6.0, 6.0)), text(1.0, 0.0, "ok", white)], &mut screen); + assert_eq!(glyph(&screen, 1, 0), "o"); +} diff --git a/crates/thing-tui/tests/screen.rs b/crates/thing-tui/tests/screen.rs new file mode 100644 index 0000000..b5f685f --- /dev/null +++ b/crates/thing-tui/tests/screen.rs @@ -0,0 +1,94 @@ +//! Screen goldens: every fixture, unedited, through resolve, bind, layout and render in Cells, +//! painted onto a 100x37 screen. A Px length of a fixture is a Px length in Cells too: it converts +//! at the cell metric (ruling cells-px-metric). 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::{Painted, 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<(Screen, Painted), Code> { + 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); + let painted = paint(&rendered.commands, &mut screen); + Ok((screen, painted)) +} + +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, painted)) => { + well_formed(&screen); + out += &format!("surface {} {COLS}x{ROWS}\n{}", document.record_key(), screen.dump()); + for (rect, kind, id) in &painted.embeds { + out += &format!("embed {} {} {} {} {kind:?} {id:?}\n", rect.x, rect.y, rect.w, rect.h); + } + } + Err(code) => out += &format!("surface {} refused {code:?}\n", document.record_key()), + } + } + out +} + +#[test] +fn goldens() { + // f11 is a chain of Boxes with no paint: its screen is blank in every mode, so a golden of it pins + // nothing. Its nesting in Cells is a layout fact, asserted in thing-core tests/layout.rs. + for fixture in Fixture::ALL.into_iter().filter(|fixture| !matches!(fixture, Fixture::F11Deep)) { + golden::check(&golden_dir(), &format!("screen-{}-cells.txt", stem(fixture)), golden_text(fixture).as_bytes()); + } +} + +/// The substitutes the table promises show up on the screens that carry them. +#[test] +fn image_and_embed_are_on_screen() { + let glyphs = |fixture| golden_text(fixture).lines().take(ROWS + 1).collect::(); + let f03 = glyphs(Fixture::F03InputTarget); + assert!(f03.contains('\u{2591}') && f03.contains("The board"), "f03 draws its Image as a shaded block with its alt"); + assert!(golden_text(Fixture::F08EmbedViewport).contains("\nembed "), "f08 reports its Embed to the host"); +}