diff --git a/crates/thing-core/src/layout/measure.rs b/crates/thing-core/src/layout/measure.rs index 5e1eadb..3ccd1ac 100644 --- a/crates/thing-core/src/layout/measure.rs +++ b/crates/thing-core/src/layout/measure.rs @@ -105,6 +105,15 @@ 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 inset of a bordered control's content from its border in a cell grid, `(x, y)`: the border +/// stands in the edge cells, so content keeps one cell clear left and right, and above and below +/// when the control is tall enough (3 rows) to have an inside. A one-row control draws its border as +/// `[` and `]` in its end cells. Layout applies it to a Button's content and render to every other +/// bordered control's; Pixels insets are render's own. +pub fn cells_inset(height: f32) -> (f32, f32) { + (1.0, if height >= 3.0 { 1.0 } else { 0.0 }) +} + /// 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. #[derive(Clone, Copy, Debug)] @@ -123,11 +132,9 @@ impl Device { if self.cells { 1.0 } else { self.px(16.0) } } - /// A Button's content inset from its border, left and right: none in Pixels (render draws the - /// chrome behind the content), one cell in Cells, where a one-row Button's `[` and `]` stand - /// in its first and last cell. - pub(super) fn button_inset(self) -> f32 { - if self.cells { 1.0 } else { 0.0 } + /// 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, or 38x10 cells. A plot is diff --git a/crates/thing-core/src/layout/mod.rs b/crates/thing-core/src/layout/mod.rs index e23b407..edb1b29 100644 --- a/crates/thing-core/src/layout/mod.rs +++ b/crates/thing-core/src/layout/mod.rs @@ -18,7 +18,7 @@ use taffy::{AvailableSpace, Size, compute_leaf_layout}; use measure::Device; use thing_contract::{NodeId, OverlayNode}; -pub use measure::{Avail, CellStyle, Constraint, FontId, Glyph, Leaf, Measure, Run, TextLayout, TextLine, TextRequest}; +pub use measure::{Avail, CellStyle, cells_inset, Constraint, FontId, Glyph, Leaf, Measure, Run, TextLayout, TextLine, TextRequest}; pub(crate) use measure::MAX_DEVICE; use crate::bind::BoundTree; diff --git a/crates/thing-core/src/layout/tree.rs b/crates/thing-core/src/layout/tree.rs index 61696ae..a50afbf 100644 --- a/crates/thing-core/src/layout/tree.rs +++ b/crates/thing-core/src/layout/tree.rs @@ -3,7 +3,7 @@ use taffy::{Style, TaffyTree}; use thing_contract::{Node, NodeId, Overflow, OverlayNode}; -use super::measure::{Device, Leaf, MAX_DEVICE, intrinsic_ratio}; +use super::measure::{Device, Leaf, MAX_DEVICE, cells_inset, intrinsic_ratio}; use super::style::{Invalid, box_style, embed_style}; use crate::bind::{Bound, BoundTree, Field}; use crate::diagnostic::{Code, Diagnostic}; @@ -189,9 +189,21 @@ impl<'a> Builder<'a, '_> { } Node::Button(b) => { if !self.hidden(&b.common.id) { - let side = taffy::LengthPercentage::length(self.dev.button_inset()); - let none = taffy::LengthPercentage::length(0.0); - let style = Style { padding: taffy::Rect { left: side, right: side, top: none, bottom: none }, ..Style::default() }; + // In Cells a Button's content keeps clear of its border (`cells_inset`), centred + // between the top and bottom borders of a tall one. Pixels: render draws the chrome behind it. + let style = if self.dev.cells() { + let side = taffy::LengthPercentage::length(cells_inset(0.0).0); + let none = taffy::LengthPercentage::length(0.0); + Style { + display: taffy::Display::Flex, + flex_direction: taffy::FlexDirection::Column, + justify_content: Some(taffy::JustifyContent::Center), + padding: taffy::Rect { left: side, right: side, top: none, bottom: none }, + ..Style::default() + } + } else { + Style::default() + }; self.container(&b.common.id, parent, (style, Vec::new()), &Overflow::Visible, &b.content, out); } } diff --git a/crates/thing-core/src/render/leaf.rs b/crates/thing-core/src/render/leaf.rs index 611b99b..8114e83 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::{Measure, Metrics, Rect, TextRequest, cells_inset}; /// 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,10 +70,12 @@ 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. + /// The content box of a control: `rect` less the inset of its border, 2 logical px all round + /// or, in a cell grid, `cells_inset`. 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 } + let (x, y) = if self.input.metrics == Metrics::Cells { cells_inset(rect.h) } else { (2.0, 2.0) }; + let (x, y) = (x.min(rect.w / 2.0).max(0.0), y.min(rect.h / 2.0).max(0.0)); + Rect { x: rect.x + x, y: rect.y + y, w: rect.w - 2.0 * x, h: rect.h - 2.0 * y } } pub(super) fn button(&mut self, n: &ButtonNode, rect: Rect) { diff --git a/crates/thing-core/tests/render.rs b/crates/thing-core/tests/render.rs index e2dcd66..758ccb5 100644 --- a/crates/thing-core/tests/render.rs +++ b/crates/thing-core/tests/render.rs @@ -1179,3 +1179,50 @@ 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 one-row control: one cell in from each end. A TextInput's text starts at x 1, not on `[`. + 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, 0.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), px(height)); + 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(1.0)), [(1.0, 0.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)); +} diff --git a/crates/thing-tui/src/paint.rs b/crates/thing-tui/src/paint.rs index bef76be..c4e3cad 100644 --- a/crates/thing-tui/src/paint.rs +++ b/crates/thing-tui/src/paint.rs @@ -117,6 +117,17 @@ impl Canvas<'_> { *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), @@ -142,6 +153,9 @@ impl Canvas<'_> { 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(); } @@ -153,7 +167,7 @@ impl Canvas<'_> { /// Put one narrow glyph at `(c, r)` if the clip lets it. `fg` composites onto the cell's bg. fn put(&mut self, c: i64, r: i64, glyph: &str, fg: Option<&Rgba>) { - if !self.clip().has(c, r) { + if !self.free(c, r) { return; } let (c, r) = (c as usize, r as usize); @@ -175,6 +189,10 @@ impl Canvas<'_> { 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()); @@ -194,6 +212,9 @@ impl Canvas<'_> { 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()); } @@ -257,7 +278,7 @@ impl Canvas<'_> { break; } let r = row as usize; - if at >= clip.c0 && at + width <= clip.c1 { + 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); } @@ -296,7 +317,7 @@ impl Canvas<'_> { fn dot(&mut self, x: i64, y: i64, color: &Rgba) { const BITS: [[u32; 4]; 2] = [[0x01, 0x02, 0x04, 0x40], [0x08, 0x10, 0x20, 0x80]]; let (c, r) = (x.div_euclid(2), y.div_euclid(4)); - if !self.clip().has(c, r) { + if !self.free(c, r) { return; } let bit = BITS[x.rem_euclid(2) as usize][y.rem_euclid(4) as usize]; diff --git a/crates/thing-tui/tests/paint.rs b/crates/thing-tui/tests/paint.rs index aa938f3..ae4573b 100644 --- a/crates/thing-tui/tests/paint.rs +++ b/crates/thing-tui/tests/paint.rs @@ -258,3 +258,37 @@ fn hostile_geometry_is_inert() { 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(&[text(5.0, 0.0, "\u{4e2d}", white.clone()), fill(rect(5.0, 0.0, 2.0, 1.0), rgb(1, 2, 3))], &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 index 297ef93..41a3be6 100644 --- a/crates/thing-tui/tests/screen.rs +++ b/crates/thing-tui/tests/screen.rs @@ -7,7 +7,7 @@ mod common; use std::path::PathBuf; use common::well_formed; -use thing_contract::SurfaceDocument; +use thing_contract::{Border, ColorRef, Dimension, Edges, Node, Rgba, SurfaceDocument}; use thing_core::bind::Binder; use thing_core::diagnostic::Code; use thing_core::layout::{LayoutFrame, Metrics, layout}; @@ -16,11 +16,12 @@ 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::build::{px, size2}; use thing_testkit::fixture::Fixture; use thing_testkit::golden; use thing_testkit::mem_state::MemState; use thing_testkit::state; -use thing_tui::{Screen, paint}; +use thing_tui::{Painted, Screen, paint}; const COLS: usize = 100; const ROWS: usize = 37; @@ -29,7 +30,36 @@ fn golden_dir() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens") } -fn screen_of(state: &mut MemState, document: &SurfaceDocument) -> Result { +/// Three fixtures carry pixel sizes, which in Cells are numbers of cells: f03's 640x360 board and +/// f08's 320x180 viewport lie far off a 100x37 screen, and f11's chain of Boxes has no paint, so +/// it draws nothing in any mode. Each is cut down (or its boxes outlined) so that its Image, +/// Embed or boxes show on screen; every other fixture runs as authored. +fn as_cells(fixture: Fixture, node: &mut Node, depth: usize) { + match node { + Node::Box(b) => { + match fixture { + Fixture::F03InputTarget if b.common.id.as_str() == "root" => b.style.size = size2(px(60.0), px(20.0)), + Fixture::F03InputTarget if b.common.id.as_str() == "target" => { + b.style.inset = Edges { left: px(20.0), top: px(6.0), right: Dimension::Auto, bottom: Dimension::Auto }; + b.style.size = size2(px(12.0), px(3.0)); + } + Fixture::F11Deep => { + let shade = (depth * 12 % 120) as u8; + let color = ColorRef::Rgba(Rgba { r: 80 + shade, g: 160, b: 255 - shade, a: 255 }); + b.paint.border = Some(Border { color, width: 1.0 }); + } + _ => {} + } + for child in &mut b.children { + as_cells(fixture, child, depth + 1); + } + } + Node::Embed(e) if fixture == Fixture::F08EmbedViewport => (e.width, e.height) = (40.0, 10.0), + _ => {} + } +} + +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 { @@ -45,8 +75,8 @@ fn screen_of(state: &mut MemState, document: &SurfaceDocument) -> Result String { @@ -59,10 +89,15 @@ fn golden_text(fixture: Fixture) -> String { state::script(fixture, &mut state); let mut out = String::new(); for document in &set.surfaces { - match screen_of(&mut state, document) { - Ok(screen) => { + let mut document = document.clone(); + as_cells(fixture, &mut document.root, 0); + 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()), } @@ -76,3 +111,13 @@ fn goldens() { 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_embed_and_deep_boxes_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"); + assert!(glyphs(Fixture::F11Deep).matches('\u{250c}').count() >= 10, "f11 shows its nested boxes"); +}