diff --git a/Cargo.lock b/Cargo.lock index bb5ab7d..c94a05f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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" diff --git a/Cargo.toml b/Cargo.toml index 509f62a..0dd9db3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" diff --git a/crates/thing-core/Cargo.toml b/crates/thing-core/Cargo.toml index 9b8c0a1..069e324 100644 --- a/crates/thing-core/Cargo.toml +++ b/crates/thing-core/Cargo.toml @@ -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" } diff --git a/crates/thing-core/src/layout/measure.rs b/crates/thing-core/src/layout/measure.rs index f35752e..079a082 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 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 }, - Cells { text: String, style: CellStyle }, + Cells { text: CellText, style: CellStyle }, } /// The Text leaf a line breaker is asked to lay out. diff --git a/crates/thing-core/src/lib.rs b/crates/thing-core/src/lib.rs index 851512d..08e7210 100644 --- a/crates/thing-core/src/lib.rs +++ b/crates/thing-core/src/lib.rs @@ -9,6 +9,7 @@ pub mod layout; pub mod port; pub mod render; pub mod resolve; +pub mod text; pub mod theme; pub mod time; diff --git a/crates/thing-core/src/text/cells.rs b/crates/thing-core/src/text/cells.rs new file mode 100644 index 0000000..500b73b --- /dev/null +++ b/crates/thing-core/src/text/cells.rs @@ -0,0 +1,317 @@ +//! 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. +//! +//! Order is sanitize, then segment and measure: the text is cleaned (controls become U+FFFD, +//! clusters without width are dropped) until segmenting it again changes nothing, so every width +//! recorded is the width of exactly the text a terminal receives. +//! +//! 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. A line takes at least one cluster, so at width 0 every cluster sits on its +//! own line. 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, whose clusters re-segment to themselves. 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 { + let (clean, open) = clean(text); + emit(&atoms(&clean, &open)) + } + + pub fn as_str(&self) -> &str { + &self.text + } + + /// Each cluster with its width in cells. + pub fn clusters(&self) -> impl Iterator { + 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() + } +} + +/// One kept cluster of a paragraph and whether a soft break may precede it. A tab is an atom of +/// its own: its width is decided where it falls in a line. +struct Atom<'a> { + text: &'a str, + width: u8, + tab: bool, + space: bool, + open: bool, +} + +impl Atom<'_> { + /// The columns this atom takes when it starts at `column` of its line. + fn cols(&self, column: u32) -> u32 { + if self.tab { TAB - column % TAB } else { u32::from(self.width) } + } +} + +fn is_terminator(c: char) -> bool { + matches!(c, '\n' | '\r' | '\u{b}' | '\u{c}' | '\u{85}' | '\u{2028}' | '\u{2029}') +} + +/// Sanitize, to a fixpoint: every control (a tab excepted) becomes U+FFFD and every cluster +/// without width is dropped, and since either can change how the rest segments, the result is +/// segmented again until nothing more changes. Returns the text and, by byte offset, where a soft +/// break may fall; the opportunity at a dropped cluster rides on the next kept one. +fn clean(paragraph: &str) -> (String, Vec) { + let mut open = vec![false; paragraph.len() + 1]; + for (at, kind) in linebreaks(paragraph) { + if kind == BreakOpportunity::Allowed { + open[at] = true; + } + } + let mut text = paragraph.to_owned(); + loop { + let mut out = String::with_capacity(text.len()); + let mut marks = Vec::new(); + let (mut pending, mut changed) = (false, false); + for (start, cluster) in text.grapheme_indices(true) { + let here = open[start] || pending; + pending = false; + let first = cluster.chars().next().expect("a cluster has a scalar"); + let kept = if cluster == "\t" { + cluster + } else if first.is_control() || is_terminator(first) { + changed = true; + "\u{fffd}" + } else if cluster.width() == 0 { + (pending, changed) = (here, true); + continue; + } else { + cluster + }; + if here { + marks.push(out.len()); + } + out.push_str(kept); + } + if !changed { + return (text, open); + } + open = vec![false; out.len() + 1]; + for mark in marks { + open[mark] = true; + } + text = out; + } +} + +/// The clusters of cleaned text. +fn atoms<'a>(text: &'a str, open: &[bool]) -> Vec> { + let mut out: Vec = text + .grapheme_indices(true) + .map(|(start, cluster)| { + let tab = cluster == "\t"; + Atom { text: cluster, width: if tab { 0 } else { cluster.width().min(255) as u8 }, tab, space: tab || cluster == " ", open: open[start] } + }) + .collect(); + if let Some(first) = out.first_mut() { + first.open = false; + } + out +} + +/// One line as terminal text: tabs become spaces to the next stop from the line's start, and the +/// result is cleaned and segmented once more, so its recorded widths are those of the emitted text. +fn emit(line: &[Atom]) -> CellText { + let mut text = String::new(); + let mut column = 0; + for atom in line { + let cols = atom.cols(column); + if atom.tab { + text.extend(std::iter::repeat_n(' ', cols as usize)); + } else { + text.push_str(atom.text); + } + column += cols; + } + let (text, _) = clean(&text); + let mut out = CellText::default(); + for cluster in text.graphemes(true) { + out.text.push_str(cluster); + out.clusters.push((out.text.len() as u32, cluster.width().min(255) as u8)); + } + 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. +fn break_lines(text: &str, wrap: bool, max_lines: Option, cols: u32) -> Vec { + let cap = max_lines.map_or(usize::MAX, |n| n as usize); + let mut lines = Vec::new(); + for paragraph in paragraphs(text) { + let (clean, open) = clean(paragraph); + let atoms = atoms(&clean, &open); + 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() && line.iter().any(|a| !a.space) { + // A soft break: the spaces before it hang. + while let Some((last, rest)) = line.split_last() { + if !last.space { + break; + } + line = rest; + } + } + lines.push(emit(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. Spaces hang: they +/// never overflow a line. +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 += atom.cols(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 (clean, open) = clean(paragraph); + let (mut column, mut from, mut shown) = (0, 0, 0); + for atom in atoms(&clean, &open) { + if atom.open { + widest = widest.max(shown - from); + (from, shown) = (column, column); + } + column += atom.cols(column); + if !atom.space { + shown = column; + } + } + widest = widest.max(shown - from); + } + widest +} + +fn lines_for(text: &str, wrap: bool, max_lines: Option, room: Avail) -> Vec { + 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(), + } + } +} diff --git a/crates/thing-core/src/text/mod.rs b/crates/thing-core/src/text/mod.rs new file mode 100644 index 0000000..2b320dd --- /dev/null +++ b/crates/thing-core/src/text/mod.rs @@ -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}; diff --git a/crates/thing-core/tests/cells.rs b/crates/thing-core/tests/cells.rs new file mode 100644 index 0000000..8fd42f7 --- /dev/null +++ b/crates/thing-core/tests/cells.rs @@ -0,0 +1,260 @@ +//! 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::{AssetEntry, NodeId}; +use thing_core::bind::Bound; +use thing_core::layout::{Avail, Constraint, Leaf, Measure, Run, TextRequest}; +use thing_core::text::{CellMeasure, CellText}; +use thing_testkit::build::count; + +fn widths(s: &str) -> Vec { + 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::(), "{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"); + assert_eq!(CellText::new("a\u{2028}b").as_str(), "a\u{fffd}b"); + assert_eq!(widths("a\u{2028}b"), [1, 1, 1]); +} + +#[test] +fn dropping_a_cluster_is_measured_after_the_drop() { + // woman, a dropped bidi control, skin tone: the terminal sees one 2-wide cluster. + let t = CellText::new("\u{1f469}\u{202c}\u{1f3fd}"); + assert_eq!(t.as_str(), "\u{1f469}\u{1f3fd}"); + assert_eq!(t.clusters().map(|(_, w)| w).collect::>(), [2]); + // A control turned U+FFFD leaves the mark after it orphaned, and an orphan is dropped. + assert_eq!(CellText::new("\u{1b}\u{301}").as_str(), "\u{fffd}"); +} + +#[test] +fn tabs_stop_at_eight_from_the_start_of_the_line() { + assert_eq!(CellText::new("\t").as_str(), " ".repeat(8)); + assert_eq!(CellText::new("\t\t").as_str(), " ".repeat(16)); + assert_eq!(CellText::new("abcdefgh\t").as_str(), format!("abcdefgh{}", " ".repeat(8))); + assert_eq!(CellText::new("abc\t\td").as_str(), format!("abc{}d", " ".repeat(13))); + assert_eq!(CellText::new("\u{4e2d}\tx").as_str(), format!("\u{4e2d}{}x", " ".repeat(6))); + // After a soft break the stop counts from the wrapped line, not the paragraph. + assert_eq!(lines("aaaaaaaa bb\tc", 9), ["aaaaaaaa", "bb c"]); + // A tab is a space: it hangs at a soft break. + assert_eq!(lines("abcdef\tgh", 7), ["abcdef", "gh"]); + assert_eq!(lines("ab cd", 9), ["ab", "cd"]); + assert_eq!(lines("ab cd", 10), ["ab cd"]); + assert_eq!(leaf_measure("a b", true, None, Avail::MinContent).0, 1.0); + assert_eq!(leaf_measure("a b", false, None, Avail::MaxContent).0, 9.0); +} + +#[test] +fn width_zero_is_one_cluster_per_line() { + assert_eq!(lines("abc", 0), ["a", "b", "c"]); + assert_eq!(lines("a b", 0), ["a", "b"]); + assert_eq!(lines("\u{4e2d}x", 0), ["\u{4e2d}", "x"]); + assert_eq!(lines(" a", 2), [" ", "a"]); + assert_eq!(layout_lines("abc", true, None, -3.0), ["a", "b", "c"]); + assert_eq!(layout_lines("abc", true, None, f32::NAN), ["a", "b", "c"]); + assert_eq!(leaf_measure("abc", true, None, Avail::Definite(0.0)), (1.0, 3.0)); + assert!(lines("abc def", 0).iter().all(|l| !l.is_empty())); +} + +#[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, 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, width: f32) -> Vec { + 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 { + 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 break opportunity that falls before a dropped mark (LRM here) is kept for the next cluster. + assert_eq!(lines("a \u{200e}bcd", 3), ["a", "bcd"]); + // 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)] = &[ + ("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)); + let entry = AssetEntry { id: "a".into(), media_type: "image/png".into(), uri: "asset://a".into(), width: count(17), height: count(33) }; + assert_eq!(m.measure(&Leaf::Image { node: &node, asset: &Bound::Asset(entry) }, c), (3.0, 3.0), "extent over (8, 16), rounded up"); +} + +/// 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 = (0u32..0x20) + .chain(0x7f..0xa0) + .chain([0x2028, 0x2029, 0x200b, 0x200d, 0xfe0f, 0x301, 0x20, 0x9, 0x4e2d, 0x1f600, 0x1f469, 0x1f3fd, 0x202c, 0x1f1ef, 0x1f1f5, 0x600, 0x20e3]) + .filter_map(char::from_u32) + .collect(); + for round in 0..400_000 { + let text: String = if round % 4 == 0 { + // Raw bytes, so truncated and surrogate encodings become U+FFFD. + let bytes: Vec = (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:?}"); + } + // What is emitted measures to what was recorded: measuring it again changes nothing. + let node = NodeId::new("n"); + let request = TextRequest { node: &node, text: &text, style_token: "body", wrap, max_lines: None }; + for line in CellMeasure.text(&request, width).lines { + let Run::Cells { text: emitted, .. } = line.run else { panic!() }; + assert_eq!(CellText::new(emitted.as_str()), emitted, "{text:?} at {width}"); + assert!(emitted.clusters().all(|(_, w)| w >= 1)); + } + let lone = CellText::new(&text); + assert_eq!(CellText::new(lone.as_str()), lone, "{text:?}"); + 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())); + } +} 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 new file mode 100644 index 0000000..1fdbefa --- /dev/null +++ b/crates/thing-core/tests/goldens/render-f12-text-edge-cells.txt @@ -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 diff --git a/crates/thing-core/tests/render.rs b/crates/thing-core/tests/render.rs index 2895b15..e2dcd66 100644 --- a/crates/thing-core/tests/render.rs +++ b/crates/thing-core/tests/render.rs @@ -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 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 { + 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 { + 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 = 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 = 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)> { + fixture_runs_with(Engine::Oracle, fixture, frame, scroll) +} + +fn fixture_runs_with(engine: Engine, fixture: Fixture, frame: &LayoutFrame, scroll: &ScrollOffsets) -> Vec<(String, Result)> { 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; diff --git a/crates/thing-testkit/src/measure.rs b/crates/thing-testkit/src/measure.rs index 2570a1e..297f482 100644 --- a/crates/thing-testkit/src/measure.rs +++ b/crates/thing-testkit/src/measure.rs @@ -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()