thing2(text): add TextLine source ranges and cluster stops (9b-2a)

This commit is contained in:
Meta Vens 2026-12-06 00:39:44 +01:00
commit 9baf938e55
6 changed files with 396 additions and 65 deletions

View file

@ -70,6 +70,15 @@ pub struct TextRequest<'a> {
pub style_token: &'a str,
pub wrap: bool,
pub max_lines: Option<u32>,
pub geometry: bool,
}
/// One cluster boundary inside a laid `TextLine`: `byte` is its UTF-8 offset in `request.text`,
/// and `x` is its distance from the line's origin in logical px (Pixels) or cells (Cells).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Stop {
pub byte: u32,
pub x: f32,
}
/// One line: `y` and `height` are measured from the top of the node, in logical px or cells.
@ -78,6 +87,8 @@ pub struct TextLine {
pub y: f32,
pub height: f32,
pub run: Run,
pub source: (u32, u32),
pub stops: Vec<Stop>,
}
#[derive(Clone, Debug, Default, PartialEq)]

View file

@ -18,7 +18,7 @@ use taffy::{AvailableSpace, Size, compute_leaf_layout};
use measure::Device;
use thing_contract::{NodeId, OverlayNode};
pub use measure::{Avail, CellStyle, Constraint, FontId, Glyph, Leaf, Measure, Run, TextLayout, TextLine, TextRequest};
pub use measure::{Avail, CellStyle, Constraint, FontId, Glyph, Leaf, Measure, Run, Stop, TextLayout, TextLine, TextRequest};
pub(crate) use measure::{CELL_PX, MAX_DEVICE};
use crate::bind::BoundTree;

View file

@ -64,7 +64,7 @@ impl<'a> Painter<'a> {
Some(style) => style.color.clone(),
None => self.fault(id, token),
};
let request = TextRequest { node: id, text: content, style_token: token, wrap, max_lines };
let request = TextRequest { node: id, text: content, style_token: token, wrap, max_lines, geometry: false };
for line in text.text(&request, at.w).lines.into_iter().filter(|line| line.y + line.height <= room) {
self.out.commands.push(RenderCommand::Text { origin: (at.x, at.y + line.y), run: line.run, color: color.clone() });
}

View file

@ -17,7 +17,7 @@ use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;
use crate::bind::Bound;
use crate::layout::{Avail, CELL_PX, CellStyle, Constraint, Leaf, Measure, Run, TextLayout, TextLine, TextRequest};
use crate::layout::{Avail, CELL_PX, CellStyle, Constraint, Leaf, Measure, Run, Stop, TextLayout, TextLine, TextRequest};
/// The tab stop, in columns (CSS `tab-size: 8`).
const TAB: u32 = 8;
@ -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) = clean(text);
emit(&atoms(&clean, &open))
let (clean, open, origin) = clean(text);
emit(&atoms(&clean, &open, &origin, text, 0))
}
pub fn as_str(&self) -> &str {
@ -69,6 +69,8 @@ struct Atom<'a> {
tab: bool,
space: bool,
open: bool,
orig_start: u32,
orig_end: u32,
}
impl Atom<'_> {
@ -84,9 +86,10 @@ fn is_terminator(c: char) -> bool {
/// 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<bool>) {
/// 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<bool>, Vec<usize>) {
let mut open = vec![false; paragraph.len() + 1];
for (at, kind) in linebreaks(paragraph) {
if kind == BreakOpportunity::Allowed {
@ -94,48 +97,76 @@ fn clean(paragraph: &str) -> (String, Vec<bool>) {
}
}
let mut text = paragraph.to_owned();
let mut origin: Vec<usize> = (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");
let kept = if cluster == "\t" {
cluster
if cluster == "\t" {
if here {
marks.push(out.len());
}
out.push_str(cluster);
out_origin.extend_from_slice(&origin[start..start + cluster.len()]);
} else if first.is_control() || is_terminator(first) {
changed = true;
"\u{fffd}"
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 {
cluster
};
if here {
marks.push(out.len());
if here {
marks.push(out.len());
}
out.push_str(cluster);
out_origin.extend_from_slice(&origin[start..start + cluster.len()]);
}
out.push_str(kept);
}
if !changed {
return (text, open);
return (text, open, origin);
}
open = vec![false; out.len() + 1];
for mark in marks {
open[mark] = true;
}
origin = out_origin;
text = out;
}
}
/// The clusters of cleaned text.
fn atoms<'a>(text: &'a str, open: &[bool]) -> Vec<Atom<'a>> {
/// 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<Atom<'a>> {
let mut out: Vec<Atom> = 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)
};
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] }
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,
}
})
.collect();
if let Some(first) = out.first_mut() {
@ -158,7 +189,7 @@ fn emit(line: &[Atom]) -> CellText {
}
column += cols;
}
let (text, _) = clean(&text);
let (text, _, _) = clean(&text);
let mut out = CellText::default();
for cluster in text.graphemes(true) {
out.text.push_str(cluster);
@ -167,18 +198,25 @@ fn emit(line: &[Atom]) -> CellText {
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> {
struct Paragraph<'a> {
start: usize,
content: &'a str,
end: usize,
}
/// The paragraphs of `text`: the pieces between mandatory breaks, terminators removed, carrying
/// their full span in `text` (the terminator included). A final terminator ends the last line and
/// starts no empty one.
fn paragraphs(text: &str) -> Vec<Paragraph<'_>> {
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]));
out.push(Paragraph { start: from, content: strip_terminator(&text[from..at]), end: at });
from = at;
}
}
out.push(strip_terminator(&text[from..]));
out.push(Paragraph { start: from, content: strip_terminator(&text[from..]), end: text.len() });
out
}
@ -189,13 +227,57 @@ fn strip_terminator(piece: &str) -> &str {
}
}
struct BrokenLine {
text: CellText,
source: (u32, u32),
stops: Vec<Stop>,
}
fn stops_for_line(
boundaries: &[u32],
cursor: &mut usize,
line: &[Atom],
source_start: u32,
source_end: u32,
include_end: bool,
) -> Vec<Stop> {
while *cursor < boundaries.len() && boundaries[*cursor] < source_start {
*cursor += 1;
}
let mut stops = Vec::new();
let mut ai = 0usize;
let mut col = 0u32;
for &b in &boundaries[*cursor..] {
if b > source_end || (!include_end && b == source_end) {
break;
}
while ai < line.len() && line[ai].orig_end <= b {
col += line[ai].cols(col);
ai += 1;
}
let x = if ai < line.len() && b > line[ai].orig_start {
col + line[ai].cols(col)
} else {
col
};
stops.push(Stop { byte: b, x: x as f32 });
}
stops
}
/// The lines of `text` at `cols` columns. `wrap` off breaks at mandatory breaks only.
fn break_lines(text: &str, wrap: bool, max_lines: Option<u32>, cols: u32) -> Vec<CellText> {
fn break_lines(text: &str, wrap: bool, max_lines: Option<u32>, cols: u32, geometry: bool) -> Vec<BrokenLine> {
let cap = max_lines.map_or(usize::MAX, |n| n as usize);
let boundaries: Vec<u32> = if geometry {
text.grapheme_indices(true).map(|(i, _)| i as u32).chain(std::iter::once(text.len() as u32)).collect()
} else {
Vec::new()
};
let mut b_cursor = 0usize;
let mut lines = Vec::new();
for paragraph in paragraphs(text) {
let (clean, open) = clean(paragraph);
let atoms = atoms(&clean, &open);
let (clean, open, origin) = clean(paragraph.content);
let atoms = atoms(&clean, &open, &origin, paragraph.content, paragraph.start);
let mut start = 0;
loop {
if lines.len() >= cap {
@ -212,8 +294,16 @@ fn break_lines(text: &str, wrap: bool, max_lines: Option<u32>, cols: u32) -> Vec
line = rest;
}
}
lines.push(emit(line));
if end >= atoms.len() {
let source_start = if start == 0 { paragraph.start as u32 } else { atoms[start].orig_start };
let include_end = end >= atoms.len();
let source_end = if include_end { paragraph.end as u32 } else { atoms[end].orig_start };
let stops = if geometry {
stops_for_line(&boundaries, &mut b_cursor, line, source_start, source_end, include_end)
} else {
Vec::new()
};
lines.push(BrokenLine { text: emit(line), source: (source_start, source_end), stops });
if include_end {
break;
}
start = end;
@ -247,9 +337,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) = clean(paragraph);
let (clean, open, origin) = clean(paragraph.content);
let (mut column, mut from, mut shown) = (0, 0, 0);
for atom in atoms(&clean, &open) {
for atom in atoms(&clean, &open, &origin, paragraph.content, paragraph.start) {
if atom.open {
widest = widest.max(shown - from);
(from, shown) = (column, column);
@ -264,13 +354,13 @@ fn longest_segment(text: &str) -> u32 {
widest
}
fn lines_for(text: &str, wrap: bool, max_lines: Option<u32>, room: Avail) -> Vec<CellText> {
fn lines_for(text: &str, wrap: bool, max_lines: Option<u32>, room: Avail, geometry: bool) -> Vec<BrokenLine> {
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)
break_lines(text, wrap, max_lines, cols, geometry)
}
/// The shipped Cells engine: text by cluster width and UAX #14, controls at fixed cell sizes.
@ -287,11 +377,11 @@ impl Measure for CellMeasure {
};
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();
let rows = lines_for(text, true, *max_lines, Avail::MaxContent, false).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)
let lines = lines_for(text, *wrap, *max_lines, room, false);
(lines.iter().map(|line| line.text.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),
@ -305,12 +395,18 @@ impl Measure for CellMeasure {
}
fn text(&mut self, request: &TextRequest, width: f32) -> TextLayout {
let lines = lines_for(request.text, request.wrap, request.max_lines, Avail::Definite(width));
let lines = lines_for(request.text, request.wrap, request.max_lines, Avail::Definite(width), request.geometry);
TextLayout {
lines: lines
.into_iter()
.enumerate()
.map(|(row, text)| TextLine { y: row as f32, height: 1.0, run: Run::Cells { text, style: CellStyle::default() } })
.map(|(row, line)| TextLine {
y: row as f32,
height: 1.0,
run: Run::Cells { text: line.text, style: CellStyle::default() },
source: line.source,
stops: line.stops,
})
.collect(),
}
}

View file

@ -1,11 +1,16 @@
//! 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 std::collections::BTreeSet;
use thing_contract::{AssetEntry, Node, NodeId, TextSource};
use thing_core::bind::Bound;
use thing_core::layout::{Avail, Constraint, Leaf, Measure, Run, TextRequest};
use thing_core::layout::{Avail, Constraint, Leaf, Measure, Run, Stop, TextRequest};
use thing_core::text::{CellMeasure, CellText};
use thing_testkit::build::count;
use thing_testkit::fixture::Fixture;
use thing_testkit::measure::FixedMeasure;
use unicode_segmentation::UnicodeSegmentation;
fn widths(s: &str) -> Vec<u8> {
CellText::new(s).clusters().map(|(_, w)| w).collect()
@ -122,7 +127,7 @@ fn leaf_measure(text: &str, wrap: bool, max_lines: Option<u32>, room: Avail) ->
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 };
let request = TextRequest { node: &node, text, style_token: "body", wrap, max_lines, geometry: false };
CellMeasure
.text(&request, width)
.lines
@ -245,12 +250,16 @@ fn fuzz_never_emits_a_control() {
}
// 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 };
let request = TextRequest { node: &node, text: &text, style_token: "body", wrap, max_lines: None, geometry: false };
for line in CellMeasure.text(&request, width).lines {
assert!(line.stops.is_empty());
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));
}
if round % 20 == 0 {
check_geometry(&text, wrap, None, width);
}
let lone = CellText::new(&text);
assert_eq!(CellText::new(lone.as_str()), lone, "{text:?}");
let _ = leaf_measure(&text, wrap, Some(3), Avail::Definite(width));
@ -258,3 +267,191 @@ fn fuzz_never_emits_a_control() {
assert!(!CellText::new(&text).as_str().chars().any(|c| c.is_control()));
}
}
fn check_geometry(text: &str, wrap: bool, max_lines: Option<u32>, width: f32) {
let node = NodeId::new("n");
let off = CellMeasure.text(&TextRequest { node: &node, text, style_token: "body", wrap, max_lines, geometry: false }, width);
let on = CellMeasure.text(&TextRequest { node: &node, text, style_token: "body", wrap, max_lines, geometry: true }, width);
assert_eq!(off.lines.len(), on.lines.len(), "{text:?} at {width}");
let boundaries: BTreeSet<u32> = text.grapheme_indices(true).map(|(i, _)| i as u32).chain(std::iter::once(text.len() as u32)).collect();
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:?}");
if idx == 0 {
assert_eq!(hi.source.0, 0, "{text:?}");
} else {
assert_eq!(hi.source.0, prev_end, "{text:?} line {idx}");
}
prev_end = hi.source.1;
let Run::Cells { text: emitted, .. } = &hi.run else { panic!() };
let max_x = emitted.width() as f32;
for s in &hi.stops {
assert!(boundaries.contains(&s.byte), "non-boundary {} in {text:?}", s.byte);
assert!(s.byte >= hi.source.0 && s.byte <= hi.source.1, "{text:?}");
assert!(s.x >= 0.0 && s.x <= max_x, "x={} > {max_x} in {text:?}", s.x);
}
for w in hi.stops.windows(2) {
assert!(w[0].byte < w[1].byte, "{text:?}");
assert!(w[0].x <= w[1].x, "{text:?}");
}
}
if max_lines.is_none() && !on.lines.is_empty() {
assert_eq!(prev_end, text.len() as u32, "{text:?}");
}
}
#[test]
fn stops_corpus() {
let f12 = Fixture::F12TextEdge.build();
let mut corpus: Vec<String> = Vec::new();
let mut stack = vec![&f12.surfaces[0].root];
while let Some(node) = stack.pop() {
match node {
Node::Text(t) => {
if let TextSource::Literal(lit) = &t.content {
corpus.push(lit.value.clone());
}
}
Node::Box(b) => stack.extend(&b.children),
_ => {}
}
}
assert_eq!(corpus.len(), 5);
corpus.extend([
"".to_string(),
" ".to_string(),
"hello world".to_string(),
"hello world".to_string(),
"one\ttwo\t\tthree\nfour\r\nfive\u{2028}six".to_string(),
"a\u{1b}b\u{85}c".to_string(),
"a\u{200b}b\u{200b}c".to_string(),
"\u{200b}abc\u{200b}".to_string(),
"\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(),
]);
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] {
for wrap in [false, true] {
for max_lines in [None, Some(2)] {
check_geometry(text, wrap, max_lines, width);
}
}
}
}
}
#[test]
fn stop_x_equals_width() {
let node = NodeId::new("n");
let cases = [
"hello",
"\u{4e2d}\u{6587}",
"e\u{301} a\u{308} o\u{302}\u{323}",
"\u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467} x",
"a\tb\tc",
"\u{4e2d}\tx",
"\t\t",
"a\u{1b}b",
];
for text in cases {
let req = TextRequest { node: &node, text, style_token: "body", wrap: false, max_lines: None, geometry: true };
let layout = CellMeasure.text(&req, 100.0);
assert_eq!(layout.lines.len(), 1, "{text:?}");
let line = &layout.lines[0];
let expected: Vec<Stop> = text
.grapheme_indices(true)
.map(|(b, _)| b)
.chain(std::iter::once(text.len()))
.map(|b| Stop { byte: b as u32, x: CellText::new(&text[..b]).width() as f32 })
.collect();
assert_eq!(line.stops, expected, "{text:?}");
}
}
#[test]
fn affinity() {
let node = NodeId::new("n");
let layout = CellMeasure.text(&TextRequest { node: &node, text: "hello world", style_token: "body", wrap: true, max_lines: None, geometry: true }, 5.0);
assert_eq!(layout.lines.len(), 2);
assert_eq!(layout.lines[0].source, (0, 6));
assert_eq!(layout.lines[0].stops, [0, 1, 2, 3, 4, 5].map(|b| Stop { byte: b, x: b as f32 }));
assert_eq!(layout.lines[1].source, (6, 11));
assert_eq!(layout.lines[1].stops, [6, 7, 8, 9, 10, 11].map(|b| Stop { byte: b, x: (b - 6) as f32 }));
let hanging = CellMeasure.text(&TextRequest { node: &node, text: "hello world", style_token: "body", wrap: true, max_lines: None, geometry: true }, 5.0);
assert_eq!(hanging.lines[0].source, (0, 8));
assert_eq!(
hanging.lines[0].stops,
[(0, 0.0), (1, 1.0), (2, 2.0), (3, 3.0), (4, 4.0), (5, 5.0), (6, 5.0), (7, 5.0)].map(|(byte, x)| Stop { byte, x })
);
assert_eq!(hanging.lines[1].source, (8, 13));
assert_eq!(hanging.lines[1].stops[0], Stop { byte: 8, x: 0.0 });
let para = CellMeasure.text(&TextRequest { node: &node, text: "a\nb", style_token: "body", wrap: true, max_lines: None, geometry: true }, 80.0);
assert_eq!(para.lines[0].source, (0, 2));
assert_eq!(para.lines[0].stops, [Stop { byte: 0, x: 0.0 }, Stop { byte: 1, x: 1.0 }, Stop { byte: 2, x: 1.0 }]);
assert_eq!(para.lines[1].source, (2, 3));
assert_eq!(para.lines[1].stops, [Stop { byte: 2, x: 0.0 }, Stop { byte: 3, x: 1.0 }]);
let crlf = CellMeasure.text(&TextRequest { node: &node, text: "a\r\nb", style_token: "body", wrap: true, max_lines: None, geometry: true }, 80.0);
assert_eq!(crlf.lines[0].source, (0, 3));
assert_eq!(crlf.lines[0].stops, [Stop { byte: 0, x: 0.0 }, Stop { byte: 1, x: 1.0 }, Stop { byte: 3, x: 1.0 }]);
assert_eq!(crlf.lines[1].source, (3, 4));
assert_eq!(crlf.lines[1].stops[0], Stop { byte: 3, x: 0.0 });
let trailing = CellMeasure.text(&TextRequest { node: &node, text: "a\n", style_token: "body", wrap: true, max_lines: None, geometry: true }, 80.0);
assert_eq!(trailing.lines.len(), 1);
assert_eq!(trailing.lines[0].source, (0, 2));
assert_eq!(trailing.lines[0].stops, [Stop { byte: 0, x: 0.0 }, Stop { byte: 1, x: 1.0 }, Stop { byte: 2, x: 1.0 }]);
}
#[test]
fn sanitized_source() {
let node = NodeId::new("n");
let ctrl = CellMeasure.text(&TextRequest { node: &node, text: "a\u{1b}b", style_token: "body", wrap: false, max_lines: None, geometry: true }, 80.0);
assert_eq!(ctrl.lines[0].source, (0, 3));
assert_eq!(ctrl.lines[0].stops, [Stop { byte: 0, x: 0.0 }, Stop { byte: 1, x: 1.0 }, Stop { byte: 2, x: 2.0 }, Stop { byte: 3, x: 3.0 }]);
let c1 = CellMeasure.text(&TextRequest { node: &node, text: "\u{85}x", style_token: "body", wrap: false, max_lines: None, geometry: true }, 80.0);
assert_eq!(c1.lines[0].source, (0, 3));
assert_eq!(c1.lines[0].stops, [Stop { byte: 0, x: 0.0 }, Stop { byte: 2, x: 1.0 }, Stop { byte: 3, x: 2.0 }]);
let zwsp = CellMeasure.text(&TextRequest { node: &node, text: "a\u{200b}b", style_token: "body", wrap: true, max_lines: None, geometry: true }, 1.0);
assert_eq!(zwsp.lines.len(), 2);
assert_eq!(zwsp.lines[0].source, (0, 4));
assert_eq!(zwsp.lines[0].stops, [Stop { byte: 0, x: 0.0 }, Stop { byte: 1, x: 1.0 }]);
assert_eq!(zwsp.lines[1].source, (4, 5));
assert_eq!(zwsp.lines[1].stops, [Stop { byte: 4, x: 0.0 }, Stop { byte: 5, x: 1.0 }]);
let merged = CellMeasure.text(&TextRequest { node: &node, text: "\u{1f469}\u{202c}\u{1f3fd}", style_token: "body", wrap: false, max_lines: None, geometry: true }, 80.0);
assert_eq!(merged.lines[0].source, (0, 11));
assert_eq!(merged.lines[0].stops, [Stop { byte: 0, x: 0.0 }, Stop { byte: 4, x: 2.0 }, Stop { byte: 7, x: 2.0 }, Stop { byte: 11, x: 2.0 }]);
let orphan = CellMeasure.text(&TextRequest { node: &node, text: "\u{1b}\u{301}", style_token: "body", wrap: false, max_lines: None, geometry: true }, 80.0);
assert_eq!(orphan.lines[0].source, (0, 3));
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 fixed_measure_geometry() {
let node = NodeId::new("n");
let px = FixedMeasure::pixels().text(&TextRequest { node: &node, text: "abcdef", style_token: "body", wrap: true, max_lines: None, geometry: true }, 24.0);
assert_eq!(px.lines.len(), 2);
assert_eq!(px.lines[0].source, (0, 3));
assert_eq!(px.lines[0].stops, [Stop { byte: 0, x: 0.0 }, Stop { byte: 1, x: 8.0 }, Stop { byte: 2, x: 16.0 }]);
assert_eq!(px.lines[1].source, (3, 6));
assert_eq!(px.lines[1].stops, [Stop { byte: 3, x: 0.0 }, Stop { byte: 4, x: 8.0 }, Stop { byte: 5, x: 16.0 }, Stop { byte: 6, x: 24.0 }]);
let cells = FixedMeasure::cells().text(&TextRequest { node: &node, text: "abcdef", style_token: "body", wrap: true, max_lines: None, geometry: true }, 3.0);
assert_eq!(cells.lines[0].source, (0, 3));
assert_eq!(cells.lines[0].stops, [Stop { byte: 0, x: 0.0 }, Stop { byte: 1, x: 1.0 }, Stop { byte: 2, x: 2.0 }]);
assert_eq!(cells.lines[1].source, (3, 6));
assert_eq!(cells.lines[1].stops, [Stop { byte: 3, x: 0.0 }, Stop { byte: 4, x: 1.0 }, Stop { byte: 5, x: 2.0 }, Stop { byte: 6, x: 3.0 }]);
let off = FixedMeasure::pixels().text(&TextRequest { node: &node, text: "abcdef", style_token: "body", wrap: true, max_lines: None, geometry: false }, 24.0);
assert!(off.lines.iter().all(|l| l.stops.is_empty()));
}

View file

@ -3,7 +3,7 @@
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};
use thing_core::layout::{Avail, CellStyle, Constraint, FontId, Glyph, Leaf, Measure, Run, Stop, TextLayout, TextLine, TextRequest};
/// Text is 8 px wide per character and 16 px tall per line (one cell each in Cells); controls
/// have fixed sizes; an Image is its bound catalog entry's extent (0x0 when missing).
@ -45,19 +45,28 @@ impl FixedMeasure {
}
impl FixedMeasure {
/// The lines a text breaks into at `width`: the chunks `text` sizes its height for, so the
/// measure and the layout of one Text leaf agree.
fn lines(&self, request: &TextRequest, width: f32) -> Vec<String> {
/// The lines a text breaks into at `width`, with their UTF-8 byte ranges in `request.text`:
/// the chunks `text` sizes its height for, so the measure and the layout of one Text leaf agree.
fn lines(&self, request: &TextRequest, width: f32) -> Vec<(String, (u32, u32))> {
let cw = if self.cells { 1.0 } else { 8.0 };
let chars: Vec<char> = request.text.chars().collect();
let capacity = (width / cw).floor().max(1.0) as usize;
let mut lines: Vec<String> = if request.wrap {
chars.chunks(capacity).map(|chunk| chunk.iter().collect()).collect()
let mut lines: Vec<(String, (u32, u32))> = if request.wrap {
let chars: Vec<(usize, char)> = request.text.char_indices().collect();
let len = request.text.len() as u32;
chars
.chunks(capacity)
.enumerate()
.map(|(i, chunk)| {
let start = chunk[0].0 as u32;
let end = chars.get((i + 1) * capacity).map_or(len, |&(b, _)| b as u32);
(chunk.iter().map(|&(_, c)| c).collect(), (start, end))
})
.collect()
} else {
vec![request.text.to_string()]
vec![(request.text.to_string(), (0, request.text.len() as u32))]
};
if lines.is_empty() {
lines.push(String::new());
lines.push((String::new(), (0, 0)));
}
if let Some(cap) = request.max_lines {
lines.truncate(cap as usize);
@ -68,25 +77,43 @@ impl FixedMeasure {
impl Measure for FixedMeasure {
fn text(&mut self, request: &TextRequest, width: f32) -> TextLayout {
let height = if self.cells { 1.0 } else { 16.0 };
let (cw, height) = if self.cells { (1.0, 1.0) } else { (8.0, 16.0) };
let lines = self.lines(request, width);
let text_len = request.text.len() as u32;
TextLayout {
lines: lines
.into_iter()
.enumerate()
.map(|(row, line)| TextLine {
y: row as f32 * height,
height,
run: if self.cells {
Run::Cells { text: CellText::new(&line), style: CellStyle::default() }
} else {
let glyphs = line
.chars()
.map(|(row, (line, source))| {
let stops = if request.geometry {
let mut stops: Vec<Stop> = line
.char_indices()
.enumerate()
.map(|(column, c)| Glyph { id: c as u32, x: 8.0 * column as f32, y: 0.0 })
.map(|(col, (rel, _))| Stop { byte: source.0 + rel as u32, x: cw * col as f32 })
.collect();
Run::Glyphs { font: FontId(0), size: 16.0, glyphs }
},
if source.1 == text_len {
stops.push(Stop { byte: source.1, x: cw * line.chars().count() as f32 });
}
stops
} else {
Vec::new()
};
TextLine {
y: row as f32 * height,
height,
run: if self.cells {
Run::Cells { text: CellText::new(&line), style: CellStyle::default() }
} else {
let glyphs = line
.chars()
.enumerate()
.map(|(column, c)| Glyph { id: c as u32, x: 8.0 * column as f32, y: 0.0 })
.collect();
Run::Glyphs { font: FontId(0), size: 16.0, glyphs }
},
source,
stops,
}
})
.collect(),
}