1use 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#[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 chain_start: u32,
39 chain_len: u32,
40}
41
42#[derive(Debug)]
45pub struct TopLayerIndex {
46 root: NodeId,
47 states: Vec<TopLayerState>,
50 owners: Vec<NodeId>,
52 marked: Vec<NodeId>,
54 hoisted: Vec<NodeId>,
55 transitions: Vec<NodeId>,
57 generation: u64,
58 recompute_count: u64,
59 needs_rebuild: bool,
60 bits: Vec<u64>,
62 bit_ids: Vec<NodeId>,
63 next: Vec<(NodeId, TopLayerState)>,
64 chains: Vec<NodeId>,
65 positions: Vec<ChildIndex>,
67 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 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 #[inline]
106 pub fn states(&self) -> &[TopLayerState] {
107 &self.states
108 }
109
110 #[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 #[inline]
122 pub fn is_hoisted(&self, id: NodeId) -> bool {
123 self.state(id) == TopLayerState::Hoisted
124 }
125
126 #[inline]
128 pub fn hoisted(&self) -> &[NodeId] {
129 &self.hoisted
130 }
131
132 #[inline]
134 pub fn generation(&self) -> u64 {
135 self.generation
136 }
137
138 #[inline]
140 pub fn recompute_count(&self) -> u64 {
141 self.recompute_count
142 }
143
144 #[inline]
146 pub fn transitions(&self) -> &[NodeId] {
147 &self.transitions
148 }
149
150 #[inline]
152 pub fn root(&self) -> NodeId {
153 self.root
154 }
155
156 #[inline]
159 pub fn invalidate(&mut self) {
160 self.needs_rebuild = true;
161 }
162
163 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 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 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 #[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 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 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 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 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 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 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;