Skip to main content

nativeview_layout/
measure.rs

1//! Pluggable text measurement (`TextMeasurer`), the inherited [`TextStyle`] every measurer
2//! receives, and the deterministic cross-platform `HeuristicTextMeasurer` fallback used by every
3//! layout engine.
4
5use std::sync::Arc;
6
7use nativeview_abi::{NvTextParagraphView, xxh64};
8use nativeview_store::{Length, NodeId, NodeStore, Rgba, StrSpan};
9use nativeview_tables::tables::{
10    FontStyle, OverflowWrap, TextAlign, TextDecoration, Typography, VerticalAlign, WhiteSpace,
11    WordBreak,
12};
13
14use crate::paragraph::measure::{
15    default_measure_paragraph, heuristic_hit_test_paragraph, heuristic_measure_paragraph,
16};
17
18/// Fully resolved, inherited typography of one node: everything a host needs to measure text
19/// exactly as it paints it. `F` is the family: a [`ResolvedFamily`] into the store while layout
20/// keeps it per node ([`ResolvedTextStyle`]), a borrowed `&str` when handed to a [`TextMeasurer`].
21#[derive(Debug, Clone, Copy, PartialEq)]
22pub struct TextStyle<F> {
23    pub color: Rgba,
24    /// CSS font-family list as authored; empty = the host's default UI font.
25    pub font_family: F,
26    /// Logical points, finite and `>= 0`.
27    pub font_size: f32,
28    /// CSS weight (`100..=900` once a host clamps it).
29    pub font_weight: u16,
30    pub font_style: FontStyle,
31    /// Extra advance after every character, logical points.
32    pub letter_spacing: f32,
33    /// Points = absolute; percent = unit-less multiplier × 100 of `font_size`; auto = `normal`.
34    pub line_height: Length,
35    pub white_space: WhiteSpace,
36    pub word_break: WordBreak,
37    pub overflow_wrap: OverflowWrap,
38    pub text_align: TextAlign,
39    pub text_decoration: TextDecoration,
40    pub vertical_align: VerticalAlign,
41    /// Maximum painted lines (`0` = unlimited); measured height never exceeds them.
42    pub max_lines: u32,
43}
44
45/// A node's resolved font family: where it lives in the store plus the `xxh64` of its text.
46/// Equality is by content hash alone, so an in-place `StrArena` replace that keeps the span
47/// (`"Arial"` → `"Inter"`) still compares unequal, while the same family at another span does not.
48#[derive(Debug, Clone, Copy, Default)]
49pub struct ResolvedFamily {
50    pub span: StrSpan,
51    pub hash: u64,
52}
53
54impl ResolvedFamily {
55    /// The family `span` of `store`, hashed now (`0` for the empty default family).
56    #[inline]
57    pub fn new(store: &NodeStore, span: StrSpan) -> Self {
58        let text = store.text(span);
59        Self { span, hash: if text.is_empty() { 0 } else { xxh64(text.as_bytes(), 0) } }
60    }
61}
62
63impl PartialEq for ResolvedFamily {
64    #[inline]
65    fn eq(&self, other: &Self) -> bool {
66        self.hash == other.hash
67    }
68}
69
70/// Inherited typography kept per node during a layout pass.
71pub type ResolvedTextStyle = TextStyle<ResolvedFamily>;
72
73impl<F: Default> Default for TextStyle<F> {
74    fn default() -> Self {
75        Self {
76            color: Rgba::BLACK,
77            font_family: F::default(),
78            font_size: HeuristicTextMeasurer::DEFAULT_FONT_SIZE,
79            font_weight: 400,
80            font_style: FontStyle::Normal,
81            letter_spacing: 0.0,
82            line_height: Length::AUTO,
83            white_space: WhiteSpace::Normal,
84            word_break: WordBreak::Normal,
85            overflow_wrap: OverflowWrap::Normal,
86            text_align: TextAlign::Start,
87            text_decoration: TextDecoration::EMPTY,
88            vertical_align: VerticalAlign::Baseline,
89            max_lines: 0,
90        }
91    }
92}
93
94impl<F> TextStyle<F> {
95    /// The same style with the family mapped to another representation.
96    #[inline]
97    pub fn map_family<'s, G>(&'s self, f: impl FnOnce(&'s F) -> G) -> TextStyle<G> {
98        TextStyle {
99            color: self.color,
100            font_family: f(&self.font_family),
101            font_size: self.font_size,
102            font_weight: self.font_weight,
103            font_style: self.font_style,
104            letter_spacing: self.letter_spacing,
105            line_height: self.line_height,
106            white_space: self.white_space,
107            word_break: self.word_break,
108            overflow_wrap: self.overflow_wrap,
109            text_align: self.text_align,
110            text_decoration: self.text_decoration,
111            vertical_align: self.vertical_align,
112            max_lines: self.max_lines,
113        }
114    }
115
116    /// `false` for `white-space: nowrap | pre`: lines break only at `\n`, never at `max_width`.
117    #[inline]
118    pub fn wraps(&self) -> bool {
119        !matches!(self.white_space, WhiteSpace::NoWrap | WhiteSpace::Pre)
120    }
121
122    /// The line height in points, `None` for `normal` (the font's own metrics).
123    #[inline]
124    pub fn line_height_points(&self) -> Option<f32> {
125        let lh = if self.line_height.is_percent() {
126            self.line_height.value() * self.font_size / 100.0
127        } else {
128            self.line_height.resolve(self.font_size)?
129        };
130        (lh.is_finite() && lh > 0.0).then_some(lh)
131    }
132}
133
134impl<F: PartialEq> TextStyle<F> {
135    /// `true` when both styles measure identically: every field except paint-only `color`,
136    /// floats compared by bits (so `NaN` never forces endless re-measurement).
137    #[inline]
138    pub fn measure_eq(&self, other: &Self) -> bool {
139        self.font_family == other.font_family
140            && self.font_size.to_bits() == other.font_size.to_bits()
141            && self.font_weight == other.font_weight
142            && self.font_style == other.font_style
143            && self.letter_spacing.to_bits() == other.letter_spacing.to_bits()
144            && self.line_height == other.line_height
145            && self.white_space == other.white_space
146            && self.word_break == other.word_break
147            && self.overflow_wrap == other.overflow_wrap
148            && self.vertical_align == other.vertical_align
149            && self.max_lines == other.max_lines
150    }
151
152    /// `true` when all typography fields (including paint-only `color`, `text_align`,
153    /// `text_decoration`) match bitwise.
154    #[inline]
155    pub fn style_eq(&self, other: &Self) -> bool {
156        self.measure_eq(other)
157            && self.color == other.color
158            && self.text_align == other.text_align
159            && self.text_decoration == other.text_decoration
160    }
161}
162
163impl<F: AsRef<str>> TextStyle<F> {
164    /// The measurer view of an owned-family style.
165    #[inline]
166    pub fn borrowed(&self) -> TextStyle<&str> {
167        self.map_family(AsRef::as_ref)
168    }
169}
170
171impl TextStyle<&str> {
172    /// Default typography at `font_size` (the host's default family).
173    pub fn sized(font_size: f32) -> Self {
174        Self {
175            font_size,
176            ..Self::default()
177        }
178    }
179}
180
181impl ResolvedTextStyle {
182    /// The measurer view of this style, its family read from `store`.
183    #[inline]
184    pub fn in_store<'a>(&self, store: &'a NodeStore) -> TextStyle<&'a str> {
185        self.map_family(|family| store.text(family.span))
186    }
187}
188
189/// Resolves one node's inherited [`ResolvedTextStyle`] from its parent's resolved typography and
190/// any explicit fields on `id`'s [`Typography`] row. Shared by every layout engine so invalid
191/// (`< 0` or non-finite) sizes and spacings fall back identically across Taffy and Yoga.
192#[inline]
193pub fn resolve_inherited_text(
194    store: &NodeStore,
195    id: NodeId,
196    mut parent: ResolvedTextStyle,
197) -> ResolvedTextStyle {
198    let Some(t) = store.try_row::<Typography>(id) else {
199        return parent;
200    };
201    if t.is_color_explicit() {
202        parent.color = t.color();
203    }
204    let fs = t.font_size();
205    if t.is_font_size_explicit() && fs.is_finite() && fs >= 0.0 {
206        parent.font_size = fs;
207    }
208    if t.is_font_weight_explicit() {
209        parent.font_weight = t.font_weight();
210    }
211    let lh = t.line_height();
212    // `NaN` / `inf` / negative heights are invalid CSS: keep the inherited value.
213    if t.is_line_height_explicit() && (lh.is_auto() || (lh.value().is_finite() && lh.value() >= 0.0)) {
214        parent.line_height = lh;
215    }
216    let ls = t.letter_spacing();
217    if t.is_letter_spacing_explicit() && ls.is_finite() {
218        parent.letter_spacing = ls;
219    }
220    if t.is_font_family_explicit() {
221        parent.font_family = ResolvedFamily::new(store, t.font_family_span());
222    }
223    if t.is_max_lines_explicit() {
224        parent.max_lines = t.max_lines().map_or(0, |n| u32::from(n.get()));
225    }
226    if t.is_font_style_explicit() {
227        parent.font_style = t.font_style();
228    }
229    if t.is_white_space_explicit() {
230        parent.white_space = t.white_space();
231    }
232    if t.is_word_break_explicit() {
233        parent.word_break = t.word_break();
234    }
235    if t.is_overflow_wrap_explicit() {
236        parent.overflow_wrap = t.overflow_wrap();
237    }
238    if t.is_text_align_explicit() {
239        parent.text_align = t.text_align();
240    }
241    if t.is_text_decoration_explicit() {
242        parent.text_decoration = t.text_decoration();
243    }
244    if t.is_vertical_align_explicit() {
245        parent.vertical_align = t.vertical_align();
246    }
247    parent
248}
249
250/// Pluggable text & multi-run paragraph measurement / hit-test provider used by layout engines.
251pub trait TextMeasurer: Send + Sync {
252    /// Measures single-run `text` with resolved typography under an optional `max_width`
253    /// constraint (`Some(0.0)` is a min-content probe). Returns `(width, height)` in logical
254    /// points.
255    fn measure(&self, text: &str, style: &TextStyle<&str>, max_width: Option<f32>) -> (f32, f32);
256
257    /// Measures a compiled multi-run paragraph (`NvTextParagraphView`) under optional `max_width`.
258    fn measure_paragraph(
259        &self,
260        paragraph: &NvTextParagraphView,
261        max_width: Option<f32>,
262    ) -> (f32, f32) {
263        default_measure_paragraph(self, paragraph, max_width)
264    }
265
266    /// Hit-tests content-box local `(local_x, local_y)` inside a paragraph laid out to
267    /// `box_width`, returning the hit run's owning `NodeId` (`None` on trailing whitespace/miss).
268    fn hit_test_paragraph(
269        &self,
270        paragraph: &NvTextParagraphView,
271        box_width: f32,
272        local_x: f32,
273        local_y: f32,
274    ) -> Option<NodeId> {
275        heuristic_hit_test_paragraph(paragraph, box_width, local_x, local_y)
276    }
277}
278
279/// Default deterministic text measurer matching NV's cross-platform heuristic
280/// (`font_size * 0.58 + letter_spacing` per character, `font_size * 1.35` `normal` line height),
281/// with explicit `\n` line breaks, `max_width` wrapping (none for `nowrap` / `pre`), explicit
282/// line heights, and `max_lines`.
283#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
284pub struct HeuristicTextMeasurer;
285
286impl HeuristicTextMeasurer {
287    pub const CHAR_WIDTH_FACTOR: f32 = 0.58;
288    pub const LINE_HEIGHT_FACTOR: f32 = 1.35;
289    pub const DEFAULT_FONT_SIZE: f32 = 16.0;
290}
291
292impl TextMeasurer for HeuristicTextMeasurer {
293    fn measure(&self, text: &str, style: &TextStyle<&str>, max_width: Option<f32>) -> (f32, f32) {
294        if text.is_empty() || style.font_size == 0.0 {
295            return (0.0, 0.0);
296        }
297        let fs = if style.font_size.is_finite() && style.font_size > 0.0 {
298            style.font_size
299        } else {
300            Self::DEFAULT_FONT_SIZE
301        };
302        let sized = TextStyle { font_size: fs, ..*style };
303        let char_w = (fs * Self::CHAR_WIDTH_FACTOR + style.letter_spacing).max(0.0);
304        let line_h = sized.line_height_points().unwrap_or(fs * Self::LINE_HEIGHT_FACTOR);
305        let height = |lines: f32| {
306            let lines = lines.max(1.0);
307            let capped = if style.max_lines > 0 { lines.min(style.max_lines as f32) } else { lines };
308            capped * line_h
309        };
310        let line_widths = || text.split('\n').map(|line| line.chars().count() as f32 * char_w);
311
312        match max_width.filter(|_| style.wraps()) {
313            Some(mw) if !mw.is_finite() || mw <= 0.0 => {
314                // Min-content probe (e.g. Yoga `AtMost 0` or Taffy `MinContent`).
315                (0.0, height(text.split('\n').count() as f32))
316            }
317            Some(mw) => {
318                // Allow a few-ULP float32 tolerance (~1e-5 relative/absolute) so padding+border
319                // add/sub round-trips (e.g. `(6.38_f32 + 18.0) - 18.0 = 6.3799992 < 6.3800001`)
320                // do not spuriously wrap an exact-fit single line onto two lines.
321                let wrap_eps = (mw * 1e-5).max(1e-5);
322                let (mut max_line_w, mut total_lines) = (0.0f32, 0.0f32);
323                for raw_w in line_widths() {
324                    if raw_w > mw + wrap_eps {
325                        max_line_w = max_line_w.max(mw);
326                        total_lines += ((raw_w - wrap_eps) / mw).ceil().max(1.0);
327                    } else {
328                        max_line_w = max_line_w.max(raw_w);
329                        total_lines += 1.0;
330                    }
331                }
332                (max_line_w.max(1.0).min(mw), height(total_lines))
333            }
334            None => {
335                let (max_line_w, lines) =
336                    line_widths().fold((0.0f32, 0.0f32), |(w, n), lw| (w.max(lw), n + 1.0));
337                (max_line_w.max(1.0), height(lines))
338            }
339        }
340    }
341
342    fn measure_paragraph(
343        &self,
344        paragraph: &NvTextParagraphView,
345        max_width: Option<f32>,
346    ) -> (f32, f32) {
347        heuristic_measure_paragraph(paragraph, max_width)
348    }
349
350    fn hit_test_paragraph(
351        &self,
352        paragraph: &NvTextParagraphView,
353        box_width: f32,
354        local_x: f32,
355        local_y: f32,
356    ) -> Option<NodeId> {
357        heuristic_hit_test_paragraph(paragraph, box_width, local_x, local_y)
358    }
359}
360
361impl<F> TextMeasurer for F
362where
363    F: Fn(&str, &TextStyle<&str>, Option<f32>) -> (f32, f32) + Send + Sync,
364{
365    fn measure(&self, text: &str, style: &TextStyle<&str>, max_width: Option<f32>) -> (f32, f32) {
366        (self)(text, style, max_width)
367    }
368}
369
370impl<T: TextMeasurer + ?Sized> TextMeasurer for Arc<T> {
371    fn measure(&self, text: &str, style: &TextStyle<&str>, max_width: Option<f32>) -> (f32, f32) {
372        (**self).measure(text, style, max_width)
373    }
374
375    fn measure_paragraph(
376        &self,
377        paragraph: &NvTextParagraphView,
378        max_width: Option<f32>,
379    ) -> (f32, f32) {
380        (**self).measure_paragraph(paragraph, max_width)
381    }
382
383    fn hit_test_paragraph(
384        &self,
385        paragraph: &NvTextParagraphView,
386        box_width: f32,
387        local_x: f32,
388        local_y: f32,
389    ) -> Option<NodeId> {
390        (**self).hit_test_paragraph(paragraph, box_width, local_x, local_y)
391    }
392}
393
394#[cfg(test)]
395mod tests {
396    use super::*;
397
398    fn sized(fs: f32) -> TextStyle<&'static str> {
399        TextStyle::sized(fs)
400    }
401
402    #[test]
403    fn heuristic_text_measurer_matches_single_line_and_wraps() {
404        let m = HeuristicTextMeasurer;
405
406        // Empty text produces zero size.
407        assert_eq!(m.measure("", &sized(16.0), None), (0.0, 0.0));
408
409        // Single-line unconstrained matches font_size * 0.58 and font_size * 1.35.
410        let (w, h) = m.measure("Hello World", &sized(20.0), None);
411        assert!((w - 11.0 * 20.0 * 0.58).abs() < 1e-4);
412        assert!((h - 20.0 * 1.35).abs() < 1e-4);
413
414        // Wrapping under max_width increases line count proportionally.
415        let (ww, wh) = m.measure("01234567890123456789", &sized(20.0), Some(100.0));
416        assert!((ww - 100.0).abs() < 1e-4);
417        // 20 * 11.6 = 232px -> ceil(232 / 100) = 3 lines
418        assert!((wh - 3.0 * 20.0 * 1.35).abs() < 1e-4);
419
420        // Explicit newline increases line count.
421        let (nw, nh) = m.measure("Line 1\nLine 2", &sized(16.0), None);
422        assert!((nw - 6.0 * 16.0 * 0.58).abs() < 1e-4);
423        assert!((nh - 2.0 * 16.0 * 1.35).abs() < 1e-4);
424
425        // Float32 padding+border round-trip (`(w + 18.0) - 18.0` losing 1 ULP) must not
426        // spuriously wrap a single-line string onto two lines.
427        let (single_w, single_h) = m.measure("8", &sized(11.0), None);
428        let round_trip_mw = (single_w + 18.0_f32) - 18.0_f32;
429        assert_eq!(m.measure("8", &sized(11.0), Some(round_trip_mw)).1, single_h);
430
431        // Closure blanket impl & Arc<dyn TextMeasurer> work identically.
432        let custom: Arc<dyn TextMeasurer> =
433            Arc::new(|text: &str, s: &TextStyle<&str>, _mw: Option<f32>| {
434                (text.len() as f32 * s.font_size, s.font_size * 2.0)
435            });
436        assert_eq!(custom.measure("abc", &sized(10.0), None), (30.0, 20.0));
437    }
438
439    #[test]
440    fn heuristic_text_measurer_honours_the_resolved_typography() {
441        let m = HeuristicTextMeasurer;
442        let text = "0123456789";
443        let base = m.measure(text, &sized(20.0), None);
444
445        // Letter spacing widens every character.
446        let spaced = TextStyle { letter_spacing: 2.0, ..sized(20.0) };
447        assert!((m.measure(text, &spaced, None).0 - (base.0 + 10.0 * 2.0)).abs() < 1e-3);
448
449        // `nowrap` / `pre` ignore the width constraint (also the min-content probe).
450        for ws in [WhiteSpace::NoWrap, WhiteSpace::Pre] {
451            let s = TextStyle { white_space: ws, ..sized(20.0) };
452            assert_eq!(m.measure(text, &s, Some(50.0)), base, "{ws:?}");
453            assert_eq!(m.measure(text, &s, Some(0.0)), base, "{ws:?}");
454        }
455        let pre_wrap = TextStyle { white_space: WhiteSpace::PreWrap, ..sized(20.0) };
456        assert!(m.measure(text, &pre_wrap, Some(50.0)).1 > base.1);
457
458        // Line heights: points are absolute, percent is a multiplier of the font size.
459        let points = TextStyle { line_height: Length::points(30.0), ..sized(20.0) };
460        assert_eq!(m.measure("a\nb", &points, None).1, 60.0);
461        let percent = TextStyle { line_height: Length::percent(150.0), ..sized(20.0) };
462        assert_eq!(m.measure("a\nb", &percent, None).1, 60.0);
463        assert_eq!(percent.line_height_points(), Some(30.0));
464        assert_eq!(sized(20.0).line_height_points(), None);
465
466        // `max_lines` caps wrapped and explicit lines.
467        let two = TextStyle { max_lines: 2, ..points };
468        assert_eq!(m.measure(text, &two, Some(20.0)).1, 60.0);
469        assert_eq!(m.measure("a\nb\nc\nd", &two, None).1, 60.0);
470    }
471
472    #[test]
473    fn resolution_sanitizes_line_height_and_hashes_the_family() {
474        let mut store = NodeStore::new();
475        let mut tx = store.tx();
476        let [parent, nan, negative, family] = [(); 4].map(|_| tx.create());
477        tx.edit::<Typography>(parent).line_height(Length::points(18.0)).font_family("Inter");
478        // Raw `NaN` points bits (tag `00`): no constructor produces them, a wire frame can.
479        tx.edit::<Typography>(nan)
480            .line_height(Length(f32::NAN.to_bits() & !0b11));
481        tx.edit::<Typography>(negative).line_height(Length::points(-4.0));
482        tx.edit::<Typography>(family).font_family("Arial");
483        tx.commit_into(&mut nativeview_store::ChangeSet::default());
484        let p = resolve_inherited_text(&store, parent, ResolvedTextStyle::default());
485        for child in [nan, negative] {
486            let r = resolve_inherited_text(&store, child, p);
487            assert_eq!(r.line_height, Length::points(18.0), "invalid heights inherit");
488            assert!(r.measure_eq(&r), "bitwise float equality is reflexive");
489        }
490        let inter = p.font_family;
491        assert_eq!(inter.hash, xxh64(b"Inter", 0));
492        let arial = resolve_inherited_text(&store, family, p);
493        assert!(!arial.measure_eq(&p), "same-length families differ by content");
494        assert!(arial.measure_eq(&TextStyle { color: Rgba::WHITE, ..arial }), "color is paint-only");
495        assert_eq!(ResolvedTextStyle::default().font_family.hash, 0);
496    }
497}