Skip to main content

cranpose_ui/widgets/nodes/
layout_node.rs

1use std::{
2    any::TypeId,
3    cell::{Cell, RefCell},
4    collections::HashMap,
5    hash::{Hash, Hasher},
6    rc::Rc,
7};
8
9use cranpose_core::{Node, NodeId};
10use cranpose_foundation::{
11    InvalidationKind, ModifierInvalidation, ModifierInvalidations, NodeCapabilities,
12    SemanticsConfiguration,
13};
14use cranpose_ui_layout::{Constraints, MeasurePolicy};
15
16#[cfg(test)]
17use crate::layout::LayoutRuntimeDebugStats;
18use crate::{
19    layout::{LayoutRuntimeState, MeasuredNode},
20    modifier::{
21        Modifier, ModifierChainHandle, ModifierLocalSource, ModifierLocalToken,
22        ModifierLocalsHandle, ModifierNodeSlices, Point, ResolvedModifierLocal, ResolvedModifiers,
23        Size,
24    },
25};
26
27#[derive(Clone, Copy)]
28enum LayoutInvalidationDispatchDiag {
29    Disabled,
30    All,
31    Node(NodeId),
32}
33
34fn layout_invalidation_dispatch_diag() -> LayoutInvalidationDispatchDiag {
35    static MODE: std::sync::OnceLock<LayoutInvalidationDispatchDiag> = std::sync::OnceLock::new();
36    *MODE.get_or_init(|| {
37        let Some(value) = std::env::var_os("CRANPOSE_LAYOUT_INVALIDATION_DISPATCH_DIAG") else {
38            return LayoutInvalidationDispatchDiag::Disabled;
39        };
40        if value == "all" {
41            return LayoutInvalidationDispatchDiag::All;
42        }
43        value.to_string_lossy().parse::<NodeId>().map_or(
44            LayoutInvalidationDispatchDiag::Disabled,
45            LayoutInvalidationDispatchDiag::Node,
46        )
47    })
48}
49
50fn log_layout_invalidation_dispatch(
51    id: NodeId,
52    invalidation: &ModifierInvalidation,
53    curr_caps: NodeCapabilities,
54    prev_caps: NodeCapabilities,
55    modifier: &Modifier,
56) {
57    let enabled = match layout_invalidation_dispatch_diag() {
58        LayoutInvalidationDispatchDiag::Disabled => false,
59        LayoutInvalidationDispatchDiag::All => true,
60        LayoutInvalidationDispatchDiag::Node(target) => target == id,
61    };
62    if enabled {
63        log::warn!(
64            "[layout-invalidation-dispatch] node={id} invalidation={invalidation:?} curr_caps={curr_caps:?} prev_caps={prev_caps:?} modifier={modifier}"
65        );
66    }
67}
68
69/// The running layout pass and how many placed nodes it has cleared and not
70/// placed again yet: the nodes it unplaces, unless their parents place them
71/// before it ends. Ids start past 0, the pass a node no pass cleared names.
72struct PlacementPass {
73    id: Cell<u64>,
74    unplaced: Cell<usize>,
75}
76
77thread_local! {
78    static PLACEMENT_PASS: PlacementPass = const {
79        PlacementPass {
80            id: Cell::new(1),
81            unplaced: Cell::new(0),
82        }
83    };
84}
85
86/// Starts the placement bookkeeping of a layout pass.
87pub(crate) fn begin_placement_pass() {
88    PLACEMENT_PASS.with(|pass| {
89        pass.id.set(pass.id.get() + 1);
90        pass.unplaced.set(0);
91    });
92}
93
94/// The running pass, when it has left a node unplaced that it found placed.
95pub(crate) fn placement_pass_with_unplaced_nodes() -> Option<u64> {
96    PLACEMENT_PASS.with(|pass| (pass.unplaced.get() > 0).then(|| pass.id.get()))
97}
98
99/// Retained layout state for a LayoutNode.
100/// This mirrors Jetpack Compose's approach where each node stores its own
101/// measured size and placed position, eliminating the need for per-frame
102/// LayoutTree reconstruction.
103/// What a node below a node needs: layout, and measure when `measure` is set.
104#[derive(Clone, Copy, Default)]
105pub(crate) struct DescendantDirt {
106    pub(crate) layout: bool,
107    pub(crate) measure: bool,
108}
109
110impl DescendantDirt {
111    pub(crate) fn marked(self, measure: bool) -> Self {
112        Self {
113            layout: true,
114            measure: self.measure || measure,
115        }
116    }
117}
118
119#[derive(Clone, Debug, Default)]
120pub struct LayoutState {
121    size: Size,
122    position: Point,
123    is_placed: bool,
124    node_id: Option<NodeId>,
125    /// The layout pass that cleared the placed flag while the node was placed.
126    cleared_in_pass: u64,
127    content_offset: Point,
128    semantics_stamp: u64,
129}
130
131impl LayoutState {
132    pub fn size(&self) -> Size {
133        self.size
134    }
135
136    pub fn position(&self) -> Point {
137        self.position
138    }
139
140    /// Offset of the content box relative to the node origin (e.g. due to
141    /// padding).
142    pub fn content_offset(&self) -> Point {
143        self.content_offset
144    }
145
146    /// Writes the content offset, reporting an actual change to the
147    /// semantics tree.
148    pub fn set_content_offset(&mut self, offset: Point) {
149        if self.content_offset != offset {
150            self.content_offset = offset;
151            self.note_semantics_change();
152        }
153    }
154
155    /// The same state placed at the origin: what a window root's own scene
156    /// starts from, since the position its parent gave it belongs to the
157    /// parent's window.
158    pub fn at_origin(mut self) -> Self {
159        self.position = Point::default();
160        self
161    }
162
163    pub fn is_placed(&self) -> bool {
164        self.is_placed
165    }
166
167    pub(crate) fn set_node_id(&mut self, node_id: NodeId) {
168        self.node_id = Some(node_id);
169    }
170
171    /// Writes the measured size, self-reporting an actual change to the
172    /// scene phase.
173    pub fn set_size(&mut self, size: Size) {
174        if self.size != size {
175            if let Some(id) = self.node_id {
176                crate::render_state::record_geometry_scene_node(id);
177            }
178            self.size = size;
179            self.note_semantics_change();
180        }
181    }
182
183    /// Writes the placed position and marks the node placed, self-reporting
184    /// an actual move to the scene phase, and a placement of a node the
185    /// scene does not draw: one the running pass did not find placed. A move
186    /// is reported apart, so the scene can keep what it drew for the node.
187    pub fn place(&mut self, position: Point) {
188        let newly_placed = !self.is_placed && !self.restore_placement();
189        let moved = self.position != position;
190        if let Some(id) = self.node_id {
191            if newly_placed {
192                crate::render_state::record_geometry_scene_node(id);
193            } else if moved {
194                crate::render_state::record_moved_scene_node(id);
195            }
196        }
197        self.position = position;
198        if moved || !self.is_placed {
199            self.is_placed = true;
200            self.note_semantics_change();
201        }
202    }
203
204    /// Whether the running pass cleared the flag of this node while it was
205    /// placed, so placing it again changes nothing the scene draws.
206    fn restore_placement(&self) -> bool {
207        PLACEMENT_PASS.with(|pass| {
208            let restored = self.cleared_in_pass == pass.id.get();
209            if restored {
210                pass.unplaced.set(pass.unplaced.get().saturating_sub(1));
211            }
212            restored
213        })
214    }
215
216    /// Clears the placed flag at the start of a layout pass. Until its parent
217    /// places it again the pass counts the node unplaced, and the pass names
218    /// it to the scene phase if it ends that way.
219    pub fn clear_placed(&mut self) {
220        if !self.is_placed {
221            return;
222        }
223        self.is_placed = false;
224        self.cleared_in_pass = PLACEMENT_PASS.with(|pass| {
225            pass.unplaced.set(pass.unplaced.get() + 1);
226            pass.id.get()
227        });
228        self.note_semantics_change();
229    }
230
231    /// Whether `pass` found this node placed and left it unplaced.
232    pub(crate) fn unplaced_in(&self, pass: u64) -> bool {
233        !self.is_placed && self.cleared_in_pass == pass
234    }
235
236    pub(crate) fn note_semantics_change(&mut self) {
237        if let Some(id) = self.node_id {
238            crate::semantics_layout_log::record_layout_change(id, &mut self.semantics_stamp);
239        }
240    }
241}
242
243#[derive(Clone)]
244struct MeasurementCacheEntry {
245    constraints: Constraints,
246    measured: Rc<MeasuredNode>,
247    /// The other incoming constraints the measurement holds for.
248    hold: Option<cranpose_ui_layout::ConstraintsHold>,
249}
250
251#[derive(Clone, Copy, Debug)]
252pub enum IntrinsicKind {
253    MinWidth(f32),
254    MaxWidth(f32),
255    MinHeight(f32),
256    MaxHeight(f32),
257}
258
259impl IntrinsicKind {
260    fn discriminant(&self) -> u8 {
261        match self {
262            IntrinsicKind::MinWidth(_) => 0,
263            IntrinsicKind::MaxWidth(_) => 1,
264            IntrinsicKind::MinHeight(_) => 2,
265            IntrinsicKind::MaxHeight(_) => 3,
266        }
267    }
268
269    fn value_bits(&self) -> u32 {
270        match self {
271            IntrinsicKind::MinWidth(value)
272            | IntrinsicKind::MaxWidth(value)
273            | IntrinsicKind::MinHeight(value)
274            | IntrinsicKind::MaxHeight(value) => value.to_bits(),
275        }
276    }
277}
278
279impl PartialEq for IntrinsicKind {
280    fn eq(&self, other: &Self) -> bool {
281        self.discriminant() == other.discriminant() && self.value_bits() == other.value_bits()
282    }
283}
284
285impl Eq for IntrinsicKind {}
286
287impl Hash for IntrinsicKind {
288    fn hash<H: Hasher>(&self, state: &mut H) {
289        self.discriminant().hash(state);
290        self.value_bits().hash(state);
291    }
292}
293
294#[derive(Default)]
295struct NodeCacheState {
296    epoch: u64,
297    measurement: Option<MeasurementCacheEntry>,
298    intrinsics: Vec<(IntrinsicKind, f32)>,
299    /// Whether a parent read intrinsic sizes since the cache was cleared.
300    intrinsics_read: bool,
301}
302
303#[derive(Default)]
304pub(crate) struct LayoutNodeCacheHandles {
305    state: Rc<RefCell<NodeCacheState>>,
306}
307
308impl Clone for LayoutNodeCacheHandles {
309    fn clone(&self) -> Self {
310        Self {
311            state: Rc::clone(&self.state),
312        }
313    }
314
315    fn clone_from(&mut self, source: &Self) {
316        if !Rc::ptr_eq(&self.state, &source.state) {
317            self.state = Rc::clone(&source.state);
318        }
319    }
320}
321
322impl LayoutNodeCacheHandles {
323    pub(crate) fn clear(&self) {
324        let mut state = self.state.borrow_mut();
325        state.measurement = None;
326        state.intrinsics.clear();
327        state.intrinsics_read = false;
328        state.epoch = 0;
329    }
330
331    pub(crate) fn activate(&self, epoch: u64) {
332        let mut state = self.state.borrow_mut();
333        if state.epoch != epoch {
334            state.measurement = None;
335            state.intrinsics.clear();
336            state.intrinsics_read = false;
337            state.epoch = epoch;
338        }
339    }
340
341    /// Drops the intrinsic sizes, which depend on every node below: one of
342    /// them changed. A parent's earlier read still counts for
343    /// [`Self::has_intrinsics`].
344    pub(crate) fn forget_intrinsics(&self) {
345        self.state.borrow_mut().intrinsics.clear();
346    }
347
348    pub(crate) fn epoch(&self) -> u64 {
349        self.state.borrow().epoch
350    }
351
352    /// The measurement the cache holds for `constraints`: one made under
353    /// them, or one whose hold contains them. A caller asks only while the
354    /// node and everything below it are clean.
355    pub(crate) fn get_measurement(&self, constraints: Constraints) -> Option<Rc<MeasuredNode>> {
356        let state = self.state.borrow();
357        state
358            .measurement
359            .as_ref()
360            .filter(|entry| {
361                entry.constraints == constraints
362                    || entry.hold.is_some_and(|hold| hold.contains(constraints))
363            })
364            .map(|entry| Rc::clone(&entry.measured))
365    }
366
367    /// The constraints of the measurement the cache holds.
368    pub(crate) fn measured_constraints(&self) -> Option<Constraints> {
369        self.state
370            .borrow()
371            .measurement
372            .as_ref()
373            .map(|entry| entry.constraints)
374    }
375
376    /// Whether a parent read intrinsic sizes from this cache.
377    pub(crate) fn has_intrinsics(&self) -> bool {
378        self.state.borrow().intrinsics_read
379    }
380
381    /// The hold of the measurement the cache has, when it is `measured`.
382    pub(crate) fn hold_of(
383        &self,
384        measured: &Rc<MeasuredNode>,
385    ) -> Option<cranpose_ui_layout::ConstraintsHold> {
386        self.state
387            .borrow()
388            .measurement
389            .as_ref()
390            .filter(|entry| Rc::ptr_eq(&entry.measured, measured))
391            .and_then(|entry| entry.hold)
392    }
393
394    /// Stores `measured` for `constraints`. The hold of a measurement the
395    /// cache already has stays with it.
396    pub(crate) fn store_measurement(&self, constraints: Constraints, measured: Rc<MeasuredNode>) {
397        let mut state = self.state.borrow_mut();
398        let hold = state
399            .measurement
400            .as_ref()
401            .filter(|entry| Rc::ptr_eq(&entry.measured, &measured))
402            .and_then(|entry| entry.hold);
403        state.measurement = Some(MeasurementCacheEntry {
404            constraints,
405            measured,
406            hold,
407        });
408    }
409
410    /// Stores `measured` for `constraints` and the other constraints `hold`
411    /// says it holds for.
412    pub(crate) fn store_held_measurement(
413        &self,
414        constraints: Constraints,
415        measured: Rc<MeasuredNode>,
416        hold: Option<cranpose_ui_layout::ConstraintsHold>,
417    ) {
418        self.state.borrow_mut().measurement = Some(MeasurementCacheEntry {
419            constraints,
420            measured,
421            hold,
422        });
423    }
424
425    pub(crate) fn get_intrinsic(&self, kind: &IntrinsicKind) -> Option<f32> {
426        let state = self.state.borrow();
427        state
428            .intrinsics
429            .iter()
430            .find(|(stored_kind, _)| stored_kind == kind)
431            .map(|(_, value)| *value)
432    }
433
434    pub(crate) fn store_intrinsic(&self, kind: IntrinsicKind, value: f32) {
435        let mut state = self.state.borrow_mut();
436        state.intrinsics_read = true;
437        if let Some((_, existing)) = state
438            .intrinsics
439            .iter_mut()
440            .find(|(stored_kind, _)| stored_kind == &kind)
441        {
442            *existing = value;
443        } else {
444            state.intrinsics.push((kind, value));
445        }
446    }
447}
448
449/// A node of the layout tree.
450///
451/// Its fields keep the order they are declared in: what a layout pass reads
452/// for every child it binds comes first and fits one cache line, then what
453/// measuring the node reads, then what composition reads. Layout reads
454/// thousands of nodes a frame, and on a phone its cost is the lines it loads.
455#[repr(C)]
456pub struct LayoutNode {
457    cache: LayoutNodeCacheHandles,
458    layout_state: Rc<RefCell<LayoutState>>,
459    layout_runtime_state: Rc<RefCell<LayoutRuntimeState>>,
460    /// The actual children of this node (folded view - includes virtual nodes as-is)
461    pub children: Vec<NodeId>,
462    /// What the chain tells the parent's policy about this node: its
463    /// weight and alignments, kept beside the binding fields.
464    parent_data: Cell<cranpose_ui_layout::ParentData>,
465    needs_measure: Cell<bool>,
466    needs_layout: Cell<bool>,
467    /// A node below this one needs layout or measure.
468    descendant_dirt: Cell<DescendantDirt>,
469
470    pub measure_policy: Rc<dyn MeasurePolicy>,
471    /// Where the chain's layout modifiers put their content, written by
472    /// layout and read by the draws and text the slices collect.
473    coordinator_geometry: Rc<crate::modifier::CoordinatorGeometry>,
474    density: crate::density::Density,
475    is_virtual: bool,
476    needs_semantics: Cell<bool>,
477    /// The semantics tree has to read this node again, though its own
478    /// semantics are unchanged: a node below it changed, or its placement
479    /// or children did.
480    descendant_needs_semantics: Cell<bool>,
481    needs_redraw: Cell<bool>,
482    needs_pointer_pass: Cell<bool>,
483    needs_focus_sync: Cell<bool>,
484    modifier_slices_dirty: Cell<bool>,
485    debug_modifiers: Cell<bool>,
486
487    id: Cell<Option<NodeId>>,
488    parent: Cell<Option<NodeId>>,
489    folded_parent: Cell<Option<NodeId>>,
490    modifier_slices_snapshot: RefCell<Rc<ModifierNodeSlices>>,
491
492    /// The chain's modal and hidden flags, read by the modal count and the
493    /// modal walk: dropped whenever the chain syncs or semantics are
494    /// invalidated, the two ways its semantics change.
495    semantics_reach: Cell<Option<cranpose_foundation::SemanticsReach>>,
496    virtual_children_count: Cell<usize>,
497    owner_context_id: Cell<Option<crate::render_state::AppContextId>>,
498    modifier_chain: ModifierChainHandle,
499    pub modifier: Modifier,
500    /// Composable definitions responsible for this node, captured only for inspection builds.
501    #[cfg(feature = "inspection")]
502    pub source_trace: Rc<[cranpose_core::source_trace::SourceLocation]>,
503}
504
505pub(crate) const RECYCLED_LAYOUT_NODE_POOL_LIMIT: usize = 128;
506
507thread_local! {
508    static EMPTY_MEASURE_POLICY: Rc<dyn MeasurePolicy> =
509        Rc::new(crate::layout::policies::EmptyMeasurePolicy);
510}
511
512fn empty_measure_policy() -> Rc<dyn MeasurePolicy> {
513    EMPTY_MEASURE_POLICY.with(Rc::clone)
514}
515
516impl LayoutNode {
517    pub fn new(modifier: Modifier, measure_policy: Rc<dyn MeasurePolicy>) -> Self {
518        Self::new_with_virtual(modifier, measure_policy, false)
519    }
520
521    /// Create a virtual LayoutNode for subcomposition slot containers.
522    /// Virtual nodes are transparent - their children are flattened into parent's children list.
523    pub fn new_virtual() -> Self {
524        Self::new_with_virtual(Modifier::empty(), empty_measure_policy(), true)
525    }
526
527    fn new_recycled_shell(is_virtual: bool) -> Self {
528        let mut shell =
529            Self::new_with_virtual(Modifier::empty(), empty_measure_policy(), is_virtual);
530        shell.needs_measure.set(false);
531        shell.needs_layout.set(false);
532        shell.needs_semantics.set(false);
533        shell.descendant_needs_semantics.set(false);
534        shell.needs_redraw.set(false);
535        shell.needs_pointer_pass.set(false);
536        shell.needs_focus_sync.set(false);
537        shell.parent.set(None);
538        shell.folded_parent.set(None);
539        shell.id.set(None);
540        shell.owner_context_id.set(None);
541        shell.debug_modifiers.set(false);
542        shell.virtual_children_count.set(0);
543        shell.modifier_slices_dirty = Cell::new(true);
544        shell
545    }
546
547    fn new_with_virtual(
548        modifier: Modifier,
549        measure_policy: Rc<dyn MeasurePolicy>,
550        is_virtual: bool,
551    ) -> Self {
552        let layout_runtime_state = Rc::new(RefCell::new(LayoutRuntimeState::new(Rc::clone(
553            &measure_policy,
554        ))));
555        let mut node = Self {
556            #[cfg(feature = "inspection")]
557            source_trace: cranpose_core::source_trace::current_source_trace(),
558            modifier,
559            modifier_chain: ModifierChainHandle::new(),
560            measure_policy,
561            density: crate::density::Density::default(),
562            children: Vec::new(),
563            cache: LayoutNodeCacheHandles::default(),
564            needs_measure: Cell::new(true),
565            needs_layout: Cell::new(true),
566            descendant_dirt: Cell::default(),
567            parent_data: Cell::default(),
568            needs_semantics: Cell::new(true),
569            descendant_needs_semantics: Cell::new(false),
570            semantics_reach: Cell::new(None),
571            needs_redraw: Cell::new(true),
572            needs_pointer_pass: Cell::new(false),
573            needs_focus_sync: Cell::new(false),
574            parent: Cell::new(None),
575            folded_parent: Cell::new(None),
576            id: Cell::new(None),
577            owner_context_id: Cell::new(None),
578            debug_modifiers: Cell::new(false),
579            is_virtual,
580            virtual_children_count: Cell::new(0),
581            modifier_slices_snapshot: RefCell::new(Rc::default()),
582            modifier_slices_dirty: Cell::new(true),
583            layout_state: Rc::new(RefCell::new(LayoutState::default())),
584            layout_runtime_state,
585            coordinator_geometry: Rc::default(),
586        };
587        node.sync_modifier_chain(false);
588        node
589    }
590
591    pub fn set_modifier(&mut self, modifier: Modifier) {
592        #[cfg(feature = "inspection")]
593        {
594            let trace = cranpose_core::source_trace::current_source_trace();
595            if !trace.is_empty() {
596                self.source_trace = trace;
597            }
598        }
599        // An equal modifier leaves every element's node as it was. Only a
600        // chain reading modifier locals resyncs, since its parent may now
601        // provide others.
602        if self.modifier == modifier
603            && !self
604                .modifier_capabilities()
605                .contains(NodeCapabilities::MODIFIER_LOCALS)
606        {
607            return;
608        }
609        // A text that changed and nothing else, as a ticker's does, keeps
610        // the slices the chain gave: their text reads the layout the update
611        // changes in place.
612        let text_only = self
613            .modifier
614            .differs_only_in::<crate::text_modifier_node::TextModifierElement>(&modifier);
615        let modifier_changed = text_only || !self.modifier.structural_eq(&modifier);
616        self.modifier = modifier;
617        self.sync_modifier_chain(text_only);
618        if modifier_changed {
619            self.cache.clear();
620            self.request_semantics_update();
621        }
622    }
623
624    /// Reconciles the chain with the node's modifier. `text_only` says the
625    /// modifier changed only in its text elements: when the chain updates
626    /// them in place, the current slices are kept.
627    fn sync_modifier_chain(&mut self, text_only: bool) {
628        let prev_caps = self.modifier_capabilities();
629        let start_parent = self.parent();
630        let mut resolver = move |token: &ModifierLocalToken| {
631            resolve_modifier_local_from_parent_chain(start_parent, token)
632        };
633        self.modifier_chain
634            .set_debug_logging(self.debug_modifiers.get());
635        self.modifier_chain.set_node_id(self.id.get());
636        let in_place = text_only
637            && self
638                .modifier_chain
639                .update_elements_in_place::<crate::text_modifier_node::TextModifierElement>(
640                    &self.modifier,
641                );
642        let modifier_local_invalidations = if in_place {
643            ModifierInvalidations::new()
644        } else {
645            let invalidations = self
646                .modifier_chain
647                .update_with_resolver(&self.modifier, &mut resolver);
648            self.refresh_parent_data();
649            invalidations
650        };
651        if prev_caps.contains(NodeCapabilities::WINDOW_ROOT)
652            != self
653                .modifier_capabilities()
654                .contains(NodeCapabilities::WINDOW_ROOT)
655        {
656            self.note_semantics_layout_change();
657        }
658        // A text element reaches nothing, so an update in place leaves the
659        // chain's reach as it was, and the modal count does not read it again.
660        if !in_place {
661            self.forget_semantics_reach();
662        }
663        let keep_slices = in_place && !self.modifier_slices_dirty.get();
664        if !keep_slices {
665            self.modifier_slices_dirty.set(true);
666        }
667
668        let mut invalidations = self.modifier_chain.take_invalidations();
669        invalidations.extend(modifier_local_invalidations);
670        self.dispatch_modifier_invalidations_with_prev(&invalidations, prev_caps, keep_slices);
671        // An update in place leaves the node's parent, capabilities and
672        // modifier locals as the registry holds them.
673        if !in_place {
674            self.refresh_registry_state();
675        }
676    }
677
678    fn update_modifier_slices_cache(&self) {
679        let mut snapshot = self.modifier_slices_snapshot.borrow_mut();
680        crate::modifier::collect_modifier_slices_into_shared(
681            self.modifier_chain.chain(),
682            &mut snapshot,
683            &self.coordinator_geometry,
684            self.density.density(),
685        );
686        self.modifier_slices_dirty.set(false);
687    }
688
689    /// Whether the modifier slices are built and current.
690    #[cfg(test)]
691    pub(crate) fn modifier_slices_ready(&self) -> bool {
692        !self.modifier_slices_dirty.get()
693    }
694
695    pub(crate) fn mark_modifier_slices_dirty(&self) {
696        self.modifier_slices_dirty.set(true);
697    }
698
699    #[cfg(test)]
700    fn dispatch_modifier_invalidations(&self, invalidations: &[ModifierInvalidation]) {
701        self.dispatch_modifier_invalidations_with_prev(
702            invalidations,
703            NodeCapabilities::empty(),
704            false,
705        );
706    }
707
708    /// Applies `invalidations` to the node. Each marks the slices for a
709    /// rebuild unless `keep_slices`.
710    fn dispatch_modifier_invalidations_with_prev(
711        &self,
712        invalidations: &[ModifierInvalidation],
713        prev_caps: NodeCapabilities,
714        keep_slices: bool,
715    ) {
716        let curr_caps = self.modifier_capabilities();
717        for invalidation in invalidations {
718            if !keep_slices {
719                self.modifier_slices_dirty.set(true);
720            }
721            let has_capability =
722                |capability| curr_caps.contains(capability) || prev_caps.contains(capability);
723            match invalidation.kind() {
724                InvalidationKind::Layout => {
725                    if has_capability(NodeCapabilities::LAYOUT) {
726                        self.mark_needs_measure();
727                        if let Some(id) = self.id.get() {
728                            log_layout_invalidation_dispatch(
729                                id,
730                                invalidation,
731                                curr_caps,
732                                prev_caps,
733                                &self.modifier,
734                            );
735                            let inside_composition =
736                                cranpose_core::composer_context::try_with_composer(|_| ())
737                                    .is_some();
738                            if inside_composition {
739                                cranpose_core::bubble_measure_dirty_in_composer(id);
740                            } else {
741                                crate::schedule_layout_repass(id);
742                            }
743                        }
744                    }
745                }
746                InvalidationKind::Draw => {
747                    if has_capability(NodeCapabilities::DRAW)
748                        || invalidation.capabilities().contains(NodeCapabilities::DRAW)
749                    {
750                        self.mark_needs_redraw();
751                    }
752                }
753                InvalidationKind::PointerInput => {
754                    if has_capability(NodeCapabilities::POINTER_INPUT) {
755                        self.mark_needs_pointer_pass();
756                        crate::request_pointer_invalidation();
757                        if let Some(id) = self.id.get() {
758                            crate::schedule_pointer_repass(id);
759                        }
760                    }
761                }
762                InvalidationKind::Semantics => {
763                    self.request_semantics_update();
764                }
765                InvalidationKind::Focus => {
766                    if has_capability(NodeCapabilities::FOCUS) {
767                        self.mark_needs_focus_sync();
768                        crate::request_focus_invalidation();
769                        if let Some(id) = self.id.get() {
770                            crate::schedule_focus_invalidation(id);
771                        }
772                    }
773                }
774            }
775        }
776    }
777
778    /// The grid this node was composed against.
779    pub fn density(&self) -> crate::density::Density {
780        self.density
781    }
782
783    /// Records the grid the composition provided, re-measuring if it moved.
784    pub fn set_density(&mut self, density: crate::density::Density) {
785        if self.density != density {
786            self.density = density;
787            self.cache.clear();
788            self.modifier_slices_dirty.set(true);
789            self.mark_needs_measure();
790        }
791    }
792
793    /// Updates relative modifier placement for this node's composition scope.
794    pub fn set_layout_direction(&mut self, direction: crate::LayoutDirection) {
795        if self.modifier_chain.set_layout_direction(direction) {
796            self.refresh_parent_data();
797            self.cache.clear();
798            self.modifier_slices_dirty.set(true);
799            self.mark_needs_measure();
800        }
801    }
802
803    pub fn set_measure_policy(&mut self, policy: Rc<dyn MeasurePolicy>) {
804        if !Rc::ptr_eq(&self.measure_policy, &policy) {
805            self.measure_policy = policy;
806            self.cache.clear();
807            self.mark_needs_measure();
808            if let Some(id) = self.id.get() {
809                cranpose_core::bubble_measure_dirty_in_composer(id);
810            }
811        }
812    }
813
814    /// Mark this node as needing measure. Also marks it as needing layout.
815    pub fn mark_needs_measure(&self) {
816        self.needs_measure.set(true);
817        self.needs_layout.set(true);
818    }
819
820    /// Mark this node as needing layout (but not necessarily measure).
821    pub fn mark_needs_layout(&self) {
822        self.needs_layout.set(true);
823    }
824
825    /// Mark this node as needing redraw without forcing measure/layout.
826    pub fn mark_needs_redraw(&self) {
827        self.needs_redraw.set(true);
828        if let Some(id) = self.id.get() {
829            crate::schedule_draw_repass(id);
830        }
831        crate::request_render_invalidation();
832    }
833
834    /// Check if this node needs measure.
835    pub fn needs_measure(&self) -> bool {
836        self.needs_measure.get()
837    }
838
839    /// Check if this node needs layout.
840    pub fn needs_layout(&self) -> bool {
841        self.needs_layout.get()
842    }
843
844    /// Mark this node as needing semantics recomputation.
845    pub fn mark_needs_semantics(&self) {
846        self.needs_semantics.set(true);
847        self.forget_semantics_reach();
848    }
849
850    pub(crate) fn clear_needs_semantics(&self) {
851        self.needs_semantics.set(false);
852        self.descendant_needs_semantics.set(false);
853    }
854
855    /// Returns true when this node's semantics or a descendant's need to be
856    /// recomputed.
857    pub fn needs_semantics(&self) -> bool {
858        self.needs_semantics.get() || self.descendant_needs_semantics.get()
859    }
860
861    /// Whether this node's own semantics changed since the tree last read
862    /// them, as opposed to only a descendant's.
863    pub(crate) fn semantics_changed(&self) -> bool {
864        self.needs_semantics.get()
865    }
866
867    /// Returns true when this node requested a redraw since the last render pass.
868    pub fn needs_redraw(&self) -> bool {
869        self.needs_redraw.get()
870    }
871
872    pub fn clear_needs_redraw(&self) {
873        self.needs_redraw.set(false);
874    }
875
876    fn request_semantics_update(&self) {
877        let already_dirty = self.needs_semantics.replace(true);
878        if already_dirty {
879            return;
880        }
881
882        if let Some(id) = self.id.get() {
883            cranpose_core::queue_semantics_invalidation(id);
884        }
885    }
886
887    pub(crate) fn clear_needs_measure(&self) {
888        self.needs_measure.set(false);
889    }
890
891    /// Clears the node's layout flag and its descendants': a layout pass
892    /// visited them.
893    pub(crate) fn clear_needs_layout(&self) {
894        self.needs_layout.set(false);
895        self.descendant_dirt.set(DescendantDirt::default());
896    }
897
898    /// Marks this node as needing a fresh pointer-input pass.
899    pub fn mark_needs_pointer_pass(&self) {
900        self.needs_pointer_pass.set(true);
901    }
902
903    /// Returns true when pointer-input state needs to be recomputed.
904    pub fn needs_pointer_pass(&self) -> bool {
905        self.needs_pointer_pass.get()
906    }
907
908    /// Clears the pointer-input dirty flag after hosts service it.
909    pub fn clear_needs_pointer_pass(&self) {
910        self.needs_pointer_pass.set(false);
911    }
912
913    /// Marks this node as needing a focus synchronization.
914    pub fn mark_needs_focus_sync(&self) {
915        self.needs_focus_sync.set(true);
916    }
917
918    /// Returns true when focus state needs to be synchronized.
919    pub fn needs_focus_sync(&self) -> bool {
920        self.needs_focus_sync.get()
921    }
922
923    /// Clears the focus dirty flag after the focus manager processes it.
924    pub fn clear_needs_focus_sync(&self) {
925        self.needs_focus_sync.set(false);
926    }
927
928    /// Set this node's ID (called by applier after creation).
929    pub fn set_node_id(&mut self, id: NodeId) {
930        if let Some(existing) = self.id.replace(Some(id))
931            && let Some(owner_context_id) = self.owner_context_id.take()
932        {
933            unregister_layout_node(owner_context_id, existing);
934        }
935        self.layout_state.borrow_mut().set_node_id(id);
936        let owner_context_id = register_layout_node(id, self);
937        self.owner_context_id.set(Some(owner_context_id));
938        self.refresh_registry_state();
939
940        self.modifier_chain.set_node_id(Some(id));
941        let invalidations = self.modifier_chain.take_invalidations();
942        self.dispatch_modifier_invalidations_with_prev(
943            &invalidations,
944            NodeCapabilities::empty(),
945            false,
946        );
947        // The slices carry the node's id; they are collected again when next read.
948        self.modifier_slices_dirty.set(true);
949    }
950
951    /// Get this node's ID.
952    pub fn node_id(&self) -> Option<NodeId> {
953        self.id.get()
954    }
955
956    /// Set this node's parent (called when node is added as child).
957    /// Sets both folded_parent (direct) and parent (first non-virtual ancestor for bubbling).
958    pub fn set_parent(&self, parent: NodeId) {
959        self.folded_parent.set(Some(parent));
960        self.parent.set(Some(parent));
961        self.refresh_registry_state();
962    }
963
964    /// Clear this node's parent (called when node is removed from parent).
965    pub fn clear_parent(&self) {
966        self.folded_parent.set(None);
967        self.parent.set(None);
968        self.refresh_registry_state();
969    }
970
971    /// Get this node's parent for dirty flag bubbling (may skip virtual nodes).
972    pub fn parent(&self) -> Option<NodeId> {
973        self.parent.get()
974    }
975
976    /// Get this node's direct parent (may be a virtual node).
977    pub fn folded_parent(&self) -> Option<NodeId> {
978        self.folded_parent.get()
979    }
980
981    pub(crate) fn cache_handles(&self) -> &LayoutNodeCacheHandles {
982        &self.cache
983    }
984
985    pub fn resolved_modifiers(&self) -> ResolvedModifiers {
986        self.modifier_chain.resolved_modifiers()
987    }
988
989    /// What the chain tells the parent's measure policy about this node.
990    pub(crate) fn parent_data(&self) -> cranpose_ui_layout::ParentData {
991        self.parent_data.get()
992    }
993
994    /// Copies the parent data out of the chain's resolved modifiers, after
995    /// they were computed again.
996    fn refresh_parent_data(&self) {
997        self.parent_data.set(crate::layout::parent_data_of(
998            self.modifier_chain.resolved_modifiers().layout_properties(),
999        ));
1000    }
1001
1002    pub fn modifier_capabilities(&self) -> NodeCapabilities {
1003        self.modifier_chain.capabilities()
1004    }
1005
1006    /// Whether this node's modifier chain makes it the root of a separate
1007    /// window. Its parent lays out as if it had no size and its parent's
1008    /// scene skips it; its own scene starts here.
1009    pub fn is_window_root(&self) -> bool {
1010        self.modifier_capabilities()
1011            .contains(NodeCapabilities::WINDOW_ROOT)
1012    }
1013
1014    pub fn modifier_child_capabilities(&self) -> NodeCapabilities {
1015        self.modifier_chain.aggregate_child_capabilities()
1016    }
1017
1018    pub fn set_debug_modifiers(&mut self, enabled: bool) {
1019        self.debug_modifiers.set(enabled);
1020        self.modifier_chain.set_debug_logging(enabled);
1021    }
1022
1023    pub fn debug_modifiers_enabled(&self) -> bool {
1024        self.debug_modifiers.get()
1025    }
1026
1027    /// The node's modifier locals, or `None` while its modifiers have never
1028    /// provided or read one.
1029    pub fn modifier_locals_handle(&self) -> Option<ModifierLocalsHandle> {
1030        self.modifier_chain.modifier_locals_handle()
1031    }
1032
1033    pub fn has_layout_modifier_nodes(&self) -> bool {
1034        self.modifier_capabilities()
1035            .contains(NodeCapabilities::LAYOUT)
1036    }
1037
1038    pub fn has_draw_modifier_nodes(&self) -> bool {
1039        self.modifier_capabilities()
1040            .contains(NodeCapabilities::DRAW)
1041    }
1042
1043    pub fn has_pointer_input_modifier_nodes(&self) -> bool {
1044        self.modifier_capabilities()
1045            .contains(NodeCapabilities::POINTER_INPUT)
1046    }
1047
1048    pub fn has_semantics_modifier_nodes(&self) -> bool {
1049        self.modifier_capabilities()
1050            .contains(NodeCapabilities::SEMANTICS)
1051    }
1052
1053    pub fn has_focus_modifier_nodes(&self) -> bool {
1054        self.modifier_capabilities()
1055            .contains(NodeCapabilities::FOCUS)
1056    }
1057
1058    fn refresh_registry_state(&self) {
1059        if let (Some(id), Some(owner_context_id)) = (self.id.get(), self.owner_context_id.get()) {
1060            let parent = self.parent();
1061            let capabilities = self.modifier_child_capabilities();
1062            let modifier_locals = self.modifier_locals_handle();
1063            let _ = crate::render_state::with_layout_node_registry_by_app_context(
1064                owner_context_id,
1065                |registry| {
1066                    registry.update_entry(id, parent, capabilities, modifier_locals);
1067                },
1068            );
1069        }
1070    }
1071
1072    pub fn modifier_slices_snapshot(&self) -> Rc<ModifierNodeSlices> {
1073        if self.modifier_slices_dirty.get() {
1074            self.update_modifier_slices_cache();
1075        }
1076        self.modifier_slices_snapshot.borrow().clone()
1077    }
1078
1079    /// Returns a clone of the current layout state.
1080    pub fn layout_state(&self) -> LayoutState {
1081        self.layout_state.borrow().clone()
1082    }
1083
1084    /// Returns the measured size of this node.
1085    pub fn measured_size(&self) -> Size {
1086        self.layout_state.borrow().size
1087    }
1088
1089    /// Returns the position of this node relative to its parent.
1090    pub fn position(&self) -> Point {
1091        self.layout_state.borrow().position
1092    }
1093
1094    /// Returns true if this node has been placed in the current layout pass.
1095    pub fn is_placed(&self) -> bool {
1096        self.layout_state.borrow().is_placed
1097    }
1098
1099    /// Updates the measured size of this node. Called during measurement.
1100    /// [`LayoutState::set_size`] self-reports actual changes to the scene
1101    /// phase.
1102    pub fn set_measured_size(&self, size: Size) {
1103        self.layout_state.borrow_mut().set_size(size);
1104    }
1105
1106    /// Updates the position of this node. Called during placement.
1107    /// [`LayoutState::place`] self-reports actual moves to the scene phase.
1108    pub fn set_position(&self, position: Point) {
1109        self.layout_state.borrow_mut().place(position);
1110    }
1111
1112    /// Records the content offset (e.g. from padding).
1113    pub fn set_content_offset(&self, offset: Point) {
1114        self.layout_state.borrow_mut().set_content_offset(offset);
1115    }
1116
1117    /// Clears the is_placed flag. Called at the start of a layout pass.
1118    pub fn clear_placed(&self) {
1119        self.layout_state.borrow_mut().clear_placed();
1120    }
1121
1122    fn note_semantics_layout_change(&self) {
1123        if let Ok(mut state) = self.layout_state.try_borrow_mut() {
1124            state.note_semantics_change();
1125        }
1126    }
1127
1128    pub fn semantics_configuration(&self) -> Option<SemanticsConfiguration> {
1129        crate::modifier::collect_semantics_from_chain(self.modifier_chain.chain())
1130    }
1131
1132    /// Drops the cached reach and queues the node for the modal count.
1133    fn forget_semantics_reach(&self) {
1134        self.semantics_reach.set(None);
1135        crate::modal_nodes::reach_changed(self.id.get());
1136    }
1137
1138    /// Whether this node's modifiers make it modal or hidden.
1139    pub fn semantics_reach(&self) -> cranpose_foundation::SemanticsReach {
1140        // A chain without semantics reaches nothing, known without touching it.
1141        if !self
1142            .modifier_capabilities()
1143            .contains(NodeCapabilities::SEMANTICS)
1144        {
1145            return cranpose_foundation::SemanticsReach::default();
1146        }
1147        if let Some(reach) = self.semantics_reach.get() {
1148            return reach;
1149        }
1150        let reach = crate::modifier::semantics_reach_of_chain(self.modifier_chain.chain());
1151        self.semantics_reach.set(Some(reach));
1152        reach
1153    }
1154
1155    pub(crate) fn modifier_chain(&self) -> &ModifierChainHandle {
1156        &self.modifier_chain
1157    }
1158
1159    /// Access the text field modifier node (if present) with a mutable callback.
1160    ///
1161    /// This is used for keyboard event dispatch to text fields.
1162    /// Returns `None` if no text field modifier is found in the chain.
1163    pub fn with_text_field_modifier_mut<R>(
1164        &mut self,
1165        f: impl FnMut(&mut crate::TextFieldModifierNode) -> R,
1166    ) -> Option<R> {
1167        self.modifier_chain.with_text_field_modifier_mut(f)
1168    }
1169
1170    /// Returns the handle to the shared layout state, which layout clones
1171    /// to update the state without borrowing the Applier.
1172    pub fn layout_state_handle(&self) -> &Rc<RefCell<LayoutState>> {
1173        &self.layout_state
1174    }
1175
1176    pub(crate) fn coordinator_geometry(&self) -> &crate::modifier::CoordinatorGeometry {
1177        &self.coordinator_geometry
1178    }
1179
1180    pub(crate) fn layout_runtime_state_handle(&self) -> Rc<RefCell<LayoutRuntimeState>> {
1181        self.layout_runtime_state.clone()
1182    }
1183
1184    #[cfg(test)]
1185    pub(crate) fn layout_runtime_debug_stats(&self) -> LayoutRuntimeDebugStats {
1186        self.layout_runtime_state.borrow().debug_stats()
1187    }
1188}
1189impl Clone for LayoutNode {
1190    fn clone(&self) -> Self {
1191        let mut node = Self {
1192            #[cfg(feature = "inspection")]
1193            source_trace: self.source_trace.clone(),
1194            modifier: self.modifier.clone(),
1195            modifier_chain: ModifierChainHandle::for_layout_direction(
1196                self.modifier_chain.layout_direction(),
1197            ),
1198            measure_policy: self.measure_policy.clone(),
1199            density: self.density,
1200            children: self.children.clone(),
1201            cache: self.cache.clone(),
1202            needs_measure: Cell::new(self.needs_measure.get()),
1203            needs_layout: Cell::new(self.needs_layout.get()),
1204            descendant_dirt: Cell::new(self.descendant_dirt.get()),
1205            parent_data: Cell::new(self.parent_data.get()),
1206            needs_semantics: Cell::new(self.needs_semantics.get()),
1207            descendant_needs_semantics: Cell::new(self.descendant_needs_semantics.get()),
1208            semantics_reach: Cell::new(None),
1209            needs_redraw: Cell::new(self.needs_redraw.get()),
1210            needs_pointer_pass: Cell::new(self.needs_pointer_pass.get()),
1211            needs_focus_sync: Cell::new(self.needs_focus_sync.get()),
1212            parent: Cell::new(self.parent.get()),
1213            folded_parent: Cell::new(self.folded_parent.get()),
1214            id: Cell::new(None),
1215            owner_context_id: Cell::new(None),
1216            debug_modifiers: Cell::new(self.debug_modifiers.get()),
1217            is_virtual: self.is_virtual,
1218            virtual_children_count: Cell::new(self.virtual_children_count.get()),
1219            modifier_slices_snapshot: RefCell::new(Rc::default()),
1220            modifier_slices_dirty: Cell::new(true),
1221            layout_state: self.layout_state.clone(),
1222            layout_runtime_state: self.layout_runtime_state.clone(),
1223            coordinator_geometry: Rc::clone(&self.coordinator_geometry),
1224        };
1225        node.sync_modifier_chain(false);
1226        node
1227    }
1228}
1229
1230impl Node for LayoutNode {
1231    fn mount(&mut self) {
1232        let (chain, mut context) = self.modifier_chain.chain_and_context_mut();
1233        chain.repair_chain();
1234        chain.attach_nodes(&mut *context);
1235        crate::modal_nodes::reach_changed(self.id.get());
1236    }
1237
1238    fn unmount(&mut self) {
1239        self.modifier_chain.chain_mut().detach_nodes();
1240    }
1241
1242    fn set_node_id(&mut self, id: NodeId) {
1243        LayoutNode::set_node_id(self, id);
1244    }
1245
1246    fn insert_child(&mut self, child: NodeId) -> bool {
1247        if self.children.contains(&child) {
1248            return false;
1249        }
1250        if is_virtual_node(child) {
1251            let count = self.virtual_children_count.get();
1252            self.virtual_children_count.set(count + 1);
1253        }
1254        self.children.push(child);
1255        self.cache.clear();
1256        self.mark_needs_measure();
1257        self.note_semantics_layout_change();
1258        true
1259    }
1260
1261    fn remove_child(&mut self, child: NodeId) -> bool {
1262        let before = self.children.len();
1263        self.children.retain(|&id| id != child);
1264        let removed = self.children.len() < before;
1265        if removed {
1266            if is_virtual_node(child) {
1267                let count = self.virtual_children_count.get();
1268                if count > 0 {
1269                    self.virtual_children_count.set(count - 1);
1270                }
1271            }
1272            self.cache.clear();
1273            self.mark_needs_measure();
1274            self.note_semantics_layout_change();
1275        }
1276        removed
1277    }
1278
1279    fn move_child(&mut self, from: usize, to: usize) {
1280        if from == to || from >= self.children.len() {
1281            return;
1282        }
1283        let child = self.children.remove(from);
1284        let target = to.min(self.children.len());
1285        self.children.insert(target, child);
1286        self.cache.clear();
1287        self.mark_needs_measure();
1288        self.note_semantics_layout_change();
1289    }
1290
1291    fn update_children(&mut self, children: &[NodeId]) {
1292        self.children.clear();
1293        self.children.extend_from_slice(children);
1294        self.cache.clear();
1295        self.mark_needs_measure();
1296        self.note_semantics_layout_change();
1297    }
1298
1299    fn collect_children_into(&self, out: &mut smallvec::SmallVec<[NodeId; 8]>) {
1300        out.clear();
1301        out.extend_from_slice(&self.children);
1302    }
1303
1304    fn owned_child_index(&self, child: NodeId) -> Option<usize> {
1305        self.children.iter().position(|&id| id == child)
1306    }
1307
1308    fn on_attached_to_parent(&mut self, parent: NodeId) {
1309        self.set_parent(parent);
1310    }
1311
1312    fn on_removed_from_parent(&mut self) {
1313        self.clear_parent();
1314    }
1315
1316    fn parent(&self) -> Option<NodeId> {
1317        self.parent.get()
1318    }
1319
1320    fn mark_needs_layout(&self) {
1321        self.needs_layout.set(true);
1322    }
1323
1324    fn needs_layout(&self) -> bool {
1325        self.needs_layout.get()
1326    }
1327
1328    fn mark_needs_measure(&self) {
1329        self.needs_measure.set(true);
1330        self.needs_layout.set(true);
1331    }
1332
1333    fn needs_measure(&self) -> bool {
1334        self.needs_measure.get()
1335    }
1336
1337    fn mark_descendant_needs_layout(&self, measure: bool) {
1338        self.descendant_dirt
1339            .set(self.descendant_dirt.get().marked(measure));
1340        if measure {
1341            self.cache.forget_intrinsics();
1342        }
1343    }
1344
1345    fn descendant_needs_layout(&self) -> bool {
1346        self.descendant_dirt.get().layout
1347    }
1348
1349    fn is_virtual(&self) -> bool {
1350        self.is_virtual
1351    }
1352
1353    fn descendant_needs_measure(&self) -> bool {
1354        self.descendant_dirt.get().measure
1355    }
1356
1357    fn mark_needs_semantics(&self) {
1358        self.needs_semantics.set(true);
1359        self.forget_semantics_reach();
1360    }
1361
1362    fn mark_descendant_needs_semantics(&self) {
1363        self.descendant_needs_semantics.set(true);
1364    }
1365
1366    fn needs_semantics(&self) -> bool {
1367        LayoutNode::needs_semantics(self)
1368    }
1369
1370    fn set_parent_for_bubbling(&mut self, parent: NodeId) {
1371        if self.parent.get().is_none() {
1372            self.parent.set(Some(parent));
1373        }
1374    }
1375
1376    fn recycle_key(&self) -> Option<TypeId> {
1377        Some(TypeId::of::<Self>())
1378    }
1379
1380    fn recycle_pool_limit(&self) -> Option<usize> {
1381        Some(RECYCLED_LAYOUT_NODE_POOL_LIMIT)
1382    }
1383
1384    fn prepare_for_recycle(&mut self) {
1385        *self = Self::new_recycled_shell(self.is_virtual);
1386    }
1387
1388    fn rehouse_for_recycle(&self) -> Option<Box<dyn cranpose_core::Node>> {
1389        Some(Box::new(Self::new_recycled_shell(self.is_virtual)))
1390    }
1391
1392    fn rehouse_for_live_compaction(&mut self) -> Option<Box<dyn cranpose_core::Node>> {
1393        let mut previous = std::mem::replace(self, Self::new_recycled_shell(self.is_virtual));
1394        let node_id = previous.id.replace(None);
1395        let parent = previous.parent.get();
1396        let folded_parent = previous.folded_parent.get();
1397        let debug_modifiers = previous.debug_modifiers.get();
1398        let density = previous.density;
1399        let layout_direction = previous.modifier_chain.layout_direction();
1400        let needs_measure = previous.needs_measure.get();
1401        let needs_layout = previous.needs_layout.get();
1402        let needs_semantics = previous.needs_semantics.get();
1403        let descendant_needs_semantics = previous.descendant_needs_semantics.get();
1404        let needs_redraw = previous.needs_redraw.get();
1405        let needs_pointer_pass = previous.needs_pointer_pass.get();
1406        let needs_focus_sync = previous.needs_focus_sync.get();
1407        let virtual_children_count = previous.virtual_children_count.get();
1408        let children = previous.children.to_vec();
1409        let modifier = previous.modifier.rehouse_for_live_compaction();
1410        let measure_policy = previous.measure_policy.clone();
1411        let layout_state = previous.layout_state.clone();
1412        let layout_runtime_state = previous.layout_runtime_state.clone();
1413        let coordinator_geometry = Rc::clone(&previous.coordinator_geometry);
1414
1415        previous.modifier_chain.chain_mut().detach_nodes();
1416
1417        let mut compact = Self::new_with_virtual(modifier, measure_policy, previous.is_virtual);
1418        compact.density = density;
1419        compact
1420            .modifier_chain
1421            .set_layout_direction(layout_direction);
1422        compact.children = children;
1423        #[cfg(feature = "inspection")]
1424        {
1425            compact.source_trace = previous.source_trace.clone();
1426        }
1427        compact.parent.set(parent);
1428        compact.folded_parent.set(folded_parent);
1429        compact.id.set(node_id);
1430        compact.debug_modifiers.set(debug_modifiers);
1431        compact.needs_measure.set(needs_measure);
1432        compact.needs_layout.set(needs_layout);
1433        compact.needs_semantics.set(needs_semantics);
1434        compact
1435            .descendant_needs_semantics
1436            .set(descendant_needs_semantics);
1437        compact.needs_redraw.set(needs_redraw);
1438        compact.needs_pointer_pass.set(needs_pointer_pass);
1439        compact.needs_focus_sync.set(needs_focus_sync);
1440        compact.virtual_children_count.set(virtual_children_count);
1441        compact.layout_state = layout_state;
1442        compact.layout_runtime_state = layout_runtime_state;
1443        compact.coordinator_geometry = coordinator_geometry;
1444        compact.sync_modifier_chain(false);
1445        if let Some(id) = node_id {
1446            let owner_context_id = register_layout_node(id, &compact);
1447            compact.owner_context_id.set(Some(owner_context_id));
1448        }
1449
1450        Some(Box::new(compact))
1451    }
1452}
1453
1454impl Drop for LayoutNode {
1455    fn drop(&mut self) {
1456        if let (Some(id), Some(owner_context_id)) = (self.id.get(), self.owner_context_id.get()) {
1457            unregister_layout_node(owner_context_id, id);
1458        }
1459    }
1460}
1461
1462const MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY: usize = 128;
1463const VIRTUAL_NODE_ID_START: NodeId = 0xC0000000;
1464
1465#[cfg(test)]
1466#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1467struct LayoutNodeRegistryDebugStats {
1468    len: usize,
1469    capacity: usize,
1470}
1471
1472struct LayoutNodeRegistryEntry {
1473    parent: Option<NodeId>,
1474    modifier_child_capabilities: NodeCapabilities,
1475    modifier_locals: Option<ModifierLocalsHandle>,
1476    is_virtual: bool,
1477}
1478
1479pub(crate) struct LayoutNodeRegistryState {
1480    entries: RefCell<HashMap<NodeId, LayoutNodeRegistryEntry>>,
1481    virtual_node_id_counter: Cell<NodeId>,
1482}
1483
1484impl LayoutNodeRegistryState {
1485    pub(crate) fn new() -> Self {
1486        Self {
1487            entries: RefCell::new(HashMap::new()),
1488            virtual_node_id_counter: Cell::new(VIRTUAL_NODE_ID_START),
1489        }
1490    }
1491
1492    fn register(&self, id: NodeId, node: &LayoutNode) {
1493        self.entries.borrow_mut().insert(
1494            id,
1495            LayoutNodeRegistryEntry {
1496                parent: node.parent(),
1497                modifier_child_capabilities: node.modifier_child_capabilities(),
1498                modifier_locals: node.modifier_locals_handle(),
1499                is_virtual: node.is_virtual(),
1500            },
1501        );
1502    }
1503
1504    fn unregister(&self, id: NodeId) {
1505        let mut entries = self.entries.borrow_mut();
1506        entries.remove(&id);
1507        let should_shrink = (entries.len() <= MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY
1508            && entries.capacity() > MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY)
1509            || entries.capacity()
1510                > entries
1511                    .len()
1512                    .max(MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY)
1513                    .saturating_mul(4);
1514        if should_shrink {
1515            let retained = entries
1516                .len()
1517                .max(MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY);
1518            let mut rebuilt = HashMap::new();
1519            rebuilt.reserve(retained);
1520            rebuilt.extend(entries.drain());
1521            *entries = rebuilt;
1522        }
1523    }
1524
1525    fn update_entry(
1526        &self,
1527        id: NodeId,
1528        parent: Option<NodeId>,
1529        modifier_child_capabilities: NodeCapabilities,
1530        modifier_locals: Option<ModifierLocalsHandle>,
1531    ) {
1532        if let Some(entry) = self.entries.borrow_mut().get_mut(&id) {
1533            entry.parent = parent;
1534            entry.modifier_child_capabilities = modifier_child_capabilities;
1535            entry.modifier_locals = modifier_locals;
1536        }
1537    }
1538
1539    #[cfg(test)]
1540    fn stats(&self) -> LayoutNodeRegistryDebugStats {
1541        let entries = self.entries.borrow();
1542        LayoutNodeRegistryDebugStats {
1543            len: entries.len(),
1544            capacity: entries.capacity(),
1545        }
1546    }
1547
1548    fn is_virtual_node(&self, id: NodeId) -> bool {
1549        self.entries
1550            .borrow()
1551            .get(&id)
1552            .is_some_and(|entry| entry.is_virtual)
1553    }
1554
1555    fn allocate_virtual_node_id(&self) -> NodeId {
1556        let id = self.virtual_node_id_counter.get();
1557        self.virtual_node_id_counter.set(id.wrapping_add(1));
1558        id
1559    }
1560
1561    fn resolve_modifier_local_from_parent_chain(
1562        &self,
1563        start: Option<NodeId>,
1564        token: &ModifierLocalToken,
1565    ) -> Option<ResolvedModifierLocal> {
1566        let mut current = start;
1567        while let Some(parent_id) = current {
1568            let (next_parent, resolved) = {
1569                let entries = self.entries.borrow();
1570                if let Some(entry) = entries.get(&parent_id) {
1571                    let resolved = entry
1572                        .modifier_child_capabilities
1573                        .contains(NodeCapabilities::MODIFIER_LOCALS)
1574                        .then_some(entry.modifier_locals.as_ref())
1575                        .flatten()
1576                        .and_then(|locals| locals.borrow().resolve(token))
1577                        .map(|value| value.with_source(ModifierLocalSource::Ancestor));
1578                    (entry.parent, resolved)
1579                } else {
1580                    (None, None)
1581                }
1582            };
1583            if let Some(value) = resolved {
1584                return Some(value);
1585            }
1586            current = next_parent;
1587        }
1588        None
1589    }
1590}
1591
1592pub(crate) fn register_layout_node(
1593    id: NodeId,
1594    node: &LayoutNode,
1595) -> crate::render_state::AppContextId {
1596    let owner_context_id = crate::render_state::current_app_context_id();
1597    let _ = crate::render_state::with_layout_node_registry_by_app_context(
1598        owner_context_id,
1599        |registry| {
1600            registry.register(id, node);
1601        },
1602    );
1603    owner_context_id
1604}
1605
1606pub(crate) fn unregister_layout_node(
1607    owner_context_id: crate::render_state::AppContextId,
1608    id: NodeId,
1609) {
1610    let _ = crate::render_state::with_layout_node_registry_by_app_context(
1611        owner_context_id,
1612        |registry| {
1613            registry.unregister(id);
1614        },
1615    );
1616}
1617
1618#[cfg(test)]
1619fn layout_node_registry_stats() -> LayoutNodeRegistryDebugStats {
1620    crate::render_state::with_layout_node_registry(LayoutNodeRegistryState::stats)
1621}
1622
1623pub(crate) fn is_virtual_node(id: NodeId) -> bool {
1624    crate::render_state::with_layout_node_registry(|registry| registry.is_virtual_node(id))
1625}
1626
1627pub(crate) fn allocate_virtual_node_id() -> NodeId {
1628    crate::render_state::with_layout_node_registry(
1629        LayoutNodeRegistryState::allocate_virtual_node_id,
1630    )
1631}
1632
1633fn resolve_modifier_local_from_parent_chain(
1634    start: Option<NodeId>,
1635    token: &ModifierLocalToken,
1636) -> Option<ResolvedModifierLocal> {
1637    crate::render_state::with_layout_node_registry(|registry| {
1638        registry.resolve_modifier_local_from_parent_chain(start, token)
1639    })
1640}
1641
1642#[cfg(test)]
1643#[path = "tests/layout_node_tests.rs"]
1644mod tests;