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 id or none in one word, where `Cell<Option<NodeId>>` takes two: a
450/// layout node keeps three, and the 24 bytes kept it out of jemalloc's
451/// 640-byte size class.
452struct NodeIdCell(Cell<NodeId>);
453
454/// The id a [`NodeIdCell`] holds for none: no node gets it, as ids index
455/// the applier's nodes and virtual ids count up from `VIRTUAL_NODE_ID_START`.
456const NO_NODE_ID: NodeId = NodeId::MAX;
457
458impl NodeIdCell {
459    fn new(id: Option<NodeId>) -> Self {
460        Self(Cell::new(id.unwrap_or(NO_NODE_ID)))
461    }
462
463    fn get(&self) -> Option<NodeId> {
464        let id = self.0.get();
465        (id != NO_NODE_ID).then_some(id)
466    }
467
468    fn set(&self, id: Option<NodeId>) {
469        debug_assert_ne!(id, Some(NO_NODE_ID), "no node takes the none id");
470        self.0.set(id.unwrap_or(NO_NODE_ID));
471    }
472
473    fn replace(&self, id: Option<NodeId>) -> Option<NodeId> {
474        let previous = self.get();
475        self.set(id);
476        previous
477    }
478}
479
480/// A node of the layout tree.
481///
482/// Its fields keep the order they are declared in: what a layout pass reads
483/// for every child it binds comes first and fits one cache line, then what
484/// measuring the node reads, then what composition reads. Layout reads
485/// thousands of nodes a frame, and on a phone its cost is the lines it loads.
486#[repr(C)]
487pub struct LayoutNode {
488    cache: LayoutNodeCacheHandles,
489    layout_state: Rc<RefCell<LayoutState>>,
490    layout_runtime_state: Rc<RefCell<LayoutRuntimeState>>,
491    /// The actual children of this node (folded view - includes virtual nodes as-is)
492    pub children: Vec<NodeId>,
493    /// What the chain tells the parent's policy about this node: its
494    /// weight and alignments, kept beside the binding fields.
495    parent_data: Cell<cranpose_ui_layout::ParentData>,
496    needs_measure: Cell<bool>,
497    needs_layout: Cell<bool>,
498    /// A node below this one needs layout or measure.
499    descendant_dirt: Cell<DescendantDirt>,
500
501    pub measure_policy: Rc<dyn MeasurePolicy>,
502    /// Where the chain's layout modifiers put their content, written by
503    /// layout and read by the draws and text the slices collect.
504    coordinator_geometry: Rc<crate::modifier::CoordinatorGeometry>,
505    density: crate::density::Density,
506    is_virtual: bool,
507    needs_semantics: Cell<bool>,
508    /// The semantics tree has to read this node again, though its own
509    /// semantics are unchanged: a node below it changed, or its placement
510    /// or children did.
511    descendant_needs_semantics: Cell<bool>,
512    needs_redraw: Cell<bool>,
513    needs_pointer_pass: Cell<bool>,
514    needs_focus_sync: Cell<bool>,
515    modifier_slices_dirty: Cell<bool>,
516    debug_modifiers: Cell<bool>,
517
518    id: NodeIdCell,
519    parent: NodeIdCell,
520    folded_parent: NodeIdCell,
521    modifier_slices_snapshot: RefCell<Rc<ModifierNodeSlices>>,
522
523    /// The chain's modal and hidden flags, read by the modal count and the
524    /// modal walk: dropped whenever the chain syncs or semantics are
525    /// invalidated, the two ways its semantics change.
526    semantics_reach: Cell<Option<cranpose_foundation::SemanticsReach>>,
527    owner_context_id: Cell<Option<crate::render_state::AppContextId>>,
528    modifier_chain: ModifierChainHandle,
529    pub modifier: Modifier,
530    /// Composable definitions responsible for this node, captured only for inspection builds.
531    #[cfg(feature = "inspection")]
532    pub source_trace: Rc<[cranpose_core::source_trace::SourceLocation]>,
533}
534
535pub(crate) const RECYCLED_LAYOUT_NODE_POOL_LIMIT: usize = 128;
536
537thread_local! {
538    static EMPTY_MEASURE_POLICY: Rc<dyn MeasurePolicy> =
539        Rc::new(crate::layout::policies::EmptyMeasurePolicy);
540}
541
542fn empty_measure_policy() -> Rc<dyn MeasurePolicy> {
543    EMPTY_MEASURE_POLICY.with(Rc::clone)
544}
545
546impl LayoutNode {
547    pub fn new(modifier: Modifier, measure_policy: Rc<dyn MeasurePolicy>) -> Self {
548        Self::new_with_virtual(modifier, measure_policy, false)
549    }
550
551    /// Create a virtual LayoutNode for subcomposition slot containers.
552    /// Virtual nodes are transparent - their children are flattened into parent's children list.
553    pub fn new_virtual() -> Self {
554        Self::new_with_virtual(Modifier::empty(), empty_measure_policy(), true)
555    }
556
557    fn new_recycled_shell(is_virtual: bool) -> Self {
558        let mut shell =
559            Self::new_with_virtual(Modifier::empty(), empty_measure_policy(), is_virtual);
560        shell.needs_measure.set(false);
561        shell.needs_layout.set(false);
562        shell.needs_semantics.set(false);
563        shell.descendant_needs_semantics.set(false);
564        shell.needs_redraw.set(false);
565        shell.needs_pointer_pass.set(false);
566        shell.needs_focus_sync.set(false);
567        shell.parent.set(None);
568        shell.folded_parent.set(None);
569        shell.id.set(None);
570        shell.owner_context_id.set(None);
571        shell.debug_modifiers.set(false);
572        shell.modifier_slices_dirty = Cell::new(true);
573        shell
574    }
575
576    fn new_with_virtual(
577        modifier: Modifier,
578        measure_policy: Rc<dyn MeasurePolicy>,
579        is_virtual: bool,
580    ) -> Self {
581        let layout_runtime_state = Rc::new(RefCell::new(LayoutRuntimeState::new(Rc::clone(
582            &measure_policy,
583        ))));
584        let mut node = Self {
585            #[cfg(feature = "inspection")]
586            source_trace: cranpose_core::source_trace::current_source_trace(),
587            modifier,
588            modifier_chain: ModifierChainHandle::new(),
589            measure_policy,
590            density: crate::density::Density::default(),
591            children: Vec::new(),
592            cache: LayoutNodeCacheHandles::default(),
593            needs_measure: Cell::new(true),
594            needs_layout: Cell::new(true),
595            descendant_dirt: Cell::default(),
596            parent_data: Cell::default(),
597            needs_semantics: Cell::new(true),
598            descendant_needs_semantics: Cell::new(false),
599            semantics_reach: Cell::new(None),
600            needs_redraw: Cell::new(true),
601            needs_pointer_pass: Cell::new(false),
602            needs_focus_sync: Cell::new(false),
603            parent: NodeIdCell::new(None),
604            folded_parent: NodeIdCell::new(None),
605            id: NodeIdCell::new(None),
606            owner_context_id: Cell::new(None),
607            debug_modifiers: Cell::new(false),
608            is_virtual,
609            modifier_slices_snapshot: RefCell::new(Rc::default()),
610            modifier_slices_dirty: Cell::new(true),
611            layout_state: Rc::new(RefCell::new(LayoutState::default())),
612            layout_runtime_state,
613            coordinator_geometry: Rc::default(),
614        };
615        node.sync_modifier_chain(false);
616        node
617    }
618
619    pub fn set_modifier(&mut self, modifier: Modifier) {
620        #[cfg(feature = "inspection")]
621        {
622            let trace = cranpose_core::source_trace::current_source_trace();
623            if !trace.is_empty() {
624                self.source_trace = trace;
625            }
626        }
627        // An equal modifier leaves every element's node as it was. Only a
628        // chain reading modifier locals resyncs, since its parent may now
629        // provide others.
630        if self.modifier == modifier
631            && !self
632                .modifier_capabilities()
633                .contains(NodeCapabilities::MODIFIER_LOCALS)
634        {
635            return;
636        }
637        // A text that changed and nothing else, as a ticker's does, keeps
638        // the slices the chain gave: their text reads the layout the update
639        // changes in place.
640        let text_only = self
641            .modifier
642            .differs_only_in::<crate::text_modifier_node::TextModifierElement>(&modifier);
643        let modifier_changed = text_only || !self.modifier.structural_eq(&modifier);
644        self.modifier = modifier;
645        self.sync_modifier_chain(text_only);
646        if modifier_changed {
647            self.cache.clear();
648            self.request_semantics_update();
649        }
650    }
651
652    /// Reconciles the chain with the node's modifier. `text_only` says the
653    /// modifier changed only in its text elements: when the chain updates
654    /// them in place, the current slices are kept.
655    fn sync_modifier_chain(&mut self, text_only: bool) {
656        let prev_caps = self.modifier_capabilities();
657        let start_parent = self.parent();
658        let mut resolver = move |token: &ModifierLocalToken| {
659            resolve_modifier_local_from_parent_chain(start_parent, token)
660        };
661        self.modifier_chain
662            .set_debug_logging(self.debug_modifiers.get());
663        self.modifier_chain.set_node_id(self.id.get());
664        let in_place = text_only
665            && self
666                .modifier_chain
667                .update_elements_in_place::<crate::text_modifier_node::TextModifierElement>(
668                    &self.modifier,
669                );
670        let modifier_local_invalidations = if in_place {
671            ModifierInvalidations::new()
672        } else {
673            let invalidations = self
674                .modifier_chain
675                .update_with_resolver(&self.modifier, &mut resolver);
676            self.refresh_parent_data();
677            invalidations
678        };
679        if prev_caps.contains(NodeCapabilities::WINDOW_ROOT)
680            != self
681                .modifier_capabilities()
682                .contains(NodeCapabilities::WINDOW_ROOT)
683        {
684            self.note_semantics_layout_change();
685        }
686        // A text element reaches nothing, so an update in place leaves the
687        // chain's reach as it was, and the modal count does not read it again.
688        if !in_place {
689            self.forget_semantics_reach();
690        }
691        let keep_slices = in_place && !self.modifier_slices_dirty.get();
692        if !keep_slices {
693            self.modifier_slices_dirty.set(true);
694        }
695
696        let mut invalidations = self.modifier_chain.take_invalidations();
697        invalidations.extend(modifier_local_invalidations);
698        self.dispatch_modifier_invalidations_with_prev(&invalidations, prev_caps, keep_slices);
699        // An update in place leaves the node's parent, capabilities and
700        // modifier locals as the registry holds them.
701        if !in_place {
702            self.refresh_registry_state();
703        }
704    }
705
706    fn update_modifier_slices_cache(&self) {
707        let mut snapshot = self.modifier_slices_snapshot.borrow_mut();
708        crate::modifier::collect_modifier_slices_into_shared(
709            self.modifier_chain.chain(),
710            &mut snapshot,
711            &self.coordinator_geometry,
712            self.density.density(),
713        );
714        self.modifier_slices_dirty.set(false);
715    }
716
717    /// Whether the modifier slices are built and current.
718    #[cfg(test)]
719    pub(crate) fn modifier_slices_ready(&self) -> bool {
720        !self.modifier_slices_dirty.get()
721    }
722
723    pub(crate) fn mark_modifier_slices_dirty(&self) {
724        self.modifier_slices_dirty.set(true);
725    }
726
727    #[cfg(test)]
728    fn dispatch_modifier_invalidations(&self, invalidations: &[ModifierInvalidation]) {
729        self.dispatch_modifier_invalidations_with_prev(
730            invalidations,
731            NodeCapabilities::empty(),
732            false,
733        );
734    }
735
736    /// Applies `invalidations` to the node. Each marks the slices for a
737    /// rebuild unless `keep_slices`.
738    fn dispatch_modifier_invalidations_with_prev(
739        &self,
740        invalidations: &[ModifierInvalidation],
741        prev_caps: NodeCapabilities,
742        keep_slices: bool,
743    ) {
744        let curr_caps = self.modifier_capabilities();
745        for invalidation in invalidations {
746            if !keep_slices {
747                self.modifier_slices_dirty.set(true);
748            }
749            let has_capability =
750                |capability| curr_caps.contains(capability) || prev_caps.contains(capability);
751            match invalidation.kind() {
752                InvalidationKind::Layout => {
753                    if has_capability(NodeCapabilities::LAYOUT) {
754                        self.mark_needs_measure();
755                        if let Some(id) = self.id.get() {
756                            log_layout_invalidation_dispatch(
757                                id,
758                                invalidation,
759                                curr_caps,
760                                prev_caps,
761                                &self.modifier,
762                            );
763                            let inside_composition =
764                                cranpose_core::composer_context::try_with_composer(|_| ())
765                                    .is_some();
766                            if inside_composition {
767                                cranpose_core::bubble_measure_dirty_in_composer(id);
768                            } else {
769                                crate::schedule_layout_repass(id);
770                            }
771                        }
772                    }
773                }
774                InvalidationKind::Draw => {
775                    if has_capability(NodeCapabilities::DRAW)
776                        || invalidation.capabilities().contains(NodeCapabilities::DRAW)
777                    {
778                        self.mark_needs_redraw();
779                    }
780                }
781                InvalidationKind::PointerInput => {
782                    if has_capability(NodeCapabilities::POINTER_INPUT) {
783                        self.mark_needs_pointer_pass();
784                        crate::request_pointer_invalidation();
785                        if let Some(id) = self.id.get() {
786                            crate::schedule_pointer_repass(id);
787                        }
788                    }
789                }
790                InvalidationKind::Semantics => {
791                    self.request_semantics_update();
792                }
793                InvalidationKind::Focus => {
794                    if has_capability(NodeCapabilities::FOCUS) {
795                        self.mark_needs_focus_sync();
796                        crate::request_focus_invalidation();
797                        if let Some(id) = self.id.get() {
798                            crate::schedule_focus_invalidation(id);
799                        }
800                    }
801                }
802            }
803        }
804    }
805
806    /// The grid this node was composed against.
807    pub fn density(&self) -> crate::density::Density {
808        self.density
809    }
810
811    /// Records the grid the composition provided, re-measuring if it moved.
812    pub fn set_density(&mut self, density: crate::density::Density) {
813        if self.density != density {
814            self.density = density;
815            self.cache.clear();
816            self.modifier_slices_dirty.set(true);
817            self.mark_needs_measure();
818        }
819    }
820
821    /// Updates relative modifier placement for this node's composition scope.
822    pub fn set_layout_direction(&mut self, direction: crate::LayoutDirection) {
823        if self.modifier_chain.set_layout_direction(direction) {
824            self.refresh_parent_data();
825            self.cache.clear();
826            self.modifier_slices_dirty.set(true);
827            self.mark_needs_measure();
828        }
829    }
830
831    pub fn set_measure_policy(&mut self, policy: Rc<dyn MeasurePolicy>) {
832        if !Rc::ptr_eq(&self.measure_policy, &policy) {
833            self.measure_policy = policy;
834            self.cache.clear();
835            self.mark_needs_measure();
836            if let Some(id) = self.id.get() {
837                cranpose_core::bubble_measure_dirty_in_composer(id);
838            }
839        }
840    }
841
842    /// Mark this node as needing measure. Also marks it as needing layout.
843    pub fn mark_needs_measure(&self) {
844        self.needs_measure.set(true);
845        self.needs_layout.set(true);
846    }
847
848    /// Mark this node as needing layout (but not necessarily measure).
849    pub fn mark_needs_layout(&self) {
850        self.needs_layout.set(true);
851    }
852
853    /// Mark this node as needing redraw without forcing measure/layout.
854    pub fn mark_needs_redraw(&self) {
855        self.needs_redraw.set(true);
856        if let Some(id) = self.id.get() {
857            crate::schedule_draw_repass(id);
858        }
859        crate::request_render_invalidation();
860    }
861
862    /// Check if this node needs measure.
863    pub fn needs_measure(&self) -> bool {
864        self.needs_measure.get()
865    }
866
867    /// Check if this node needs layout.
868    pub fn needs_layout(&self) -> bool {
869        self.needs_layout.get()
870    }
871
872    /// Mark this node as needing semantics recomputation.
873    pub fn mark_needs_semantics(&self) {
874        self.needs_semantics.set(true);
875        self.forget_semantics_reach();
876    }
877
878    pub(crate) fn clear_needs_semantics(&self) {
879        self.needs_semantics.set(false);
880        self.descendant_needs_semantics.set(false);
881    }
882
883    /// Returns true when this node's semantics or a descendant's need to be
884    /// recomputed.
885    pub fn needs_semantics(&self) -> bool {
886        self.needs_semantics.get() || self.descendant_needs_semantics.get()
887    }
888
889    /// Whether this node's own semantics changed since the tree last read
890    /// them, as opposed to only a descendant's.
891    pub(crate) fn semantics_changed(&self) -> bool {
892        self.needs_semantics.get()
893    }
894
895    /// Returns true when this node requested a redraw since the last render pass.
896    pub fn needs_redraw(&self) -> bool {
897        self.needs_redraw.get()
898    }
899
900    pub fn clear_needs_redraw(&self) {
901        self.needs_redraw.set(false);
902    }
903
904    fn request_semantics_update(&self) {
905        let already_dirty = self.needs_semantics.replace(true);
906        if already_dirty {
907            return;
908        }
909
910        if let Some(id) = self.id.get() {
911            cranpose_core::queue_semantics_invalidation(id);
912        }
913    }
914
915    pub(crate) fn clear_needs_measure(&self) {
916        self.needs_measure.set(false);
917    }
918
919    /// Clears the node's layout flag and its descendants': a layout pass
920    /// visited them.
921    pub(crate) fn clear_needs_layout(&self) {
922        self.needs_layout.set(false);
923        self.descendant_dirt.set(DescendantDirt::default());
924    }
925
926    /// Marks this node as needing a fresh pointer-input pass.
927    pub fn mark_needs_pointer_pass(&self) {
928        self.needs_pointer_pass.set(true);
929    }
930
931    /// Returns true when pointer-input state needs to be recomputed.
932    pub fn needs_pointer_pass(&self) -> bool {
933        self.needs_pointer_pass.get()
934    }
935
936    /// Clears the pointer-input dirty flag after hosts service it.
937    pub fn clear_needs_pointer_pass(&self) {
938        self.needs_pointer_pass.set(false);
939    }
940
941    /// Marks this node as needing a focus synchronization.
942    pub fn mark_needs_focus_sync(&self) {
943        self.needs_focus_sync.set(true);
944    }
945
946    /// Returns true when focus state needs to be synchronized.
947    pub fn needs_focus_sync(&self) -> bool {
948        self.needs_focus_sync.get()
949    }
950
951    /// Clears the focus dirty flag after the focus manager processes it.
952    pub fn clear_needs_focus_sync(&self) {
953        self.needs_focus_sync.set(false);
954    }
955
956    /// Set this node's ID (called by applier after creation).
957    pub fn set_node_id(&mut self, id: NodeId) {
958        if let Some(existing) = self.id.replace(Some(id))
959            && let Some(owner_context_id) = self.owner_context_id.take()
960        {
961            unregister_layout_node(owner_context_id, existing);
962        }
963        self.layout_state.borrow_mut().set_node_id(id);
964        let owner_context_id = register_layout_node(id, self);
965        self.owner_context_id.set(Some(owner_context_id));
966        self.refresh_registry_state();
967
968        self.modifier_chain.set_node_id(Some(id));
969        let invalidations = self.modifier_chain.take_invalidations();
970        self.dispatch_modifier_invalidations_with_prev(
971            &invalidations,
972            NodeCapabilities::empty(),
973            false,
974        );
975        // The slices carry the node's id; they are collected again when next read.
976        self.modifier_slices_dirty.set(true);
977    }
978
979    /// Get this node's ID.
980    pub fn node_id(&self) -> Option<NodeId> {
981        self.id.get()
982    }
983
984    /// Set this node's parent (called when node is added as child).
985    /// Sets both folded_parent (direct) and parent (first non-virtual ancestor for bubbling).
986    pub fn set_parent(&self, parent: NodeId) {
987        self.folded_parent.set(Some(parent));
988        self.parent.set(Some(parent));
989        self.refresh_registry_state();
990    }
991
992    /// Clear this node's parent (called when node is removed from parent).
993    pub fn clear_parent(&self) {
994        self.folded_parent.set(None);
995        self.parent.set(None);
996        self.refresh_registry_state();
997    }
998
999    /// Get this node's parent for dirty flag bubbling (may skip virtual nodes).
1000    pub fn parent(&self) -> Option<NodeId> {
1001        self.parent.get()
1002    }
1003
1004    /// Get this node's direct parent (may be a virtual node).
1005    pub fn folded_parent(&self) -> Option<NodeId> {
1006        self.folded_parent.get()
1007    }
1008
1009    pub(crate) fn cache_handles(&self) -> &LayoutNodeCacheHandles {
1010        &self.cache
1011    }
1012
1013    pub fn resolved_modifiers(&self) -> ResolvedModifiers {
1014        self.modifier_chain.resolved_modifiers()
1015    }
1016
1017    /// What the chain tells the parent's measure policy about this node.
1018    pub(crate) fn parent_data(&self) -> cranpose_ui_layout::ParentData {
1019        self.parent_data.get()
1020    }
1021
1022    /// Copies the parent data out of the chain's resolved modifiers, after
1023    /// they were computed again.
1024    fn refresh_parent_data(&self) {
1025        self.parent_data.set(crate::layout::parent_data_of(
1026            self.modifier_chain.resolved_modifiers().layout_properties(),
1027        ));
1028    }
1029
1030    pub fn modifier_capabilities(&self) -> NodeCapabilities {
1031        self.modifier_chain.capabilities()
1032    }
1033
1034    /// Whether this node's modifier chain makes it the root of a separate
1035    /// window. Its parent lays out as if it had no size and its parent's
1036    /// scene skips it; its own scene starts here.
1037    pub fn is_window_root(&self) -> bool {
1038        self.modifier_capabilities()
1039            .contains(NodeCapabilities::WINDOW_ROOT)
1040    }
1041
1042    pub fn modifier_child_capabilities(&self) -> NodeCapabilities {
1043        self.modifier_chain.aggregate_child_capabilities()
1044    }
1045
1046    pub fn set_debug_modifiers(&mut self, enabled: bool) {
1047        self.debug_modifiers.set(enabled);
1048        self.modifier_chain.set_debug_logging(enabled);
1049    }
1050
1051    pub fn debug_modifiers_enabled(&self) -> bool {
1052        self.debug_modifiers.get()
1053    }
1054
1055    /// The node's modifier locals, or `None` while its modifiers have never
1056    /// provided or read one.
1057    pub fn modifier_locals_handle(&self) -> Option<ModifierLocalsHandle> {
1058        self.modifier_chain.modifier_locals_handle()
1059    }
1060
1061    pub fn has_layout_modifier_nodes(&self) -> bool {
1062        self.modifier_capabilities()
1063            .contains(NodeCapabilities::LAYOUT)
1064    }
1065
1066    pub fn has_draw_modifier_nodes(&self) -> bool {
1067        self.modifier_capabilities()
1068            .contains(NodeCapabilities::DRAW)
1069    }
1070
1071    pub fn has_pointer_input_modifier_nodes(&self) -> bool {
1072        self.modifier_capabilities()
1073            .contains(NodeCapabilities::POINTER_INPUT)
1074    }
1075
1076    pub fn has_semantics_modifier_nodes(&self) -> bool {
1077        self.modifier_capabilities()
1078            .contains(NodeCapabilities::SEMANTICS)
1079    }
1080
1081    pub fn has_focus_modifier_nodes(&self) -> bool {
1082        self.modifier_capabilities()
1083            .contains(NodeCapabilities::FOCUS)
1084    }
1085
1086    fn refresh_registry_state(&self) {
1087        if let (Some(id), Some(owner_context_id)) = (self.id.get(), self.owner_context_id.get()) {
1088            let parent = self.parent();
1089            let capabilities = self.modifier_child_capabilities();
1090            let modifier_locals = self.modifier_locals_handle();
1091            let _ = crate::render_state::with_layout_node_registry_by_app_context(
1092                owner_context_id,
1093                |registry| {
1094                    registry.update_entry(id, parent, capabilities, modifier_locals);
1095                },
1096            );
1097        }
1098    }
1099
1100    pub fn modifier_slices_snapshot(&self) -> Rc<ModifierNodeSlices> {
1101        if self.modifier_slices_dirty.get() {
1102            self.update_modifier_slices_cache();
1103        }
1104        self.modifier_slices_snapshot.borrow().clone()
1105    }
1106
1107    /// Returns a clone of the current layout state.
1108    pub fn layout_state(&self) -> LayoutState {
1109        self.layout_state.borrow().clone()
1110    }
1111
1112    /// Returns the measured size of this node.
1113    pub fn measured_size(&self) -> Size {
1114        self.layout_state.borrow().size
1115    }
1116
1117    /// Returns the position of this node relative to its parent.
1118    pub fn position(&self) -> Point {
1119        self.layout_state.borrow().position
1120    }
1121
1122    /// Returns true if this node has been placed in the current layout pass.
1123    pub fn is_placed(&self) -> bool {
1124        self.layout_state.borrow().is_placed
1125    }
1126
1127    /// Updates the measured size of this node. Called during measurement.
1128    /// [`LayoutState::set_size`] self-reports actual changes to the scene
1129    /// phase.
1130    pub fn set_measured_size(&self, size: Size) {
1131        self.layout_state.borrow_mut().set_size(size);
1132    }
1133
1134    /// Updates the position of this node. Called during placement.
1135    /// [`LayoutState::place`] self-reports actual moves to the scene phase.
1136    pub fn set_position(&self, position: Point) {
1137        self.layout_state.borrow_mut().place(position);
1138    }
1139
1140    /// Records the content offset (e.g. from padding).
1141    pub fn set_content_offset(&self, offset: Point) {
1142        self.layout_state.borrow_mut().set_content_offset(offset);
1143    }
1144
1145    /// Clears the is_placed flag. Called at the start of a layout pass.
1146    pub fn clear_placed(&self) {
1147        self.layout_state.borrow_mut().clear_placed();
1148    }
1149
1150    fn note_semantics_layout_change(&self) {
1151        if let Ok(mut state) = self.layout_state.try_borrow_mut() {
1152            state.note_semantics_change();
1153        }
1154    }
1155
1156    pub fn semantics_configuration(&self) -> Option<SemanticsConfiguration> {
1157        crate::modifier::collect_semantics_from_chain(self.modifier_chain.chain())
1158    }
1159
1160    /// Drops the cached reach and queues the node for the modal count.
1161    fn forget_semantics_reach(&self) {
1162        self.semantics_reach.set(None);
1163        crate::modal_nodes::reach_changed(self.id.get());
1164    }
1165
1166    /// Whether this node's modifiers make it modal or hidden.
1167    pub fn semantics_reach(&self) -> cranpose_foundation::SemanticsReach {
1168        // A chain without semantics reaches nothing, known without touching it.
1169        if !self
1170            .modifier_capabilities()
1171            .contains(NodeCapabilities::SEMANTICS)
1172        {
1173            return cranpose_foundation::SemanticsReach::default();
1174        }
1175        if let Some(reach) = self.semantics_reach.get() {
1176            return reach;
1177        }
1178        let reach = crate::modifier::semantics_reach_of_chain(self.modifier_chain.chain());
1179        self.semantics_reach.set(Some(reach));
1180        reach
1181    }
1182
1183    pub(crate) fn modifier_chain(&self) -> &ModifierChainHandle {
1184        &self.modifier_chain
1185    }
1186
1187    /// Access the text field modifier node (if present) with a mutable callback.
1188    ///
1189    /// This is used for keyboard event dispatch to text fields.
1190    /// Returns `None` if no text field modifier is found in the chain.
1191    pub fn with_text_field_modifier_mut<R>(
1192        &mut self,
1193        f: impl FnMut(&mut crate::TextFieldModifierNode) -> R,
1194    ) -> Option<R> {
1195        self.modifier_chain.with_text_field_modifier_mut(f)
1196    }
1197
1198    /// Returns the handle to the shared layout state, which layout clones
1199    /// to update the state without borrowing the Applier.
1200    pub fn layout_state_handle(&self) -> &Rc<RefCell<LayoutState>> {
1201        &self.layout_state
1202    }
1203
1204    pub(crate) fn coordinator_geometry(&self) -> &crate::modifier::CoordinatorGeometry {
1205        &self.coordinator_geometry
1206    }
1207
1208    pub(crate) fn layout_runtime_state_handle(&self) -> Rc<RefCell<LayoutRuntimeState>> {
1209        self.layout_runtime_state.clone()
1210    }
1211
1212    #[cfg(test)]
1213    pub(crate) fn layout_runtime_debug_stats(&self) -> LayoutRuntimeDebugStats {
1214        self.layout_runtime_state.borrow().debug_stats()
1215    }
1216}
1217impl Clone for LayoutNode {
1218    fn clone(&self) -> Self {
1219        let mut node = Self {
1220            #[cfg(feature = "inspection")]
1221            source_trace: self.source_trace.clone(),
1222            modifier: self.modifier.clone(),
1223            modifier_chain: ModifierChainHandle::for_layout_direction(
1224                self.modifier_chain.layout_direction(),
1225            ),
1226            measure_policy: self.measure_policy.clone(),
1227            density: self.density,
1228            children: self.children.clone(),
1229            cache: self.cache.clone(),
1230            needs_measure: Cell::new(self.needs_measure.get()),
1231            needs_layout: Cell::new(self.needs_layout.get()),
1232            descendant_dirt: Cell::new(self.descendant_dirt.get()),
1233            parent_data: Cell::new(self.parent_data.get()),
1234            needs_semantics: Cell::new(self.needs_semantics.get()),
1235            descendant_needs_semantics: Cell::new(self.descendant_needs_semantics.get()),
1236            semantics_reach: Cell::new(None),
1237            needs_redraw: Cell::new(self.needs_redraw.get()),
1238            needs_pointer_pass: Cell::new(self.needs_pointer_pass.get()),
1239            needs_focus_sync: Cell::new(self.needs_focus_sync.get()),
1240            parent: NodeIdCell::new(self.parent.get()),
1241            folded_parent: NodeIdCell::new(self.folded_parent.get()),
1242            id: NodeIdCell::new(None),
1243            owner_context_id: Cell::new(None),
1244            debug_modifiers: Cell::new(self.debug_modifiers.get()),
1245            is_virtual: self.is_virtual,
1246            modifier_slices_snapshot: RefCell::new(Rc::default()),
1247            modifier_slices_dirty: Cell::new(true),
1248            layout_state: self.layout_state.clone(),
1249            layout_runtime_state: self.layout_runtime_state.clone(),
1250            coordinator_geometry: Rc::clone(&self.coordinator_geometry),
1251        };
1252        node.sync_modifier_chain(false);
1253        node
1254    }
1255}
1256
1257impl Node for LayoutNode {
1258    fn mount(&mut self) {
1259        let (chain, mut context) = self.modifier_chain.chain_and_context_mut();
1260        chain.repair_chain();
1261        chain.attach_nodes(&mut *context);
1262        crate::modal_nodes::reach_changed(self.id.get());
1263    }
1264
1265    fn unmount(&mut self) {
1266        self.modifier_chain.chain_mut().detach_nodes();
1267    }
1268
1269    fn set_node_id(&mut self, id: NodeId) {
1270        LayoutNode::set_node_id(self, id);
1271    }
1272
1273    fn insert_child(&mut self, child: NodeId) -> bool {
1274        if self.children.contains(&child) {
1275            return false;
1276        }
1277        self.children.push(child);
1278        self.cache.clear();
1279        self.mark_needs_measure();
1280        self.note_semantics_layout_change();
1281        true
1282    }
1283
1284    fn remove_child(&mut self, child: NodeId) -> bool {
1285        let before = self.children.len();
1286        self.children.retain(|&id| id != child);
1287        let removed = self.children.len() < before;
1288        if removed {
1289            self.cache.clear();
1290            self.mark_needs_measure();
1291            self.note_semantics_layout_change();
1292        }
1293        removed
1294    }
1295
1296    fn move_child(&mut self, from: usize, to: usize) {
1297        if from == to || from >= self.children.len() {
1298            return;
1299        }
1300        let child = self.children.remove(from);
1301        let target = to.min(self.children.len());
1302        self.children.insert(target, child);
1303        self.cache.clear();
1304        self.mark_needs_measure();
1305        self.note_semantics_layout_change();
1306    }
1307
1308    fn update_children(&mut self, children: &[NodeId]) {
1309        self.children.clear();
1310        self.children.extend_from_slice(children);
1311        self.cache.clear();
1312        self.mark_needs_measure();
1313        self.note_semantics_layout_change();
1314    }
1315
1316    fn collect_children_into(&self, out: &mut smallvec::SmallVec<[NodeId; 8]>) {
1317        out.clear();
1318        out.extend_from_slice(&self.children);
1319    }
1320
1321    fn owned_child_index(&self, child: NodeId) -> Option<usize> {
1322        self.children.iter().position(|&id| id == child)
1323    }
1324
1325    fn on_attached_to_parent(&mut self, parent: NodeId) {
1326        self.set_parent(parent);
1327    }
1328
1329    fn on_removed_from_parent(&mut self) {
1330        self.clear_parent();
1331    }
1332
1333    fn parent(&self) -> Option<NodeId> {
1334        self.parent.get()
1335    }
1336
1337    fn mark_needs_layout(&self) {
1338        self.needs_layout.set(true);
1339    }
1340
1341    fn needs_layout(&self) -> bool {
1342        self.needs_layout.get()
1343    }
1344
1345    fn mark_needs_measure(&self) {
1346        self.needs_measure.set(true);
1347        self.needs_layout.set(true);
1348    }
1349
1350    fn needs_measure(&self) -> bool {
1351        self.needs_measure.get()
1352    }
1353
1354    fn mark_descendant_needs_layout(&self, measure: bool) {
1355        self.descendant_dirt
1356            .set(self.descendant_dirt.get().marked(measure));
1357        if measure {
1358            self.cache.forget_intrinsics();
1359        }
1360    }
1361
1362    fn descendant_needs_layout(&self) -> bool {
1363        self.descendant_dirt.get().layout
1364    }
1365
1366    fn is_virtual(&self) -> bool {
1367        self.is_virtual
1368    }
1369
1370    fn descendant_needs_measure(&self) -> bool {
1371        self.descendant_dirt.get().measure
1372    }
1373
1374    fn mark_needs_semantics(&self) {
1375        self.needs_semantics.set(true);
1376        self.forget_semantics_reach();
1377    }
1378
1379    fn mark_descendant_needs_semantics(&self) {
1380        self.descendant_needs_semantics.set(true);
1381    }
1382
1383    fn needs_semantics(&self) -> bool {
1384        LayoutNode::needs_semantics(self)
1385    }
1386
1387    fn set_parent_for_bubbling(&mut self, parent: NodeId) {
1388        if self.parent.get().is_none() {
1389            self.parent.set(Some(parent));
1390        }
1391    }
1392
1393    fn recycle_key(&self) -> Option<TypeId> {
1394        Some(TypeId::of::<Self>())
1395    }
1396
1397    fn recycle_pool_limit(&self) -> Option<usize> {
1398        Some(RECYCLED_LAYOUT_NODE_POOL_LIMIT)
1399    }
1400
1401    fn prepare_for_recycle(&mut self) {
1402        *self = Self::new_recycled_shell(self.is_virtual);
1403    }
1404
1405    fn rehouse_for_recycle(&self) -> Option<Box<dyn cranpose_core::Node>> {
1406        Some(Box::new(Self::new_recycled_shell(self.is_virtual)))
1407    }
1408
1409    fn rehouse_for_live_compaction(&mut self) -> Option<Box<dyn cranpose_core::Node>> {
1410        // The whole node moves into the new box. Its modifier nodes keep
1411        // what the user is doing with it, such as a focus, a held press or an
1412        // IME composition, and its caches and registry entry stay true for
1413        // it. Only its child list, which a spike of children may have grown,
1414        // is cut to size. The shell left behind has no id to unregister.
1415        let mut node = std::mem::replace(self, Self::new_recycled_shell(self.is_virtual));
1416        node.children.shrink_to_fit();
1417        Some(Box::new(node))
1418    }
1419}
1420
1421impl Drop for LayoutNode {
1422    fn drop(&mut self) {
1423        if let (Some(id), Some(owner_context_id)) = (self.id.get(), self.owner_context_id.get()) {
1424            unregister_layout_node(owner_context_id, id);
1425        }
1426    }
1427}
1428
1429const MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY: usize = 128;
1430const VIRTUAL_NODE_ID_START: NodeId = 0xC0000000;
1431
1432#[cfg(test)]
1433#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1434struct LayoutNodeRegistryDebugStats {
1435    len: usize,
1436    capacity: usize,
1437}
1438
1439struct LayoutNodeRegistryEntry {
1440    parent: Option<NodeId>,
1441    modifier_child_capabilities: NodeCapabilities,
1442    modifier_locals: Option<ModifierLocalsHandle>,
1443}
1444
1445pub(crate) struct LayoutNodeRegistryState {
1446    entries: RefCell<HashMap<NodeId, LayoutNodeRegistryEntry>>,
1447    virtual_node_id_counter: Cell<NodeId>,
1448}
1449
1450impl LayoutNodeRegistryState {
1451    pub(crate) fn new() -> Self {
1452        Self {
1453            entries: RefCell::new(HashMap::new()),
1454            virtual_node_id_counter: Cell::new(VIRTUAL_NODE_ID_START),
1455        }
1456    }
1457
1458    fn register(&self, id: NodeId, node: &LayoutNode) {
1459        self.entries.borrow_mut().insert(
1460            id,
1461            LayoutNodeRegistryEntry {
1462                parent: node.parent(),
1463                modifier_child_capabilities: node.modifier_child_capabilities(),
1464                modifier_locals: node.modifier_locals_handle(),
1465            },
1466        );
1467    }
1468
1469    fn unregister(&self, id: NodeId) {
1470        let mut entries = self.entries.borrow_mut();
1471        entries.remove(&id);
1472        let should_shrink = (entries.len() <= MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY
1473            && entries.capacity() > MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY)
1474            || entries.capacity()
1475                > entries
1476                    .len()
1477                    .max(MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY)
1478                    .saturating_mul(4);
1479        if should_shrink {
1480            let retained = entries
1481                .len()
1482                .max(MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY);
1483            let mut rebuilt = HashMap::new();
1484            rebuilt.reserve(retained);
1485            rebuilt.extend(entries.drain());
1486            *entries = rebuilt;
1487        }
1488    }
1489
1490    fn update_entry(
1491        &self,
1492        id: NodeId,
1493        parent: Option<NodeId>,
1494        modifier_child_capabilities: NodeCapabilities,
1495        modifier_locals: Option<ModifierLocalsHandle>,
1496    ) {
1497        if let Some(entry) = self.entries.borrow_mut().get_mut(&id) {
1498            entry.parent = parent;
1499            entry.modifier_child_capabilities = modifier_child_capabilities;
1500            entry.modifier_locals = modifier_locals;
1501        }
1502    }
1503
1504    #[cfg(test)]
1505    fn stats(&self) -> LayoutNodeRegistryDebugStats {
1506        let entries = self.entries.borrow();
1507        LayoutNodeRegistryDebugStats {
1508            len: entries.len(),
1509            capacity: entries.capacity(),
1510        }
1511    }
1512
1513    fn allocate_virtual_node_id(&self) -> NodeId {
1514        let id = self.virtual_node_id_counter.get();
1515        self.virtual_node_id_counter.set(id.wrapping_add(1));
1516        id
1517    }
1518
1519    fn resolve_modifier_local_from_parent_chain(
1520        &self,
1521        start: Option<NodeId>,
1522        token: &ModifierLocalToken,
1523    ) -> Option<ResolvedModifierLocal> {
1524        let mut current = start;
1525        while let Some(parent_id) = current {
1526            let (next_parent, resolved) = {
1527                let entries = self.entries.borrow();
1528                if let Some(entry) = entries.get(&parent_id) {
1529                    let resolved = entry
1530                        .modifier_child_capabilities
1531                        .contains(NodeCapabilities::MODIFIER_LOCALS)
1532                        .then_some(entry.modifier_locals.as_ref())
1533                        .flatten()
1534                        .and_then(|locals| locals.borrow().resolve(token))
1535                        .map(|value| value.with_source(ModifierLocalSource::Ancestor));
1536                    (entry.parent, resolved)
1537                } else {
1538                    (None, None)
1539                }
1540            };
1541            if let Some(value) = resolved {
1542                return Some(value);
1543            }
1544            current = next_parent;
1545        }
1546        None
1547    }
1548}
1549
1550pub(crate) fn register_layout_node(
1551    id: NodeId,
1552    node: &LayoutNode,
1553) -> crate::render_state::AppContextId {
1554    let owner_context_id = crate::render_state::current_app_context_id();
1555    let _ = crate::render_state::with_layout_node_registry_by_app_context(
1556        owner_context_id,
1557        |registry| {
1558            registry.register(id, node);
1559        },
1560    );
1561    owner_context_id
1562}
1563
1564pub(crate) fn unregister_layout_node(
1565    owner_context_id: crate::render_state::AppContextId,
1566    id: NodeId,
1567) {
1568    let _ = crate::render_state::with_layout_node_registry_by_app_context(
1569        owner_context_id,
1570        |registry| {
1571            registry.unregister(id);
1572        },
1573    );
1574}
1575
1576#[cfg(test)]
1577fn layout_node_registry_stats() -> LayoutNodeRegistryDebugStats {
1578    crate::render_state::with_layout_node_registry(LayoutNodeRegistryState::stats)
1579}
1580
1581pub(crate) fn allocate_virtual_node_id() -> NodeId {
1582    crate::render_state::with_layout_node_registry(
1583        LayoutNodeRegistryState::allocate_virtual_node_id,
1584    )
1585}
1586
1587fn resolve_modifier_local_from_parent_chain(
1588    start: Option<NodeId>,
1589    token: &ModifierLocalToken,
1590) -> Option<ResolvedModifierLocal> {
1591    crate::render_state::with_layout_node_registry(|registry| {
1592        registry.resolve_modifier_local_from_parent_chain(start, token)
1593    })
1594}
1595
1596#[cfg(test)]
1597#[path = "tests/layout_node_tests.rs"]
1598mod tests;