Skip to main content

cranpose_ui/
subcompose_layout.rs

1use std::{
2    cell::{Cell, Ref, RefCell, RefMut},
3    collections::HashMap,
4    rc::Rc,
5};
6
7use cranpose_core::{
8    Composer, NodeError, NodeId, Phase, SlotId, SlotTable, SlotsHost, SubcomposeState,
9};
10use cranpose_foundation::{
11    InvalidationKind, ModifierInvalidation, NodeCapabilities, SemanticsConfiguration,
12};
13pub use cranpose_ui_layout::{Constraints, MeasureResult, Placement};
14use smallvec::SmallVec;
15use web_time::Instant;
16
17use crate::{
18    layout::MeasuredNode,
19    modifier::{Modifier, ModifierChainHandle, ModifierNodeSlices, Point, ResolvedModifiers, Size},
20    widgets::nodes::{
21        LayoutNode, LayoutNodeCacheHandles, LayoutState, allocate_virtual_node_id, is_virtual_node,
22        register_layout_node,
23    },
24};
25
26fn subcompose_telemetry_enabled() -> bool {
27    cranpose_core::env_flag!("CRANPOSE_SUBCOMPOSE_TELEMETRY")
28}
29
30#[derive(Clone, Copy, Debug)]
31pub struct SubcomposeChild {
32    node_id: NodeId,
33    measured_size: Option<Size>,
34}
35
36impl SubcomposeChild {
37    pub fn new(node_id: NodeId) -> Self {
38        Self {
39            node_id,
40            measured_size: None,
41        }
42    }
43
44    pub fn with_size(node_id: NodeId, size: Size) -> Self {
45        Self {
46            node_id,
47            measured_size: Some(size),
48        }
49    }
50
51    pub fn node_id(&self) -> NodeId {
52        self.node_id
53    }
54
55    pub fn size(&self) -> Size {
56        self.measured_size.unwrap_or(Size {
57            width: 0.0,
58            height: 0.0,
59        })
60    }
61
62    pub fn width(&self) -> f32 {
63        self.size().width
64    }
65
66    pub fn height(&self) -> f32 {
67        self.size().height
68    }
69
70    pub fn set_size(&mut self, size: Size) {
71        self.measured_size = Some(size);
72    }
73}
74
75impl PartialEq for SubcomposeChild {
76    fn eq(&self, other: &Self) -> bool {
77        self.node_id == other.node_id
78    }
79}
80
81pub type SubcomposePlaceable = cranpose_ui_layout::Placeable;
82
83type CachedMeasureBatchRegistrar<'a> =
84    Box<dyn FnMut(&[NodeId], Constraints, &mut Vec<Option<Size>>) + 'a>;
85type RetainedMeasureLookup<'a> = Box<dyn FnMut(NodeId) -> Option<Rc<MeasuredNode>> + 'a>;
86type RetainedMeasureRegistrar<'a> = Box<dyn FnMut(&[Rc<MeasuredNode>]) + 'a>;
87
88pub(crate) struct CachedBatchMeasureInputs<'a> {
89    pub(crate) measurer: Box<dyn FnMut(NodeId, Constraints) -> Size + 'a>,
90    pub(crate) cached_measure_batch_registrar: CachedMeasureBatchRegistrar<'a>,
91    pub(crate) retained_measure_lookup: RetainedMeasureLookup<'a>,
92    pub(crate) retained_measure_registrar: RetainedMeasureRegistrar<'a>,
93    pub(crate) error: &'a RefCell<Option<NodeError>>,
94}
95
96/// Base trait for measurement scopes.
97pub trait SubcomposeLayoutScope: cranpose_ui_layout::MeasureScope {
98    fn constraints(&self) -> Constraints;
99
100    fn layout<I>(&mut self, width: f32, height: f32, placements: I) -> MeasureResult
101    where
102        I: IntoIterator<Item = Placement>,
103    {
104        MeasureResult::new(Size { width, height }, placements.into_iter().collect())
105    }
106}
107
108/// Public trait exposed to measure policies for subcomposition.
109pub trait SubcomposeMeasureScope: SubcomposeLayoutScope {
110    /// Composes `content` into the slot, or reuses the retained composition
111    /// when it is provably current.
112    ///
113    /// `key` must carry every value that flows into `content` from the
114    /// measure policy itself rather than from reactive state — a scaffold's
115    /// computed padding, a box's constraints. Such values never invalidate a
116    /// recompose scope when they change, so an equal key is the caller's
117    /// promise that the retained composition is not stale on that channel.
118    /// Values read from reactive state inside `content` need no key entry:
119    /// their writes invalidate the slot's scopes and block reuse. Content
120    /// must not read a non-reactive container (`Cell`, `RefCell`) for a value
121    /// that changes between measure passes unless that value is part of
122    /// `key`; debug builds recompose skipped slots and panic when the
123    /// retained topology diverges from a fresh composition.
124    fn subcompose<K, Content>(
125        &mut self,
126        slot_id: SlotId,
127        key: K,
128        content: Content,
129    ) -> Vec<SubcomposeChild>
130    where
131        K: PartialEq + 'static,
132        Content: FnMut() + 'static;
133
134    /// Measures a subcomposed child with the given constraints.
135    fn measure(&mut self, child: SubcomposeChild, constraints: Constraints) -> SubcomposePlaceable;
136
137    /// Checks if a node has no parent (is a root node).
138    /// Used to filter subcompose results to only include true root nodes.
139    fn node_has_no_parent(&self, node_id: NodeId) -> bool;
140}
141
142/// Concrete implementation of [`SubcomposeMeasureScope`].
143pub struct SubcomposeMeasureScopeImpl<'a> {
144    composer: Composer,
145    density_scope: crate::density::DensityMeasureScope,
146    state: &'a mut SubcomposeState,
147    constraints: Constraints,
148    measurer: Box<dyn FnMut(NodeId, Constraints) -> Size + 'a>,
149    cached_measure_batch_registrar: CachedMeasureBatchRegistrar<'a>,
150    retained_measure_lookup: RetainedMeasureLookup<'a>,
151    retained_measure_registrar: RetainedMeasureRegistrar<'a>,
152    error: &'a RefCell<Option<NodeError>>,
153    parent_handle: SubcomposeLayoutNodeHandle,
154    root_id: NodeId,
155    placement_scratch: Vec<Placement>,
156    cached_measure_node_scratch: Vec<NodeId>,
157    cached_measure_size_scratch: Vec<Option<Size>>,
158    cached_measure_missing_scratch: Vec<NodeId>,
159    registered_measurement_node_ids: Vec<NodeId>,
160    pending_commands_applied: bool,
161    #[cfg(debug_assertions)]
162    shadow_stash: Option<(Vec<NodeId>, Vec<NodeId>)>,
163}
164
165thread_local! {
166    static CLEAN_SLOT_SKIPS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
167}
168
169fn record_clean_slot_skip() {
170    CLEAN_SLOT_SKIPS.with(|count| count.set(count.get() + 1));
171}
172
173/// Number of subcompose measure passes on this thread that reused a retained
174/// slot without a compose walk. Diagnostic surface for tests and telemetry;
175/// see [`SubcomposeMeasureScope::subcompose`] for when a slot may skip.
176pub fn clean_slot_skip_count() -> u64 {
177    CLEAN_SLOT_SKIPS.with(Cell::get)
178}
179
180struct SubcomposeMeasureScopeInit<'a> {
181    composer: Composer,
182    density: crate::density::Density,
183    state: &'a mut SubcomposeState,
184    constraints: Constraints,
185    measurer: Box<dyn FnMut(NodeId, Constraints) -> Size + 'a>,
186    cached_measure_batch_registrar: CachedMeasureBatchRegistrar<'a>,
187    retained_measure_lookup: RetainedMeasureLookup<'a>,
188    retained_measure_registrar: RetainedMeasureRegistrar<'a>,
189    error: &'a RefCell<Option<NodeError>>,
190    parent_handle: SubcomposeLayoutNodeHandle,
191    root_id: NodeId,
192    placement_scratch: Vec<Placement>,
193}
194
195impl<'a> SubcomposeMeasureScopeImpl<'a> {
196    pub(crate) fn root_id(&self) -> NodeId {
197        self.root_id
198    }
199
200    fn new(init: SubcomposeMeasureScopeInit<'a>) -> Self {
201        Self {
202            composer: init.composer,
203            density_scope: crate::density::DensityMeasureScope::new(init.density),
204            state: init.state,
205            constraints: init.constraints,
206            measurer: init.measurer,
207            cached_measure_batch_registrar: init.cached_measure_batch_registrar,
208            retained_measure_lookup: init.retained_measure_lookup,
209            retained_measure_registrar: init.retained_measure_registrar,
210            error: init.error,
211            parent_handle: init.parent_handle,
212            root_id: init.root_id,
213            placement_scratch: init.placement_scratch,
214            cached_measure_node_scratch: Vec::new(),
215            cached_measure_size_scratch: Vec::new(),
216            cached_measure_missing_scratch: Vec::new(),
217            registered_measurement_node_ids: Vec::new(),
218            pending_commands_applied: false,
219            #[cfg(debug_assertions)]
220            shadow_stash: None,
221        }
222    }
223
224    fn register_measurement_node_id(&mut self, node_id: NodeId) {
225        if !self.registered_measurement_node_ids.contains(&node_id) {
226            self.registered_measurement_node_ids.push(node_id);
227        }
228    }
229
230    fn into_placement_scratch(self) -> Vec<Placement> {
231        self.placement_scratch
232    }
233
234    pub(crate) fn layout_with_placement_builder(
235        &mut self,
236        width: f32,
237        height: f32,
238        build: impl FnOnce(&mut Vec<Placement>),
239    ) -> MeasureResult {
240        self.placement_scratch.clear();
241        build(&mut self.placement_scratch);
242        MeasureResult::new(
243            Size { width, height },
244            std::mem::take(&mut self.placement_scratch),
245        )
246    }
247
248    fn record_error(&self, err: NodeError) {
249        let mut slot = self.error.borrow_mut();
250        if slot.is_none() {
251            eprintln!("[SubcomposeLayout] Error suppressed: {err:?}");
252            *slot = Some(err);
253        }
254    }
255
256    fn owner_chain_deactivation_epoch(&self) -> u64 {
257        self.parent_handle
258            .inner
259            .borrow()
260            .captured_context
261            .as_ref()
262            .map_or(
263                0,
264                cranpose_core::CapturedCompositionContext::owner_chain_deactivation_epoch,
265            )
266    }
267
268    fn ensure_pending_commands_applied(&mut self) -> bool {
269        if self.pending_commands_applied {
270            return true;
271        }
272
273        let telemetry_start = subcompose_telemetry_enabled().then(Instant::now);
274        if let Err(err) = self.composer.apply_pending_commands() {
275            self.record_error(err);
276            return false;
277        }
278        if let Some(start) = telemetry_start {
279            log::warn!(
280                "[subcompose-telemetry] apply_pending_commands_ms={:.2}",
281                start.elapsed().as_secs_f64() * 1000.0
282            );
283        }
284
285        self.pending_commands_applied = true;
286        true
287    }
288
289    fn perform_subcompose<Content>(&mut self, slot_id: SlotId, content: Content) -> Vec<NodeId>
290    where
291        Content: FnMut() + 'static,
292    {
293        let telemetry_start = subcompose_telemetry_enabled().then(Instant::now);
294        let mut inner = self.parent_handle.inner.borrow_mut();
295
296        let (virtual_node_id, is_rebound) =
297            if let Some((node_id, rebound)) = self.state.take_node_from_reusables(slot_id) {
298                (node_id, rebound)
299            } else {
300                let id = allocate_virtual_node_id();
301                let node = LayoutNode::new_virtual();
302                if let Err(e) = self
303                    .composer
304                    .register_virtual_node(id, Box::new(node.clone()))
305                {
306                    eprintln!("[Subcompose] Failed to register virtual node {id}: {e:?}");
307                }
308                register_layout_node(id, &node);
309
310                inner.virtual_nodes.insert(id, Rc::new(node));
311                inner.children.push(id);
312                (id, false)
313            };
314
315        self.composer.record_subcompose_child(virtual_node_id);
316
317        if let Some(v_node) = inner.virtual_nodes.get(&virtual_node_id) {
318            v_node.set_parent(self.root_id);
319        }
320
321        drop(inner);
322
323        let children = self.compose_into_slot(slot_id, virtual_node_id, content);
324        if is_rebound {
325            self.composer.record_rebound_slot_children(&children);
326        }
327        if let Some(start) = telemetry_start {
328            log::warn!(
329                "[subcompose-telemetry] slot={} reused={} children={} subcompose_ms={:.2}",
330                slot_id.raw(),
331                is_rebound,
332                children.len(),
333                start.elapsed().as_secs_f64() * 1000.0
334            );
335        }
336        children
337    }
338
339    fn compose_into_slot<Content>(
340        &mut self,
341        slot_id: SlotId,
342        virtual_node_id: NodeId,
343        content: Content,
344    ) -> Vec<NodeId>
345    where
346        Content: FnMut() + 'static,
347    {
348        let content_holder = self.state.callback_holder(slot_id);
349        content_holder.update(content);
350
351        let _ = self
352            .composer
353            .with_node_mut::<LayoutNode, _>(virtual_node_id, |node| {
354                node.set_parent(self.root_id);
355            });
356
357        let slot_host = self.state.get_or_create_slots(slot_id);
358        self.parent_handle.note_slot_host(&slot_host);
359        let scopes = self
360            .composer
361            .subcompose_slot(&slot_host, Some(virtual_node_id), move |_| {
362                compose_subcompose_slot_content(content_holder);
363            })
364            .map(|((), scopes)| scopes)
365            .unwrap_or_default();
366        self.pending_commands_applied = false;
367
368        let owner_epoch = self.owner_chain_deactivation_epoch();
369        self.state
370            .register_active(slot_id, &[virtual_node_id], &scopes);
371        self.state.mark_slot_composed_current(slot_id, owner_epoch);
372
373        self.composer.get_node_children(virtual_node_id).to_vec()
374    }
375
376    fn activate_clean_retained_slot(&mut self, slot_id: SlotId) -> Option<Vec<NodeId>> {
377        if self.state.has_pending_precompositions(slot_id) {
378            return None;
379        }
380        if !self
381            .state
382            .slot_content_generation_current(slot_id, self.owner_chain_deactivation_epoch())
383        {
384            return None;
385        }
386        if !self.ensure_pending_commands_applied() {
387            return None;
388        }
389        let virtual_node_ids = self.state.activate_current_active_slot(slot_id)?;
390
391        {
392            let inner = self.parent_handle.inner.borrow();
393            for virtual_node_id in &virtual_node_ids {
394                self.composer.record_subcompose_child(*virtual_node_id);
395                if let Some(v_node) = inner.virtual_nodes.get(virtual_node_id) {
396                    v_node.set_parent(self.root_id);
397                }
398            }
399        }
400        for virtual_node_id in &virtual_node_ids {
401            let _ = self
402                .composer
403                .with_node_mut::<LayoutNode, _>(*virtual_node_id, |node| {
404                    node.set_parent(self.root_id);
405                });
406        }
407
408        let mut children = Vec::new();
409        for virtual_node_id in &virtual_node_ids {
410            children.extend(self.composer.get_node_children(*virtual_node_id));
411        }
412        record_clean_slot_skip();
413
414        #[cfg(debug_assertions)]
415        {
416            self.shadow_stash = Some((virtual_node_ids, children.clone()));
417        }
418
419        Some(children)
420    }
421
422    #[cfg(debug_assertions)]
423    fn shadow_verify_clean_slot<Content>(&mut self, slot_id: SlotId, content: Content)
424    where
425        Content: FnMut() + 'static,
426    {
427        let Some((virtual_node_ids, skipped_children)) = self.shadow_stash.take() else {
428            return;
429        };
430        if virtual_node_ids.len() != 1 {
431            return;
432        }
433        let composed = self.compose_into_slot(slot_id, virtual_node_ids[0], content);
434        assert!(
435            composed == skipped_children,
436            "clean-slot skip diverged for slot {slot_id:?}: recomposing produced root \
437             children {composed:?} but the retained slot held {skipped_children:?}. The slot content \
438             read a value that changed between measure passes without any \
439             invalidation path — make that value reactive state, or part of \
440             the subcompose capture key",
441        );
442    }
443
444    pub(crate) fn activate_exact_retained_slot_with_known_children(
445        &mut self,
446        slot_id: SlotId,
447        known_children: &[u64],
448    ) -> Option<(Vec<SubcomposeChild>, bool)> {
449        for &node_id in known_children {
450            NodeId::try_from(node_id).ok()?;
451        }
452
453        let virtual_node_ids = match self.activate_current_active_slot_roots(slot_id) {
454            Some(virtual_node_ids) => {
455                for virtual_node_id in &virtual_node_ids {
456                    self.composer.record_subcompose_child(*virtual_node_id);
457                }
458                virtual_node_ids
459            }
460            None => self.activate_recycled_exact_retained_slot_roots(slot_id)?,
461        };
462
463        if !self.ensure_pending_commands_applied() {
464            return None;
465        }
466
467        let mut activated_children = Vec::with_capacity(known_children.len());
468        for virtual_node_id in virtual_node_ids {
469            activated_children.extend(
470                self.composer
471                    .get_node_children(virtual_node_id)
472                    .iter()
473                    .copied()
474                    .map(SubcomposeChild::new),
475            );
476        }
477        let children_match = activated_children
478            .iter()
479            .map(|child| child.node_id() as u64)
480            .eq(known_children.iter().copied());
481        Some((activated_children, children_match))
482    }
483
484    fn activate_current_active_slot_roots(&mut self, slot_id: SlotId) -> Option<Vec<NodeId>> {
485        self.state.activate_current_active_slot(slot_id)
486    }
487
488    fn activate_recycled_exact_retained_slot_roots(
489        &mut self,
490        slot_id: SlotId,
491    ) -> Option<Vec<NodeId>> {
492        let activation = self.state.take_exact_slot_activation(slot_id)?;
493        let virtual_node_ids = activation.nodes;
494        let scopes = activation.scopes;
495        let reactivate_scopes = activation.reactivate_scopes;
496
497        if reactivate_scopes {
498            let inner = self.parent_handle.inner.borrow();
499            for virtual_node_id in &virtual_node_ids {
500                self.composer.record_subcompose_child(*virtual_node_id);
501                if let Some(v_node) = inner.virtual_nodes.get(virtual_node_id) {
502                    v_node.set_parent(self.root_id);
503                }
504            }
505            for virtual_node_id in &virtual_node_ids {
506                let _ = self
507                    .composer
508                    .with_node_mut::<LayoutNode, _>(*virtual_node_id, |node| {
509                        node.set_parent(self.root_id);
510                    });
511            }
512        } else {
513            for virtual_node_id in &virtual_node_ids {
514                self.composer.record_subcompose_child(*virtual_node_id);
515            }
516        }
517
518        self.state.register_active_with_scope_reactivation(
519            slot_id,
520            &virtual_node_ids,
521            &scopes,
522            reactivate_scopes,
523        );
524        Some(virtual_node_ids)
525    }
526}
527
528impl SubcomposeLayoutScope for SubcomposeMeasureScopeImpl<'_> {
529    fn constraints(&self) -> Constraints {
530        self.constraints
531    }
532
533    fn layout<I>(&mut self, width: f32, height: f32, placements: I) -> MeasureResult
534    where
535        I: IntoIterator<Item = Placement>,
536    {
537        self.layout_with_placement_builder(width, height, |scratch| {
538            scratch.extend(placements);
539        })
540    }
541}
542
543impl cranpose_ui_layout::MeasureScope for SubcomposeMeasureScopeImpl<'_> {
544    fn density(&self) -> f32 {
545        self.density_scope.density()
546    }
547
548    fn font_scale(&self) -> f32 {
549        self.density_scope.font_scale()
550    }
551}
552
553impl SubcomposeMeasureScope for SubcomposeMeasureScopeImpl<'_> {
554    fn subcompose<K, Content>(
555        &mut self,
556        slot_id: SlotId,
557        key: K,
558        content: Content,
559    ) -> Vec<SubcomposeChild>
560    where
561        K: PartialEq + 'static,
562        Content: FnMut() + 'static,
563    {
564        if self.state.retained_capture_key_matches(slot_id, &key)
565            && let Some(children) = self.activate_clean_retained_slot(slot_id)
566        {
567            #[cfg(debug_assertions)]
568            self.shadow_verify_clean_slot(slot_id, content);
569            return children.into_iter().map(SubcomposeChild::new).collect();
570        }
571        self.state.store_retained_capture_key(slot_id, key);
572        let nodes = self.perform_subcompose(slot_id, content);
573        nodes.into_iter().map(SubcomposeChild::new).collect()
574    }
575
576    fn measure(&mut self, child: SubcomposeChild, constraints: Constraints) -> SubcomposePlaceable {
577        if self.error.borrow().is_some() {
578            return SubcomposePlaceable::value(0.0, 0.0, child.node_id);
579        }
580
581        let telemetry_start = subcompose_telemetry_enabled().then(Instant::now);
582        if !self.ensure_pending_commands_applied() {
583            return SubcomposePlaceable::value(0.0, 0.0, child.node_id);
584        }
585
586        let size = (self.measurer)(child.node_id, constraints);
587        self.register_measurement_node_id(child.node_id);
588        if let Some(start) = telemetry_start {
589            log::warn!(
590                "[subcompose-telemetry] child={} measure_ms={:.2} size=({:.2},{:.2})",
591                child.node_id,
592                start.elapsed().as_secs_f64() * 1000.0,
593                size.width,
594                size.height
595            );
596        }
597        SubcomposePlaceable::value(size.width, size.height, child.node_id)
598    }
599
600    fn node_has_no_parent(&self, node_id: NodeId) -> bool {
601        self.composer.node_has_no_parent(node_id)
602    }
603}
604
605impl SubcomposeMeasureScopeImpl<'_> {
606    /// Returns the number of active slots in the subcompose state.
607    ///
608    /// Used by lazy layouts to report statistics about slot usage.
609    pub fn active_slots_count(&self) -> usize {
610        self.state.active_slots_count()
611    }
612
613    /// Returns the number of reusable slots in the pool.
614    ///
615    /// Used by lazy layouts to report statistics about cached slots.
616    pub fn reusable_slots_count(&self) -> usize {
617        self.state.reusable_slots_count()
618    }
619
620    /// Whether `slot_id` still has a composition: active or in the reuse pool.
621    pub(crate) fn slot_is_retained(&self, slot_id: SlotId) -> bool {
622        self.state.slot_is_retained(slot_id)
623    }
624
625    /// Registers the content type for a slot.
626    ///
627    /// Call this before `subcompose()` to enable content-type-aware slot reuse.
628    /// If the policy supports content types (like `ContentTypeReusePolicy`),
629    /// slots with matching content types can reuse each other's nodes.
630    pub fn register_content_type(&mut self, slot_id: SlotId, content_type: u64) {
631        self.state.register_content_type(slot_id, content_type);
632    }
633
634    /// Updates the content type for a slot, handling Some→None transitions.
635    ///
636    /// If `content_type` is `Some(type)`, registers the type for the slot.
637    /// If `content_type` is `None`, removes any previously registered type.
638    /// This ensures stale types don't drive incorrect reuse after transitions.
639    pub fn update_content_type(&mut self, slot_id: SlotId, content_type: Option<u64>) {
640        self.state.update_content_type(slot_id, content_type);
641    }
642
643    pub(crate) fn set_reusable_pool_limits(&mut self, per_type: usize, untyped: usize) {
644        self.state.set_reusable_pool_limits(per_type, untyped);
645    }
646
647    pub(crate) fn focused_slot(&self) -> Option<SlotId> {
648        let mut node_id = crate::active_focus_target()?;
649        while node_id != self.root_id {
650            if let Some(slot) = self.state.active_slot_for_node(node_id) {
651                return Some(slot);
652            }
653            node_id = self.composer.node_parent(node_id).ok()??;
654        }
655        None
656    }
657
658    pub(crate) fn recycle_active_slots_where(&mut self, predicate: impl FnMut(SlotId) -> bool) {
659        let disposed = self.state.recycle_active_slots_where(predicate);
660        debug_assert!(
661            disposed.is_empty(),
662            "lazy subcompose reusable pool limits must retain recycled active slots"
663        );
664    }
665
666    /// Returns whether the last subcomposed slot was reused.
667    ///
668    /// Returns `Some(true)` if the slot already existed (was reused from pool or
669    /// was recomposed), `Some(false)` if it was newly created, or `None` if no
670    /// slot has been subcomposed yet this pass.
671    ///
672    /// This is useful for tracking composition statistics in lazy layouts.
673    pub fn was_last_slot_reused(&self) -> Option<bool> {
674        self.state.was_last_slot_reused()
675    }
676
677    pub(crate) fn measure_retained(
678        &mut self,
679        child: SubcomposeChild,
680        constraints: Constraints,
681    ) -> (SubcomposePlaceable, Option<Rc<MeasuredNode>>) {
682        let placeable = self.measure(child, constraints);
683        let retained = (self.retained_measure_lookup)(child.node_id);
684        (placeable, retained)
685    }
686
687    pub(crate) fn register_retained_measurements(&mut self, measurements: &[Rc<MeasuredNode>]) {
688        if measurements.is_empty() {
689            return;
690        }
691
692        for measured in measurements {
693            self.register_measurement_node_id(measured.node_id());
694        }
695        (self.retained_measure_registrar)(measurements);
696    }
697
698    pub(crate) fn children_need_relayout(&mut self, children: &[SubcomposeChild]) -> bool {
699        if !self.ensure_pending_commands_applied() {
700            return true;
701        }
702
703        let mut root_ids = smallvec::SmallVec::<[NodeId; 8]>::new();
704        root_ids.extend(children.iter().map(SubcomposeChild::node_id));
705        self.composer.nodes_need_measure(&root_ids) || self.composer.nodes_need_layout(&root_ids)
706    }
707
708    pub(crate) fn ensure_cached_measurement_node_ids<I>(
709        &mut self,
710        node_ids: I,
711        constraints: Constraints,
712    ) -> usize
713    where
714        I: IntoIterator<Item = NodeId>,
715    {
716        if self.error.borrow().is_some() || !self.ensure_pending_commands_applied() {
717            return 0;
718        }
719
720        self.cached_measure_node_scratch.clear();
721        self.cached_measure_node_scratch.extend(
722            node_ids
723                .into_iter()
724                .filter(|node_id| !self.registered_measurement_node_ids.contains(node_id)),
725        );
726        if self.cached_measure_node_scratch.is_empty() {
727            return 0;
728        }
729
730        self.cached_measure_size_scratch.clear();
731        (self.cached_measure_batch_registrar)(
732            &self.cached_measure_node_scratch,
733            constraints,
734            &mut self.cached_measure_size_scratch,
735        );
736        self.cached_measure_size_scratch
737            .resize(self.cached_measure_node_scratch.len(), None);
738
739        let mut cached_count = 0;
740        self.cached_measure_missing_scratch.clear();
741        for index in 0..self.cached_measure_node_scratch.len() {
742            let node_id = self.cached_measure_node_scratch[index];
743            if self.cached_measure_size_scratch[index].is_some() {
744                cached_count += 1;
745                self.register_measurement_node_id(node_id);
746            } else {
747                self.cached_measure_missing_scratch.push(node_id);
748            }
749        }
750
751        let mut missing = std::mem::take(&mut self.cached_measure_missing_scratch);
752        for node_id in missing.drain(..) {
753            let _ = self.measure(SubcomposeChild::new(node_id), constraints);
754        }
755        self.cached_measure_missing_scratch = missing;
756
757        cached_count
758    }
759}
760
761fn compose_subcompose_slot_content(holder: cranpose_core::CallbackHolder) {
762    cranpose_core::with_current_composer(|composer| {
763        let holder_for_recompose = holder.clone();
764        composer.set_recompose_callback(move |_composer| {
765            compose_subcompose_slot_content(holder_for_recompose.clone());
766        });
767    });
768
769    let invoke = holder.clone_rc();
770    invoke();
771}
772
773pub type MeasurePolicy =
774    dyn for<'scope> Fn(&mut SubcomposeMeasureScopeImpl<'scope>, Constraints) -> MeasureResult;
775
776/// Node responsible for orchestrating measure-time subcomposition.
777pub struct SubcomposeLayoutNode {
778    inner: Rc<RefCell<SubcomposeLayoutNodeInner>>,
779    parent: Cell<Option<NodeId>>,
780    id: Cell<Option<NodeId>>,
781    needs_measure: Cell<bool>,
782    needs_layout: Cell<bool>,
783    needs_semantics: Cell<bool>,
784    needs_redraw: Cell<bool>,
785    needs_pointer_pass: Cell<bool>,
786    needs_focus_sync: Cell<bool>,
787    virtual_children_count: Cell<usize>,
788    layout_state: RefCell<LayoutState>,
789    cache_handles: LayoutNodeCacheHandles,
790    modifier_slices_snapshot: RefCell<Rc<ModifierNodeSlices>>,
791    modifier_slices_dirty: Cell<bool>,
792}
793
794impl SubcomposeLayoutNode {
795    pub fn new(modifier: Modifier, measure_policy: Rc<MeasurePolicy>) -> Self {
796        let inner = Rc::new(RefCell::new(SubcomposeLayoutNodeInner::new(measure_policy)));
797        let node = Self {
798            inner,
799            parent: Cell::new(None),
800            id: Cell::new(None),
801            needs_measure: Cell::new(true),
802            needs_layout: Cell::new(true),
803            needs_semantics: Cell::new(true),
804            needs_redraw: Cell::new(true),
805            needs_pointer_pass: Cell::new(false),
806            needs_focus_sync: Cell::new(false),
807            virtual_children_count: Cell::new(0),
808            layout_state: RefCell::new(LayoutState::default()),
809            cache_handles: LayoutNodeCacheHandles::default(),
810            modifier_slices_snapshot: RefCell::new(Rc::default()),
811            modifier_slices_dirty: Cell::new(true),
812        };
813        let (invalidations, _) = node.inner.borrow_mut().set_modifier_collect(modifier);
814        node.dispatch_modifier_invalidations(&invalidations, NodeCapabilities::empty());
815        node.note_host_to_the_composition_that_made_it();
816        node
817    }
818
819    fn note_host_to_the_composition_that_made_it(&self) {
820        let host = Rc::clone(&self.inner.borrow().slots);
821        cranpose_core::note_nested_slots_host(&host);
822    }
823
824    /// Creates a SubcomposeLayoutNode with ContentTypeReusePolicy.
825    ///
826    /// Use this for lazy lists to enable content-type-aware slot reuse.
827    /// Slots with matching content types can reuse each other's nodes,
828    /// improving efficiency when scrolling through items with different types.
829    pub fn with_content_type_policy(modifier: Modifier, measure_policy: Rc<MeasurePolicy>) -> Self {
830        let mut inner_data = SubcomposeLayoutNodeInner::new(measure_policy);
831        inner_data
832            .state
833            .set_policy(Box::new(cranpose_core::ContentTypeReusePolicy::new()));
834        let inner = Rc::new(RefCell::new(inner_data));
835        let node = Self {
836            inner,
837            parent: Cell::new(None),
838            id: Cell::new(None),
839            needs_measure: Cell::new(true),
840            needs_layout: Cell::new(true),
841            needs_semantics: Cell::new(true),
842            needs_redraw: Cell::new(true),
843            needs_pointer_pass: Cell::new(false),
844            needs_focus_sync: Cell::new(false),
845            virtual_children_count: Cell::new(0),
846            layout_state: RefCell::new(LayoutState::default()),
847            cache_handles: LayoutNodeCacheHandles::default(),
848            modifier_slices_snapshot: RefCell::new(Rc::default()),
849            modifier_slices_dirty: Cell::new(true),
850        };
851        let (invalidations, _) = node.inner.borrow_mut().set_modifier_collect(modifier);
852        node.dispatch_modifier_invalidations(&invalidations, NodeCapabilities::empty());
853        node.note_host_to_the_composition_that_made_it();
854        node
855    }
856
857    pub fn handle(&self) -> SubcomposeLayoutNodeHandle {
858        SubcomposeLayoutNodeHandle {
859            inner: Rc::clone(&self.inner),
860        }
861    }
862
863    #[doc(hidden)]
864    pub fn debug_scope_ids_by_slot(&self) -> Vec<(u64, Vec<usize>)> {
865        self.inner.borrow().state.debug_scope_ids_by_slot()
866    }
867
868    #[doc(hidden)]
869    pub fn debug_slot_table_for_slot(
870        &self,
871        slot_id: cranpose_core::SlotId,
872    ) -> Option<Vec<cranpose_core::SlotDebugEntry>> {
873        self.inner.borrow().state.debug_slot_table_for_slot(slot_id)
874    }
875
876    #[doc(hidden)]
877    pub fn debug_slot_table_groups_for_slot(
878        &self,
879        slot_id: cranpose_core::SlotId,
880    ) -> Option<Vec<cranpose_core::subcompose::DebugSlotGroup>> {
881        self.inner
882            .borrow()
883            .state
884            .debug_slot_table_groups_for_slot(slot_id)
885    }
886
887    pub fn set_measure_policy(&mut self, policy: Rc<MeasurePolicy>) {
888        let mut inner = self.inner.borrow_mut();
889        if Rc::ptr_eq(&inner.measure_policy, &policy) {
890            return;
891        }
892        inner.set_measure_policy(policy);
893        drop(inner);
894        self.invalidate_subcomposition();
895    }
896
897    /// Records the source composition context for measure-time subcomposition.
898    pub fn set_captured_context(&mut self, context: cranpose_core::CapturedCompositionContext) {
899        self.inner.borrow_mut().captured_context = Some(context);
900    }
901
902    /// Records the grid the composition provided, re-measuring if it moved.
903    ///
904    /// Mirrors [`LayoutNode::set_density`](crate::widgets::nodes::LayoutNode::set_density):
905    /// `SubcomposeLayout` captures this at the same composition site that
906    /// captures the subcomposition context, so the two cannot disagree.
907    pub fn set_density(&mut self, density: crate::density::Density) {
908        let mut inner = self.inner.borrow_mut();
909        if inner.density != density {
910            inner.density = density;
911            drop(inner);
912            self.mark_needs_measure();
913        }
914    }
915
916    pub fn set_modifier(&mut self, modifier: Modifier) {
917        let prev_caps = self.modifier_capabilities();
918        let (invalidations, modifier_changed) = {
919            let mut inner = self.inner.borrow_mut();
920            inner.set_modifier_collect(modifier)
921        };
922        self.dispatch_modifier_invalidations(&invalidations, prev_caps);
923        self.modifier_slices_dirty.set(true);
924        if modifier_changed {
925            self.request_semantics_update();
926        }
927    }
928
929    fn update_modifier_slices_cache(&self) {
930        let inner = self.inner.borrow();
931        let mut snapshot = self.modifier_slices_snapshot.borrow_mut();
932        crate::modifier::collect_modifier_slices_into_shared(
933            inner.modifier_chain.chain(),
934            &mut snapshot,
935        );
936        self.modifier_slices_dirty.set(false);
937    }
938
939    pub(crate) fn mark_modifier_slices_dirty(&self) {
940        self.modifier_slices_dirty.set(true);
941    }
942
943    pub fn set_debug_modifiers(&mut self, enabled: bool) {
944        self.inner.borrow_mut().set_debug_modifiers(enabled);
945    }
946
947    pub fn modifier(&self) -> Modifier {
948        self.handle().modifier()
949    }
950
951    pub fn resolved_modifiers(&self) -> ResolvedModifiers {
952        self.inner.borrow().resolved_modifiers
953    }
954
955    /// Returns a clone of the current layout state.
956    pub fn layout_state(&self) -> LayoutState {
957        self.layout_state.borrow().clone()
958    }
959
960    pub(crate) fn cache_handles(&self) -> LayoutNodeCacheHandles {
961        self.cache_handles.clone()
962    }
963
964    /// Updates the position of this node. Called during placement.
965    /// [`LayoutState::place`] self-reports actual moves to the scene phase.
966    pub fn set_position(&self, position: Point) {
967        self.layout_state.borrow_mut().place(position);
968    }
969
970    /// Updates the measured size of this node. Called during measurement.
971    /// [`LayoutState::set_size`] self-reports actual changes to the scene
972    /// phase.
973    pub fn set_measured_size(&self, size: Size) {
974        self.layout_state.borrow_mut().set_size(size);
975    }
976
977    /// Clears the is_placed flag. Called at the start of a layout pass.
978    pub fn clear_placed(&self) {
979        self.layout_state.borrow_mut().clear_placed();
980    }
981
982    /// Semantics reported by this node's live modifier chain.
983    pub fn semantics_configuration(&self) -> Option<SemanticsConfiguration> {
984        crate::modifier::collect_semantics_from_chain(self.inner.borrow().modifier_chain.chain())
985    }
986
987    /// Whether this node's modifiers make it modal or hidden.
988    pub fn semantics_reach(&self) -> cranpose_foundation::SemanticsReach {
989        crate::modifier::semantics_reach_of_chain(self.inner.borrow().modifier_chain.chain())
990    }
991
992    /// Returns the modifier slices snapshot for rendering.
993    pub fn modifier_slices_snapshot(&self) -> Rc<ModifierNodeSlices> {
994        if self.modifier_slices_dirty.get() {
995            self.update_modifier_slices_cache();
996        }
997        self.modifier_slices_snapshot.borrow().clone()
998    }
999
1000    pub fn state(&self) -> Ref<'_, SubcomposeState> {
1001        Ref::map(self.inner.borrow(), |inner| &inner.state)
1002    }
1003
1004    pub fn state_mut(&self) -> RefMut<'_, SubcomposeState> {
1005        RefMut::map(self.inner.borrow_mut(), |inner| &mut inner.state)
1006    }
1007
1008    pub fn invalidate_subcomposition(&self) {
1009        self.inner.borrow().state.invalidate_scopes();
1010        self.mark_needs_measure();
1011        if let Some(id) = self.id.get() {
1012            cranpose_core::bubble_measure_dirty_in_composer(id);
1013        }
1014    }
1015
1016    pub fn request_measure_recompose(&self) {
1017        self.mark_needs_measure();
1018        if let Some(id) = self.id.get() {
1019            cranpose_core::bubble_measure_dirty_in_composer(id);
1020        }
1021    }
1022
1023    /// Calls `f` with the children this node placed in its last layout, in
1024    /// placement order, without copying them.
1025    pub fn with_active_children<R>(&self, f: impl FnOnce(&[NodeId]) -> R) -> R {
1026        f(&self.inner.borrow().last_placements)
1027    }
1028
1029    /// Mark this node as needing measure. Also marks it as needing layout.
1030    pub fn mark_needs_measure(&self) {
1031        self.needs_measure.set(true);
1032        self.needs_layout.set(true);
1033    }
1034
1035    /// Mark this node as needing layout (but not necessarily measure).
1036    pub fn mark_needs_layout_flag(&self) {
1037        self.needs_layout.set(true);
1038    }
1039
1040    /// Mark this node as needing redraw without forcing measure/layout.
1041    pub fn mark_needs_redraw(&self) {
1042        self.needs_redraw.set(true);
1043        if let Some(id) = self.id.get() {
1044            crate::schedule_draw_repass(id);
1045        }
1046        crate::request_render_invalidation();
1047    }
1048
1049    /// Check if this node needs measure.
1050    pub fn needs_measure(&self) -> bool {
1051        self.needs_measure.get()
1052    }
1053
1054    pub(crate) fn clear_needs_measure(&self) {
1055        self.needs_measure.set(false);
1056    }
1057
1058    pub(crate) fn clear_needs_layout(&self) {
1059        self.needs_layout.set(false);
1060    }
1061
1062    /// Mark this node as needing semantics recomputation.
1063    pub fn mark_needs_semantics(&self) {
1064        self.needs_semantics.set(true);
1065    }
1066
1067    pub(crate) fn clear_needs_semantics(&self) {
1068        self.needs_semantics.set(false);
1069    }
1070
1071    #[cfg(test)]
1072    pub(crate) fn clear_needs_semantics_for_tests(&self) {
1073        self.clear_needs_semantics();
1074    }
1075
1076    /// Returns true when this node requested a redraw since the last render pass.
1077    pub fn needs_redraw(&self) -> bool {
1078        self.needs_redraw.get()
1079    }
1080
1081    pub fn clear_needs_redraw(&self) {
1082        self.needs_redraw.set(false);
1083    }
1084
1085    /// Marks this node as needing a fresh pointer-input pass.
1086    pub fn mark_needs_pointer_pass(&self) {
1087        self.needs_pointer_pass.set(true);
1088    }
1089
1090    /// Returns true when pointer-input state needs to be recomputed.
1091    pub fn needs_pointer_pass(&self) -> bool {
1092        self.needs_pointer_pass.get()
1093    }
1094
1095    /// Clears the pointer-input dirty flag after hosts service it.
1096    pub fn clear_needs_pointer_pass(&self) {
1097        self.needs_pointer_pass.set(false);
1098    }
1099
1100    /// Marks this node as needing a focus synchronization.
1101    pub fn mark_needs_focus_sync(&self) {
1102        self.needs_focus_sync.set(true);
1103    }
1104
1105    /// Returns true when focus state needs to be synchronized.
1106    pub fn needs_focus_sync(&self) -> bool {
1107        self.needs_focus_sync.get()
1108    }
1109
1110    /// Clears the focus dirty flag after the focus manager processes it.
1111    pub fn clear_needs_focus_sync(&self) {
1112        self.needs_focus_sync.set(false);
1113    }
1114
1115    fn request_semantics_update(&self) {
1116        let already_dirty = self.needs_semantics.replace(true);
1117        if already_dirty {
1118            return;
1119        }
1120
1121        if let Some(id) = self.id.get() {
1122            cranpose_core::queue_semantics_invalidation(id);
1123        }
1124    }
1125
1126    /// Returns the modifier capabilities for this node.
1127    pub fn modifier_capabilities(&self) -> NodeCapabilities {
1128        self.inner.borrow().modifier_capabilities
1129    }
1130
1131    pub fn has_layout_modifier_nodes(&self) -> bool {
1132        self.modifier_capabilities()
1133            .contains(NodeCapabilities::LAYOUT)
1134    }
1135
1136    pub fn has_draw_modifier_nodes(&self) -> bool {
1137        self.modifier_capabilities()
1138            .contains(NodeCapabilities::DRAW)
1139    }
1140
1141    pub fn has_pointer_input_modifier_nodes(&self) -> bool {
1142        self.modifier_capabilities()
1143            .contains(NodeCapabilities::POINTER_INPUT)
1144    }
1145
1146    pub fn has_semantics_modifier_nodes(&self) -> bool {
1147        self.modifier_capabilities()
1148            .contains(NodeCapabilities::SEMANTICS)
1149    }
1150
1151    pub fn has_focus_modifier_nodes(&self) -> bool {
1152        self.modifier_capabilities()
1153            .contains(NodeCapabilities::FOCUS)
1154    }
1155
1156    fn dispatch_modifier_invalidations(
1157        &self,
1158        invalidations: &[ModifierInvalidation],
1159        prev_caps: NodeCapabilities,
1160    ) {
1161        let curr_caps = self.modifier_capabilities();
1162        for invalidation in invalidations {
1163            self.modifier_slices_dirty.set(true);
1164            let invalidation_caps = invalidation.capabilities();
1165            let has_capability = |capability| {
1166                curr_caps.contains(capability)
1167                    || prev_caps.contains(capability)
1168                    || invalidation_caps.contains(capability)
1169            };
1170            match invalidation.kind() {
1171                InvalidationKind::Layout => {
1172                    if has_capability(NodeCapabilities::LAYOUT) {
1173                        self.mark_needs_measure();
1174                    }
1175                }
1176                InvalidationKind::Draw => {
1177                    if has_capability(NodeCapabilities::DRAW) {
1178                        self.mark_needs_redraw();
1179                    }
1180                }
1181                InvalidationKind::PointerInput => {
1182                    if has_capability(NodeCapabilities::POINTER_INPUT) {
1183                        self.mark_needs_pointer_pass();
1184                        crate::request_pointer_invalidation();
1185                        if let Some(id) = self.id.get() {
1186                            crate::schedule_pointer_repass(id);
1187                        }
1188                    }
1189                }
1190                InvalidationKind::Semantics => {
1191                    self.request_semantics_update();
1192                }
1193                InvalidationKind::Focus => {
1194                    if has_capability(NodeCapabilities::FOCUS) {
1195                        self.mark_needs_focus_sync();
1196                        crate::request_focus_invalidation();
1197                        if let Some(id) = self.id.get() {
1198                            crate::schedule_focus_invalidation(id);
1199                        }
1200                    }
1201                }
1202            }
1203        }
1204    }
1205}
1206
1207impl cranpose_core::Node for SubcomposeLayoutNode {
1208    fn mount(&mut self) {
1209        let mut inner = self.inner.borrow_mut();
1210        let (chain, mut context) = inner.modifier_chain.chain_and_context_mut();
1211        chain.repair_chain();
1212        chain.attach_nodes(&mut *context);
1213    }
1214
1215    fn unmount(&mut self) {
1216        self.inner
1217            .borrow_mut()
1218            .modifier_chain
1219            .chain_mut()
1220            .detach_nodes();
1221    }
1222
1223    fn insert_child(&mut self, child: NodeId) -> bool {
1224        let mut inner = self.inner.borrow_mut();
1225        if inner.children.contains(&child) {
1226            return false;
1227        }
1228        if is_virtual_node(child) {
1229            let count = self.virtual_children_count.get();
1230            self.virtual_children_count.set(count + 1);
1231        }
1232        inner.children.push(child);
1233        true
1234    }
1235
1236    fn remove_child(&mut self, child: NodeId) -> bool {
1237        let mut inner = self.inner.borrow_mut();
1238        let before = inner.children.len();
1239        inner.children.retain(|&id| id != child);
1240        let removed = inner.children.len() < before;
1241        if removed && is_virtual_node(child) {
1242            let count = self.virtual_children_count.get();
1243            if count > 0 {
1244                self.virtual_children_count.set(count - 1);
1245            }
1246        }
1247        removed
1248    }
1249
1250    fn move_child(&mut self, from: usize, to: usize) {
1251        let mut inner = self.inner.borrow_mut();
1252        if from == to || from >= inner.children.len() {
1253            return;
1254        }
1255        let child = inner.children.remove(from);
1256        let target = to.min(inner.children.len());
1257        inner.children.insert(target, child);
1258    }
1259
1260    fn update_children(&mut self, children: &[NodeId]) {
1261        let mut inner = self.inner.borrow_mut();
1262        inner.children.clear();
1263        inner.children.extend_from_slice(children);
1264    }
1265
1266    fn collect_children_into(&self, out: &mut SmallVec<[NodeId; 8]>) {
1267        out.clear();
1268        self.with_active_children(|children| out.extend_from_slice(children));
1269    }
1270
1271    fn collect_owned_children_into(&self, out: &mut SmallVec<[NodeId; 8]>) {
1272        out.clear();
1273        out.extend_from_slice(&self.inner.borrow().children);
1274    }
1275
1276    fn set_node_id(&mut self, id: NodeId) {
1277        self.id.set(Some(id));
1278        self.layout_state.borrow_mut().set_node_id(id);
1279        {
1280            let mut inner = self.inner.borrow_mut();
1281            inner.node_id = Some(id);
1282            inner.modifier_chain.set_node_id(Some(id));
1283        }
1284        // The slices carry the node's id; they are collected again when next read.
1285        self.modifier_slices_dirty.set(true);
1286    }
1287
1288    fn on_attached_to_parent(&mut self, parent: NodeId) {
1289        self.parent.set(Some(parent));
1290    }
1291
1292    fn on_removed_from_parent(&mut self) {
1293        self.parent.set(None);
1294        self.inner.borrow().state.bump_content_generation();
1295    }
1296
1297    fn parent(&self) -> Option<NodeId> {
1298        self.parent.get()
1299    }
1300
1301    fn mark_needs_layout(&self) {
1302        self.needs_layout.set(true);
1303    }
1304
1305    fn needs_layout(&self) -> bool {
1306        self.needs_layout.get()
1307    }
1308
1309    fn mark_needs_measure(&self) {
1310        self.needs_measure.set(true);
1311        self.needs_layout.set(true);
1312    }
1313
1314    fn needs_measure(&self) -> bool {
1315        self.needs_measure.get()
1316    }
1317
1318    fn mark_needs_semantics(&self) {
1319        self.needs_semantics.set(true);
1320    }
1321
1322    fn needs_semantics(&self) -> bool {
1323        self.needs_semantics.get()
1324    }
1325
1326    fn set_parent_for_bubbling(&mut self, parent: NodeId) {
1327        if self.parent.get().is_none() {
1328            self.parent.set(Some(parent));
1329        }
1330    }
1331}
1332
1333#[derive(Clone)]
1334pub struct SubcomposeLayoutNodeHandle {
1335    inner: Rc<RefCell<SubcomposeLayoutNodeInner>>,
1336}
1337
1338impl SubcomposeLayoutNodeHandle {
1339    pub(crate) fn note_slot_host(&self, slot_host: &Rc<cranpose_core::SlotsHost>) {
1340        let Ok(inner) = self.inner.try_borrow() else {
1341            return;
1342        };
1343        if Rc::ptr_eq(&inner.slots, slot_host) {
1344            return;
1345        }
1346        inner.slots.note_nested_host(slot_host);
1347    }
1348
1349    pub(crate) fn measured_children_scratch(
1350        &self,
1351    ) -> Rc<RefCell<HashMap<NodeId, Rc<MeasuredNode>>>> {
1352        let scratch = {
1353            let inner = self.inner.borrow();
1354            Rc::clone(&inner.measured_children_scratch)
1355        };
1356        scratch.borrow_mut().clear();
1357        scratch
1358    }
1359
1360    pub fn modifier(&self) -> Modifier {
1361        self.inner.borrow().modifier.clone()
1362    }
1363
1364    pub fn layout_properties(&self) -> crate::modifier::LayoutProperties {
1365        self.resolved_modifiers().layout_properties()
1366    }
1367
1368    pub fn resolved_modifiers(&self) -> ResolvedModifiers {
1369        self.inner.borrow().resolved_modifiers
1370    }
1371
1372    pub fn total_offset(&self) -> Point {
1373        self.resolved_modifiers().offset()
1374    }
1375
1376    pub fn modifier_capabilities(&self) -> NodeCapabilities {
1377        self.inner.borrow().modifier_capabilities
1378    }
1379
1380    pub fn has_layout_modifier_nodes(&self) -> bool {
1381        self.modifier_capabilities()
1382            .contains(NodeCapabilities::LAYOUT)
1383    }
1384
1385    pub fn has_draw_modifier_nodes(&self) -> bool {
1386        self.modifier_capabilities()
1387            .contains(NodeCapabilities::DRAW)
1388    }
1389
1390    pub fn has_pointer_input_modifier_nodes(&self) -> bool {
1391        self.modifier_capabilities()
1392            .contains(NodeCapabilities::POINTER_INPUT)
1393    }
1394
1395    pub fn has_semantics_modifier_nodes(&self) -> bool {
1396        self.modifier_capabilities()
1397            .contains(NodeCapabilities::SEMANTICS)
1398    }
1399
1400    pub fn has_focus_modifier_nodes(&self) -> bool {
1401        self.modifier_capabilities()
1402            .contains(NodeCapabilities::FOCUS)
1403    }
1404
1405    pub fn set_debug_modifiers(&self, enabled: bool) {
1406        self.inner.borrow_mut().set_debug_modifiers(enabled);
1407    }
1408
1409    pub fn measure<'a>(
1410        &self,
1411        composer: &Composer,
1412        node_id: NodeId,
1413        constraints: Constraints,
1414        measurer: Box<dyn FnMut(NodeId, Constraints) -> Size + 'a>,
1415        mut cached_measure_registrar: Box<dyn FnMut(NodeId, Constraints) -> Option<Size> + 'a>,
1416        error: &'a RefCell<Option<NodeError>>,
1417    ) -> Result<MeasureResult, NodeError> {
1418        self.measure_with_cached_batch(
1419            composer,
1420            node_id,
1421            constraints,
1422            CachedBatchMeasureInputs {
1423                measurer,
1424                cached_measure_batch_registrar: Box::new(
1425                    move |node_ids, child_constraints, out| {
1426                        out.clear();
1427                        out.reserve(node_ids.len());
1428                        for &child_id in node_ids {
1429                            out.push(cached_measure_registrar(child_id, child_constraints));
1430                        }
1431                    },
1432                ),
1433                retained_measure_lookup: Box::new(|_| None),
1434                retained_measure_registrar: Box::new(|_| {}),
1435                error,
1436            },
1437        )
1438    }
1439
1440    pub(crate) fn measure_with_cached_batch(
1441        &self,
1442        composer: &Composer,
1443        node_id: NodeId,
1444        constraints: Constraints,
1445        callbacks: CachedBatchMeasureInputs<'_>,
1446    ) -> Result<MeasureResult, NodeError> {
1447        let CachedBatchMeasureInputs {
1448            measurer,
1449            cached_measure_batch_registrar,
1450            retained_measure_lookup,
1451            retained_measure_registrar,
1452            error,
1453        } = callbacks;
1454        let (policy, mut state, slots_host, placement_scratch, captured_context, density) = {
1455            let mut inner = self.inner.borrow_mut();
1456            let policy = Rc::clone(&inner.measure_policy);
1457            let state = std::mem::take(&mut inner.state);
1458            let slots_host = Rc::clone(&inner.slots);
1459            let placement_scratch = std::mem::take(&mut inner.placement_scratch);
1460            let captured_context = inner.captured_context.clone();
1461            let density = inner.density;
1462            (
1463                policy,
1464                state,
1465                slots_host,
1466                placement_scratch,
1467                captured_context,
1468                density,
1469            )
1470        };
1471        state.begin_pass();
1472
1473        let previous = composer.phase();
1474        if !matches!(previous, Phase::Measure | Phase::Layout) {
1475            composer.enter_phase(Phase::Measure);
1476        }
1477
1478        let constraints_copy = constraints;
1479        let fallback_context;
1480        let context = if let Some(context) = captured_context.as_ref() {
1481            context
1482        } else {
1483            fallback_context = composer.capture_composition_context();
1484            &fallback_context
1485        };
1486        let ((result, placement_scratch), _) = composer.subcompose_slot_with_context(
1487            &slots_host,
1488            Some(node_id),
1489            context,
1490            |inner_composer| {
1491                let mut scope = SubcomposeMeasureScopeImpl::new(SubcomposeMeasureScopeInit {
1492                    composer: inner_composer.clone(),
1493                    density,
1494                    state: &mut state,
1495                    constraints: constraints_copy,
1496                    measurer,
1497                    cached_measure_batch_registrar,
1498                    retained_measure_lookup,
1499                    retained_measure_registrar,
1500                    error,
1501                    parent_handle: self.clone(),
1502                    root_id: node_id,
1503                    placement_scratch,
1504                });
1505                let result = (policy)(&mut scope, constraints_copy);
1506                (result, scope.into_placement_scratch())
1507            },
1508        )?;
1509
1510        state.finish_pass();
1511
1512        if previous != composer.phase() {
1513            composer.enter_phase(previous);
1514        }
1515
1516        {
1517            let mut inner = self.inner.borrow_mut();
1518            inner.state = state;
1519            inner.placement_scratch = placement_scratch;
1520
1521            inner.replace_placed_children(
1522                result.placements.iter().map(|placement| placement.node_id),
1523            );
1524        }
1525
1526        Ok(result)
1527    }
1528
1529    pub(crate) fn recycle_placement_scratch(&self, mut placements: Vec<Placement>) {
1530        placements.clear();
1531        let mut inner = self.inner.borrow_mut();
1532        if placements.capacity() > inner.placement_scratch.capacity() {
1533            inner.placement_scratch = placements;
1534        }
1535    }
1536
1537    pub fn set_active_children<I>(&self, children: I)
1538    where
1539        I: IntoIterator<Item = NodeId>,
1540    {
1541        self.inner.borrow_mut().replace_placed_children(children);
1542    }
1543}
1544
1545struct SubcomposeLayoutNodeInner {
1546    modifier: Modifier,
1547    modifier_chain: ModifierChainHandle,
1548    resolved_modifiers: ResolvedModifiers,
1549    modifier_capabilities: NodeCapabilities,
1550    state: SubcomposeState,
1551    measure_policy: Rc<MeasurePolicy>,
1552    children: Vec<NodeId>,
1553    slots: Rc<SlotsHost>,
1554    debug_modifiers: bool,
1555    virtual_nodes: HashMap<NodeId, Rc<LayoutNode>>,
1556    node_id: Option<NodeId>,
1557    last_placements: Vec<NodeId>,
1558    placement_scratch: Vec<Placement>,
1559    measured_children_scratch: Rc<RefCell<HashMap<NodeId, Rc<MeasuredNode>>>>,
1560    captured_context: Option<cranpose_core::CapturedCompositionContext>,
1561    density: crate::density::Density,
1562}
1563
1564impl SubcomposeLayoutNodeInner {
1565    /// Writes the children this node placed, self-reporting an actual change
1566    /// to the scene phase the way [`LayoutState::place`] reports a move.
1567    ///
1568    /// These children *are* the node's render-graph children, and a
1569    /// subcomposition changes them without the applier seeing an insert or a
1570    /// remove: a lazy row that leaves the content keeps its nodes parked in
1571    /// the reusable pool, still attached and still carrying the position it
1572    /// was last placed at. Nothing else in the frame then says the child set
1573    /// shrank, so a scoped scene update would keep the departed row's layer
1574    /// and paint it under the row that took its place.
1575    fn replace_placed_children<I>(&mut self, children: I)
1576    where
1577        I: IntoIterator<Item = NodeId>,
1578    {
1579        let mut changed = false;
1580        let mut count = 0usize;
1581        for child in children {
1582            match self.last_placements.get(count) {
1583                Some(&placed) if placed == child => {}
1584                Some(_) => {
1585                    self.last_placements[count] = child;
1586                    changed = true;
1587                }
1588                None => {
1589                    self.last_placements.push(child);
1590                    changed = true;
1591                }
1592            }
1593            count += 1;
1594        }
1595        if self.last_placements.len() > count {
1596            self.last_placements.truncate(count);
1597            changed = true;
1598        }
1599        if changed && let Some(id) = self.node_id {
1600            crate::render_state::record_geometry_scene_node(id);
1601        }
1602    }
1603
1604    fn new(measure_policy: Rc<MeasurePolicy>) -> Self {
1605        Self {
1606            modifier: Modifier::empty(),
1607            modifier_chain: ModifierChainHandle::new(),
1608            resolved_modifiers: ResolvedModifiers::default(),
1609            modifier_capabilities: NodeCapabilities::default(),
1610            state: SubcomposeState::default(),
1611            measure_policy,
1612            children: Vec::new(),
1613            slots: Rc::new(SlotsHost::new(SlotTable::default())),
1614            debug_modifiers: false,
1615            virtual_nodes: HashMap::new(),
1616            node_id: None,
1617            last_placements: Vec::new(),
1618            placement_scratch: Vec::new(),
1619            measured_children_scratch: Rc::new(RefCell::new(HashMap::default())),
1620            captured_context: None,
1621            density: crate::density::Density::default(),
1622        }
1623    }
1624
1625    fn set_measure_policy(&mut self, policy: Rc<MeasurePolicy>) {
1626        self.measure_policy = policy;
1627        if let Err(err) = self.slots.reset() {
1628            log::error!(
1629                "failed to reset root measurement slots after measure policy update: {err}"
1630            );
1631        }
1632    }
1633
1634    fn set_modifier_collect(&mut self, modifier: Modifier) -> (Vec<ModifierInvalidation>, bool) {
1635        let modifier_changed = !self.modifier.structural_eq(&modifier);
1636        self.modifier = modifier;
1637        self.modifier_chain.set_debug_logging(self.debug_modifiers);
1638        let modifier_local_invalidations = self.modifier_chain.update(&self.modifier);
1639        self.resolved_modifiers = self.modifier_chain.resolved_modifiers();
1640        self.modifier_capabilities = self.modifier_chain.capabilities();
1641
1642        let mut invalidations = self.modifier_chain.take_invalidations();
1643        invalidations.extend(modifier_local_invalidations);
1644
1645        (invalidations, modifier_changed)
1646    }
1647
1648    fn set_debug_modifiers(&mut self, enabled: bool) {
1649        self.debug_modifiers = enabled;
1650        self.modifier_chain.set_debug_logging(enabled);
1651    }
1652}
1653
1654#[cfg(test)]
1655#[path = "tests/subcompose_layout_tests.rs"]
1656mod tests;