Thing 2.0 cut 9a-cells: CellText and CellMeasure, the Cells text engine behind Measure

Per-grapheme-cluster widths (unicode-width 0.2.3, ambiguous narrow), UAX #14 breaks,
controls sanitized to U+FFFD; Run::Cells carries a CellText; f12 Cells goldens.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-28 08:59:03 +01:00
commit bc66506c24
11 changed files with 596 additions and 28 deletions

21
Cargo.lock generated
View file

@ -536,6 +536,9 @@ dependencies = [
"taffy",
"thing-contract",
"thing-testkit",
"unicode-linebreak",
"unicode-segmentation",
"unicode-width",
]
[[package]]
@ -573,6 +576,24 @@ version = "1.0.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
[[package]]
name = "unicode-linebreak"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f"
[[package]]
name = "unicode-segmentation"
version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
[[package]]
name = "unicode-width"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557"
[[package]]
name = "uuid"
version = "1.28.0"

View file

@ -8,3 +8,8 @@ cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "4c9af40
serde = { version = "1", features = ["derive"] }
rmp-serde = "1.3"
taffy = { version = "0.16", default-features = false, features = ["std", "taffy_tree", "flexbox", "grid", "block_layout", "content_size"] }
# The terminal text tables, pinned exactly: a width is a golden. unicode-width drops its cjk
# tables, so ambiguous width is narrow.
unicode-width = { version = "=0.2.3", default-features = false }
unicode-segmentation = "=1.13.3"
unicode-linebreak = "=0.1.5"

View file

@ -5,12 +5,16 @@ edition = "2024"
license = "MIT"
publish = false
# Normal dependencies are thing-contract, stacker and taffy: layout is thing-core's job, and no
# Taffy type is in its public API.
# Normal dependencies are thing-contract, stacker, taffy and the three Unicode tables of the Cells
# text engine (unicode-width, unicode-segmentation, unicode-linebreak): layout and terminal text
# are thing-core's job, and no Taffy type is in its public API.
[dependencies]
thing-contract = { path = "../thing-contract" }
stacker = "0.1.25"
taffy.workspace = true
unicode-width.workspace = true
unicode-segmentation.workspace = true
unicode-linebreak.workspace = true
[dev-dependencies]
thing-testkit = { path = "../thing-testkit" }

View file

@ -6,6 +6,7 @@ use taffy::{AvailableSpace, Size};
use thing_contract::NodeId;
use crate::bind::Bound;
use crate::text::CellText;
/// The room a leaf is offered on one axis.
#[derive(Clone, Copy, Debug, PartialEq)]
@ -57,7 +58,7 @@ pub struct CellStyle {
#[derive(Clone, Debug, PartialEq)]
pub enum Run {
Glyphs { font: FontId, size: f32, glyphs: Vec<Glyph> },
Cells { text: String, style: CellStyle },
Cells { text: CellText, style: CellStyle },
}
/// The Text leaf a line breaker is asked to lay out.

View file

@ -7,4 +7,5 @@ pub mod layout;
pub mod port;
pub mod render;
pub mod resolve;
pub mod text;
pub mod theme;

View file

@ -0,0 +1,263 @@
//! The Cells text engine: `CellText` is the one constructor of terminal text and `CellMeasure` the
//! one `Measure` for Cells. Every width and every break a cell backend advances by is decided
//! here, per extended grapheme cluster, and no backend computes either.
//!
//! Breaking is CSS `white-space: pre-wrap` with `overflow-wrap: break-word`: mandatory breaks
//! always break, soft breaks are UAX #14 Allowed positions on a cluster boundary, trailing spaces
//! at a soft break hang (are not emitted), and an unbreakable segment wider than the line breaks
//! between clusters. Text is laid out in logical order; bidi reordering is Pixels-only.
use unicode_linebreak::{BreakOpportunity, linebreaks};
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;
use crate::bind::Bound;
use crate::layout::{Avail, CellStyle, Constraint, Leaf, Measure, Run, TextLayout, TextLine, TextRequest};
/// The tab stop, in columns (CSS `tab-size: 8`).
const TAB: u32 = 8;
/// Terminal text: a string with one width per extended grapheme cluster, free of control
/// characters and of zero-width clusters. A document never writes an escape code into a terminal
/// because no other constructor exists.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CellText {
text: String,
/// The end byte offset and the width in cells of each cluster, in order.
clusters: Vec<(u32, u8)>,
}
impl CellText {
/// One line of terminal text. Tabs stop at multiples of 8 columns from the start of `text`;
/// every control character, line terminators included, becomes U+FFFD (width 1); a cluster
/// without width is dropped.
pub fn new(text: &str) -> Self {
Self::from_atoms(&atoms(text))
}
pub fn as_str(&self) -> &str {
&self.text
}
/// Each cluster with its width in cells.
pub fn clusters(&self) -> impl Iterator<Item = (&str, u8)> {
let mut start = 0;
self.clusters.iter().map(move |&(end, width)| {
let cluster = &self.text[start as usize..end as usize];
start = end as usize;
(cluster, width)
})
}
/// The width of the line in cells: the sum of its cluster widths.
pub fn width(&self) -> u32 {
self.clusters.iter().map(|&(_, w)| u32::from(w)).sum()
}
fn from_atoms(atoms: &[Atom]) -> Self {
let mut out = Self::default();
for atom in atoms {
out.text.push_str(atom.text);
out.clusters.push((out.text.len() as u32, atom.width));
}
out
}
}
/// One kept cluster of a paragraph, sanitized, and whether a soft break may precede it.
struct Atom<'a> {
text: &'a str,
width: u8,
space: bool,
open: bool,
}
fn is_terminator(c: char) -> bool {
matches!(c, '\n' | '\r' | '\u{b}' | '\u{c}' | '\u{85}' | '\u{2028}' | '\u{2029}')
}
/// The clusters of one paragraph (no line terminator inside it, or one that is plain text).
fn atoms(paragraph: &str) -> Vec<Atom<'_>> {
let mut open_at = vec![false; paragraph.len() + 1];
for (at, kind) in linebreaks(paragraph) {
if kind == BreakOpportunity::Allowed {
open_at[at] = true;
}
}
let mut out: Vec<Atom> = Vec::new();
let mut column = 0u32;
// A break opportunity that fell on a dropped cluster rides on the next kept one.
let mut pending = false;
for (start, cluster) in paragraph.grapheme_indices(true) {
let open = open_at[start] || pending;
pending = false;
let first = cluster.chars().next().expect("a cluster has a scalar");
if cluster == "\t" {
let stop = TAB - column % TAB;
for i in 0..stop {
out.push(Atom { text: " ", width: 1, space: true, open: open && i == 0 });
}
column += stop;
} else if first.is_control() || is_terminator(first) {
out.push(Atom { text: "\u{fffd}", width: 1, space: false, open });
column += 1;
} else {
let width = cluster.width().min(255) as u8;
if width == 0 {
pending = open;
} else {
out.push(Atom { text: cluster, width, space: cluster == " ", open });
column += u32::from(width);
}
}
}
if let Some(first) = out.first_mut() {
first.open = false;
}
out
}
/// The paragraphs of `text`: the pieces between mandatory breaks, terminators removed. A final
/// terminator ends the last line and starts no empty one.
fn paragraphs(text: &str) -> Vec<&str> {
let mut out = Vec::new();
let mut from = 0;
for (at, kind) in linebreaks(text) {
if kind == BreakOpportunity::Mandatory && at < text.len() {
out.push(strip_terminator(&text[from..at]));
from = at;
}
}
out.push(strip_terminator(&text[from..]));
out
}
fn strip_terminator(piece: &str) -> &str {
match piece.graphemes(true).next_back() {
Some(last) if last.chars().any(is_terminator) => &piece[..piece.len() - last.len()],
_ => piece,
}
}
/// The lines of `text` at `cols` columns. `wrap` off breaks at mandatory breaks only. Every line
/// takes at least one cluster, so a cluster wider than the room sits alone and overflows.
fn break_lines(text: &str, wrap: bool, max_lines: Option<u32>, cols: u32) -> Vec<CellText> {
let cap = max_lines.map_or(usize::MAX, |n| n as usize);
let mut lines = Vec::new();
for paragraph in paragraphs(text) {
let atoms = atoms(paragraph);
let mut start = 0;
loop {
if lines.len() >= cap {
return lines;
}
let end = if wrap { fit(&atoms, start, cols) } else { atoms.len() };
let mut line = &atoms[start..end];
if end < atoms.len() {
// A soft break: the spaces before it hang.
while let Some((last, rest)) = line.split_last() {
if !last.space {
break;
}
line = rest;
}
}
lines.push(CellText::from_atoms(line));
if end >= atoms.len() {
break;
}
start = end;
}
}
lines
}
/// Where the line that starts at `start` ends: the last soft break that fits, else the last
/// cluster that fits, else (a cluster wider than the room) just that cluster.
fn fit(atoms: &[Atom], start: usize, cols: u32) -> usize {
let (mut width, mut shown) = (0u32, 0u32);
let mut candidate = None;
for (i, atom) in atoms.iter().enumerate().skip(start) {
if atom.open && i > start {
candidate = Some(i);
}
width += u32::from(atom.width);
if !atom.space {
shown = width;
}
if shown > cols && i > start {
return candidate.unwrap_or(i);
}
}
atoms.len()
}
/// The widest unbreakable segment, trailing spaces excluded.
fn longest_segment(text: &str) -> u32 {
let mut widest = 0;
for paragraph in paragraphs(text) {
let atoms = atoms(paragraph);
let mut start = 0;
for i in 1..=atoms.len() {
if i == atoms.len() || atoms[i].open {
let segment = &atoms[start..i];
let shown = segment.iter().rposition(|a| !a.space).map_or(0, |last| segment[..=last].iter().map(|a| u32::from(a.width)).sum());
widest = widest.max(shown);
start = i;
}
}
}
widest
}
fn lines_for(text: &str, wrap: bool, max_lines: Option<u32>, room: Avail) -> Vec<CellText> {
let cols = match room {
// `as` saturates: negative and NaN are 0, huge is u32::MAX.
Avail::Definite(w) if wrap => w.floor() as u32,
_ => u32::MAX,
};
break_lines(text, wrap, max_lines, cols)
}
/// The shipped Cells engine: text by cluster width and UAX #14, controls at fixed cell sizes.
#[derive(Clone, Copy, Debug, Default)]
pub struct CellMeasure;
impl Measure for CellMeasure {
fn measure(&mut self, leaf: &Leaf, c: Constraint) -> (f32, f32) {
match leaf {
Leaf::Text { content, wrap, max_lines, .. } => {
let text = match content {
Bound::Text(text) => text.as_str(),
_ => "",
};
let room = c.known[0].map(Avail::Definite).unwrap_or(c.available[0]);
if *wrap && room == Avail::MinContent {
let rows = lines_for(text, true, *max_lines, Avail::MaxContent).len();
return (longest_segment(text) as f32, rows as f32);
}
let lines = lines_for(text, *wrap, *max_lines, room);
(lines.iter().map(CellText::width).max().unwrap_or(0) as f32, lines.len() as f32)
}
Leaf::TextInput { multiline, .. } => (25.0, if *multiline { 3.0 } else { 1.0 }),
Leaf::Toggle { .. } => (5.0, 1.0),
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()),
_ => (0.0, 0.0),
},
}
}
fn text(&mut self, request: &TextRequest, width: f32) -> TextLayout {
let lines = lines_for(request.text, request.wrap, request.max_lines, Avail::Definite(width));
TextLayout {
lines: lines
.into_iter()
.enumerate()
.map(|(row, text)| TextLine { y: row as f32, height: 1.0, run: Run::Cells { text, style: CellStyle::default() } })
.collect(),
}
}
}

View file

@ -0,0 +1,6 @@
//! Terminal text: what a string is made of in a cell grid. The one owner of every Cells width and
//! line break (Pixels text is the shaper's, behind the same `Measure` seam).
mod cells;
pub use cells::{CellMeasure, CellText};

View file

@ -0,0 +1,204 @@
//! The Cells text engine: pinned widths, sanitizing, wrapping, and that `measure` and `text`
//! agree. Vectors were checked against unicode-width 0.2.3 (ambiguous width narrow).
use thing_contract::NodeId;
use thing_core::bind::Bound;
use thing_core::layout::{Avail, Constraint, Leaf, Measure, Run, TextRequest};
use thing_core::text::{CellMeasure, CellText};
fn widths(s: &str) -> Vec<u8> {
CellText::new(s).clusters().map(|(_, w)| w).collect()
}
#[test]
fn width_vectors() {
let vectors: &[(&str, &[u8])] = &[
("a", &[1]),
("\u{4e2d}", &[2]),
("\u{ff21}", &[2]),
("\u{d55c}", &[2]),
("e\u{301}", &[1]),
("\u{b1}", &[1]),
("\u{3b1}", &[1]),
("\u{1f600}", &[2]),
("\u{2764}", &[1]),
("\u{2764}\u{fe0f}", &[2]),
("\u{263a}\u{fe0e}", &[1]),
("\u{1f44d}\u{1f3fd}", &[2]),
("\u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}", &[2]),
("\u{1f1ef}\u{1f1f5}", &[2]),
("\u{1f1ef}", &[1]),
("1\u{fe0f}\u{20e3}", &[2]),
("\u{1f3f3}\u{fe0f}\u{200d}\u{1f308}", &[2]),
("\u{1100}\u{1161}\u{11a8}", &[2]),
("\u{915}\u{94d}\u{937}", &[2]),
("\u{e01}\u{e33}", &[2]),
("\u{17d8}", &[3]),
("\u{a0}", &[1]),
("\u{644}\u{627}", &[1, 1]),
];
for (text, expected) in vectors {
assert_eq!(&widths(text), expected, "{text:?}");
assert_eq!(CellText::new(text).width(), expected.iter().map(|&w| u32::from(w)).sum::<u32>(), "{text:?} line width is the cluster sum");
}
}
#[test]
fn sanitizing() {
for c in ['\u{1b}', '\u{7f}', '\u{9b}'] {
let s = c.to_string();
assert_eq!((CellText::new(&s).as_str(), widths(&s)), ("\u{fffd}", vec![1]), "{c:?}");
}
assert_eq!(CellText::new("a\tb").as_str(), "a b");
assert_eq!(CellText::new("abcdefgh\ti").as_str(), "abcdefgh i");
for vanishing in ["\u{202e}", "\u{200b}", "\u{ad}", "\u{200d}", "\u{301}"] {
assert_eq!(CellText::new(vanishing).as_str(), "", "{vanishing:?}");
}
assert_eq!(CellText::new("\u{301}a").as_str(), "a");
assert_eq!(CellText::new("x\u{200b}y").as_str(), "xy");
// The break opportunity of a dropped cluster survives.
assert_eq!(lines("x\u{200b}y", 1), ["x", "y"]);
// A terminator handed straight to `new` is a control like any other.
assert_eq!(CellText::new("a\nb").as_str(), "a\u{fffd}b");
}
#[test]
fn every_scalar_is_clean() {
for c in (0..=char::MAX as u32).filter_map(char::from_u32) {
let t = CellText::new(&c.to_string());
assert!(!t.as_str().chars().any(|c| c.is_control()), "{:#x}", c as u32);
assert!(t.clusters().all(|(_, w)| (1..=3).contains(&w)), "{:#x}", c as u32);
}
}
fn leaf_measure(text: &str, wrap: bool, max_lines: Option<u32>, room: Avail) -> (f32, f32) {
let node = NodeId::new("n");
let content = Bound::Text(text.to_string());
let leaf = Leaf::Text { node: &node, content: &content, style_token: "body", wrap, max_lines };
CellMeasure.measure(&leaf, Constraint { known: [None, None], available: [room, Avail::MaxContent] })
}
fn layout_lines(text: &str, wrap: bool, max_lines: Option<u32>, width: f32) -> Vec<String> {
let node = NodeId::new("n");
let request = TextRequest { node: &node, text, style_token: "body", wrap, max_lines };
CellMeasure
.text(&request, width)
.lines
.into_iter()
.enumerate()
.map(|(row, line)| {
assert_eq!((line.y, line.height), (row as f32, 1.0));
match line.run {
Run::Cells { text, .. } => text.as_str().to_string(),
other => panic!("{other:?}"),
}
})
.collect()
}
fn lines(text: &str, width: u32) -> Vec<String> {
layout_lines(text, true, None, width as f32)
}
#[test]
fn wrap_table() {
assert_eq!(lines("hello world", 5), ["hello", "world"]);
assert_eq!(lines("hello world", 11), ["hello world"]);
let han = "\u{4e2d}\u{6587}\u{6587}\u{5b57}";
assert_eq!(lines(han, 5), ["\u{4e2d}\u{6587}", "\u{6587}\u{5b57}"]);
assert_eq!(lines(han, 3).len(), 4);
assert_eq!(lines("\u{4e2d}", 1), ["\u{4e2d}"]);
assert_eq!(leaf_measure("\u{4e2d}", true, None, Avail::Definite(1.0)), (2.0, 1.0));
assert_eq!(lines("abcdefgh", 3), ["abc", "def", "gh"]);
assert_eq!(layout_lines("a\nb", false, None, 80.0), ["a", "b"]);
assert_eq!(layout_lines("a\r\nb\u{2028}c", true, None, 80.0), ["a", "b", "c"]);
assert_eq!(layout_lines("a\nb", true, Some(1), 80.0), ["a"]);
assert_eq!(lines("hello world", 5), ["hello", "world"]);
assert_eq!(lines("", 5), [""]);
assert_eq!(lines("a\n\nb", 5), ["a", "", "b"]);
assert_eq!(lines("a\n", 5), ["a"]);
// A cluster never splits, however narrow the room.
assert_eq!(lines("\u{1f468}\u{200d}\u{1f469}", 1), ["\u{1f468}\u{200d}\u{1f469}"]);
assert_eq!(lines("e\u{301}e\u{301}", 1), ["e\u{301}", "e\u{301}"]);
assert_eq!(leaf_measure("hello world", true, None, Avail::MinContent).0, 5.0);
assert_eq!(leaf_measure("a\nbcd", true, None, Avail::MaxContent).0, 3.0);
assert_eq!(leaf_measure("a\nbcd", false, None, Avail::MinContent), (3.0, 2.0));
}
#[test]
fn measure_agrees_with_text() {
let rows: &[(&str, bool, Option<u32>, u32)] = &[
("hello world", true, None, 5),
("hello world", true, None, 11),
("\u{4e2d}\u{6587}\u{6587}\u{5b57}", true, None, 5),
("\u{4e2d}\u{6587}\u{6587}\u{5b57}", true, None, 3),
("\u{4e2d}", true, None, 1),
("abcdefgh", true, None, 3),
("a\nb", false, None, 80),
("a\nb", true, Some(1), 80),
("one two three\tfour five", true, Some(3), 7),
("\u{1f469}\u{200d}\u{1f469} x \u{1f600}\u{1f600}\u{1f600}", true, None, 4),
("", true, None, 4),
];
for &(text, wrap, max_lines, width) in rows {
let laid = layout_lines(text, wrap, max_lines, width as f32);
let (w, h) = leaf_measure(text, wrap, max_lines, Avail::Definite(width as f32));
let widest = laid.iter().map(|l| CellText::new(l).width()).max().unwrap_or(0);
assert_eq!((w, h), (widest as f32, laid.len() as f32), "{text:?} at {width}");
}
}
#[test]
fn controls_have_shipped_sizes() {
let node = NodeId::new("n");
let text = Bound::Text(String::new());
let c = Constraint { known: [None, None], available: [Avail::MaxContent, Avail::MaxContent] };
let mut m = CellMeasure;
assert_eq!(m.measure(&Leaf::TextInput { node: &node, multiline: false, placeholder: &text, value: &text }, c), (25.0, 1.0));
assert_eq!(m.measure(&Leaf::TextInput { node: &node, multiline: true, placeholder: &text, value: &text }, c), (25.0, 3.0));
assert_eq!(m.measure(&Leaf::Toggle { node: &node }, c), (5.0, 1.0));
assert_eq!(m.measure(&Leaf::Slider { node: &node }, c), (20.0, 1.0));
assert_eq!(m.measure(&Leaf::Select { node: &node, selected: &text }, c), (20.0, 1.0));
assert_eq!(m.measure(&Leaf::Image { node: &node, asset: &Bound::Absent }, c), (0.0, 0.0));
}
/// Random strings, every control among them, never panic and never put a control character into
/// any line at any width.
#[test]
fn fuzz_never_emits_a_control() {
let mut seed = 0x9e37_79b9_7f4a_7c15_u64;
let mut next = move || {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
seed
};
let pool: Vec<char> = (0u32..0x20)
.chain(0x7f..0xa0)
.chain([0x2028, 0x2029, 0x200b, 0x200d, 0xfe0f, 0x301, 0x20, 0x4e2d, 0x1f600])
.filter_map(char::from_u32)
.collect();
for round in 0..4000 {
let text: String = if round % 4 == 0 {
// Raw bytes, so truncated and surrogate encodings become U+FFFD.
let bytes: Vec<u8> = (0..(next() % 40)).map(|_| next() as u8).collect();
String::from_utf8_lossy(&bytes).into_owned()
} else {
(0..(next() % 40))
.map(|_| match next() % 3 {
0 => pool[(next() % pool.len() as u64) as usize],
1 => char::from_u32((next() % 0x30000) as u32).unwrap_or('\u{fffd}'),
_ => char::from(b'a' + (next() % 26) as u8),
})
.collect()
};
let width = (next() % 12) as f32;
let wrap = next() % 2 == 0;
for line in layout_lines(&text, wrap, None, width) {
assert!(!line.chars().any(|c| c.is_control() || matches!(c, '\u{2028}' | '\u{2029}')), "{text:?} -> {line:?}");
}
let _ = leaf_measure(&text, wrap, Some(3), Avail::Definite(width));
let _ = leaf_measure(&text, wrap, None, Avail::MinContent);
assert!(!CellText::new(&text).as_str().chars().any(|c| c.is_control()));
}
}

View file

@ -0,0 +1,31 @@
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

View file

@ -6,8 +6,9 @@ use std::path::PathBuf;
use thing_contract::*;
use thing_core::bind::{Binder, BoundTree};
use thing_core::diagnostic::Code;
use thing_core::layout::{LaidTree, LayoutFrame, Metrics, Run, layout};
use thing_core::layout::{LaidTree, LayoutFrame, Measure, Metrics, Run, layout};
use thing_core::port::Ledger;
use thing_core::text::CellMeasure;
use thing_core::render::{Placed, RenderCommand, RenderInput, Rendered, ScrollOffsets, balanced, clamp, render};
use thing_core::resolve::{Limits, resolve};
use thing_core::theme::Theme;
@ -41,20 +42,36 @@ fn bind(state: &mut MemState, document: &SurfaceDocument) -> Result<BoundTree, C
Ok(binder.tree(&document.record_key()).expect("bound").clone())
}
fn measure(frame: &LayoutFrame) -> FixedMeasure {
match frame.metrics {
Metrics::Pixels => FixedMeasure::pixels(),
Metrics::Cells => FixedMeasure::cells(),
/// The measure a frame is laid out with: the oracle, or in Cells the shipped engine.
#[derive(Clone, Copy, PartialEq)]
enum Engine {
Oracle,
Real,
}
fn measure_with(engine: Engine, frame: &LayoutFrame) -> Box<dyn Measure> {
match (frame.metrics, engine) {
(Metrics::Pixels, _) => Box::new(FixedMeasure::pixels()),
(Metrics::Cells, Engine::Oracle) => Box::new(FixedMeasure::cells()),
(Metrics::Cells, Engine::Real) => Box::new(CellMeasure),
}
}
fn measure(frame: &LayoutFrame) -> Box<dyn Measure> {
measure_with(Engine::Oracle, frame)
}
fn input<'a>(frame: &LayoutFrame, scroll: &'a ScrollOffsets, theme: &'a Theme) -> RenderInput<'a> {
RenderInput { scale: frame.scale, metrics: frame.metrics, viewport: frame.viewport, scroll, theme }
}
fn draw(tree: &BoundTree, frame: &LayoutFrame, scroll: &ScrollOffsets) -> (LaidTree, Rendered) {
let laid = layout(tree, frame, &mut measure(frame)).unwrap();
let rendered = render(tree, &laid, &input(frame, scroll, &Theme::std()), &mut measure(frame));
draw_with(Engine::Oracle, tree, frame, scroll)
}
fn draw_with(engine: Engine, tree: &BoundTree, frame: &LayoutFrame, scroll: &ScrollOffsets) -> (LaidTree, Rendered) {
let laid = layout(tree, frame, &mut *measure_with(engine, frame)).unwrap();
let rendered = render(tree, &laid, &input(frame, scroll, &Theme::std()), &mut *measure_with(engine, frame));
(laid, rendered)
}
@ -97,15 +114,20 @@ fn line(command: &RenderCommand) -> String {
let glyphs: Vec<String> = glyphs.iter().map(|g| format!("{}@{},{}", g.id, g.x, g.y)).collect();
format!("text {} {} {} font{} size{size} [{}]", origin.0, origin.1, hex(color), font.0, glyphs.join(" "))
}
Run::Cells { text, style } => format!(
"text {} {} {} cells {text:?} bold={} italic={} underline={}",
origin.0,
origin.1,
hex(color),
style.bold,
style.italic,
style.underline
),
Run::Cells { text, style } => {
let widths: Vec<String> = text.clusters().map(|(_, w)| w.to_string()).collect();
let widths = if text.clusters().all(|(_, w)| w == 1) { String::new() } else { format!(" widths={}", widths.join(",")) };
format!(
"text {} {} {} cells {:?} bold={} italic={} underline={}{widths}",
origin.0,
origin.1,
hex(color),
text.as_str(),
style.bold,
style.italic,
style.underline
)
}
},
RenderCommand::Image { rect, uri, alt } => format!("image {} {uri:?} {alt:?}", rect_text(rect)),
RenderCommand::ClipPush { rect, radius } => format!("clip-push {} r{radius}", rect_text(rect)),
@ -132,18 +154,22 @@ fn text_form(rendered: &Rendered) -> String {
/// Every surface of a fixture, bound under the fixture's state script and rendered.
fn fixture_runs(fixture: Fixture, frame: &LayoutFrame, scroll: &ScrollOffsets) -> Vec<(String, Result<Rendered, Code>)> {
fixture_runs_with(Engine::Oracle, fixture, frame, scroll)
}
fn fixture_runs_with(engine: Engine, fixture: Fixture, frame: &LayoutFrame, scroll: &ScrollOffsets) -> Vec<(String, Result<Rendered, Code>)> {
let set = fixture.load();
let mut state = MemState::from_fixture(fixture);
state::script(fixture, &mut state);
set.surfaces
.iter()
.map(|document| (document.record_key(), bind(&mut state, document).map(|tree| draw(&tree, frame, scroll).1)))
.map(|document| (document.record_key(), bind(&mut state, document).map(|tree| draw_with(engine, &tree, frame, scroll).1)))
.collect()
}
fn fixture_text(fixture: Fixture, frame: &LayoutFrame, scroll: &ScrollOffsets) -> String {
fn fixture_text(engine: Engine, fixture: Fixture, frame: &LayoutFrame, scroll: &ScrollOffsets) -> String {
let mut out = String::new();
for (key, run) in fixture_runs(fixture, frame, scroll) {
for (key, run) in fixture_runs_with(engine, fixture, frame, scroll) {
match run {
Ok(rendered) => {
let mode = if frame.metrics == Metrics::Cells { "cells" } else { "pixels" };
@ -162,7 +188,11 @@ fn stem(fixture: Fixture) -> String {
}
fn check(fixture: Fixture, suffix: &str, frame: &LayoutFrame, scroll: &ScrollOffsets) {
let text = fixture_text(fixture, frame, scroll);
check_with(Engine::Oracle, fixture, suffix, frame, scroll);
}
fn check_with(engine: Engine, fixture: Fixture, suffix: &str, frame: &LayoutFrame, scroll: &ScrollOffsets) {
let text = fixture_text(engine, fixture, frame, scroll);
golden::check(&golden_dir(), &format!("render-{}{suffix}.txt", stem(fixture)), text.as_bytes());
}
@ -179,6 +209,7 @@ fn goldens() {
check(fixture, "", &pixels(1.0), &none);
}
check(Fixture::F01SwarmDashboard, "-cells", &frame(100.0, 37.0, 1.0, Metrics::Cells), &none);
check_with(Engine::Real, Fixture::F12TextEdge, "-cells", &frame(40.0, 60.0, 1.0, Metrics::Cells), &none);
check(Fixture::F05ModalOverlay, "-scale1.5", &pixels(1.5), &none);
check(Fixture::F06ScrollList, "-scale1.5", &pixels(1.5), &none);
check(Fixture::F06ScrollList, "-scroll1000", &pixels(1.0), &scrolled("root", (0.0, 1000.0)));
@ -533,7 +564,7 @@ fn wrapping_text_is_one_command_per_engine_line_at_the_node_origin() {
.commands
.iter()
.filter_map(|c| match c {
RenderCommand::Text { origin, run: Run::Cells { text, .. }, .. } => Some((origin.0, origin.1, text.clone())),
RenderCommand::Text { origin, run: Run::Cells { text, .. }, .. } => Some((origin.0, origin.1, text.as_str().to_string())),
_ => None,
})
.collect();
@ -674,13 +705,13 @@ fn random_documents_render_without_panic_balanced_and_equal() {
refused += 1;
continue;
};
let Ok(laid) = layout(&tree, &frame, &mut measure(&frame)) else {
let Ok(laid) = layout(&tree, &frame, &mut *measure(&frame)) else {
refused += 1;
continue;
};
let theme = Theme::std();
let first = render(&tree, &laid, &input(&frame, &scroll, &theme), &mut measure(&frame));
let second = render(&tree, &laid, &input(&frame, &scroll, &theme), &mut measure(&frame));
let first = render(&tree, &laid, &input(&frame, &scroll, &theme), &mut *measure(&frame));
let second = render(&tree, &laid, &input(&frame, &scroll, &theme), &mut *measure(&frame));
assert_eq!(first, second, "round {round}");
with_image += first.commands.iter().any(|c| matches!(c, RenderCommand::Image { .. })) as u32;
with_plot += first.commands.iter().any(|c| matches!(c, RenderCommand::Polyline { .. } | RenderCommand::Polygon { .. })) as u32;

View file

@ -2,6 +2,7 @@
//! goldens never move when a real text measure changes.
use thing_core::bind::Bound;
use thing_core::text::CellText;
use thing_core::layout::{Avail, CellStyle, Constraint, FontId, Glyph, Leaf, Measure, Run, TextLayout, TextLine, TextRequest};
/// Text is 8 px wide per character and 16 px tall per line (one cell each in Cells); controls
@ -77,7 +78,7 @@ impl Measure for FixedMeasure {
y: row as f32 * height,
height,
run: if self.cells {
Run::Cells { text: line, style: CellStyle::default() }
Run::Cells { text: CellText::new(&line), style: CellStyle::default() }
} else {
let glyphs = line
.chars()