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