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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
//! Isolated dry-run scratch (`DryRunScratch`) for [`super::TaffyStoreLayout::measure_root`].
//!
//! Keeps dry-run Taffy caches, root-level result memoization, and fallback inheritance buffers
//! completely disjoint from committed layout state so `measure_root` never mutates committed
//! caches, boxes, rects, hoisted lists, `inherit_dirty`, or `layout_dirty`.

use std::cell::RefCell;
use std::sync::Arc;

use nativeview_engine::ext::slot_registry::SlotRegistry;
use nativeview_store::{NodeId, NodeStore};
use nativeview_tables::media::MediaEnv;
use nativeview_tables::tables::{Direction as NvDirection, Layout as NvLayout, Responsive};
use taffy::LayoutPartialTree;
use taffy::geometry::{Line, Size};
use taffy::style::AvailableSpace;
use taffy::tree::{Cache, LayoutInput, RequestedAxis, RunMode, SizingMode};

use crate::{
    LeafMeasureHook, ParagraphStore, ResolvedTextStyle, SizeConstraints, SurfaceMeasure,
    TextMeasurer, TopLayerIndex, resolve_inherited_text,
};

use super::container::scope::{ActiveContainer, ContainerRecord, GenSlots};
use super::contents::BoxChildren;
use super::layout_view::{LayoutView, tid_from_nv};
use super::responsive::{MediaBreakpoints, RespMemo, RespMemoSlot, SyncOnlyMut};
use super::responsive::sync::NodeStyleFlags;
use super::responsive::text::{
    MeasureParagraphs, node_has_own_responsive_typo, paragraph_has_inline_responsive_typo,
};

const DRY_ROOT_CACHE_SLOTS: usize = 16;

/// Borrowed resolved-inheritance state a dry run lays out against: the committed engine's when
/// it is current, else the dry run's own.
#[derive(Clone, Copy)]
pub(super) struct InheritView<'a> {
    pub(super) resolved_rtl: &'a [bool],
    pub(super) resolved_text: &'a [ResolvedTextStyle],
    pub(super) paragraphs: &'a ParagraphStore,
    pub(super) box_children: &'a BoxChildren,
    pub(super) top_layer: &'a TopLayerIndex,
    pub(super) responsive_node_count: u32,
    pub(super) container_node_count: u32,
    pub(super) media_signature: u64,
    pub(super) subtree_has_responsive: &'a [bool],
    pub(super) has_responsive_typo: &'a [bool],
    pub(super) style_flags: &'a [NodeStyleFlags],
    pub(super) resp_memo_slot: &'a [RespMemoSlot],
    pub(super) resp_memo_len: usize,
}

#[derive(Clone, Copy, PartialEq, Eq)]
struct DryMeasureKey {
    root: NodeId,
    ideal: bool,
    min_w: u32,
    min_h: u32,
    max_w: u32,
    max_h: u32,
    media_hash: u64,
}

impl DryMeasureKey {
    #[inline]
    fn new(root: NodeId, c: SizeConstraints, ideal: bool, media_hash: u64) -> Self {
        Self {
            root,
            ideal,
            min_w: if ideal { 0 } else { c.min_w.to_bits() },
            min_h: if ideal { 0 } else { c.min_h.to_bits() },
            max_w: if ideal { 0 } else { c.max_w.to_bits() },
            max_h: if ideal { 0 } else { c.max_h.to_bits() },
            media_hash,
        }
    }
}

#[inline]
pub(super) fn valid_size_constraints(c: SizeConstraints) -> bool {
    c.min_w.is_finite()
        && c.min_w >= 0.0
        && c.min_h.is_finite()
        && c.min_h >= 0.0
        && !c.max_w.is_nan()
        && c.max_w >= c.min_w
        && !c.max_h.is_nan()
        && c.max_h >= c.min_h
}

#[derive(Default)]
pub(super) struct DryRunScratch {
    caches: Vec<Cache>,
    cache_gen: Vec<u64>,
    pass_gen: u64,
    store_rev: Option<(u64, u64)>,
    root_results: [Option<(DryMeasureKey, SurfaceMeasure)>; DRY_ROOT_CACHE_SLOTS],
    root_next_slot: usize,
    resolved_rtl: Vec<bool>,
    resolved_text: Vec<ResolvedTextStyle>,
    paragraphs: ParagraphStore,
    box_children: BoxChildren,
    top_layer: TopLayerIndex,
    inherit_stack: Vec<(NodeId, bool, ResolvedTextStyle)>,
    cached_env_hash: Vec<u64>,
    container_records: GenSlots<ContainerRecord>,
    media_breakpoints: MediaBreakpoints,
    subtree_has_responsive: Vec<bool>,
    has_responsive_typo: Vec<bool>,
    style_flags: Vec<NodeStyleFlags>,
    resp_order: Vec<NodeId>,
    responsive_node_count: u32,
    container_node_count: u32,
    measure_paragraphs: MeasureParagraphs,
    resp_memo_slot: Vec<RespMemoSlot>,
    resp_memo: SyncOnlyMut<Vec<RefCell<RespMemo>>>,
    resp_memo_len: usize,
    resp_pass_gen: u64,
}

impl DryRunScratch {
    pub(super) fn invalidate(&mut self) {
        self.root_results = [None; DRY_ROOT_CACHE_SLOTS];
        self.root_next_slot = 0;
    }

    pub(super) fn reset(&mut self) {
        self.invalidate();
        self.caches.clear();
        self.cache_gen.clear();
        self.pass_gen = 0;
        self.store_rev = None;
        self.resolved_rtl.clear();
        self.resolved_text.clear();
        self.paragraphs.reset();
        self.box_children.reset();
        self.top_layer.clear();
        self.inherit_stack.clear();
        self.cached_env_hash.clear();
        self.container_records.release();
        self.subtree_has_responsive.clear();
        self.has_responsive_typo.clear();
        self.style_flags.clear();
        self.resp_order.clear();
        self.responsive_node_count = 0;
        self.container_node_count = 0;
        self.measure_paragraphs.reset();
        self.resp_memo_slot.clear();
        self.resp_memo.get_mut().clear();
        self.resp_memo_len = 0;
        self.resp_pass_gen = 0;
    }

    #[inline]
    fn next_pass_gen(&mut self) -> u64 {
        self.pass_gen = self.pass_gen.wrapping_add(1);
        if self.pass_gen == 0 {
            self.cache_gen.fill(0);
            self.pass_gen = 1;
        }
        self.pass_gen
    }

    fn ensure_caches(&mut self, cap: usize) {
        if self.caches.len() < cap {
            self.caches.resize_with(cap, Cache::new);
            self.cache_gen.resize(cap, 0);
        }
    }

    fn populate_inheritance(&mut self, store: &NodeStore, root: NodeId, media_env: &MediaEnv) {
        let cap = store.capacity();
        if self.resolved_rtl.len() < cap {
            self.resolved_rtl.resize(cap, false);
            self.resolved_text.resize(cap, ResolvedTextStyle::default());
            self.style_flags.resize(cap, NodeStyleFlags::empty());
        }
        self.style_flags[..cap].fill(NodeStyleFlags::empty());
        self.paragraphs.reset();
        self.box_children.ensure_len(cap);
        self.top_layer.invalidate();
        // Dry runs resolve `@media` (no committed `@container` env, no pseudo-state).
        let env = crate::DisplayEnv {
            media: Some(media_env),
            ..Default::default()
        };
        let _ = self.top_layer.refresh(store, root, &env);
        self.responsive_node_count = 0;
        self.container_node_count = 0;
        self.resp_order.clear();
        self.inherit_stack.clear();
        self.inherit_stack
            .push((root, false, ResolvedTextStyle::default()));
        while let Some((id, parent_rtl, parent_text)) = self.inherit_stack.pop() {
            if !store.is_live(id) || store.is_inline(id) {
                continue;
            }
            let idx = id.index();
            let flags = NodeStyleFlags::of(store, id);
            self.style_flags[idx] = flags;
            self.responsive_node_count += u32::from(flags.contains(NodeStyleFlags::RESPONSIVE));
            self.container_node_count += u32::from(flags.contains(NodeStyleFlags::CONTAINER));
            self.resp_order.push(id);
            let rtl = if let Some(l) = store.try_row::<NvLayout>(id) {
                match l.direction() {
                    NvDirection::Inherit => parent_rtl,
                    NvDirection::Ltr => false,
                    NvDirection::Rtl => true,
                }
            } else {
                parent_rtl
            };
            let text = resolve_inherited_text(store, id, parent_text);
            self.resolved_rtl[idx] = rtl;
            self.resolved_text[idx] = text;
            if store.is_inline_context_root(id) {
                if paragraph_has_inline_responsive_typo(store, id) && !store.has::<Responsive>(id) {
                    self.responsive_node_count += 1;
                }
                let _ = self.paragraphs.sync_inherited_paragraph(
                    store,
                    id,
                    parent_text,
                    parent_rtl,
                    None,
                    None,
                );
                self.box_children.release(idx);
                continue;
            }
            if id != root && env.is_display_contents(store, id) {
                self.box_children.release(idx);
            } else {
                // Hoisted top-layer roots never join a dry-run box list, so floating
                // dialogs/popovers never inflate intrinsic surface sizing.
                self.box_children
                    .rebuild(store, &self.top_layer, id, &[], &env);
            }
            for &child in store.children(id).iter().rev() {
                self.inherit_stack.push((child, rtl, text));
            }
        }
        self.resp_memo_len = 0;
        if self.responsive_node_count > 0 {
            if self.subtree_has_responsive.len() < cap {
                self.subtree_has_responsive.resize(cap, false);
                self.has_responsive_typo.resize(cap, false);
            }
            if self.resp_memo_slot.len() < cap {
                self.resp_memo_slot.resize(cap, RespMemoSlot::NONE);
            }
            self.resp_memo_slot[..cap].fill(RespMemoSlot::NONE);
            self.subtree_has_responsive[..cap].fill(false);
            self.has_responsive_typo[..cap].fill(false);
            for &id in &self.resp_order {
                let idx = id.index();
                if store.has::<Responsive>(id) {
                    let slot = self.resp_memo_len;
                    self.resp_memo_len += 1;
                    self.resp_memo_slot[idx] = RespMemoSlot::new(slot);
                }
                let parent_typo = store.parent(id).is_some_and(|p| {
                    self.has_responsive_typo
                        .get(p.index())
                        .copied()
                        .unwrap_or(false)
                });
                let own_typo = if store.is_inline_context_root(id) {
                    paragraph_has_inline_responsive_typo(store, id)
                } else {
                    node_has_own_responsive_typo(store, id)
                };
                if parent_typo || own_typo {
                    self.has_responsive_typo[idx] = true;
                }
            }
            for &id in self.resp_order.iter().rev() {
                let idx = id.index();
                let mut any = store.has::<Responsive>(id) || self.has_responsive_typo[idx];
                if !any && !store.is_inline_context_root(id) {
                    for &c in store.children(id) {
                        if self
                            .subtree_has_responsive
                            .get(c.index())
                            .copied()
                            .unwrap_or(false)
                        {
                            any = true;
                            break;
                        }
                    }
                }
                self.subtree_has_responsive[idx] = any;
            }
        }
    }

    #[allow(clippy::too_many_arguments)]
    pub(super) fn measure_root(
        &mut self,
        store: &NodeStore,
        root: NodeId,
        constraints: SizeConstraints,
        ideal: bool,
        media_env: MediaEnv,
        committed_inherit: Option<InheritView<'_>>,
        measurer: &dyn TextMeasurer,
        measure_hooks: &SlotRegistry<Arc<dyn LeafMeasureHook>>,
    ) -> SurfaceMeasure {
        let empty = SurfaceMeasure {
            width: 0.0,
            height: 0.0,
            first_baseline: f32::NAN,
            last_baseline: f32::NAN,
        };
        if !store.is_live(root) || !valid_size_constraints(constraints) {
            return empty;
        }
        let rev = (store.instance_id(), store.frame());
        if self.store_rev != Some(rev) {
            self.invalidate();
            self.store_rev = Some(rev);
            // Once per store revision and before any signature reads it: rules only change with
            // the store.
            self.media_breakpoints.rebuild(store);
        }
        let signature = match committed_inherit {
            Some(c) => c.media_signature,
            None => self.media_breakpoints.signature(&media_env),
        };
        let key = DryMeasureKey::new(root, constraints, ideal, signature);
        if let Some((_, hit)) = self.root_results.iter().flatten().find(|(k, _)| *k == key) {
            return *hit;
        }

        let cap = store.capacity();
        self.ensure_caches(cap);
        if committed_inherit.is_none() {
            self.populate_inheritance(store, root, &media_env);
        }
        let pass_gen = self.next_pass_gen();
        let inherit = committed_inherit.unwrap_or(InheritView {
            resolved_rtl: &self.resolved_rtl,
            resolved_text: &self.resolved_text,
            paragraphs: &self.paragraphs,
            box_children: &self.box_children,
            top_layer: &self.top_layer,
            responsive_node_count: self.responsive_node_count,
            container_node_count: self.container_node_count,
            media_signature: signature,
            subtree_has_responsive: &self.subtree_has_responsive,
            has_responsive_typo: &self.has_responsive_typo,
            style_flags: &self.style_flags,
            resp_memo_slot: &self.resp_memo_slot,
            resp_memo_len: self.resp_memo_len,
        });
        if inherit.responsive_node_count > 0 && self.cached_env_hash.len() < cap {
            self.cached_env_hash.resize(cap, 0);
        }
        if inherit.container_node_count > 0 {
            self.container_records.ensure_len(cap);
        }
        if inherit.responsive_node_count > 0 {
            self.measure_paragraphs.begin_pass(cap);
        }
        let memo_len = inherit.resp_memo_len;
        let resp_memo = self.resp_memo.get_mut();
        if resp_memo.len() < memo_len {
            resp_memo.resize_with(memo_len, || RefCell::new((0, None)));
        }
        self.resp_pass_gen = self.resp_pass_gen.wrapping_add(1);
        if self.resp_pass_gen == 0 {
            for entry in &mut resp_memo[..memo_len] {
                entry.get_mut().0 = 0;
            }
            self.resp_pass_gen = 1;
        }
        let mut view = LayoutView {
            store,
            root_index: root.index() as u32,
            root_fills_viewport: false,
            dry_run: true,
            viewport: (0.0, 0.0),
            media_env,
            media_signature: inherit.media_signature,
            responsive_node_count: inherit.responsive_node_count,
            container_node_count: inherit.container_node_count,
            resolved_rtl: inherit.resolved_rtl,
            resolved_text: inherit.resolved_text,
            subtree_has_responsive: inherit.subtree_has_responsive,
            has_responsive_typo: inherit.has_responsive_typo,
            style_flags: inherit.style_flags,
            paragraphs: inherit.paragraphs,
            caches: &mut self.caches,
            cached_env_hash: &mut self.cached_env_hash,
            container_records: &mut self.container_records,
            boundary_records: None,
            active_container: ActiveContainer::ROOT,
            measure_paragraphs: RefCell::new(&mut self.measure_paragraphs),
            resp_memo_slot: inherit.resp_memo_slot,
            resp_memo: &resp_memo[..memo_len],
            resp_pass_gen: self.resp_pass_gen,
            cache_gen: Some((&mut self.cache_gen, pass_gen)),
            boxes: &mut [],
            box_edges: None,
            hoisted: None,
            box_children: inherit.box_children,
            top_layer: inherit.top_layer,
            interaction: None,
            measurer,
            measure_hooks,
        };
        let measured = measure_root_dry_run(&mut view, root, constraints, ideal);
        if let Some((_, final_gen)) = view.cache_gen {
            self.pass_gen = final_gen;
        }
        self.root_results[self.root_next_slot] = Some((key, measured));
        self.root_next_slot = (self.root_next_slot + 1) % DRY_ROOT_CACHE_SLOTS;
        measured
    }
}

/// Pure dry-run measurement pass over `root` using `RunMode::PerformLayout` (so CSS flex/grid
/// baselines are computed) while leaving committed boxes, rects, caches, and hoisted lists
/// untouched. Re-measures at the clamped width/height whenever `0 < min < max` or an explicit
/// root size exceeds `max` so wrapped height and baselines reflect the clamped axis.
fn measure_root_dry_run(
    view: &mut LayoutView<'_>,
    root: NodeId,
    constraints: SizeConstraints,
    ideal: bool,
) -> SurfaceMeasure {
    let min_w = constraints.min_w;
    let min_h = constraints.min_h;
    let max_w = constraints.max_w.is_finite().then_some(constraints.max_w);
    let max_h = constraints.max_h.is_finite().then_some(constraints.max_h);

    let (known_dimensions, available_space, parent_size) = if ideal {
        (
            Size::NONE,
            Size {
                width: AvailableSpace::MaxContent,
                height: AvailableSpace::MaxContent,
            },
            Size::NONE,
        )
    } else {
        let axis = |min_v: f32, max_v: Option<f32>| match max_v {
            Some(m) if (m - min_v).abs() <= f32::EPSILON => {
                (Some(m), AvailableSpace::Definite(m), Some(m))
            }
            Some(m) => (None, AvailableSpace::Definite(m), Some(m)),
            None => (None, AvailableSpace::MaxContent, None),
        };
        let (kw, aw, pw) = axis(min_w, max_w);
        let (kh, ah, ph) = axis(min_h, max_h);
        (
            Size {
                width: kw,
                height: kh,
            },
            Size {
                width: aw,
                height: ah,
            },
            Size {
                width: pw,
                height: ph,
            },
        )
    };

    let make_input = |kd: Size<Option<f32>>,
                      avail: Size<AvailableSpace>,
                      ps: Size<Option<f32>>| LayoutInput {
        run_mode: RunMode::PerformLayout,
        sizing_mode: SizingMode::InherentSize,
        axis: RequestedAxis::Both,
        known_dimensions: kd,
        known_dimensions_are_definite: Size {
            width: kd.width.is_some(),
            height: kd.height.is_some(),
        },
        parent_size: ps,
        available_space: avail,
        vertical_margins_are_collapsible: Line::FALSE,
    };
    let finite_non_neg = |v: f32| if v.is_finite() && v >= 0.0 { v } else { 0.0 };
    let clamp = |v: f32, min_v: f32, max_v: Option<f32>| {
        let f = finite_non_neg(v);
        if ideal {
            f
        } else {
            max_v.map_or(f, |m| f.min(m)).max(min_v)
        }
    };

    let mut out = view.compute_child_layout(
        tid_from_nv(root),
        make_input(known_dimensions, available_space, parent_size),
    );
    if !ideal {
        let raw_w = finite_non_neg(out.size.width);
        let clamped_w = clamp(raw_w, min_w, max_w);
        let need_w =
            known_dimensions.width.is_none() && (clamped_w - raw_w).abs() > f32::EPSILON;
        let (cur_kw, cur_aw, cur_pw) = if need_w {
            view.bump_dry_cache_gen();
            let kd = Size {
                width: Some(clamped_w),
                height: known_dimensions.height,
            };
            let avail = Size {
                width: AvailableSpace::Definite(clamped_w),
                height: available_space.height,
            };
            let ps = Size {
                width: Some(clamped_w),
                height: parent_size.height,
            };
            out = view.compute_child_layout(tid_from_nv(root), make_input(kd, avail, ps));
            (
                Some(clamped_w),
                AvailableSpace::Definite(clamped_w),
                Some(clamped_w),
            )
        } else {
            (
                known_dimensions.width,
                available_space.width,
                parent_size.width,
            )
        };
        let raw_h = finite_non_neg(out.size.height);
        let clamped_h = clamp(raw_h, min_h, max_h);
        let need_h =
            known_dimensions.height.is_none() && (clamped_h - raw_h).abs() > f32::EPSILON;
        if need_h {
            view.bump_dry_cache_gen();
            let kd = Size {
                width: cur_kw,
                height: Some(clamped_h),
            };
            let avail = Size {
                width: cur_aw,
                height: AvailableSpace::Definite(clamped_h),
            };
            let ps = Size {
                width: cur_pw,
                height: Some(clamped_h),
            };
            out = view.compute_child_layout(tid_from_nv(root), make_input(kd, avail, ps));
        }
    }

    SurfaceMeasure {
        width: clamp(out.size.width, min_w, max_w),
        height: clamp(out.size.height, min_h, max_h),
        first_baseline: out
            .baselines
            .first
            .filter(|v| v.is_finite())
            .unwrap_or(f32::NAN),
        last_baseline: out
            .baselines
            .last
            .filter(|v| v.is_finite())
            .unwrap_or(f32::NAN),
    }
}