Skip to main content

nativeview_layout/top/
mod.rs

1//! [`TopLayerIndex`]: the single definition of which `Overlay` roots live in the top layer.
2//!
3//! Computed once per commit by the layout engine that owns it, with that engine's
4//! [`DisplayEnv`] (the shared effective-display cascade), and read in O(1) by Taffy, Yoga,
5//! `OverlayState` (which owns the resolved paint order, topmost modal and inertness), scene
6//! publication and the stacking plan, so no consumer re-derives "effectively open".
7//!
8//! A recompute never walks the document: it iterates the `Overlay` table's row owners, walks
9//! each owner's ancestor chain (O(overlays × depth)), and sorts the hoisted roots into document
10//! order by their root-first child-index paths. Child indices are computed once per recompute,
11//! scanning each distinct parent on the hoisted chains once, and only when two or more roots are
12//! hoisted. A commit runs it only when the `Overlay` table changed, a node with a non-`None`
13//! state was removed, a hoisted owner became disconnected (`detach_child`), or a created /
14//! touched / re-parented / `display` node lies on an open owner's ancestor chain
15//! (reused changed-node bitset); engines also feed pseudo-state changes
16//! ([`TopLayerIndex::sync_nodes`]) and invalidate on media / committed container env changes.
17//! Steady-state and open/close frames allocate nothing once the scratch buffers are warm.
18
19use nativeview_store::{ChangeSet, MAX_TREE_DEPTH, NodeId, NodeStore, NvTable, TableStorage};
20use nativeview_tables::semantics::walk_top_layer_chain;
21use nativeview_tables::tables::{Layout, Overlay, OverlayFlags, TopLayerState};
22
23use crate::DisplayEnv;
24
25/// A node's position in its parent's child list (`UNSET` = not computed this recompute).
26#[repr(transparent)]
27#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
28struct ChildIndex(u32);
29
30impl ChildIndex {
31    const UNSET: Self = Self(u32::MAX);
32}
33
34#[derive(Debug, Clone, Copy)]
35struct Candidate {
36    id: NodeId,
37    /// Root-first ancestor chain (root .. id) in `chains` / `positions`.
38    chain_start: u32,
39    chain_len: u32,
40}
41
42/// Dense per-node [`TopLayerState`] plus the hoisted overlay roots in document (= back-to-front
43/// paint) order, relative to one layout root (`NodeId::ROOT` unless an engine lays out a subtree).
44#[derive(Debug)]
45pub struct TopLayerIndex {
46    root: NodeId,
47    /// Per `NodeId::index()` state (`#[repr(u8)]`: published zero-copy in `NvSceneView`). Valid
48    /// for the full id in `owners`; a reused slot reads `None` through [`Self::state`].
49    states: Vec<TopLayerState>,
50    /// Full id owning each non-`None` slot (generation-safe state lookups).
51    owners: Vec<NodeId>,
52    /// Every node whose state is not [`TopLayerState::None`].
53    marked: Vec<NodeId>,
54    hoisted: Vec<NodeId>,
55    /// Full ids whose state changed in the last recompute (removed ids included).
56    transitions: Vec<NodeId>,
57    generation: u64,
58    recompute_count: u64,
59    needs_rebuild: bool,
60    /// Reused bitset over `NodeId::index()` (changed nodes, recompute membership, chain nodes).
61    bits: Vec<u64>,
62    bit_ids: Vec<NodeId>,
63    next: Vec<(NodeId, TopLayerState)>,
64    chains: Vec<NodeId>,
65    /// Child index of each `chains` entry within its parent (root: 0).
66    positions: Vec<ChildIndex>,
67    /// Dense child index by `NodeId::index()` during one recompute (`ChildIndex::UNSET` = unset).
68    child_index: Vec<ChildIndex>,
69    candidates: Vec<Candidate>,
70}
71
72impl Default for TopLayerIndex {
73    fn default() -> Self {
74        Self::new()
75    }
76}
77
78impl TopLayerIndex {
79    /// An empty index rooted at `NodeId::ROOT` that rebuilds on its first sync / refresh.
80    pub const fn new() -> Self {
81        Self {
82            root: NodeId::ROOT,
83            states: Vec::new(),
84            owners: Vec::new(),
85            marked: Vec::new(),
86            hoisted: Vec::new(),
87            transitions: Vec::new(),
88            generation: 0,
89            recompute_count: 0,
90            needs_rebuild: true,
91            bits: Vec::new(),
92            bit_ids: Vec::new(),
93            next: Vec::new(),
94            chains: Vec::new(),
95            positions: Vec::new(),
96            child_index: Vec::new(),
97            candidates: Vec::new(),
98        }
99    }
100
101    /// Per-node state column indexed by `NodeId::index()`. After every [`Self::sync`] /
102    /// [`Self::refresh`] it covers every store slot (`len() >= store.capacity()`); the runtime
103    /// publishes it zero-copy as the `top_layer_states` scene fact. A slot reused by a newer node
104    /// is corrected at the next commit.
105    #[inline]
106    pub fn states(&self) -> &[TopLayerState] {
107        &self.states
108    }
109
110    /// Generation-safe state of `id` (`None` for a stale id whose slot was reused).
111    #[inline]
112    pub fn state(&self, id: NodeId) -> TopLayerState {
113        let i = id.index();
114        match self.owners.get(i) {
115            Some(&owner) if owner == id => self.states[i],
116            _ => TopLayerState::None,
117        }
118    }
119
120    /// Whether `id` is an effectively-open overlay root hoisted into the top layer.
121    #[inline]
122    pub fn is_hoisted(&self, id: NodeId) -> bool {
123        self.state(id) == TopLayerState::Hoisted
124    }
125
126    /// Hoisted overlay roots in document order (back-to-front paint order).
127    #[inline]
128    pub fn hoisted(&self) -> &[NodeId] {
129        &self.hoisted
130    }
131
132    /// Bumped only when [`Self::hoisted`] changes (membership or order).
133    #[inline]
134    pub fn generation(&self) -> u64 {
135        self.generation
136    }
137
138    /// Number of recomputes so far (regression guard against per-frame rescans).
139    #[inline]
140    pub fn recompute_count(&self) -> u64 {
141        self.recompute_count
142    }
143
144    /// Full ids whose state changed in the most recent recompute.
145    #[inline]
146    pub fn transitions(&self) -> &[NodeId] {
147        &self.transitions
148    }
149
150    /// The layout root hoisting is relative to.
151    #[inline]
152    pub fn root(&self) -> NodeId {
153        self.root
154    }
155
156    /// Forces a full recompute on the next [`Self::sync`] / [`Self::sync_nodes`] /
157    /// [`Self::refresh`] (engine reset, media or committed container environment changed).
158    #[inline]
159    pub fn invalidate(&mut self) {
160        self.needs_rebuild = true;
161    }
162
163    /// Drops every state (engine reset); the next sync / refresh rebuilds.
164    pub fn clear(&mut self) {
165        for &id in &self.marked {
166            let i = id.index();
167            self.states[i] = TopLayerState::None;
168            self.owners[i] = NodeId::NULL;
169        }
170        self.marked.clear();
171        if !self.hoisted.is_empty() {
172            self.generation = self.generation.wrapping_add(1);
173        }
174        self.hoisted.clear();
175        self.transitions.clear();
176        self.needs_rebuild = true;
177    }
178
179    /// Rebuilds when the root changed or a rebuild is pending. Returns `true` when
180    /// [`Self::hoisted`] changed.
181    pub fn refresh(&mut self, store: &NodeStore, root: NodeId, env: &DisplayEnv<'_>) -> bool {
182        if root != self.root {
183            self.root = root;
184            self.needs_rebuild = true;
185        }
186        self.transitions.clear();
187        let changed = self.needs_rebuild && self.recompute(store, env);
188        self.cover_capacity(store.capacity());
189        changed
190    }
191
192    /// Applies one committed `ChangeSet`, recomputing only when it can change a state. Returns
193    /// `true` when [`Self::hoisted`] changed.
194    pub fn sync(&mut self, store: &NodeStore, changes: &ChangeSet, env: &DisplayEnv<'_>) -> bool {
195        self.transitions.clear();
196        let changed =
197            (self.needs_rebuild || self.affected_by(store, changes)) && self.recompute(store, env);
198        self.cover_capacity(store.capacity());
199        changed
200    }
201
202    /// Grows `states` / `owners` with `None` to cover `capacity` slots (allocates only when the
203    /// store grew), so the published column never under-covers the store.
204    #[inline]
205    fn cover_capacity(&mut self, capacity: usize) {
206        if self.states.len() < capacity {
207            self.states.resize(capacity, TopLayerState::None);
208            self.owners.resize(capacity, NodeId::NULL);
209        }
210    }
211
212    /// Applies a pseudo-state change of `nodes` (`StateRules` may patch their `display`).
213    /// Returns `true` when [`Self::hoisted`] changed.
214    pub fn sync_nodes(
215        &mut self,
216        store: &NodeStore,
217        nodes: &[NodeId],
218        env: &DisplayEnv<'_>,
219    ) -> bool {
220        self.transitions.clear();
221        if !self.needs_rebuild {
222            if !has_overlay_rows(store) && self.marked.is_empty() {
223                return false;
224            }
225            self.ensure_bits(store.capacity());
226            for &id in nodes {
227                self.set_bit(id);
228            }
229            let hit = self.any_owner_affected(store);
230            self.clear_bits();
231            if !hit {
232                return false;
233            }
234        }
235        self.recompute(store, env)
236    }
237
238    fn affected_by(&mut self, store: &NodeStore, changes: &ChangeSet) -> bool {
239        if !has_overlay_rows(store) {
240            return !self.marked.is_empty();
241        }
242        if changes.table(Overlay::slot()).is_some()
243            || changes
244                .removed
245                .iter()
246                .any(|&id| self.state(id) != TopLayerState::None)
247        {
248            return true;
249        }
250        let display_bit = 1u32 << Layout::DISPLAY.word();
251        self.ensure_bits(store.capacity());
252        for (slot, bit) in [(Layout::slot(), display_bit)] {
253            if let Some(td) = changes.table(slot) {
254                for (&id, &m) in td.nodes.iter().zip(&td.masks) {
255                    if m & bit != 0 {
256                        self.set_bit(id);
257                    }
258                }
259                for &id in &td.detached {
260                    self.set_bit(id);
261                }
262            }
263        }
264        // `touched` carries detached / re-parented children and table attaches that turn a node
265        // into a paragraph root (`is_inline_context_root`); `children` carries new parents.
266        for &id in changes
267            .created
268            .iter()
269            .chain(&changes.children)
270            .chain(&changes.touched)
271        {
272            self.set_bit(id);
273        }
274        let hit = self.any_owner_affected(store);
275        self.clear_bits();
276        hit
277    }
278
279    /// Whether any open (or hoisted) overlay owner or one of its ancestors carries a changed-node
280    /// bit, or a hoisted owner's chain no longer reaches the root (detached without a parent
281    /// change). Closed owners are skipped: their `Hidden` state never depends on ancestors and
282    /// their own `OPEN` flip arrives as an `Overlay` table change.
283    fn any_owner_affected(&self, store: &NodeStore) -> bool {
284        let Some(TableStorage {
285            owners, row_count, ..
286        }) = store.table_storage(Overlay::slot())
287        else {
288            return false;
289        };
290        for &oid in owners.iter().take(row_count) {
291            if oid.is_null() || !store.is_live(oid) {
292                continue;
293            }
294            let hoisted = self.is_hoisted(oid);
295            if !hoisted
296                && store
297                    .try_row::<Overlay>(oid)
298                    .is_none_or(|ov| !ov.options().contains(OverlayFlags::OPEN))
299            {
300                continue;
301            }
302            let mut cur = oid;
303            let mut connected = false;
304            for _ in 0..MAX_TREE_DEPTH {
305                if self.has_bit(cur) {
306                    return true;
307                }
308                if cur == self.root {
309                    connected = true;
310                    break;
311                }
312                match store.parent(cur) {
313                    Some(p) if p != cur => cur = p,
314                    _ => break,
315                }
316            }
317            if !connected && hoisted {
318                return true;
319            }
320        }
321        false
322    }
323
324    fn recompute(&mut self, store: &NodeStore, env: &DisplayEnv<'_>) -> bool {
325        self.needs_rebuild = false;
326        self.recompute_count = self.recompute_count.wrapping_add(1);
327        self.next.clear();
328        self.chains.clear();
329        self.candidates.clear();
330        if let Some(TableStorage {
331            owners, row_count, ..
332        }) = store.table_storage(Overlay::slot())
333        {
334            for &oid in owners.iter().take(row_count) {
335                if oid.is_null() || !store.is_live(oid) {
336                    continue;
337                }
338                let Some(ov) = store.try_row::<Overlay>(oid) else {
339                    continue;
340                };
341                if !ov.options().contains(OverlayFlags::OPEN) {
342                    self.next.push((oid, TopLayerState::Hidden));
343                } else if let Some((chain_start, chain_len)) = self.hoist_chain(store, env, oid) {
344                    self.candidates.push(Candidate {
345                        id: oid,
346                        chain_start,
347                        chain_len,
348                    });
349                }
350            }
351        }
352        if self.candidates.len() > 1 {
353            self.compute_positions(store);
354            let positions = &self.positions;
355            let path = |c: &Candidate| {
356                &positions[c.chain_start as usize..(c.chain_start + c.chain_len) as usize]
357            };
358            self.candidates
359                .sort_unstable_by(|a, b| path(a).cmp(path(b)));
360        }
361        let hoisted_changed = self.hoisted.len() != self.candidates.len()
362            || self
363                .hoisted
364                .iter()
365                .zip(&self.candidates)
366                .any(|(&h, c)| h != c.id);
367        self.hoisted.clear();
368        for c in &self.candidates {
369            self.hoisted.push(c.id);
370            self.next.push((c.id, TopLayerState::Hoisted));
371        }
372        if hoisted_changed {
373            self.generation = self.generation.wrapping_add(1);
374        }
375        self.apply_next_states(store.capacity());
376        hoisted_changed
377    }
378
379    /// Writes `next` into `states` / `owners` / `marked`, recording every full id whose state
380    /// changed (a reused slot reports both the old and the new id).
381    fn apply_next_states(&mut self, capacity: usize) {
382        self.ensure_bits(capacity);
383        let need = self
384            .next
385            .iter()
386            .map(|&(id, _)| id.index() + 1)
387            .max()
388            .unwrap_or(0)
389            .max(capacity);
390        if self.states.len() < need {
391            self.states.resize(need, TopLayerState::None);
392            self.owners.resize(need, NodeId::NULL);
393        }
394        for i in 0..self.next.len() {
395            let (id, s) = self.next[i];
396            if self.state(id) != s {
397                self.transitions.push(id);
398            }
399            let idx = id.index();
400            self.states[idx] = s;
401            self.owners[idx] = id;
402            self.set_bit(id);
403        }
404        for i in 0..self.marked.len() {
405            let id = self.marked[i];
406            let idx = id.index();
407            if self.has_bit(id) && self.owners[idx] == id {
408                continue;
409            }
410            self.transitions.push(id);
411            if !self.has_bit(id) {
412                self.states[idx] = TopLayerState::None;
413                self.owners[idx] = NodeId::NULL;
414            }
415        }
416        self.clear_bits();
417        self.marked.clear();
418        for &(id, _) in &self.next {
419            self.marked.push(id);
420        }
421    }
422
423    /// Appends `id`'s root-first ancestor chain to `chains` when `id` is a top-layer root of
424    /// `root` under `env` (`nativeview_tables::semantics::walk_top_layer_chain`, the single predicate
425    /// focus, semantic queries and accessibility share).
426    fn hoist_chain(
427        &mut self,
428        store: &NodeStore,
429        env: &DisplayEnv<'_>,
430        id: NodeId,
431    ) -> Option<(u32, u32)> {
432        let start = self.chains.len();
433        self.chains.push(id);
434        let chains = &mut self.chains;
435        if walk_top_layer_chain(store, env, self.root, id, |p| chains.push(p)) {
436            self.chains[start..].reverse();
437            Some((start as u32, (self.chains.len() - start) as u32))
438        } else {
439            self.chains.truncate(start);
440            None
441        }
442    }
443
444    /// Fills `positions` (each chain entry's index within its parent), scanning every distinct
445    /// parent on the hoisted chains once: O(Σ children of those parents) per recompute however
446    /// many roots share one wide parent.
447    fn compute_positions(&mut self, store: &NodeStore) {
448        let cap = store.capacity();
449        if self.child_index.len() < cap {
450            self.child_index.resize(cap, ChildIndex::UNSET);
451        }
452        self.ensure_bits(cap);
453        for i in 0..self.chains.len() {
454            let id = self.chains[i];
455            self.set_bit(id);
456        }
457        self.positions.clear();
458        for i in 0..self.chains.len() {
459            let id = self.chains[i];
460            let Some(parent) = store.parent(id).filter(|_| id != self.root) else {
461                self.positions.push(ChildIndex(0));
462                continue;
463            };
464            if self.child_index[id.index()] == ChildIndex::UNSET {
465                for (pos, &child) in store.children(parent).iter().enumerate() {
466                    if self.has_bit(child) {
467                        self.child_index[child.index()] = ChildIndex(pos as u32);
468                    }
469                }
470            }
471            let pos = self.child_index[id.index()];
472            debug_assert!(
473                pos != ChildIndex::UNSET,
474                "a hoisted chain node must be its parent's child"
475            );
476            self.positions.push(pos);
477        }
478        for i in 0..self.bit_ids.len() {
479            let idx = self.bit_ids[i].index();
480            self.child_index[idx] = ChildIndex::UNSET;
481        }
482        self.clear_bits();
483    }
484
485    fn ensure_bits(&mut self, capacity: usize) {
486        let words = capacity.div_ceil(64);
487        if self.bits.len() < words {
488            self.bits.resize(words, 0);
489        }
490    }
491
492    #[inline]
493    fn set_bit(&mut self, id: NodeId) {
494        let i = id.index();
495        if let Some(w) = self.bits.get_mut(i / 64) {
496            let m = 1u64 << (i % 64);
497            if *w & m == 0 {
498                *w |= m;
499                self.bit_ids.push(id);
500            }
501        }
502    }
503
504    #[inline]
505    fn has_bit(&self, id: NodeId) -> bool {
506        let i = id.index();
507        self.bits
508            .get(i / 64)
509            .is_some_and(|w| w & (1u64 << (i % 64)) != 0)
510    }
511
512    fn clear_bits(&mut self) {
513        for &id in &self.bit_ids {
514            let i = id.index();
515            if let Some(w) = self.bits.get_mut(i / 64) {
516                *w &= !(1u64 << (i % 64));
517            }
518        }
519        self.bit_ids.clear();
520    }
521}
522
523#[inline]
524fn has_overlay_rows(store: &NodeStore) -> bool {
525    store
526        .table_storage(Overlay::slot())
527        .is_some_and(|s| s.row_count > 0)
528}
529
530pub(crate) mod display;
531
532#[cfg(test)]
533mod tests;