diff --git a/crates/thing-core/src/text/cells.rs b/crates/thing-core/src/text/cells.rs index 8ee3d60..500b73b 100644 --- a/crates/thing-core/src/text/cells.rs +++ b/crates/thing-core/src/text/cells.rs @@ -2,10 +2,15 @@ //! 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. Text is laid out in logical order; bidi reordering is Pixels-only. +//! 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; @@ -18,8 +23,8 @@ use crate::layout::{Avail, CellStyle, Constraint, Leaf, Measure, Run, TextLayout 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. +/// 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, @@ -32,7 +37,8 @@ impl CellText { /// 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)) + let (clean, open) = clean(text); + emit(&atoms(&clean, &open)) } pub fn as_str(&self) -> &str { @@ -53,70 +59,114 @@ impl CellText { 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. +/// 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}') } -/// The clusters of one paragraph (no line terminator inside it, or one that is plain text). -fn atoms(paragraph: &str) -> Vec> { - let mut open_at = vec![false; paragraph.len() + 1]; +/// 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[at] = true; + open[at] = true; } } - let mut out: Vec = 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; + 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 { - out.push(Atom { text: cluster, width, space: cluster == " ", open }); - column += u32::from(width); + 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> { @@ -139,13 +189,13 @@ fn strip_terminator(piece: &str) -> &str { } } -/// 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. +/// 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 atoms = atoms(paragraph); + let (clean, open) = clean(paragraph); + let atoms = atoms(&clean, &open); let mut start = 0; loop { if lines.len() >= cap { @@ -153,7 +203,7 @@ fn break_lines(text: &str, wrap: bool, max_lines: Option, cols: u32) -> Vec } let end = if wrap { fit(&atoms, start, cols) } else { atoms.len() }; let mut line = &atoms[start..end]; - if end < atoms.len() { + 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 { @@ -162,7 +212,7 @@ fn break_lines(text: &str, wrap: bool, max_lines: Option, cols: u32) -> Vec line = rest; } } - lines.push(CellText::from_atoms(line)); + lines.push(emit(line)); if end >= atoms.len() { break; } @@ -173,7 +223,8 @@ fn break_lines(text: &str, wrap: bool, max_lines: Option, cols: u32) -> Vec } /// 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. +/// 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; @@ -181,12 +232,12 @@ fn fit(atoms: &[Atom], start: usize, cols: u32) -> usize { if atom.open && i > start { candidate = Some(i); } - width += u32::from(atom.width); + width += atom.cols(width); if !atom.space { shown = width; - } - if shown > cols && i > start { - return candidate.unwrap_or(i); + if shown > cols && i > start { + return candidate.unwrap_or(i); + } } } atoms.len() @@ -196,16 +247,19 @@ fn fit(atoms: &[Atom], start: usize, cols: u32) -> usize { 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; + 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 } diff --git a/crates/thing-core/tests/cells.rs b/crates/thing-core/tests/cells.rs index 8e1da50..f21d6c7 100644 --- a/crates/thing-core/tests/cells.rs +++ b/crates/thing-core/tests/cells.rs @@ -61,6 +61,44 @@ fn sanitizing() { 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!(leaf_measure("a\tb", true, None, Avail::MinContent).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] @@ -180,10 +218,10 @@ fn fuzz_never_emits_a_control() { }; let pool: Vec = (0u32..0x20) .chain(0x7f..0xa0) - .chain([0x2028, 0x2029, 0x200b, 0x200d, 0xfe0f, 0x301, 0x20, 0x4e2d, 0x1f600]) + .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..4000 { + 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(); @@ -202,6 +240,16 @@ fn fuzz_never_emits_a_control() { 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()));