Skip to main content

cranpose_ui/widgets/nodes/
layout_node.rs

1use std::{
2    cell::{Cell, RefCell},
3    rc::Rc,
4};
5
6use cranpose_core::{NodeId, NodeIdCell, RecyclableShell};
7use cranpose_foundation::{
8    InvalidationKind, ModifierInvalidation, ModifierInvalidations, NodeCapabilities,
9    SemanticsConfiguration,
10};
11use cranpose_ui_layout::MeasurePolicy;
12
13use super::layout_invalidation_diag::log_layout_invalidation_dispatch;
14
15mod tree_node;
16use crate::{
17    layout::LayoutRuntimeState,
18    modifier::{
19        InPlaceUpdate, Modifier, ModifierChainHandle, ModifierLocalToken, ModifierLocalsHandle,
20        ModifierNodeSlices, Point, ResolvedModifiers, Size,
21    },
22    render_state::AppContext,
23    widgets::{
24        layout::LayoutEnvironment,
25        nodes::{
26            ChildPlacement, LayoutDirt, LayoutParts, LayoutState, NodeCache,
27            layout_node_registry::{
28                register_layout_node, resolve_modifier_local_from_parent_chain,
29                unregister_layout_node,
30            },
31        },
32    },
33};
34
35/// A node of the layout tree.
36///
37/// Its fields keep the order they are declared in: what a layout pass reads
38/// for every child it binds comes first and fits one cache line, then what
39/// measuring the node reads, then what composition reads. Layout reads
40/// thousands of nodes a frame, and on a phone its cost is the lines it loads.
41#[repr(C)]
42pub struct LayoutNode {
43    parts: Rc<LayoutParts>,
44    // The actual children of this node (folded view - includes virtual nodes as-is)
45    pub(crate) children: Vec<NodeId>,
46
47    /// Where the chain's layout modifiers put their content, written by
48    /// layout and read by the draws and text the slices collect.
49    density: Rc<crate::density::Density>,
50    is_virtual: bool,
51    needs_semantics: Cell<bool>,
52    /// The semantics tree has to read this node again, though its own
53    /// semantics are unchanged: a node below it changed, or its placement
54    /// or children did.
55    descendant_needs_semantics: Cell<bool>,
56    needs_redraw: Cell<bool>,
57    needs_pointer_pass: Cell<bool>,
58    needs_focus_sync: Cell<bool>,
59    modifier_slices_dirty: Cell<bool>,
60    debug_modifiers: Cell<bool>,
61
62    id: NodeIdCell,
63    parent: NodeIdCell,
64    folded_parent: NodeIdCell,
65    modifier_slices_snapshot: crate::modifier::SlicesSnapshot,
66
67    /// The chain's modal and hidden flags, read by the modal count and the
68    /// modal walk: dropped whenever the chain syncs or semantics are
69    /// invalidated, the two ways its semantics change.
70    semantics_reach: Cell<Option<cranpose_foundation::SemanticsReach>>,
71    owner_context_id: Cell<Option<crate::render_state::AppContextId>>,
72    // The node's modifier nodes, with the elements of the modifier last set:
73    // the node keeps no modifier of its own.
74    modifier_chain: ModifierChainHandle,
75    /// Composable definitions responsible for this node, captured only for inspection builds.
76    #[cfg(feature = "inspection")]
77    pub source_trace: Rc<[cranpose_core::source_trace::SourceLocation]>,
78}
79
80pub(crate) fn empty_measure_policy() -> Rc<dyn MeasurePolicy> {
81    crate::thread_state::with(|state| {
82        Rc::clone(
83            state
84                .empty_measure_policy
85                .get_or_init(|| Rc::new(crate::layout::policies::EmptyMeasurePolicy)),
86        )
87    })
88}
89
90impl LayoutNode {
91    /// Creates a node with `modifier` whose children `measure_policy` measures and places.
92    pub fn new(modifier: Modifier, measure_policy: Rc<dyn MeasurePolicy>) -> Self {
93        Self::new_with_virtual(
94            modifier,
95            measure_policy,
96            false,
97            LayoutEnvironment::default(),
98        )
99    }
100
101    /// Create a virtual LayoutNode for subcomposition slot containers.
102    /// Virtual nodes are transparent - their children are flattened into parent's children list.
103    pub fn new_virtual() -> Self {
104        Self::new_with_virtual(
105            Modifier::empty(),
106            empty_measure_policy(),
107            true,
108            LayoutEnvironment::default(),
109        )
110    }
111
112    // A node that waits in a recycle pool for the node that takes its place
113    // whole. It holds no parts of its own and no chain: the shells of a
114    // thread share one clean, empty block of parts.
115    fn new_recycled_shell(is_virtual: bool) -> Self {
116        let parts = crate::thread_state::with(|state| {
117            Rc::clone(state.shell_parts.get_or_init(|| {
118                let parts = Rc::new(LayoutParts::empty());
119                parts.cache().set_dirt(LayoutDirt::CLEAN);
120                parts
121            }))
122        });
123        let shell = Self::without_modifier(parts, is_virtual, LayoutEnvironment::default());
124        shell.needs_semantics.set(false);
125        shell.needs_redraw.set(false);
126        shell
127    }
128
129    // A shell for an emit that finds none pooled to fill.
130    pub(crate) fn bare_shell() -> Self {
131        Self::new_recycled_shell(false)
132    }
133
134    // Makes this shell, which `shell` names, the node a composition makes in
135    // `environment` with `modifier` and `measure_policy`, in the place it
136    // lies, so its box takes no new node whole. A shell holds a made node's
137    // values in every field but these. A pooled shell's parts take the node
138    // when nothing else holds them; a fresh shell shares the thread's.
139    pub(crate) fn fill(
140        &mut self,
141        modifier: &Modifier,
142        measure_policy: Rc<dyn MeasurePolicy>,
143        environment: LayoutEnvironment,
144        shell: RecyclableShell,
145    ) {
146        let Self {
147            parts,
148            children,
149            density,
150            is_virtual,
151            needs_semantics,
152            descendant_needs_semantics,
153            needs_redraw,
154            needs_pointer_pass,
155            needs_focus_sync,
156            modifier_slices_dirty,
157            debug_modifiers,
158            id,
159            parent,
160            folded_parent,
161            modifier_slices_snapshot: _,
162            semantics_reach,
163            owner_context_id,
164            modifier_chain,
165            #[cfg(feature = "inspection")]
166            source_trace,
167        } = self;
168        debug_assert!(
169            children.is_empty()
170                && id.get().is_none()
171                && parent.get().is_none()
172                && folded_parent.get().is_none()
173                && owner_context_id.get().is_none()
174                && semantics_reach.get().is_none()
175                && !descendant_needs_semantics.get()
176                && !needs_pointer_pass.get()
177                && !needs_focus_sync.get()
178                && !debug_modifiers.get()
179                && modifier_slices_dirty.get(),
180            "only a shell fills"
181        );
182        let measure_policy = match shell {
183            RecyclableShell::Fresh => Err(measure_policy),
184            RecyclableShell::Pooled => LayoutParts::refill(parts, measure_policy),
185        };
186        if let Err(measure_policy) = measure_policy {
187            *parts = Rc::new(LayoutParts::new(LayoutRuntimeState::new(measure_policy)));
188        }
189        *density = crate::density::shared_density(environment.density);
190        *is_virtual = false;
191        needs_semantics.set(true);
192        needs_redraw.set(true);
193        modifier_chain.set_layout_direction(environment.direction);
194        #[cfg(feature = "inspection")]
195        {
196            *source_trace = cranpose_core::source_trace::current_source_trace();
197        }
198        self.sync_modifier_chain(modifier, None);
199    }
200
201    fn new_with_virtual(
202        modifier: Modifier,
203        measure_policy: Rc<dyn MeasurePolicy>,
204        is_virtual: bool,
205        environment: LayoutEnvironment,
206    ) -> Self {
207        let parts = Rc::new(LayoutParts::new(LayoutRuntimeState::new(measure_policy)));
208        let mut node = Self::without_modifier(parts, is_virtual, environment);
209        node.sync_modifier_chain(&modifier, None);
210        node
211    }
212
213    // A node with `parts` whose chain no modifier has reached yet.
214    fn without_modifier(
215        parts: Rc<LayoutParts>,
216        is_virtual: bool,
217        environment: LayoutEnvironment,
218    ) -> Self {
219        Self {
220            #[cfg(feature = "inspection")]
221            source_trace: cranpose_core::source_trace::current_source_trace(),
222            modifier_chain: ModifierChainHandle::detached(environment.direction),
223            density: crate::density::shared_density(environment.density),
224            children: Vec::new(),
225            needs_semantics: Cell::new(true),
226            descendant_needs_semantics: Cell::new(false),
227            semantics_reach: Cell::new(None),
228            needs_redraw: Cell::new(true),
229            needs_pointer_pass: Cell::new(false),
230            needs_focus_sync: Cell::new(false),
231            parent: NodeIdCell::new(None),
232            folded_parent: NodeIdCell::new(None),
233            id: NodeIdCell::new(None),
234            owner_context_id: Cell::new(None),
235            debug_modifiers: Cell::new(false),
236            is_virtual,
237            modifier_slices_snapshot: crate::modifier::SlicesSnapshot::default(),
238            modifier_slices_dirty: Cell::new(true),
239            parts,
240        }
241    }
242
243    /// The node's children, in the order they were inserted, virtual nodes as they are.
244    pub fn children(&self) -> &[NodeId] {
245        &self.children
246    }
247
248    /// Returns the modifier that was last set on this node.
249    pub fn modifier(&self) -> Modifier {
250        self.modifier_chain.modifier()
251    }
252
253    /// Replaces the node's modifier and updates its modifier chain, invalidating the work that the
254    /// change affects.
255    pub fn set_modifier(&mut self, modifier: Modifier) {
256        #[cfg(feature = "inspection")]
257        {
258            let trace = cranpose_core::source_trace::current_source_trace();
259            if !trace.is_empty() {
260                self.source_trace = trace;
261            }
262        }
263        // An equal modifier leaves every element's node as it was. Only a
264        // chain reading modifier locals resyncs, since its parent may now
265        // provide others.
266        let matched = self.modifier_chain.match_for_set(&modifier);
267        if matched.equal
268            && !self
269                .modifier_capabilities()
270                .contains(NodeCapabilities::MODIFIER_LOCALS)
271        {
272            return;
273        }
274        // A change only in elements nothing else reads, as a ticker's text
275        // or an animated size, keeps the slices the chain gave.
276        let update = matched.in_place;
277        let modifier_changed = update.is_some() || !matched.structural;
278        self.sync_modifier_chain(&modifier, update);
279        if modifier_changed {
280            self.parts.cache().clear();
281            self.request_semantics_update();
282        }
283    }
284
285    // The node after `modifier`'s elements in the node's chain, when the
286    // chain holds them and that one node more, and a set of an equal
287    // modifier would leave the chain as it is: `None` too for a chain that
288    // reads modifier locals, which a set syncs again.
289    pub(crate) fn node_after(
290        &self,
291        modifier: &Modifier,
292    ) -> Option<&Rc<RefCell<dyn cranpose_foundation::ModifierNode>>> {
293        if self
294            .modifier_capabilities()
295            .contains(NodeCapabilities::MODIFIER_LOCALS)
296        {
297            return None;
298        }
299        self.modifier_chain.node_after(modifier)
300    }
301
302    // Reconciles the chain with `modifier`. `in_place` says how far the
303    // change reaches when the modifier changed only in elements the chain can
304    // update in place: when it does, the current slices are kept.
305    fn sync_modifier_chain(&mut self, modifier: &Modifier, in_place: Option<InPlaceUpdate>) {
306        let prev_caps = self.modifier_capabilities();
307        let start_parent = self.parent();
308        let mut resolver = move |token: &ModifierLocalToken| {
309            resolve_modifier_local_from_parent_chain(start_parent, token)
310        };
311        self.modifier_chain
312            .set_debug_logging(self.debug_modifiers.get());
313        let mut context = self.modifier_chain.context(self.id.get());
314        let in_place = in_place.is_some_and(|update| {
315            self.modifier_chain
316                .update_elements_in_place(modifier, update, &mut context)
317        });
318        let modifier_local_invalidations = if in_place {
319            ModifierInvalidations::new()
320        } else {
321            self.modifier_chain
322                .update_with_resolver(modifier, &mut resolver, &mut context)
323        };
324        if prev_caps.contains(NodeCapabilities::WINDOW_ROOT)
325            != self
326                .modifier_capabilities()
327                .contains(NodeCapabilities::WINDOW_ROOT)
328        {
329            self.note_semantics_layout_change();
330        }
331        // An element updated in place reaches nothing, so the update leaves
332        // the chain's reach as it was, and the modal count does not read it
333        // again.
334        if !in_place {
335            self.forget_semantics_reach();
336        }
337        let mut invalidations = context.take_invalidations();
338        // Most chains read no modifier locals: an extend by an empty list
339        // still moves the list.
340        if !modifier_local_invalidations.is_empty() {
341            invalidations.extend(modifier_local_invalidations);
342        }
343        self.dispatch_chain_update(&invalidations, prev_caps, in_place);
344        // An update in place leaves the node's parent, capabilities and
345        // modifier locals as the registry holds them.
346        if !in_place {
347            self.refresh_registry_state();
348        }
349    }
350
351    // Dispatches `invalidations`, what an update of the chain asked for. An
352    // update in place keeps the slices the chain gave, unless they are stale
353    // already.
354    fn dispatch_chain_update(
355        &self,
356        invalidations: &[ModifierInvalidation],
357        prev_caps: NodeCapabilities,
358        in_place: bool,
359    ) {
360        let keep_slices = in_place && !self.modifier_slices_dirty.get();
361        if !keep_slices {
362            self.modifier_slices_dirty.set(true);
363        }
364        self.dispatch_modifier_invalidations_with_prev(invalidations, prev_caps, keep_slices);
365    }
366
367    // Takes an update its caller made in place to the values of the chain's
368    // last node, whose capabilities stay: what the node's capabilities
369    // invalidate, a new measurement and new semantics.
370    pub(crate) fn note_last_node_updated(&mut self) {
371        let prev_caps = self.modifier_capabilities();
372        let mut context = self.modifier_chain.context(self.id.get());
373        self.modifier_chain.invalidate_last(&mut context);
374        self.dispatch_chain_update(&context.take_invalidations(), prev_caps, true);
375        self.parts.cache().clear();
376        self.request_semantics_update();
377    }
378
379    fn update_modifier_slices_cache(&self) {
380        self.modifier_slices_snapshot.collect(
381            self.modifier_chain.chain(),
382            Some(&self.parts),
383            self.density.density(),
384        );
385        self.modifier_slices_dirty.set(false);
386    }
387
388    /// Whether the modifier slices are built and current.
389    #[cfg(test)]
390    pub(crate) fn modifier_slices_ready(&self) -> bool {
391        !self.modifier_slices_dirty.get()
392    }
393
394    pub(crate) fn mark_modifier_slices_dirty(&self) {
395        self.modifier_slices_dirty.set(true);
396    }
397
398    #[cfg(test)]
399    fn dispatch_modifier_invalidations(&self, invalidations: &[ModifierInvalidation]) {
400        self.dispatch_modifier_invalidations_with_prev(
401            invalidations,
402            NodeCapabilities::empty(),
403            false,
404        );
405    }
406
407    /// Applies `invalidations` to the node. Each marks the slices for a
408    /// rebuild unless `keep_slices`.
409    fn dispatch_modifier_invalidations_with_prev(
410        &self,
411        invalidations: &[ModifierInvalidation],
412        prev_caps: NodeCapabilities,
413        keep_slices: bool,
414    ) {
415        let curr_caps = self.modifier_capabilities();
416        for invalidation in invalidations {
417            if !keep_slices {
418                self.modifier_slices_dirty.set(true);
419            }
420            let has_capability =
421                |capability| curr_caps.contains(capability) || prev_caps.contains(capability);
422            match invalidation.kind() {
423                InvalidationKind::Layout => {
424                    if has_capability(NodeCapabilities::LAYOUT) {
425                        self.mark_needs_measure();
426                        if let Some(id) = self.id.get() {
427                            log_layout_invalidation_dispatch(
428                                id,
429                                invalidation,
430                                curr_caps,
431                                prev_caps,
432                                &self.modifier_chain,
433                            );
434                            let inside_composition =
435                                cranpose_core::composer_context::try_with_composer(|_| ())
436                                    .is_some();
437                            if inside_composition {
438                                cranpose_core::bubble_measure_dirty_in_composer(id);
439                            } else {
440                                crate::schedule_layout_repass(id);
441                            }
442                        }
443                    }
444                }
445                InvalidationKind::Draw => {
446                    if has_capability(NodeCapabilities::DRAW)
447                        || invalidation.capabilities().contains(NodeCapabilities::DRAW)
448                    {
449                        self.mark_needs_redraw();
450                    }
451                }
452                InvalidationKind::PointerInput => {
453                    if has_capability(NodeCapabilities::POINTER_INPUT) {
454                        self.request_pointer_pass();
455                    }
456                }
457                InvalidationKind::Semantics => {
458                    self.request_semantics_update();
459                }
460                InvalidationKind::Focus => {
461                    if has_capability(NodeCapabilities::FOCUS) {
462                        self.request_focus_sync();
463                    }
464                }
465            }
466        }
467    }
468
469    // Applies `invalidations`, which the chain of a node made under a parent
470    // made with it asked for as the node took its id. Such a node needs
471    // measure, draw and semantics as it is made, and the attach of its new
472    // subtree's root carries layout dirt and a structural change above it:
473    // only pointer input and focus have passes of their own to tell, and the
474    // frame a draw to request.
475    fn dispatch_made_node_invalidations(&self, invalidations: &[ModifierInvalidation]) {
476        let caps = self.modifier_capabilities();
477        for invalidation in invalidations {
478            match invalidation.kind() {
479                InvalidationKind::Draw => {
480                    if caps.contains(NodeCapabilities::DRAW)
481                        || invalidation.capabilities().contains(NodeCapabilities::DRAW)
482                    {
483                        crate::request_render_invalidation();
484                    }
485                }
486                InvalidationKind::PointerInput => {
487                    if caps.contains(NodeCapabilities::POINTER_INPUT) {
488                        self.request_pointer_pass();
489                    }
490                }
491                InvalidationKind::Focus => {
492                    if caps.contains(NodeCapabilities::FOCUS) {
493                        self.request_focus_sync();
494                    }
495                }
496                InvalidationKind::Layout | InvalidationKind::Semantics => {}
497            }
498        }
499    }
500
501    // Has the pointer pass read the node's pointer input again.
502    fn request_pointer_pass(&self) {
503        self.mark_needs_pointer_pass();
504        crate::request_pointer_invalidation();
505        if let Some(id) = self.id.get() {
506            crate::schedule_pointer_repass(id);
507        }
508    }
509
510    // Has the focus manager read the node's focus nodes again.
511    fn request_focus_sync(&self) {
512        self.mark_needs_focus_sync();
513        crate::request_focus_invalidation();
514        if let Some(id) = self.id.get() {
515            crate::schedule_focus_invalidation(id);
516        }
517    }
518
519    /// The grid this node was composed against.
520    pub fn density(&self) -> crate::density::Density {
521        *self.density
522    }
523
524    /// Records the grid the composition provided, re-measuring if it moved.
525    pub fn set_density(&mut self, density: crate::density::Density) {
526        if *self.density != density {
527            self.density = crate::density::shared_density(density);
528            self.parts.cache().clear();
529            self.modifier_slices_dirty.set(true);
530            self.mark_needs_measure();
531        }
532    }
533
534    /// Updates relative modifier placement for this node's composition scope.
535    pub fn set_layout_direction(&mut self, direction: crate::LayoutDirection) {
536        if self.modifier_chain.set_layout_direction(direction) {
537            self.parts.cache().clear();
538            self.modifier_slices_dirty.set(true);
539            self.mark_needs_measure();
540        }
541    }
542
543    /// Replaces the measure policy and schedules a measure. Does nothing if `policy` is the same
544    /// `Rc` as the current one.
545    pub fn set_measure_policy(&mut self, policy: Rc<dyn MeasurePolicy>) {
546        if self
547            .parts
548            .runtime_state()
549            .borrow_mut()
550            .replace_measure_policy(policy)
551        {
552            self.parts.cache().clear();
553            self.mark_needs_measure();
554            if let Some(id) = self.id.get() {
555                cranpose_core::bubble_measure_dirty_in_composer(id);
556            }
557        }
558    }
559
560    /// Mark this node as needing measure. Also marks it as needing layout.
561    pub fn mark_needs_measure(&self) {
562        self.parts.cache().mark_needs_measure();
563    }
564
565    /// Mark this node as needing layout (but not necessarily measure).
566    pub fn mark_needs_layout(&self) {
567        self.parts.cache().mark_needs_layout();
568    }
569
570    /// Mark this node as needing redraw without forcing measure/layout.
571    pub fn mark_needs_redraw(&self) {
572        self.needs_redraw.set(true);
573        if let Some(id) = self.id.get() {
574            crate::schedule_draw_repass(id);
575        }
576        crate::request_render_invalidation();
577    }
578
579    /// Check if this node needs measure.
580    pub fn needs_measure(&self) -> bool {
581        self.parts.cache().dirt().measure
582    }
583
584    /// Check if this node needs layout.
585    pub fn needs_layout(&self) -> bool {
586        self.parts.cache().dirt().layout
587    }
588
589    /// Mark this node as needing semantics recomputation.
590    pub fn mark_needs_semantics(&self) {
591        self.needs_semantics.set(true);
592        self.forget_semantics_reach();
593    }
594
595    pub(crate) fn clear_needs_semantics(&self) {
596        self.needs_semantics.set(false);
597        self.descendant_needs_semantics.set(false);
598    }
599
600    /// Returns true when this node's semantics or a descendant's need to be
601    /// recomputed.
602    pub fn needs_semantics(&self) -> bool {
603        self.needs_semantics.get() || self.descendant_needs_semantics.get()
604    }
605
606    /// Whether this node's own semantics changed since the tree last read
607    /// them, as opposed to only a descendant's.
608    pub(crate) fn semantics_changed(&self) -> bool {
609        self.needs_semantics.get()
610    }
611
612    /// Returns true when this node requested a redraw since the last render pass.
613    pub fn needs_redraw(&self) -> bool {
614        self.needs_redraw.get()
615    }
616
617    /// Clears the pending redraw flag once the node has been drawn.
618    pub fn clear_needs_redraw(&self) {
619        self.needs_redraw.set(false);
620    }
621
622    fn request_semantics_update(&self) {
623        let already_dirty = self.needs_semantics.replace(true);
624        if already_dirty {
625            return;
626        }
627
628        if let Some(id) = self.id.get() {
629            cranpose_core::queue_semantics_invalidation(id);
630        }
631    }
632
633    pub(crate) fn clear_needs_measure(&self) {
634        self.parts.cache().clear_needs_measure();
635    }
636
637    /// Clears the node's layout flag and its descendants': a layout pass
638    /// visited them.
639    pub(crate) fn clear_needs_layout(&self) {
640        self.parts.cache().clear_layout_dirt();
641    }
642
643    /// Marks this node as needing a fresh pointer-input pass.
644    pub fn mark_needs_pointer_pass(&self) {
645        self.needs_pointer_pass.set(true);
646    }
647
648    /// Returns true when pointer-input state needs to be recomputed.
649    pub fn needs_pointer_pass(&self) -> bool {
650        self.needs_pointer_pass.get()
651    }
652
653    /// Clears the pointer-input dirty flag after hosts service it.
654    pub fn clear_needs_pointer_pass(&self) {
655        self.needs_pointer_pass.set(false);
656    }
657
658    /// Marks this node as needing a focus synchronization.
659    pub fn mark_needs_focus_sync(&self) {
660        self.needs_focus_sync.set(true);
661    }
662
663    /// Returns true when focus state needs to be synchronized.
664    pub fn needs_focus_sync(&self) -> bool {
665        self.needs_focus_sync.get()
666    }
667
668    /// Clears the focus dirty flag after the focus manager processes it.
669    pub fn clear_needs_focus_sync(&self) {
670        self.needs_focus_sync.set(false);
671    }
672
673    /// Set this node's ID (called by applier after creation).
674    pub fn set_node_id(&mut self, id: NodeId) {
675        let invalidations = self.take_node_id(id);
676        self.dispatch_modifier_invalidations_with_prev(
677            &invalidations,
678            NodeCapabilities::empty(),
679            false,
680        );
681    }
682
683    // Takes `id` and `parent` at once, as a node a pass made under a parent
684    // it made takes them: the registry entry holds the parent from the
685    // start, and the node joins the parent's children with no update of it.
686    fn mount_under_made_parent(&mut self, parent: NodeId, id: NodeId) {
687        self.parent.set(Some(parent));
688        self.folded_parent.set(Some(parent));
689        let invalidations = self.take_node_id(id);
690        self.dispatch_made_node_invalidations(&invalidations);
691    }
692
693    // Takes `id` as the node's id: the node registers under it and its chain
694    // moves to it. Returns what the chain asks to invalidate for the move.
695    fn take_node_id(&mut self, id: NodeId) -> ModifierInvalidations {
696        let previous = self.id.replace(Some(id));
697        if let Some(existing) = previous
698            && let Some(owner_context_id) = self.owner_context_id.take()
699        {
700            unregister_layout_node(owner_context_id, existing);
701        }
702        // The new entry holds the node's parent, capabilities and modifier
703        // locals as they are now.
704        let owner_context_id = register_layout_node(id, self);
705        self.owner_context_id.set(Some(owner_context_id));
706
707        let mut context = self.modifier_chain.context(Some(id));
708        self.modifier_chain.move_to_node(previous, &mut context);
709        // The slices carry the node's id; they are collected again when next read.
710        self.modifier_slices_dirty.set(true);
711        context.take_invalidations()
712    }
713
714    /// Get this node's ID.
715    pub fn node_id(&self) -> Option<NodeId> {
716        self.id.get()
717    }
718
719    /// Set this node's parent (called when node is added as child).
720    /// Sets both folded_parent (direct) and parent (first non-virtual ancestor for bubbling).
721    pub fn set_parent(&self, parent: NodeId) {
722        // The registry holds the parent the node has; the same one again
723        // changes nothing.
724        if self.parent.get() == Some(parent) && self.folded_parent.get() == Some(parent) {
725            return;
726        }
727        self.folded_parent.set(Some(parent));
728        self.parent.set(Some(parent));
729        self.refresh_registry_state();
730    }
731
732    /// Clear this node's parent (called when node is removed from parent).
733    pub fn clear_parent(&self) {
734        self.folded_parent.set(None);
735        self.parent.set(None);
736        self.refresh_registry_state();
737    }
738
739    /// Get this node's parent for dirty flag bubbling (may skip virtual nodes).
740    pub fn parent(&self) -> Option<NodeId> {
741        self.parent.get()
742    }
743
744    /// Get this node's direct parent (may be a virtual node).
745    pub fn folded_parent(&self) -> Option<NodeId> {
746        self.folded_parent.get()
747    }
748
749    pub(crate) fn cache(&self) -> &NodeCache {
750        self.parts.cache()
751    }
752
753    /// Returns the padding, layout properties and offset that the modifier chain resolved to.
754    pub fn resolved_modifiers(&self) -> ResolvedModifiers {
755        self.modifier_chain.resolved_modifiers()
756    }
757
758    /// What the chain tells the parent's measure policy about this node.
759    pub(crate) fn parent_data(&self) -> crate::modifier::SharedParentData {
760        self.modifier_chain.parent_data()
761    }
762
763    /// Returns the union of the capabilities of all nodes in the modifier chain.
764    pub fn modifier_capabilities(&self) -> NodeCapabilities {
765        self.modifier_chain.capabilities()
766    }
767
768    /// Whether this node's modifier chain makes it the root of a separate
769    /// window. Its parent lays out as if it had no size and its parent's
770    /// scene skips it; its own scene starts here.
771    pub fn is_window_root(&self) -> bool {
772        self.modifier_capabilities()
773            .contains(NodeCapabilities::WINDOW_ROOT)
774    }
775
776    /// Returns the capabilities of the chain's nodes counted from the head of the chain. Compose's
777    /// `aggregateChildKindSet`.
778    pub fn modifier_child_capabilities(&self) -> NodeCapabilities {
779        self.modifier_chain.aggregate_child_capabilities()
780    }
781
782    /// Turns debug logging of the modifier chain on or off.
783    pub fn set_debug_modifiers(&mut self, enabled: bool) {
784        self.debug_modifiers.set(enabled);
785        self.modifier_chain.set_debug_logging(enabled);
786    }
787
788    /// Returns whether debug logging of the modifier chain is on.
789    pub fn debug_modifiers_enabled(&self) -> bool {
790        self.debug_modifiers.get()
791    }
792
793    /// The node's modifier locals, or `None` while its modifiers have never
794    /// provided or read one.
795    pub fn modifier_locals_handle(&self) -> Option<ModifierLocalsHandle> {
796        self.modifier_chain.modifier_locals_handle()
797    }
798
799    /// Returns whether the modifier chain contains layout modifier nodes.
800    pub fn has_layout_modifier_nodes(&self) -> bool {
801        self.modifier_capabilities()
802            .contains(NodeCapabilities::LAYOUT)
803    }
804
805    /// Returns whether the modifier chain contains draw modifier nodes.
806    pub fn has_draw_modifier_nodes(&self) -> bool {
807        self.modifier_capabilities()
808            .contains(NodeCapabilities::DRAW)
809    }
810
811    /// Returns whether the modifier chain contains pointer input modifier nodes.
812    pub fn has_pointer_input_modifier_nodes(&self) -> bool {
813        self.modifier_capabilities()
814            .contains(NodeCapabilities::POINTER_INPUT)
815    }
816
817    /// Returns whether the modifier chain contains semantics modifier nodes.
818    pub fn has_semantics_modifier_nodes(&self) -> bool {
819        self.modifier_capabilities()
820            .contains(NodeCapabilities::SEMANTICS)
821    }
822
823    /// Returns whether the modifier chain contains focus modifier nodes.
824    pub fn has_focus_modifier_nodes(&self) -> bool {
825        self.modifier_capabilities()
826            .contains(NodeCapabilities::FOCUS)
827    }
828
829    fn refresh_registry_state(&self) {
830        if let (Some(id), Some(owner_context_id)) = (self.id.get(), self.owner_context_id.get()) {
831            let parent = self.parent();
832            let capabilities = self.modifier_child_capabilities();
833            let modifier_locals = self.modifier_locals_handle();
834            let _ = crate::render_state::with_layout_node_registry_by_app_context(
835                owner_context_id,
836                |registry| {
837                    registry.update_entry(id, parent, capabilities, modifier_locals);
838                },
839            );
840        }
841    }
842
843    /// Returns the draw commands, pointer input handlers, text and graphics layer data collected
844    /// from the modifier nodes. The snapshot is rebuilt after the chain changed.
845    pub fn modifier_slices_snapshot(&self) -> Rc<ModifierNodeSlices> {
846        if self.modifier_slices_dirty.get() {
847            self.update_modifier_slices_cache();
848        }
849        self.modifier_slices_snapshot.get()
850    }
851
852    /// Returns a clone of the current layout state.
853    pub fn layout_state(&self) -> LayoutState {
854        self.parts.layout_state().snapshot()
855    }
856
857    /// Returns the measured size of this node.
858    pub fn measured_size(&self) -> Size {
859        self.parts.layout_state().size()
860    }
861
862    /// Returns the position of this node relative to its parent.
863    pub fn position(&self) -> Point {
864        self.parts.layout_state().position()
865    }
866
867    /// Returns true if this node has been placed in the current layout pass.
868    pub fn is_placed(&self) -> bool {
869        self.parts.layout_state().is_placed()
870    }
871
872    /// Updates the measured size of this node. Called during measurement. An
873    /// actual change reports itself to the scene phase.
874    pub fn set_measured_size(&self, size: Size, context: &AppContext) {
875        self.parts.set_size(self.id.get(), size, context);
876    }
877
878    // Updates the position of this node, which `placer` placed. Called
879    // during placement. `LayoutState::place` self-reports actual moves to
880    // the scene phase.
881    pub(crate) fn place(&self, at: ChildPlacement, placer: Option<NodeId>, context: &AppContext) {
882        self.parts.place(self.id.get(), at, placer, context);
883    }
884
885    /// Records the content offset (e.g. from padding).
886    pub fn set_content_offset(&self, offset: Point) {
887        self.parts
888            .layout_state()
889            .set_content_offset(self.id.get(), offset);
890    }
891
892    /// Clears the is_placed flag. Called at the start of a layout pass.
893    pub fn clear_placed(&self, context: &AppContext) {
894        self.parts.clear_placed(self.id.get(), context);
895    }
896
897    fn note_semantics_layout_change(&self) {
898        self.parts
899            .layout_state()
900            .note_semantics_change(self.id.get());
901    }
902
903    /// Returns the semantics that the modifier chain reports, or `None` if it reports none.
904    pub fn semantics_configuration(&self) -> Option<SemanticsConfiguration> {
905        crate::modifier::collect_semantics_from_chain(self.modifier_chain.chain())
906    }
907
908    /// Drops the cached reach and queues the node for the modal count.
909    fn forget_semantics_reach(&self) {
910        self.semantics_reach.set(None);
911        crate::modal_nodes::reach_changed(self.id.get());
912    }
913
914    /// Whether this node's modifiers make it modal or hidden.
915    pub fn semantics_reach(&self) -> cranpose_foundation::SemanticsReach {
916        // A chain without semantics reaches nothing, known without touching it.
917        if !self
918            .modifier_capabilities()
919            .contains(NodeCapabilities::SEMANTICS)
920        {
921            return cranpose_foundation::SemanticsReach::default();
922        }
923        if let Some(reach) = self.semantics_reach.get() {
924            return reach;
925        }
926        let reach = crate::modifier::semantics_reach_of_chain(self.modifier_chain.chain());
927        self.semantics_reach.set(Some(reach));
928        reach
929    }
930
931    pub(crate) fn modifier_chain(&self) -> &ModifierChainHandle {
932        &self.modifier_chain
933    }
934
935    /// Runs `read` on the node's layout state.
936    pub fn with_layout_state<R>(&self, read: impl FnOnce(&LayoutState) -> R) -> R {
937        read(&self.parts.layout_state().snapshot())
938    }
939
940    pub(crate) fn layout_parts(&self) -> &Rc<LayoutParts> {
941        &self.parts
942    }
943
944    pub(crate) fn layout_runtime_state(&self) -> &RefCell<LayoutRuntimeState> {
945        self.parts.runtime_state()
946    }
947}
948impl Clone for LayoutNode {
949    fn clone(&self) -> Self {
950        let mut node = Self {
951            #[cfg(feature = "inspection")]
952            source_trace: Rc::clone(&self.source_trace),
953            modifier_chain: ModifierChainHandle::for_layout_direction(
954                self.modifier_chain.layout_direction(),
955            ),
956            density: Rc::clone(&self.density),
957            children: self.children.clone(),
958            needs_semantics: Cell::new(self.needs_semantics.get()),
959            descendant_needs_semantics: Cell::new(self.descendant_needs_semantics.get()),
960            semantics_reach: Cell::new(None),
961            needs_redraw: Cell::new(self.needs_redraw.get()),
962            needs_pointer_pass: Cell::new(self.needs_pointer_pass.get()),
963            needs_focus_sync: Cell::new(self.needs_focus_sync.get()),
964            parent: NodeIdCell::new(self.parent.get()),
965            folded_parent: NodeIdCell::new(self.folded_parent.get()),
966            id: NodeIdCell::new(None),
967            owner_context_id: Cell::new(None),
968            debug_modifiers: Cell::new(self.debug_modifiers.get()),
969            is_virtual: self.is_virtual,
970            modifier_slices_snapshot: crate::modifier::SlicesSnapshot::default(),
971            modifier_slices_dirty: Cell::new(true),
972            parts: Rc::clone(&self.parts),
973        };
974        node.sync_modifier_chain(&self.modifier(), None);
975        node
976    }
977}
978
979impl Drop for LayoutNode {
980    fn drop(&mut self) {
981        self.parts.cache().advance_revision();
982        if let (Some(id), Some(owner_context_id)) = (self.id.get(), self.owner_context_id.get()) {
983            unregister_layout_node(owner_context_id, id);
984        }
985    }
986}
987
988#[cfg(test)]
989#[path = "tests/layout_node_tests.rs"]
990mod tests;