nativeview-layout 0.1.0-rc.1

Shared NodeStore layout layer: StoreLayoutEngine / TextMeasurer traits and the default direct Taffy engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
//! Multi-run paragraph view helpers and deterministic cross-platform heuristic measurement +
//! strict visual-bounds per-run hit-testing (never clamping trailing whitespace).

use nativeview_abi::{
    NodeId, NvTextParagraphView, NvTextRun, TextRunFlags, NV_LINE_HEIGHT_AUTO,
    NV_LINE_HEIGHT_PERCENT,
};
use nativeview_store::{Length, Rgba};
use nativeview_tables::tables::{
    FontStyle, OverflowWrap, TextAlign, TextDecoration, VerticalAlign, WhiteSpace, WordBreak,
};

use crate::measure::{HeuristicTextMeasurer, TextMeasurer, TextStyle};

/// Safely extracts the UTF-8 paragraph text slice from `view` (`""` if null/empty/invalid).
#[inline]
pub fn paragraph_text_str(view: &NvTextParagraphView) -> &str {
    if view.text.ptr.is_null() || view.text.len == 0 {
        return "";
    }
    // SAFETY: `NvTextParagraphView::text` is borrowed from `ParagraphStore` or `NodeStore::text_slab`
    // for the lifetime of `view` and validated at ingress.
    let bytes = unsafe { core::slice::from_raw_parts(view.text.ptr, view.text.len) };
    core::str::from_utf8(bytes).unwrap_or("")
}

/// Safely extracts the slice of [`NvTextRun`] entries from `view` (`&[]` if null/empty).
#[inline]
pub fn paragraph_runs(view: &NvTextParagraphView) -> &[NvTextRun] {
    if view.runs.is_null() || view.run_count == 0 {
        return &[];
    }
    // SAFETY: `NvTextParagraphView::runs` points to `run_count` initialized `NvTextRun` values
    // borrowed for the lifetime of `view`.
    unsafe { core::slice::from_raw_parts(view.runs, view.run_count as usize) }
}

/// Safely extracts `run`'s font family string from `view.font_families_slab` (`""` = default).
#[inline]
pub fn run_font_family<'a>(view: &'a NvTextParagraphView, run: &NvTextRun) -> &'a str {
    if view.font_families_slab.ptr.is_null() || run.font_family_len.raw() == 0 {
        return "";
    }
    let start = run.font_family_off.as_usize();
    let Some(end) = start.checked_add(run.font_family_len.as_usize()) else {
        return "";
    };
    if end > view.font_families_slab.len {
        return "";
    }
    // SAFETY: Bounds `[start..end]` checked against `font_families_slab.len` above.
    let bytes = unsafe {
        core::slice::from_raw_parts(
            view.font_families_slab.ptr.add(start),
            run.font_family_len.as_usize(),
        )
    };
    core::str::from_utf8(bytes).unwrap_or("")
}

/// Safely extracts `run`'s UTF-8 slice from `full_text` (`""` if out-of-bounds or mid-codepoint).
#[inline]
pub fn run_text_slice<'a>(full_text: &'a str, run: &NvTextRun) -> &'a str {
    let start = run.text_off.as_usize();
    let Some(end) = start.checked_add(run.text_len.as_usize()) else {
        return "";
    };
    full_text.get(start..end).unwrap_or("")
}

/// Resolves `run`'s explicit line height in logical points (`None` for `auto`/`normal`).
#[inline]
pub fn run_line_height_points(run: &NvTextRun) -> Option<f32> {
    if run.line_height_unit == NV_LINE_HEIGHT_AUTO || !run.line_height.is_finite() {
        return None;
    }
    let fs = sanitize_run_font_size(run.font_size);
    let lh = if run.line_height_unit == NV_LINE_HEIGHT_PERCENT {
        run.line_height * fs / 100.0
    } else {
        run.line_height
    };
    (lh.is_finite() && lh > 0.0).then_some(lh)
}

#[inline]
pub fn sanitize_run_font_size(font_size: f32) -> f32 {
    if font_size.is_finite() && font_size > 0.0 {
        font_size
    } else {
        HeuristicTextMeasurer::DEFAULT_FONT_SIZE
    }
}

#[inline]
pub fn paragraph_wraps(white_space: u8) -> bool {
    !matches!(
        WhiteSpace::from_word(u32::from(white_space)),
        WhiteSpace::NoWrap | WhiteSpace::Pre
    )
}

/// Reconstructs a [`TextStyle<&str>`] from a single-run [`NvTextParagraphView`].
#[inline]
pub fn single_run_text_style<'a>(
    view: &'a NvTextParagraphView,
    run: &NvTextRun,
) -> TextStyle<&'a str> {
    let line_height = match run.line_height_unit {
        NV_LINE_HEIGHT_AUTO => Length::AUTO,
        NV_LINE_HEIGHT_PERCENT => Length::percent(run.line_height),
        _ => Length::points(run.line_height),
    };
    TextStyle {
        color: Rgba(run.color),
        font_family: run_font_family(view, run),
        font_size: run.font_size,
        font_weight: run.font_weight,
        font_style: FontStyle::from_word(u32::from(run.font_style)),
        letter_spacing: run.letter_spacing,
        line_height,
        white_space: WhiteSpace::from_word(u32::from(view.white_space)),
        word_break: WordBreak::from_word(u32::from(view.word_break)),
        overflow_wrap: OverflowWrap::from_word(u32::from(view.overflow_wrap)),
        text_align: TextAlign::from_word(u32::from(view.text_align)),
        text_decoration: TextDecoration::from_bits_truncate(run.text_decoration),
        vertical_align: VerticalAlign::from_word(u32::from(run.vertical_align)),
        max_lines: view.max_lines,
    }
}

/// Default [`TextMeasurer::measure_paragraph`] bridge: delegates single-run paragraphs to
/// `measurer.measure` (preserving custom/closure/mock measurers) and uses deterministic multi-run
/// heuristic measurement for multi-run paragraphs.
pub fn default_measure_paragraph<M: TextMeasurer + ?Sized>(
    measurer: &M,
    view: &NvTextParagraphView,
    max_width: Option<f32>,
) -> (f32, f32) {
    let text = paragraph_text_str(view);
    let runs = paragraph_runs(view);
    if text.is_empty() || runs.is_empty() {
        return (0.0, 0.0);
    }
    if runs.len() == 1 {
        let style = single_run_text_style(view, &runs[0]);
        return measurer.measure(text, &style, max_width);
    }
    heuristic_measure_paragraph(view, max_width)
}

#[inline]
fn run_metrics(run: &NvTextRun) -> (f32, f32) {
    let fs = sanitize_run_font_size(run.font_size);
    if fs == 0.0 {
        return (0.0, 0.0);
    }
    let ls = if run.letter_spacing.is_finite() {
        run.letter_spacing
    } else {
        0.0
    };
    let char_w = (fs * HeuristicTextMeasurer::CHAR_WIDTH_FACTOR + ls).max(0.0);
    let line_h =
        run_line_height_points(run).unwrap_or(fs * HeuristicTextMeasurer::LINE_HEIGHT_FACTOR);
    (char_w, line_h)
}

/// Deterministic cross-platform multi-run paragraph measurement matching [`HeuristicTextMeasurer`].
pub fn heuristic_measure_paragraph(
    view: &NvTextParagraphView,
    max_width: Option<f32>,
) -> (f32, f32) {
    let text = paragraph_text_str(view);
    let runs = paragraph_runs(view);
    if text.is_empty() || runs.is_empty() {
        return (0.0, 0.0);
    }
    if runs.len() == 1 {
        let style = single_run_text_style(view, &runs[0]);
        return HeuristicTextMeasurer.measure(text, &style, max_width);
    }

    let para_wraps = paragraph_wraps(view.white_space);
    let max_lines = view.max_lines;
    let effective_mw = if para_wraps { max_width } else { None };
    if let Some(mw) = effective_mw
        && (!mw.is_finite() || mw <= 0.0)
    {
        // Min-content probe: explicit `\n` lines, max line height across each line's runs.
        let mut total_h = 0.0f32;
        let mut cur_h = 0.0f32;
        let mut lines = 0u32;
        for run in runs {
            let (_, lh) = run_metrics(run);
            let slice = run_text_slice(text, run);
            for ch in slice.chars() {
                if ch == '\n' {
                    if max_lines == 0 || lines < max_lines {
                        total_h += cur_h.max(lh);
                        lines += 1;
                    }
                    cur_h = 0.0;
                } else {
                    cur_h = cur_h.max(lh);
                }
            }
        }
        if max_lines == 0 || lines < max_lines {
            let fallback_h = runs.first().map_or(0.0, |r| run_metrics(r).1);
            total_h += if cur_h > 0.0 { cur_h } else { fallback_h };
        }
        return (0.0, total_h);
    }

    let wrap_mw = effective_mw.map(|mw| (mw, (mw * 1e-5).max(1e-5)));
    let mut max_line_w = 0.0f32;
    let mut total_h = 0.0f32;
    let mut cur_w = 0.0f32;
    let mut cur_h = 0.0f32;
    let mut lines_done = 0u32;
    let mut any_visible = false;

    for run in runs {
        let (char_w, lh) = run_metrics(run);
        if lh > 0.0 {
            any_visible = true;
        }
        let run_wraps = para_wraps && !run.run_flags.contains(TextRunFlags::NOWRAP);
        let slice = run_text_slice(text, run);
        for ch in slice.chars() {
            if ch == '\n' {
                let line_h = cur_h.max(lh);
                if max_lines == 0 || lines_done < max_lines {
                    max_line_w = max_line_w.max(cur_w);
                    total_h += line_h;
                    lines_done += 1;
                }
                cur_w = 0.0;
                cur_h = 0.0;
                continue;
            }
            if run_wraps
                && let Some((mw, eps)) = wrap_mw
                && cur_w > 0.0
                && cur_w + char_w > mw + eps
            {
                if max_lines == 0 || lines_done < max_lines {
                    max_line_w = max_line_w.max(cur_w.min(mw));
                    total_h += cur_h.max(lh);
                    lines_done += 1;
                }
                cur_w = 0.0;
                cur_h = 0.0;
            }
            cur_w += char_w;
            cur_h = cur_h.max(lh);
        }
    }

    if !any_visible {
        return (0.0, 0.0);
    }
    if max_lines == 0 || lines_done < max_lines {
        let clamped_cur = wrap_mw.map_or(cur_w, |(mw, _)| cur_w.min(mw));
        max_line_w = max_line_w.max(clamped_cur);
        let fallback_h = runs.first().map_or(0.0, |r| run_metrics(r).1);
        total_h += if cur_h > 0.0 { cur_h } else { fallback_h };
    }
    let out_w = match wrap_mw {
        Some((mw, _)) => max_line_w.max(1.0).min(mw),
        None => max_line_w.max(1.0),
    };
    (out_w, total_h)
}

/// Deterministic heuristic per-run hit-tester used when no OS/Skia shaper is attached.
///
/// Tests `(local_x, local_y)` strictly against each run's character horizontal spans on the line
/// enclosing `local_y` — returning `None` on trailing empty space (never clamping to the last run).
pub fn heuristic_hit_test_paragraph(
    view: &NvTextParagraphView,
    box_width: f32,
    local_x: f32,
    local_y: f32,
) -> Option<NodeId> {
    if !local_x.is_finite()
        || !local_y.is_finite()
        || local_x < 0.0
        || local_y < 0.0
        || !box_width.is_finite()
    {
        return None;
    }
    let text = paragraph_text_str(view);
    let runs = paragraph_runs(view);
    if text.is_empty() || runs.is_empty() {
        return None;
    }

    let para_wraps = paragraph_wraps(view.white_space);
    let wrap_mw = if para_wraps && box_width > 0.0 {
        Some((box_width, (box_width * 1e-5).max(1e-5)))
    } else {
        None
    };
    let align = TextAlign::from_word(u32::from(view.text_align));
    let max_lines = view.max_lines;

    // Two lightweight streaming passes (zero allocations):
    // Track current line segments directly on stack (up to 64 run segments per line) or stream
    // line width first when centered/right-aligned.
    let align_offset = |line_w: f32| -> f32 {
        if box_width <= 0.0 || line_w >= box_width {
            return 0.0;
        }
        match align {
            TextAlign::Center => (box_width - line_w) * 0.5,
            TextAlign::Right | TextAlign::End => box_width - line_w,
            TextAlign::Start | TextAlign::Left | TextAlign::Justify => 0.0,
        }
    };

    // Pass 1: find line ranges (line_w, line_h, y_top) and test segments on the matching line.
    // Because we avoid heap allocation, collect up to 32 inline run segments per line on the stack
    // and evaluate each line as soon as it finishes!
    const LINE_SEG_CAP: usize = 64;
    let mut segs: [(f32, f32, NodeId); LINE_SEG_CAP] = [(0.0, 0.0, NodeId::NULL); LINE_SEG_CAP];
    let mut seg_len = 0usize;
    let mut cur_x = 0.0f32;
    let mut cur_h = 0.0f32;
    let mut cur_y = 0.0f32;
    let mut lines_done = 0u32;

    let check_line = |segs: &[(f32, f32, NodeId)],
                      line_w: f32,
                      y_top: f32,
                      line_h: f32|
     -> Option<NodeId> {
        if local_y < y_top || local_y >= y_top + line_h {
            return None;
        }
        let ox = align_offset(line_w);
        for &(x0, x1, nid) in segs {
            if local_x >= ox + x0 && local_x < ox + x1 && !nid.is_null() {
                return Some(nid);
            }
        }
        None
    };

    let push_seg = |segs: &mut [(f32, f32, NodeId); LINE_SEG_CAP],
                    seg_len: &mut usize,
                    x0: f32,
                    x1: f32,
                    nid: NodeId| {
        if *seg_len > 0 && segs[*seg_len - 1].2 == nid && (segs[*seg_len - 1].1 - x0).abs() < 1e-4
        {
            segs[*seg_len - 1].1 = x1;
        } else if *seg_len < LINE_SEG_CAP {
            segs[*seg_len] = (x0, x1, nid);
            *seg_len += 1;
        }
    };

    for run in runs {
        let (char_w, lh) = run_metrics(run);
        let run_hidden = run.run_flags.contains(TextRunFlags::HIDDEN);
        let run_wraps = para_wraps && !run.run_flags.contains(TextRunFlags::NOWRAP);
        let slice = run_text_slice(text, run);
        for ch in slice.chars() {
            if ch == '\n' {
                let line_h = cur_h.max(lh);
                if max_lines == 0 || lines_done < max_lines {
                    if let Some(hit) = check_line(&segs[..seg_len], cur_x, cur_y, line_h) {
                        return Some(hit);
                    }
                    cur_y += line_h;
                    lines_done += 1;
                }
                seg_len = 0;
                cur_x = 0.0;
                cur_h = 0.0;
                continue;
            }
            if run_wraps
                && let Some((mw, eps)) = wrap_mw
                && cur_x > 0.0
                && cur_x + char_w > mw + eps
            {
                let line_h = cur_h.max(lh);
                if max_lines == 0 || lines_done < max_lines {
                    if let Some(hit) = check_line(&segs[..seg_len], cur_x, cur_y, line_h) {
                        return Some(hit);
                    }
                    cur_y += line_h;
                    lines_done += 1;
                }
                seg_len = 0;
                cur_x = 0.0;
                cur_h = 0.0;
            }
            if char_w > 0.0 {
                if !run_hidden {
                    push_seg(&mut segs, &mut seg_len, cur_x, cur_x + char_w, run.node_id);
                }
                cur_x += char_w;
            }
            cur_h = cur_h.max(lh);
        }
    }

    if (max_lines == 0 || lines_done < max_lines) && seg_len > 0 {
        let fallback_h = runs.first().map_or(0.0, |r| run_metrics(r).1);
        let line_h = if cur_h > 0.0 { cur_h } else { fallback_h };
        if let Some(hit) = check_line(&segs[..seg_len], cur_x, cur_y, line_h) {
            return Some(hit);
        }
    }
    None
}