From 8042a6ea469bac0c73b5a17a8e76cf275ffb8a4a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 6 Dec 2026 04:16:29 +0100 Subject: [PATCH] thing2(text): keep cleaned clusters bound to source boundaries and verify stop completeness --- crates/thing-core/src/text/cells.rs | 167 +++++++++++++++------------- crates/thing-core/tests/cells.rs | 74 ++++++++++++ 2 files changed, 166 insertions(+), 75 deletions(-) diff --git a/crates/thing-core/src/text/cells.rs b/crates/thing-core/src/text/cells.rs index d562733..76de0c7 100644 --- a/crates/thing-core/src/text/cells.rs +++ b/crates/thing-core/src/text/cells.rs @@ -37,8 +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 { - let (clean, open, origin) = clean(text); - emit(&atoms(&clean, &open, &origin, text, 0)) + let cleaned = clean(text); + emit(&atoms(&cleaned, 0)) } pub fn as_str(&self) -> &str { @@ -84,95 +84,112 @@ 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, by byte offset where a soft -/// break may fall (the opportunity at a dropped cluster rides on the next kept one), and for each -/// byte of the cleaned text the byte of `paragraph` it came from. -fn clean(paragraph: &str) -> (String, Vec, Vec) { +struct CleanEntry { + start: usize, + end: usize, + open: bool, + orig_start: u32, + orig_end: u32, +} + +struct Cleaned { + buf: String, + entries: Vec, +} + +/// Sanitize each source extended-grapheme cluster without re-segmenting across dropped zero-width +/// clusters: every control (a tab excepted) becomes U+FFFD and every zero-width cluster is dropped +/// (its soft-break opportunity rides on the next kept cluster). A following cluster merges into the +/// previous kept one only when concatenating them collapses their width into a single cluster +/// (e.g. a modifier across a dropped bidi control), never splitting or re-pairing Regional +/// Indicators across a dropped boundary. +fn clean(paragraph: &str) -> Cleaned { 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(); - let mut origin: Vec = (0..paragraph.len()).collect(); - loop { - let mut out = String::with_capacity(text.len()); - let mut out_origin = Vec::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"); - if cluster == "\t" { - if here { - marks.push(out.len()); + let mut buf = String::with_capacity(paragraph.len()); + let mut entries: Vec = Vec::new(); + let (mut pending, mut dropped) = (false, false); + for (start, cluster) in paragraph.grapheme_indices(true) { + let orig_end = (start + cluster.len()) as u32; + let here = open[start] || pending; + pending = false; + let first = cluster.chars().next().expect("a cluster has a scalar"); + let piece = if cluster == "\t" { + "\t" + } else if first.is_control() || is_terminator(first) { + "\u{fffd}" + } else if cluster.width() == 0 { + pending = here; + dropped = true; + continue; + } else { + cluster + }; + + let merged = if dropped { + if let Some(prev) = entries.last_mut() { + let prev_slice = &buf[prev.start..prev.end]; + let prev_width = prev_slice.width(); + let piece_width = piece.width(); + buf.push_str(piece); + let combined = &buf[prev.start..]; + if combined.graphemes(true).count() == 1 && combined.width() != prev_width + piece_width { + prev.end = buf.len(); + prev.orig_end = orig_end; + true + } else { + buf.truncate(prev.end); + false } - out.push_str(cluster); - out_origin.extend_from_slice(&origin[start..start + cluster.len()]); - } else if first.is_control() || is_terminator(first) { - changed = true; - if here { - marks.push(out.len()); - } - let orig = origin[start]; - out.push('\u{fffd}'); - out_origin.extend([orig, orig, orig]); - } else if cluster.width() == 0 { - (pending, changed) = (here, true); - continue; } else { - if here { - marks.push(out.len()); - } - out.push_str(cluster); - out_origin.extend_from_slice(&origin[start..start + cluster.len()]); + false } + } else { + false + }; + + if !merged { + let buf_start = buf.len(); + buf.push_str(piece); + entries.push(CleanEntry { + start: buf_start, + end: buf.len(), + open: here, + orig_start: start as u32, + orig_end, + }); } - if !changed { - return (text, open, origin); - } - open = vec![false; out.len() + 1]; - for mark in marks { - open[mark] = true; - } - origin = out_origin; - text = out; + dropped = false; } + if let Some(first) = entries.first_mut() { + first.open = false; + } + Cleaned { buf, entries } } /// The clusters of cleaned text, carrying their byte ranges in the original text. -fn atoms<'a>(text: &'a str, open: &[bool], origin: &[usize], raw: &str, base: usize) -> Vec> { - let mut out: Vec = text - .grapheme_indices(true) - .map(|(start, cluster)| { - let end = start + cluster.len(); - let orig_start = origin[start]; - let last_orig = origin[end - 1]; - let orig_end = if raw.is_char_boundary(last_orig + 1) && (cluster.len() < 3 || origin[end - 2] != last_orig) { - last_orig + 1 - } else { - last_orig + raw[last_orig..].graphemes(true).next().map_or(1, str::len) - }; +fn atoms(cleaned: &Cleaned, base: usize) -> Vec> { + cleaned + .entries + .iter() + .map(|entry| { + let cluster = &cleaned.buf[entry.start..entry.end]; 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], - orig_start: (base + orig_start) as u32, - orig_end: (base + orig_end) as u32, + open: entry.open, + orig_start: base as u32 + entry.orig_start, + orig_end: base as u32 + entry.orig_end, } }) - .collect(); - if let Some(first) = out.first_mut() { - first.open = false; - } - out + .collect() } /// One line as terminal text: tabs become spaces to the next stop from the line's start, and the @@ -189,9 +206,9 @@ fn emit(line: &[Atom]) -> CellText { } column += cols; } - let (text, _, _) = clean(&text); + let cleaned = clean(&text); let mut out = CellText::default(); - for cluster in text.graphemes(true) { + for cluster in cleaned.buf.graphemes(true) { out.text.push_str(cluster); out.clusters.push((out.text.len() as u32, cluster.width().min(255) as u8)); } @@ -276,8 +293,8 @@ fn break_lines(text: &str, wrap: bool, max_lines: Option, cols: u32, geomet let mut b_cursor = 0usize; let mut lines = Vec::new(); for paragraph in paragraphs(text) { - let (clean, open, origin) = clean(paragraph.content); - let atoms = atoms(&clean, &open, &origin, paragraph.content, paragraph.start); + let cleaned = clean(paragraph.content); + let atoms = atoms(&cleaned, paragraph.start); let mut start = 0; loop { if lines.len() >= cap { @@ -337,9 +354,9 @@ 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 (clean, open, origin) = clean(paragraph.content); + let cleaned = clean(paragraph.content); let (mut column, mut from, mut shown) = (0, 0, 0); - for atom in atoms(&clean, &open, &origin, paragraph.content, paragraph.start) { + for atom in atoms(&cleaned, paragraph.start) { if atom.open { widest = widest.max(shown - from); (from, shown) = (column, column); diff --git a/crates/thing-core/tests/cells.rs b/crates/thing-core/tests/cells.rs index 9e6094d..e3bb59b 100644 --- a/crates/thing-core/tests/cells.rs +++ b/crates/thing-core/tests/cells.rs @@ -10,6 +10,7 @@ use thing_core::text::{CellMeasure, CellText}; use thing_testkit::build::count; use thing_testkit::fixture::Fixture; use thing_testkit::measure::FixedMeasure; +use unicode_linebreak::{BreakOpportunity, linebreaks}; use unicode_segmentation::UnicodeSegmentation; fn widths(s: &str) -> Vec { @@ -275,11 +276,18 @@ fn check_geometry(text: &str, wrap: bool, max_lines: Option, width: f32) { assert_eq!(off.lines.len(), on.lines.len(), "{text:?} at {width}"); let boundaries: BTreeSet = text.grapheme_indices(true).map(|(i, _)| i as u32).chain(std::iter::once(text.len() as u32)).collect(); + let mut para_ends: BTreeSet = linebreaks(text) + .filter(|&(_, kind)| kind == BreakOpportunity::Mandatory) + .map(|(at, _)| at as u32) + .collect(); + para_ends.insert(text.len() as u32); let mut prev_end = 0u32; for (idx, (lo, hi)) in off.lines.iter().zip(&on.lines).enumerate() { assert_eq!((lo.y, lo.height, &lo.run, lo.source), (hi.y, hi.height, &hi.run, hi.source)); assert!(lo.stops.is_empty()); assert!(hi.source.0 <= hi.source.1 && hi.source.1 <= text.len() as u32, "{text:?}"); + assert!(boundaries.contains(&hi.source.0), "source.0 {} not a boundary in {text:?}", hi.source.0); + assert!(boundaries.contains(&hi.source.1), "source.1 {} not a boundary in {text:?}", hi.source.1); if idx == 0 { assert_eq!(hi.source.0, 0, "{text:?}"); } else { @@ -297,6 +305,14 @@ fn check_geometry(text: &str, wrap: bool, max_lines: Option, width: f32) { assert!(w[0].byte < w[1].byte, "{text:?}"); assert!(w[0].x <= w[1].x, "{text:?}"); } + let include_end = para_ends.contains(&hi.source.1); + let expected_bytes: Vec = boundaries + .iter() + .copied() + .filter(|&b| b >= hi.source.0 && (b < hi.source.1 || (include_end && b == hi.source.1))) + .collect(); + let actual_bytes: Vec = hi.stops.iter().map(|s| s.byte).collect(); + assert_eq!(actual_bytes, expected_bytes, "{text:?} line {idx} source={:?}", hi.source); } if max_lines.is_none() && !on.lines.is_empty() { assert_eq!(prev_end, text.len() as u32, "{text:?}"); @@ -332,6 +348,10 @@ fn stops_corpus() { "\u{1f469}\u{202c}\u{1f3fd}".to_string(), "\u{1b}\u{301}".to_string(), "\u{4e2d}\u{6587}\tx\u{1f600}\u{1f600}".to_string(), + "\u{1f1ef}\u{200b}\u{1f1f5}\u{1f1f5}".to_string(), + "\u{1f1ef}\u{200b}\u{1f1f5}".to_string(), + "\u{1f1ef}\u{202c}\u{1f1f5}\u{1f1f5}".to_string(), + "\u{1f1ef}\u{200b}\u{1f1f5}\u{1f1f5}\u{1f1fa}".to_string(), ]); for text in &corpus { for width in [0.0, 1.0, 2.0, 3.0, 5.0, 8.0, 12.0, 40.0, 120.0] { @@ -356,6 +376,9 @@ fn stop_x_equals_width() { "\u{4e2d}\tx", "\t\t", "a\u{1b}b", + "\u{1f1ef}\u{200b}\u{1f1f5}\u{1f1f5}", + "\u{1f1ef}\u{200b}\u{1f1f5}", + "\u{1f1ef}\u{202c}\u{1f1f5}\u{1f1f5}", ]; for text in cases { let req = TextRequest { node: &node, text, style_token: "body", wrap: false, max_lines: None, geometry: true }; @@ -443,6 +466,57 @@ fn sanitized_source() { assert_eq!(orphan.lines[0].stops, [Stop { byte: 0, x: 0.0 }, Stop { byte: 1, x: 1.0 }, Stop { byte: 3, x: 1.0 }]); } +#[test] +fn ri_does_not_re_pair_across_dropped_cluster() { + let node = NodeId::new("n"); + let text = "\u{1f1ef}\u{200b}\u{1f1f5}\u{1f1f5}"; + + let wrapped = CellMeasure.text(&TextRequest { node: &node, text, style_token: "body", wrap: true, max_lines: None, geometry: true }, 2.0); + assert_eq!(wrapped.lines.len(), 2); + assert_eq!(wrapped.lines[0].source, (0, 7)); + assert_eq!(wrapped.lines[0].stops, [Stop { byte: 0, x: 0.0 }, Stop { byte: 4, x: 1.0 }]); + let Run::Cells { text: line0, .. } = &wrapped.lines[0].run else { panic!() }; + assert_eq!(line0.as_str(), "\u{1f1ef}"); + assert_eq!(wrapped.lines[1].source, (7, 15)); + assert_eq!(wrapped.lines[1].stops, [Stop { byte: 7, x: 0.0 }, Stop { byte: 15, x: 2.0 }]); + let Run::Cells { text: line1, .. } = &wrapped.lines[1].run else { panic!() }; + assert_eq!(line1.as_str(), "\u{1f1f5}\u{1f1f5}"); + + let unwrapped = CellMeasure.text(&TextRequest { node: &node, text, style_token: "body", wrap: false, max_lines: None, geometry: true }, 80.0); + assert_eq!(unwrapped.lines.len(), 1); + assert_eq!(unwrapped.lines[0].source, (0, 15)); + assert_eq!( + unwrapped.lines[0].stops, + [ + Stop { byte: 0, x: 0.0 }, + Stop { byte: 4, x: 1.0 }, + Stop { byte: 7, x: 1.0 }, + Stop { byte: 15, x: 3.0 }, + ] + ); + for stop in &unwrapped.lines[0].stops { + assert_eq!(stop.x, CellText::new(&text[..stop.byte as usize]).width() as f32); + } + let Run::Cells { text: full, .. } = &unwrapped.lines[0].run else { panic!() }; + assert_eq!(full.width(), 3); + assert_eq!(CellText::new(text).width(), 3); + + let no_break = CellMeasure.text(&TextRequest { node: &node, text: "\u{1f1ef}\u{202c}\u{1f1f5}\u{1f1f5}", style_token: "body", wrap: true, max_lines: None, geometry: true }, 2.0); + assert_eq!(no_break.lines.len(), 2); + assert_eq!(no_break.lines[0].source, (0, 7)); + assert_eq!(no_break.lines[0].stops, [Stop { byte: 0, x: 0.0 }, Stop { byte: 4, x: 1.0 }]); + assert_eq!(no_break.lines[1].source, (7, 15)); + assert_eq!(no_break.lines[1].stops, [Stop { byte: 7, x: 0.0 }, Stop { byte: 15, x: 2.0 }]); + + let pair = "\u{1f1ef}\u{200b}\u{1f1f5}"; + let pair_wrapped = CellMeasure.text(&TextRequest { node: &node, text: pair, style_token: "body", wrap: true, max_lines: None, geometry: true }, 1.0); + assert_eq!(pair_wrapped.lines.len(), 2); + assert_eq!(pair_wrapped.lines[0].source, (0, 7)); + assert_eq!(pair_wrapped.lines[0].stops, [Stop { byte: 0, x: 0.0 }, Stop { byte: 4, x: 1.0 }]); + assert_eq!(pair_wrapped.lines[1].source, (7, 11)); + assert_eq!(pair_wrapped.lines[1].stops, [Stop { byte: 7, x: 0.0 }, Stop { byte: 11, x: 1.0 }]); +} + #[test] fn fixed_measure_geometry() { let node = NodeId::new("n");