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
//! [`TopLayerIndex`]: the single definition of which `Overlay` roots live in the top layer.
//!
//! Computed once per commit by the layout engine that owns it, with that engine's
//! [`DisplayEnv`] (the shared effective-display cascade), and read in O(1) by Taffy, Yoga,
//! `OverlayState` (which owns the resolved paint order, topmost modal and inertness), scene
//! publication and the stacking plan, so no consumer re-derives "effectively open".
//!
//! A recompute never walks the document: it iterates the `Overlay` table's row owners, walks
//! each owner's ancestor chain (O(overlays × depth)), and sorts the hoisted roots into document
//! order by their root-first child-index paths. Child indices are computed once per recompute,
//! scanning each distinct parent on the hoisted chains once, and only when two or more roots are
//! hoisted. A commit runs it only when the `Overlay` table changed, a node with a non-`None`
//! state was removed, a hoisted owner became disconnected (`detach_child`), or a created /
//! touched / re-parented / `display` node lies on an open owner's ancestor chain
//! (reused changed-node bitset); engines also feed pseudo-state changes
//! ([`TopLayerIndex::sync_nodes`]) and invalidate on media / committed container env changes.
//! Steady-state and open/close frames allocate nothing once the scratch buffers are warm.

use nativeview_store::{ChangeSet, MAX_TREE_DEPTH, NodeId, NodeStore, NvTable, TableStorage};
use nativeview_tables::semantics::walk_top_layer_chain;
use nativeview_tables::tables::{Layout, Overlay, OverlayFlags, TopLayerState};

use crate::DisplayEnv;

/// A node's position in its parent's child list (`UNSET` = not computed this recompute).
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct ChildIndex(u32);

impl ChildIndex {
    const UNSET: Self = Self(u32::MAX);
}

#[derive(Debug, Clone, Copy)]
struct Candidate {
    id: NodeId,
    /// Root-first ancestor chain (root .. id) in `chains` / `positions`.
    chain_start: u32,
    chain_len: u32,
}

/// Dense per-node [`TopLayerState`] plus the hoisted overlay roots in document (= back-to-front
/// paint) order, relative to one layout root (`NodeId::ROOT` unless an engine lays out a subtree).
#[derive(Debug)]
pub struct TopLayerIndex {
    root: NodeId,
    /// Per `NodeId::index()` state (`#[repr(u8)]`: published zero-copy in `NvSceneView`). Valid
    /// for the full id in `owners`; a reused slot reads `None` through [`Self::state`].
    states: Vec<TopLayerState>,
    /// Full id owning each non-`None` slot (generation-safe state lookups).
    owners: Vec<NodeId>,
    /// Every node whose state is not [`TopLayerState::None`].
    marked: Vec<NodeId>,
    hoisted: Vec<NodeId>,
    /// Full ids whose state changed in the last recompute (removed ids included).
    transitions: Vec<NodeId>,
    generation: u64,
    recompute_count: u64,
    needs_rebuild: bool,
    /// Reused bitset over `NodeId::index()` (changed nodes, recompute membership, chain nodes).
    bits: Vec<u64>,
    bit_ids: Vec<NodeId>,
    next: Vec<(NodeId, TopLayerState)>,
    chains: Vec<NodeId>,
    /// Child index of each `chains` entry within its parent (root: 0).
    positions: Vec<ChildIndex>,
    /// Dense child index by `NodeId::index()` during one recompute (`ChildIndex::UNSET` = unset).
    child_index: Vec<ChildIndex>,
    candidates: Vec<Candidate>,
}

impl Default for TopLayerIndex {
    fn default() -> Self {
        Self::new()
    }
}

impl TopLayerIndex {
    /// An empty index rooted at `NodeId::ROOT` that rebuilds on its first sync / refresh.
    pub const fn new() -> Self {
        Self {
            root: NodeId::ROOT,
            states: Vec::new(),
            owners: Vec::new(),
            marked: Vec::new(),
            hoisted: Vec::new(),
            transitions: Vec::new(),
            generation: 0,
            recompute_count: 0,
            needs_rebuild: true,
            bits: Vec::new(),
            bit_ids: Vec::new(),
            next: Vec::new(),
            chains: Vec::new(),
            positions: Vec::new(),
            child_index: Vec::new(),
            candidates: Vec::new(),
        }
    }

    /// Per-node state column indexed by `NodeId::index()`. After every [`Self::sync`] /
    /// [`Self::refresh`] it covers every store slot (`len() >= store.capacity()`); the runtime
    /// publishes it zero-copy as the `top_layer_states` scene fact. A slot reused by a newer node
    /// is corrected at the next commit.
    #[inline]
    pub fn states(&self) -> &[TopLayerState] {
        &self.states
    }

    /// Generation-safe state of `id` (`None` for a stale id whose slot was reused).
    #[inline]
    pub fn state(&self, id: NodeId) -> TopLayerState {
        let i = id.index();
        match self.owners.get(i) {
            Some(&owner) if owner == id => self.states[i],
            _ => TopLayerState::None,
        }
    }

    /// Whether `id` is an effectively-open overlay root hoisted into the top layer.
    #[inline]
    pub fn is_hoisted(&self, id: NodeId) -> bool {
        self.state(id) == TopLayerState::Hoisted
    }

    /// Hoisted overlay roots in document order (back-to-front paint order).
    #[inline]
    pub fn hoisted(&self) -> &[NodeId] {
        &self.hoisted
    }

    /// Bumped only when [`Self::hoisted`] changes (membership or order).
    #[inline]
    pub fn generation(&self) -> u64 {
        self.generation
    }

    /// Number of recomputes so far (regression guard against per-frame rescans).
    #[inline]
    pub fn recompute_count(&self) -> u64 {
        self.recompute_count
    }

    /// Full ids whose state changed in the most recent recompute.
    #[inline]
    pub fn transitions(&self) -> &[NodeId] {
        &self.transitions
    }

    /// The layout root hoisting is relative to.
    #[inline]
    pub fn root(&self) -> NodeId {
        self.root
    }

    /// Forces a full recompute on the next [`Self::sync`] / [`Self::sync_nodes`] /
    /// [`Self::refresh`] (engine reset, media or committed container environment changed).
    #[inline]
    pub fn invalidate(&mut self) {
        self.needs_rebuild = true;
    }

    /// Drops every state (engine reset); the next sync / refresh rebuilds.
    pub fn clear(&mut self) {
        for &id in &self.marked {
            let i = id.index();
            self.states[i] = TopLayerState::None;
            self.owners[i] = NodeId::NULL;
        }
        self.marked.clear();
        if !self.hoisted.is_empty() {
            self.generation = self.generation.wrapping_add(1);
        }
        self.hoisted.clear();
        self.transitions.clear();
        self.needs_rebuild = true;
    }

    /// Rebuilds when the root changed or a rebuild is pending. Returns `true` when
    /// [`Self::hoisted`] changed.
    pub fn refresh(&mut self, store: &NodeStore, root: NodeId, env: &DisplayEnv<'_>) -> bool {
        if root != self.root {
            self.root = root;
            self.needs_rebuild = true;
        }
        self.transitions.clear();
        let changed = self.needs_rebuild && self.recompute(store, env);
        self.cover_capacity(store.capacity());
        changed
    }

    /// Applies one committed `ChangeSet`, recomputing only when it can change a state. Returns
    /// `true` when [`Self::hoisted`] changed.
    pub fn sync(&mut self, store: &NodeStore, changes: &ChangeSet, env: &DisplayEnv<'_>) -> bool {
        self.transitions.clear();
        let changed =
            (self.needs_rebuild || self.affected_by(store, changes)) && self.recompute(store, env);
        self.cover_capacity(store.capacity());
        changed
    }

    /// Grows `states` / `owners` with `None` to cover `capacity` slots (allocates only when the
    /// store grew), so the published column never under-covers the store.
    #[inline]
    fn cover_capacity(&mut self, capacity: usize) {
        if self.states.len() < capacity {
            self.states.resize(capacity, TopLayerState::None);
            self.owners.resize(capacity, NodeId::NULL);
        }
    }

    /// Applies a pseudo-state change of `nodes` (`StateRules` may patch their `display`).
    /// Returns `true` when [`Self::hoisted`] changed.
    pub fn sync_nodes(
        &mut self,
        store: &NodeStore,
        nodes: &[NodeId],
        env: &DisplayEnv<'_>,
    ) -> bool {
        self.transitions.clear();
        if !self.needs_rebuild {
            if !has_overlay_rows(store) && self.marked.is_empty() {
                return false;
            }
            self.ensure_bits(store.capacity());
            for &id in nodes {
                self.set_bit(id);
            }
            let hit = self.any_owner_affected(store);
            self.clear_bits();
            if !hit {
                return false;
            }
        }
        self.recompute(store, env)
    }

    fn affected_by(&mut self, store: &NodeStore, changes: &ChangeSet) -> bool {
        if !has_overlay_rows(store) {
            return !self.marked.is_empty();
        }
        if changes.table(Overlay::slot()).is_some()
            || changes
                .removed
                .iter()
                .any(|&id| self.state(id) != TopLayerState::None)
        {
            return true;
        }
        let display_bit = 1u32 << Layout::DISPLAY.word();
        self.ensure_bits(store.capacity());
        for (slot, bit) in [(Layout::slot(), display_bit)] {
            if let Some(td) = changes.table(slot) {
                for (&id, &m) in td.nodes.iter().zip(&td.masks) {
                    if m & bit != 0 {
                        self.set_bit(id);
                    }
                }
                for &id in &td.detached {
                    self.set_bit(id);
                }
            }
        }
        // `touched` carries detached / re-parented children and table attaches that turn a node
        // into a paragraph root (`is_inline_context_root`); `children` carries new parents.
        for &id in changes
            .created
            .iter()
            .chain(&changes.children)
            .chain(&changes.touched)
        {
            self.set_bit(id);
        }
        let hit = self.any_owner_affected(store);
        self.clear_bits();
        hit
    }

    /// Whether any open (or hoisted) overlay owner or one of its ancestors carries a changed-node
    /// bit, or a hoisted owner's chain no longer reaches the root (detached without a parent
    /// change). Closed owners are skipped: their `Hidden` state never depends on ancestors and
    /// their own `OPEN` flip arrives as an `Overlay` table change.
    fn any_owner_affected(&self, store: &NodeStore) -> bool {
        let Some(TableStorage {
            owners, row_count, ..
        }) = store.table_storage(Overlay::slot())
        else {
            return false;
        };
        for &oid in owners.iter().take(row_count) {
            if oid.is_null() || !store.is_live(oid) {
                continue;
            }
            let hoisted = self.is_hoisted(oid);
            if !hoisted
                && store
                    .try_row::<Overlay>(oid)
                    .is_none_or(|ov| !ov.options().contains(OverlayFlags::OPEN))
            {
                continue;
            }
            let mut cur = oid;
            let mut connected = false;
            for _ in 0..MAX_TREE_DEPTH {
                if self.has_bit(cur) {
                    return true;
                }
                if cur == self.root {
                    connected = true;
                    break;
                }
                match store.parent(cur) {
                    Some(p) if p != cur => cur = p,
                    _ => break,
                }
            }
            if !connected && hoisted {
                return true;
            }
        }
        false
    }

    fn recompute(&mut self, store: &NodeStore, env: &DisplayEnv<'_>) -> bool {
        self.needs_rebuild = false;
        self.recompute_count = self.recompute_count.wrapping_add(1);
        self.next.clear();
        self.chains.clear();
        self.candidates.clear();
        if let Some(TableStorage {
            owners, row_count, ..
        }) = store.table_storage(Overlay::slot())
        {
            for &oid in owners.iter().take(row_count) {
                if oid.is_null() || !store.is_live(oid) {
                    continue;
                }
                let Some(ov) = store.try_row::<Overlay>(oid) else {
                    continue;
                };
                if !ov.options().contains(OverlayFlags::OPEN) {
                    self.next.push((oid, TopLayerState::Hidden));
                } else if let Some((chain_start, chain_len)) = self.hoist_chain(store, env, oid) {
                    self.candidates.push(Candidate {
                        id: oid,
                        chain_start,
                        chain_len,
                    });
                }
            }
        }
        if self.candidates.len() > 1 {
            self.compute_positions(store);
            let positions = &self.positions;
            let path = |c: &Candidate| {
                &positions[c.chain_start as usize..(c.chain_start + c.chain_len) as usize]
            };
            self.candidates
                .sort_unstable_by(|a, b| path(a).cmp(path(b)));
        }
        let hoisted_changed = self.hoisted.len() != self.candidates.len()
            || self
                .hoisted
                .iter()
                .zip(&self.candidates)
                .any(|(&h, c)| h != c.id);
        self.hoisted.clear();
        for c in &self.candidates {
            self.hoisted.push(c.id);
            self.next.push((c.id, TopLayerState::Hoisted));
        }
        if hoisted_changed {
            self.generation = self.generation.wrapping_add(1);
        }
        self.apply_next_states(store.capacity());
        hoisted_changed
    }

    /// Writes `next` into `states` / `owners` / `marked`, recording every full id whose state
    /// changed (a reused slot reports both the old and the new id).
    fn apply_next_states(&mut self, capacity: usize) {
        self.ensure_bits(capacity);
        let need = self
            .next
            .iter()
            .map(|&(id, _)| id.index() + 1)
            .max()
            .unwrap_or(0)
            .max(capacity);
        if self.states.len() < need {
            self.states.resize(need, TopLayerState::None);
            self.owners.resize(need, NodeId::NULL);
        }
        for i in 0..self.next.len() {
            let (id, s) = self.next[i];
            if self.state(id) != s {
                self.transitions.push(id);
            }
            let idx = id.index();
            self.states[idx] = s;
            self.owners[idx] = id;
            self.set_bit(id);
        }
        for i in 0..self.marked.len() {
            let id = self.marked[i];
            let idx = id.index();
            if self.has_bit(id) && self.owners[idx] == id {
                continue;
            }
            self.transitions.push(id);
            if !self.has_bit(id) {
                self.states[idx] = TopLayerState::None;
                self.owners[idx] = NodeId::NULL;
            }
        }
        self.clear_bits();
        self.marked.clear();
        for &(id, _) in &self.next {
            self.marked.push(id);
        }
    }

    /// Appends `id`'s root-first ancestor chain to `chains` when `id` is a top-layer root of
    /// `root` under `env` (`nativeview_tables::semantics::walk_top_layer_chain`, the single predicate
    /// focus, semantic queries and accessibility share).
    fn hoist_chain(
        &mut self,
        store: &NodeStore,
        env: &DisplayEnv<'_>,
        id: NodeId,
    ) -> Option<(u32, u32)> {
        let start = self.chains.len();
        self.chains.push(id);
        let chains = &mut self.chains;
        if walk_top_layer_chain(store, env, self.root, id, |p| chains.push(p)) {
            self.chains[start..].reverse();
            Some((start as u32, (self.chains.len() - start) as u32))
        } else {
            self.chains.truncate(start);
            None
        }
    }

    /// Fills `positions` (each chain entry's index within its parent), scanning every distinct
    /// parent on the hoisted chains once: O(Σ children of those parents) per recompute however
    /// many roots share one wide parent.
    fn compute_positions(&mut self, store: &NodeStore) {
        let cap = store.capacity();
        if self.child_index.len() < cap {
            self.child_index.resize(cap, ChildIndex::UNSET);
        }
        self.ensure_bits(cap);
        for i in 0..self.chains.len() {
            let id = self.chains[i];
            self.set_bit(id);
        }
        self.positions.clear();
        for i in 0..self.chains.len() {
            let id = self.chains[i];
            let Some(parent) = store.parent(id).filter(|_| id != self.root) else {
                self.positions.push(ChildIndex(0));
                continue;
            };
            if self.child_index[id.index()] == ChildIndex::UNSET {
                for (pos, &child) in store.children(parent).iter().enumerate() {
                    if self.has_bit(child) {
                        self.child_index[child.index()] = ChildIndex(pos as u32);
                    }
                }
            }
            let pos = self.child_index[id.index()];
            debug_assert!(
                pos != ChildIndex::UNSET,
                "a hoisted chain node must be its parent's child"
            );
            self.positions.push(pos);
        }
        for i in 0..self.bit_ids.len() {
            let idx = self.bit_ids[i].index();
            self.child_index[idx] = ChildIndex::UNSET;
        }
        self.clear_bits();
    }

    fn ensure_bits(&mut self, capacity: usize) {
        let words = capacity.div_ceil(64);
        if self.bits.len() < words {
            self.bits.resize(words, 0);
        }
    }

    #[inline]
    fn set_bit(&mut self, id: NodeId) {
        let i = id.index();
        if let Some(w) = self.bits.get_mut(i / 64) {
            let m = 1u64 << (i % 64);
            if *w & m == 0 {
                *w |= m;
                self.bit_ids.push(id);
            }
        }
    }

    #[inline]
    fn has_bit(&self, id: NodeId) -> bool {
        let i = id.index();
        self.bits
            .get(i / 64)
            .is_some_and(|w| w & (1u64 << (i % 64)) != 0)
    }

    fn clear_bits(&mut self) {
        for &id in &self.bit_ids {
            let i = id.index();
            if let Some(w) = self.bits.get_mut(i / 64) {
                *w &= !(1u64 << (i % 64));
            }
        }
        self.bit_ids.clear();
    }
}

#[inline]
fn has_overlay_rows(store: &NodeStore) -> bool {
    store
        .table_storage(Overlay::slot())
        .is_some_and(|s| s.row_count > 0)
}

pub(crate) mod display;

#[cfg(test)]
mod tests;