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;
#[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,
chain_start: u32,
chain_len: u32,
}
#[derive(Debug)]
pub struct TopLayerIndex {
root: NodeId,
states: Vec<TopLayerState>,
owners: Vec<NodeId>,
marked: Vec<NodeId>,
hoisted: Vec<NodeId>,
transitions: Vec<NodeId>,
generation: u64,
recompute_count: u64,
needs_rebuild: bool,
bits: Vec<u64>,
bit_ids: Vec<NodeId>,
next: Vec<(NodeId, TopLayerState)>,
chains: Vec<NodeId>,
positions: Vec<ChildIndex>,
child_index: Vec<ChildIndex>,
candidates: Vec<Candidate>,
}
impl Default for TopLayerIndex {
fn default() -> Self {
Self::new()
}
}
impl TopLayerIndex {
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(),
}
}
#[inline]
pub fn states(&self) -> &[TopLayerState] {
&self.states
}
#[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,
}
}
#[inline]
pub fn is_hoisted(&self, id: NodeId) -> bool {
self.state(id) == TopLayerState::Hoisted
}
#[inline]
pub fn hoisted(&self) -> &[NodeId] {
&self.hoisted
}
#[inline]
pub fn generation(&self) -> u64 {
self.generation
}
#[inline]
pub fn recompute_count(&self) -> u64 {
self.recompute_count
}
#[inline]
pub fn transitions(&self) -> &[NodeId] {
&self.transitions
}
#[inline]
pub fn root(&self) -> NodeId {
self.root
}
#[inline]
pub fn invalidate(&mut self) {
self.needs_rebuild = true;
}
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;
}
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
}
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
}
#[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);
}
}
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);
}
}
}
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
}
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
}
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);
}
}
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
}
}
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;