Skip to main content

cranpose_core/
composer.rs

1use std::{
2    any::Any,
3    cell::{Cell, RefCell, RefMut},
4    hash::Hash,
5    marker::PhantomData,
6    rc::{Rc, Weak},
7};
8
9use smallvec::SmallVec;
10
11use crate::{
12    AnchorId, Applier, ApplierHost, COMMAND_FLUSH_THRESHOLD, ChildList, Command, CommandQueue,
13    CompositionLocal, DirtyBubble, Key, LocalKey, LocalStackSnapshot, LocalStateEntry,
14    MutableState, Node, NodeError, NodeId, Owned, ProvidedValue, RecomposeOptions, RecomposeScope,
15    RecomposeScopeInner, RecycledNode, RetentionMode, RetentionPolicy, RuntimeHandle, ScopeId,
16    SlotId, SlotPassOutcome, SlotTable, SlotsHost, SnapshotStateList, SnapshotStateMap,
17    SnapshotStateObserver, StaticCompositionLocal, StaticLocalEntry, SubcomposeState,
18    collections::map::{HashMap, HashSet},
19    composer_context, empty_local_stack, explicit_group_key_seed,
20    retention::{RetainKey, RetentionManager},
21    runtime,
22    slot::{FinishGroupResult, GroupStart, GroupStartKind, PayloadKind, ValueSlotId},
23};
24
25pub struct ValueSlotHandle<'pass, T: 'static> {
26    slot: ValueSlotId,
27    _pass: PhantomData<&'pass Composer>,
28    _value: PhantomData<fn() -> T>,
29}
30
31impl<T: 'static> Copy for ValueSlotHandle<'_, T> {}
32
33impl<T: 'static> Clone for ValueSlotHandle<'_, T> {
34    fn clone(&self) -> Self {
35        *self
36    }
37}
38
39impl<T: 'static> ValueSlotHandle<'_, T> {
40    pub(crate) fn new(slot: ValueSlotId) -> Self {
41        Self {
42            slot,
43            _pass: PhantomData,
44            _value: PhantomData,
45        }
46    }
47
48    pub(crate) fn slot(self) -> ValueSlotId {
49        self.slot
50    }
51}
52
53fn slots_storage_key(host: &Rc<SlotsHost>) -> usize {
54    host.storage_key()
55}
56
57fn bind_slots_host_to_runtime_state(
58    state: &Rc<ComposerRuntimeState>,
59    host: &Rc<SlotsHost>,
60) -> Rc<SlotsHost> {
61    if let Some(bound_state) = host.runtime_state() {
62        if Rc::ptr_eq(&bound_state, state) {
63            state.bind_slots_host(host);
64            return Rc::clone(host);
65        }
66        drop(bound_state);
67        if host.rebind_orphaned_runtime_state(state) {
68            state.bind_slots_host(host);
69            return Rc::clone(host);
70        }
71        log::error!(
72            "slot host already belongs to a different composer runtime state; using a fresh slot host"
73        );
74        let replacement = Rc::new(SlotsHost::new(SlotTable::new()));
75        state.bind_slots_host(&replacement);
76        return replacement;
77    }
78    state.bind_slots_host(host);
79    Rc::clone(host)
80}
81
82struct GroupEntry {
83    key: crate::slot::GroupKey,
84    restored: Option<crate::slot::DetachedSubtree>,
85    placeholder_for: Option<crate::slot::GroupKey>,
86}
87
88struct GroupScopeEntry<'a> {
89    parent_scope: Option<RecomposeScope>,
90    options: RecomposeOptions,
91    start_kind: GroupStartKind,
92    host: &'a Rc<SlotsHost>,
93    restored_scopes: Option<Vec<ScopeId>>,
94}
95
96struct SlotHostPassGuard {
97    core: Rc<ComposerCore>,
98    host: Rc<SlotsHost>,
99    active: bool,
100}
101
102impl SlotHostPassGuard {
103    fn close(&mut self) {
104        if !self.active {
105            return;
106        }
107        if self.host.has_active_pass() {
108            self.host.abandon_active_pass();
109        }
110        match self.core.slot_hosts.borrow_mut().pop() {
111            Some(host) if Rc::ptr_eq(&host, &self.host) => {}
112            Some(_) => {
113                log::error!("slot host stack mismatch while closing slot host pass");
114            }
115            None => {
116                log::error!("slot host stack underflow while closing slot host pass");
117            }
118        }
119        self.active = false;
120    }
121}
122
123impl Drop for SlotHostPassGuard {
124    fn drop(&mut self) {
125        self.close();
126    }
127}
128
129pub(crate) struct PendingMovable {
130    pub(crate) key: crate::slot::GroupKey,
131    pub(crate) placeholder: AnchorId,
132    pub(crate) parent_scope: Option<ScopeId>,
133}
134
135fn movable_retain_key(id: Key) -> RetainKey {
136    RetainKey::for_group(
137        None,
138        crate::slot::GroupKey::new(crate::slot::MOVABLE_STATIC_KEY, Some(id), 0),
139    )
140}
141
142pub(crate) struct ComposerRuntimeState {
143    scope_registry: RefCell<HashMap<ScopeId, RecomposeScope>>,
144    retention_by_host: RefCell<HashMap<usize, RetentionManager>>,
145    pending_movables_by_host: RefCell<HashMap<usize, Vec<PendingMovable>>>,
146    retention_policy: Cell<RetentionPolicy>,
147    live_hosts: RefCell<HashMap<usize, std::rc::Weak<SlotsHost>>>,
148    applier_host: RefCell<Option<std::rc::Weak<dyn ApplierHost>>>,
149}
150
151impl Default for ComposerRuntimeState {
152    fn default() -> Self {
153        Self {
154            scope_registry: RefCell::new(HashMap::default()),
155            retention_by_host: RefCell::new(HashMap::default()),
156            pending_movables_by_host: RefCell::new(HashMap::default()),
157            retention_policy: Cell::new(RetentionPolicy::default()),
158            live_hosts: RefCell::new(HashMap::default()),
159            applier_host: RefCell::new(None),
160        }
161    }
162}
163
164impl ComposerRuntimeState {
165    pub(crate) fn clear_host_storage_key(&self, host_key: usize) {
166        self.retention_by_host.borrow_mut().remove(&host_key);
167        self.pending_movables_by_host.borrow_mut().remove(&host_key);
168        self.live_hosts.borrow_mut().remove(&host_key);
169        let removed_scopes = {
170            let mut removed = Vec::new();
171            self.scope_registry.borrow_mut().retain(|_, scope| {
172                if scope.slots_storage_key() == Some(host_key) {
173                    removed.push(scope.clone());
174                    false
175                } else {
176                    true
177                }
178            });
179            removed
180        };
181        for scope in removed_scopes {
182            scope.deactivate();
183        }
184    }
185
186    pub(crate) fn force_recompose_host_scopes(&self, host_key: usize) {
187        for scope in self.scope_registry.borrow().values() {
188            if scope.slots_storage_key() == Some(host_key) {
189                scope.force_recompose();
190            }
191        }
192    }
193
194    pub(crate) fn bind_applier_host(&self, applier: &Rc<dyn ApplierHost>) {
195        *self.applier_host.borrow_mut() = Some(Rc::downgrade(applier));
196    }
197
198    pub(crate) fn has_live_applier_host(&self) -> bool {
199        self.applier_host
200            .borrow()
201            .as_ref()
202            .and_then(std::rc::Weak::upgrade)
203            .is_some()
204    }
205
206    pub(crate) fn bind_slots_host(self: &Rc<Self>, host: &Rc<SlotsHost>) {
207        host.bind_runtime_state(self);
208        self.live_hosts
209            .borrow_mut()
210            .insert(host.storage_key(), Rc::downgrade(host));
211    }
212
213    pub(crate) fn scope_for_id(&self, scope_id: ScopeId) -> Option<RecomposeScope> {
214        self.scope_registry.borrow().get(&scope_id).cloned()
215    }
216
217    pub(crate) fn register_scope(&self, scope: &RecomposeScope) {
218        self.scope_registry
219            .borrow_mut()
220            .insert(scope.id(), scope.clone());
221    }
222
223    pub(crate) fn remove_scope(&self, scope_id: ScopeId) -> Option<RecomposeScope> {
224        self.scope_registry.borrow_mut().remove(&scope_id)
225    }
226
227    pub(crate) fn set_retention_policy(&self, policy: RetentionPolicy) {
228        self.retention_policy.set(policy);
229    }
230
231    pub(crate) fn retention_policy(&self) -> RetentionPolicy {
232        self.retention_policy.get()
233    }
234
235    pub(crate) fn scope_registry_len(&self) -> usize {
236        self.scope_registry.borrow().len()
237    }
238
239    pub(crate) fn take_retained(
240        &self,
241        host: &Rc<SlotsHost>,
242        key: RetainKey,
243        preflight: impl FnOnce(&mut crate::slot::DetachedSubtree) -> bool,
244    ) -> Option<crate::slot::DetachedSubtree> {
245        let host_key = slots_storage_key(host);
246        let mut retention = self.retention_by_host.borrow_mut();
247        let subtree = retention
248            .get_mut(&host_key)?
249            .take_after_restore_preflight(key, preflight);
250        if retention
251            .get(&host_key)
252            .is_some_and(|manager| manager.is_empty() && manager.evictions_total() == 0)
253        {
254            retention.remove(&host_key);
255        }
256        subtree
257    }
258
259    pub(crate) fn insert_retained(
260        &self,
261        host: &Rc<SlotsHost>,
262        key: RetainKey,
263        subtree: crate::slot::DetachedSubtree,
264        pinned: bool,
265    ) -> Vec<crate::slot::DetachedSubtree> {
266        let policy = self.retention_policy();
267        let mut retention_by_host = self.retention_by_host.borrow_mut();
268        let manager = retention_by_host
269            .entry(slots_storage_key(host))
270            .or_insert_with(|| RetentionManager::new(policy));
271        manager.set_policy(policy);
272        if pinned {
273            manager.insert_pinned(key, subtree)
274        } else {
275            manager.insert(key, subtree)
276        }
277    }
278
279    pub(crate) fn take_retained_movable(
280        &self,
281        id: Key,
282    ) -> Option<(Rc<SlotsHost>, crate::slot::DetachedSubtree)> {
283        self.take_retained_movable_by_key(movable_retain_key(id))
284    }
285
286    fn take_retained_movable_by_key(
287        &self,
288        key: RetainKey,
289    ) -> Option<(Rc<SlotsHost>, crate::slot::DetachedSubtree)> {
290        let mut retention_by_host = self.retention_by_host.borrow_mut();
291        let (host_key, manager) = retention_by_host
292            .iter_mut()
293            .find(|(_, manager)| manager.contains(key))?;
294        let host = self.host_for_storage_key(*host_key)?;
295        let subtree = manager.take(key)?;
296        Some((host, subtree))
297    }
298
299    /// Takes a movable's retained content out of a slot table other than the
300    /// one composing, which is how it crosses a subcomposition.
301    pub(crate) fn take_retained_movable_elsewhere(
302        &self,
303        besides: &Rc<SlotsHost>,
304        key: RetainKey,
305    ) -> Option<(Rc<SlotsHost>, crate::slot::DetachedSubtree)> {
306        let besides_key = slots_storage_key(besides);
307        let mut retention_by_host = self.retention_by_host.borrow_mut();
308        let (host_key, manager) = retention_by_host
309            .iter_mut()
310            .find(|(host_key, manager)| **host_key != besides_key && manager.contains(key))?;
311        let host = self.host_for_storage_key(*host_key)?;
312        let subtree = manager.take(key)?;
313        Some((host, subtree))
314    }
315
316    /// Whether a movable's content is retained in any slot table, which is
317    /// what a site waiting for it has to know: the content may have been let
318    /// go by a parent composed in another host, such as a subcomposition.
319    pub(crate) fn movable_retained_anywhere(&self, key: RetainKey) -> bool {
320        self.retention_by_host
321            .borrow()
322            .values()
323            .any(|manager| manager.contains(key))
324    }
325
326    /// The slot table a movable's content is attached to right now, if any.
327    pub(crate) fn host_holding_movable(&self, id: Key) -> Option<Rc<SlotsHost>> {
328        self.live_hosts
329            .borrow()
330            .values()
331            .filter_map(std::rc::Weak::upgrade)
332            .find(|host| host.borrow().movable_is_attached(id))
333    }
334
335    pub(crate) fn record_pending_movable(&self, host: &Rc<SlotsHost>, pending: PendingMovable) {
336        let mut by_host = self.pending_movables_by_host.borrow_mut();
337        let sites = by_host.entry(slots_storage_key(host)).or_default();
338        if sites
339            .iter()
340            .all(|site| site.placeholder != pending.placeholder)
341        {
342            sites.push(pending);
343        }
344    }
345
346    pub(crate) fn take_pending_movables(&self, host: &Rc<SlotsHost>) -> Vec<PendingMovable> {
347        self.pending_movables_by_host
348            .borrow_mut()
349            .remove(&slots_storage_key(host))
350            .unwrap_or_default()
351    }
352
353    /// Every slot table with a site still waiting for movable content. The
354    /// content may be let go by a parent composed in another table, so a pass
355    /// that ends has to look wider than itself.
356    pub(crate) fn hosts_awaiting_movables(&self) -> Vec<Rc<SlotsHost>> {
357        let waiting = self
358            .pending_movables_by_host
359            .borrow()
360            .iter()
361            .filter(|(_, sites)| !sites.is_empty())
362            .map(|(host_key, _)| *host_key)
363            .collect::<Vec<_>>();
364        waiting
365            .into_iter()
366            .filter_map(|host_key| self.host_for_storage_key(host_key))
367            .collect()
368    }
369
370    pub(crate) fn keep_pending_movables(&self, host: &Rc<SlotsHost>, sites: Vec<PendingMovable>) {
371        if sites.is_empty() {
372            return;
373        }
374        self.pending_movables_by_host
375            .borrow_mut()
376            .insert(slots_storage_key(host), sites);
377    }
378
379    pub(crate) fn advance_retention_pass(
380        &self,
381        host: &Rc<SlotsHost>,
382    ) -> Vec<crate::slot::DetachedSubtree> {
383        let host_key = slots_storage_key(host);
384        let policy = self.retention_policy();
385        let mut retention_by_host = self.retention_by_host.borrow_mut();
386        let Some(manager) = retention_by_host.get_mut(&host_key) else {
387            return Vec::new();
388        };
389        manager.set_policy(policy);
390        manager.advance_pass()
391    }
392
393    pub(crate) fn fill_slot_debug_snapshot(
394        &self,
395        host: &SlotsHost,
396        snapshot: &mut crate::SlotDebugSnapshot,
397    ) {
398        let retention = self.retention_debug_stats(host.storage_key());
399        snapshot.runtime_scope_registry_count = Some(self.scope_registry_len());
400        snapshot.retained_subtree_count = retention.subtree_count;
401        snapshot.retained_group_count = retention.group_count;
402        snapshot.retained_payload_count = retention.payload_count;
403        snapshot.retained_node_count = retention.node_count;
404        snapshot.retained_scope_count = retention.scope_count;
405    }
406
407    pub(crate) fn slot_retention_debug_stats(
408        &self,
409        host: &SlotsHost,
410    ) -> crate::slot::SlotRetentionDebugStats {
411        let retention = self.retention_debug_stats(host.storage_key());
412        crate::slot::SlotRetentionDebugStats {
413            retained_subtree_count: retention.subtree_count,
414            retained_group_count: retention.group_count,
415            retained_payload_count: retention.payload_count,
416            retained_node_count: retention.node_count,
417            retained_scope_count: retention.scope_count,
418            retained_anchor_count: retention.anchor_count,
419            retained_heap_bytes: retention.heap_bytes,
420            retained_evictions_total: retention.evictions_total,
421        }
422    }
423
424    pub(crate) fn compact_table_identity_storage_for_host(
425        &self,
426        host: &SlotsHost,
427        table: &mut SlotTable,
428        compact_anchors: bool,
429        compact_payloads: bool,
430    ) {
431        if !compact_anchors && !compact_payloads {
432            return;
433        }
434
435        let host_key = host.storage_key();
436        let mut retention = self.retention_by_host.borrow_mut();
437        if let Some(retained) = retention.get_mut(&host_key) {
438            if compact_anchors {
439                table.compact_anchor_registry_storage(Some(&mut *retained));
440            }
441            if compact_payloads {
442                table.compact_payload_anchor_registry_storage(Some(&mut *retained));
443            }
444        } else {
445            if compact_anchors {
446                table.compact_anchor_registry_storage(None);
447            }
448            if compact_payloads {
449                table.compact_payload_anchor_registry_storage(None);
450            }
451        }
452    }
453
454    pub(crate) fn clear_host(&self, host: &SlotsHost) {
455        let host_key = host.storage_key();
456        debug_assert!(
457            self.host_retention_is_empty(host),
458            "host retention must be drained before clearing host ownership"
459        );
460        self.clear_host_storage_key(host_key);
461    }
462
463    fn deactivate_and_queue_subtrees(
464        &self,
465        retention: RetentionManager,
466        table: &mut SlotTable,
467        lifecycle: &mut crate::slot::SlotLifecycleCoordinator,
468    ) {
469        for subtree in retention.into_subtrees() {
470            for scope_id in subtree.scope_ids() {
471                if let Some(scope) = self.remove_scope(scope_id) {
472                    scope.deactivate();
473                }
474            }
475            table.invalidate_detached_subtree_anchors(&subtree);
476            lifecycle.queue_subtree_disposal(subtree);
477        }
478    }
479
480    pub(crate) fn dispose_retained_subtrees_for_host(
481        &self,
482        host_key: usize,
483        table: &mut SlotTable,
484        lifecycle: &mut crate::slot::SlotLifecycleCoordinator,
485    ) -> Result<(), NodeError> {
486        let applier_host = self
487            .applier_host
488            .borrow()
489            .as_ref()
490            .and_then(std::rc::Weak::upgrade);
491        if let Some(applier_host) = applier_host.as_ref() {
492            let retention_by_host = self.retention_by_host.borrow();
493            let Some(retention) = retention_by_host.get(&host_key) else {
494                return Ok(());
495            };
496            let mut applier = applier_host.borrow_dyn();
497            for subtree in retention.subtrees() {
498                crate::slot::dispose_detached_subtree_now(&mut *applier, subtree)?;
499            }
500        }
501        let Some(retention) = self.retention_by_host.borrow_mut().remove(&host_key) else {
502            return Ok(());
503        };
504        self.deactivate_and_queue_subtrees(retention, table, lifecycle);
505        Ok(())
506    }
507
508    pub(crate) fn abandon_retained_subtrees_for_host(
509        &self,
510        host_key: usize,
511        table: &mut SlotTable,
512        lifecycle: &mut crate::slot::SlotLifecycleCoordinator,
513    ) {
514        let Some(retention) = self.retention_by_host.borrow_mut().remove(&host_key) else {
515            self.clear_host_storage_key(host_key);
516            return;
517        };
518        self.deactivate_and_queue_subtrees(retention, table, lifecycle);
519        self.clear_host_storage_key(host_key);
520    }
521
522    pub(crate) fn host_retention_is_empty(&self, host: &SlotsHost) -> bool {
523        self.retention_by_host
524            .borrow()
525            .get(&host.storage_key())
526            .is_none_or(RetentionManager::is_empty)
527    }
528
529    #[cfg(any(test, debug_assertions))]
530    pub(crate) fn debug_verify_host(&self, host: &SlotsHost, table: &SlotTable) {
531        if let Some(retention) = self.retention_by_host.borrow().get(&host.storage_key()) {
532            retention.debug_verify(table);
533        }
534    }
535
536    #[cfg(test)]
537    pub(crate) fn validate_host_retention(
538        &self,
539        host: &SlotsHost,
540        table: &SlotTable,
541    ) -> Result<(), crate::slot::SlotInvariantError> {
542        if let Some(retention) = self.retention_by_host.borrow().get(&host.storage_key()) {
543            retention.validate(table)?;
544        }
545        Ok(())
546    }
547
548    pub(crate) fn host_for_storage_key(&self, storage_key: usize) -> Option<Rc<SlotsHost>> {
549        self.live_hosts
550            .borrow()
551            .get(&storage_key)
552            .and_then(std::rc::Weak::upgrade)
553    }
554
555    fn retention_debug_stats(&self, host_key: usize) -> crate::retention::RetentionDebugStats {
556        self.retention_by_host
557            .borrow()
558            .get(&host_key)
559            .map(RetentionManager::debug_stats)
560            .unwrap_or_default()
561    }
562}
563
564pub(crate) struct ParentFrame {
565    pub(crate) id: NodeId,
566    pub(crate) previous: ChildList,
567    pub(crate) new_children: ChildList,
568    pub(crate) new_children_membership: Option<HashSet<NodeId>>,
569    pub(crate) attach_mode: ParentAttachMode,
570    pub(crate) synthetic_root: bool,
571}
572
573#[derive(Clone, Copy)]
574pub(crate) enum InitialParentFrame {
575    SyntheticRoot,
576    RealParent,
577}
578
579const LARGE_DEFERRED_CHILD_TRACKING_THRESHOLD: usize = 16;
580
581#[derive(Clone, Copy, Debug, PartialEq, Eq)]
582pub(crate) enum ParentAttachMode {
583    ImmediateAppend,
584    DeferredSync,
585}
586
587#[derive(Default)]
588pub(crate) struct SubcomposeFrame {
589    pub(crate) nodes: Vec<NodeId>,
590    pub(crate) scopes: Vec<RecomposeScope>,
591}
592
593#[derive(Default, Clone)]
594pub(crate) struct LocalContext {
595    pub(crate) values: HashMap<LocalKey, Rc<dyn Any>>,
596}
597
598pub(crate) struct ComposerCore {
599    pub(crate) shared_state: Rc<ComposerRuntimeState>,
600    pub(crate) slots: Rc<SlotsHost>,
601    slot_hosts: RefCell<Vec<Rc<SlotsHost>>>,
602    pub(crate) applier: Rc<dyn ApplierHost>,
603    pub(crate) runtime: RuntimeHandle,
604    pub(crate) observer: SnapshotStateObserver,
605    pub(crate) parent_stack: RefCell<Vec<ParentFrame>>,
606    pub(crate) subcompose_stack: RefCell<Vec<SubcomposeFrame>>,
607    pub(crate) root: Cell<Option<NodeId>>,
608    pub(crate) commands: RefCell<CommandQueue>,
609    pub(crate) scope_stack: RefCell<Vec<RecomposeScope>>,
610    subcomposition_owner_scope: RefCell<Option<RecomposeScope>>,
611    pub(crate) local_stack: RefCell<LocalStackSnapshot>,
612    pub(crate) side_effects: RefCell<Vec<Box<dyn FnOnce()>>>,
613    pub(crate) pending_scope_options: RefCell<Option<RecomposeOptions>>,
614    pub(crate) phase: Cell<crate::Phase>,
615    pub(crate) last_node_reused: Cell<Option<bool>>,
616    pub(crate) recompose_parent_hint: Cell<Option<NodeId>>,
617    pub(crate) recompose_child_cursor: Cell<Option<usize>>,
618    pub(crate) root_render_requested: Cell<bool>,
619    pub(crate) _not_send: PhantomData<*const ()>,
620}
621
622/// The composition context inherited by work that is composed in another slot
623/// host. Besides composition locals, this carries the source owner scope so a
624/// secondary tree cannot outlive the composition that supplied its callbacks.
625#[derive(Clone)]
626pub struct CapturedCompositionContext {
627    locals: LocalStackSnapshot,
628    owner_scope: Option<Weak<RecomposeScopeInner>>,
629}
630
631impl CapturedCompositionContext {
632    /// Total deactivations along the capturing scope's owner chain right now;
633    /// see [`crate::RecomposeScope::owner_chain_deactivation_epoch`]. Zero
634    /// when the context has no owner scope or it is gone.
635    pub fn owner_chain_deactivation_epoch(&self) -> u64 {
636        self.owner_scope
637            .as_ref()
638            .and_then(Weak::upgrade)
639            .map(|inner| crate::RecomposeScope { inner }.owner_chain_deactivation_epoch())
640            .unwrap_or(0)
641    }
642}
643
644fn take_subcompose_frame(core: &ComposerCore, operation: &str) -> SubcomposeFrame {
645    match core.subcompose_stack.borrow_mut().pop() {
646        Some(frame) => frame,
647        None => {
648            log::error!("subcompose stack underflow while finishing {operation}");
649            SubcomposeFrame::default()
650        }
651    }
652}
653
654struct SubcomposeStackGuard {
655    core: Rc<ComposerCore>,
656    leaked: bool,
657}
658
659impl Drop for SubcomposeStackGuard {
660    fn drop(&mut self) {
661        if !self.leaked {
662            self.core.subcompose_stack.borrow_mut().pop();
663        }
664    }
665}
666
667impl ComposerCore {
668    pub(crate) fn new(
669        shared_state: Rc<ComposerRuntimeState>,
670        slots: Rc<SlotsHost>,
671        applier: Rc<dyn ApplierHost>,
672        runtime: RuntimeHandle,
673        observer: SnapshotStateObserver,
674        root: Option<NodeId>,
675        initial_parent_frame: InitialParentFrame,
676    ) -> Self {
677        let parent_stack = if let Some(root_id) = root {
678            vec![ParentFrame {
679                id: root_id,
680                previous: ChildList::new(),
681                new_children: ChildList::new(),
682                new_children_membership: None,
683                attach_mode: ParentAttachMode::DeferredSync,
684                synthetic_root: matches!(initial_parent_frame, InitialParentFrame::SyntheticRoot),
685            }]
686        } else {
687            Vec::new()
688        };
689
690        Self {
691            shared_state,
692            slots,
693            slot_hosts: RefCell::new(Vec::new()),
694            applier,
695            runtime,
696            observer,
697            parent_stack: RefCell::new(parent_stack),
698            subcompose_stack: RefCell::new(Vec::new()),
699            root: Cell::new(root),
700            commands: RefCell::new(CommandQueue::default()),
701            scope_stack: RefCell::new(Vec::new()),
702            subcomposition_owner_scope: RefCell::new(None),
703            local_stack: RefCell::new(empty_local_stack()),
704            side_effects: RefCell::new(Vec::new()),
705            pending_scope_options: RefCell::new(None),
706            phase: Cell::new(crate::Phase::Compose),
707            last_node_reused: Cell::new(None),
708            recompose_parent_hint: Cell::new(None),
709            recompose_child_cursor: Cell::new(None),
710            root_render_requested: Cell::new(false),
711            _not_send: PhantomData,
712        }
713    }
714}
715
716#[derive(Clone)]
717pub struct Composer {
718    pub(crate) core: Rc<ComposerCore>,
719}
720
721pub struct BranchGroupGuard {
722    composer: Composer,
723    fold_token: Option<usize>,
724}
725
726impl Drop for BranchGroupGuard {
727    fn drop(&mut self) {
728        let Some(token) = self.fold_token else {
729            return;
730        };
731        if !self
732            .composer
733            .active_slots_host()
734            .try_close_branch_fold(token)
735        {
736            log::error!("a branch fold guard closed while its slot host was busy");
737        }
738    }
739}
740
741pub(crate) enum EmittedNode {
742    Fresh(Box<dyn Node>),
743    Recycled(RecycledNode),
744}
745
746impl Composer {
747    pub(crate) fn new_with_shared_state(
748        shared_state: Rc<ComposerRuntimeState>,
749        slots: Rc<SlotsHost>,
750        applier: Rc<dyn ApplierHost>,
751        runtime: RuntimeHandle,
752        observer: SnapshotStateObserver,
753        root: Option<NodeId>,
754    ) -> Self {
755        Self::new_with_shared_state_with_parent_frame(
756            shared_state,
757            slots,
758            applier,
759            runtime,
760            observer,
761            root,
762            InitialParentFrame::SyntheticRoot,
763        )
764    }
765
766    fn new_with_shared_state_with_parent_frame(
767        shared_state: Rc<ComposerRuntimeState>,
768        slots: Rc<SlotsHost>,
769        applier: Rc<dyn ApplierHost>,
770        runtime: RuntimeHandle,
771        observer: SnapshotStateObserver,
772        root: Option<NodeId>,
773        initial_parent_frame: InitialParentFrame,
774    ) -> Self {
775        shared_state.bind_applier_host(&applier);
776        let slots = bind_slots_host_to_runtime_state(&shared_state, &slots);
777        let core = Rc::new(ComposerCore::new(
778            shared_state,
779            slots,
780            applier,
781            runtime,
782            observer,
783            root,
784            initial_parent_frame,
785        ));
786        Self { core }
787    }
788
789    pub fn new(
790        slots: Rc<SlotsHost>,
791        applier: Rc<dyn ApplierHost>,
792        runtime: RuntimeHandle,
793        observer: SnapshotStateObserver,
794        root: Option<NodeId>,
795    ) -> Self {
796        Self::new_with_shared_state_with_parent_frame(
797            slots
798                .runtime_state()
799                .unwrap_or_else(|| Rc::new(ComposerRuntimeState::default())),
800            slots,
801            applier,
802            runtime,
803            observer,
804            root,
805            InitialParentFrame::RealParent,
806        )
807    }
808
809    pub(crate) fn from_core(core: Rc<ComposerCore>) -> Self {
810        Self { core }
811    }
812
813    pub(crate) fn clone_core(&self) -> Rc<ComposerCore> {
814        Rc::clone(&self.core)
815    }
816
817    fn observer(&self) -> SnapshotStateObserver {
818        self.core.observer.clone()
819    }
820
821    pub(crate) fn request_root_render(&self) {
822        self.core.root_render_requested.set(true);
823    }
824
825    pub(crate) fn take_root_render_request(&self) -> bool {
826        self.core.root_render_requested.replace(false)
827    }
828
829    pub(crate) fn observe_scope<R>(&self, scope: &RecomposeScope, block: impl FnOnce() -> R) -> R {
830        let observer = self.observer();
831        let scope_clone = scope.clone();
832        observer.observe_reads(scope_clone, move |scope_ref| scope_ref.invalidate(), block)
833    }
834
835    pub fn active_slots_host(&self) -> Rc<SlotsHost> {
836        self.core
837            .slot_hosts
838            .borrow()
839            .last()
840            .cloned()
841            .unwrap_or_else(|| Rc::clone(&self.core.slots))
842    }
843
844    pub(crate) fn with_slots<R>(&self, f: impl FnOnce(&SlotTable) -> R) -> R {
845        let host = self.active_slots_host();
846        let slots = host.borrow();
847        f(&slots)
848    }
849
850    pub(crate) fn with_slots_mut<R>(&self, f: impl FnOnce(&mut SlotTable) -> R) -> R {
851        let host = self.active_slots_host();
852        let mut slots = host.borrow_mut();
853        f(&mut slots)
854    }
855
856    pub(crate) fn with_slot_session_mut<R>(
857        &self,
858        f: impl FnOnce(&mut crate::slot::SlotWriteSession<'_>) -> R,
859    ) -> R {
860        self.active_slots_host().with_write_session(f)
861    }
862
863    pub(crate) fn try_with_slot_host_pass<R>(
864        &self,
865        slots: Rc<SlotsHost>,
866        mode: crate::slot::SlotPassMode,
867        f: impl FnOnce(&Composer) -> R,
868    ) -> Result<(R, SlotPassOutcome), NodeError> {
869        let mut guard = self.begin_slot_host_pass(&slots, mode);
870        let result = f(self);
871        let outcome = self.finish_slot_host_pass(&guard.host)?;
872        guard.close();
873        Ok((result, outcome))
874    }
875
876    pub(crate) fn with_slot_host_pass<R>(
877        &self,
878        slots: Rc<SlotsHost>,
879        mode: crate::slot::SlotPassMode,
880        f: impl FnOnce(&Composer) -> R,
881    ) -> (R, SlotPassOutcome) {
882        let mut guard = self.begin_slot_host_pass(&slots, mode);
883        let result = f(self);
884        let outcome = match self.finish_slot_host_pass(&guard.host) {
885            Ok(outcome) => outcome,
886            Err(err) => {
887                log::error!("slot host pass finalization failed: {err}");
888                SlotPassOutcome::default()
889            }
890        };
891        guard.close();
892        (result, outcome)
893    }
894
895    pub(crate) fn with_slot_override<R>(
896        &self,
897        slots: Rc<SlotsHost>,
898        f: impl FnOnce(&Composer) -> R,
899    ) -> (R, SlotPassOutcome) {
900        self.with_slot_host_pass(slots, crate::slot::SlotPassMode::Compose, f)
901    }
902
903    fn begin_slot_host_pass(
904        &self,
905        slots: &Rc<SlotsHost>,
906        mode: crate::slot::SlotPassMode,
907    ) -> SlotHostPassGuard {
908        let slots = bind_slots_host_to_runtime_state(&self.core.shared_state, slots);
909        slots.begin_pass(mode);
910        {
911            let mut stack = self.core.slot_hosts.borrow_mut();
912            if let Some(parent) = stack.last()
913                && !Rc::ptr_eq(parent, &slots)
914            {
915                parent.note_nested_host(&slots);
916            }
917            stack.push(Rc::clone(&slots));
918        }
919        SlotHostPassGuard {
920            core: self.clone_core(),
921            host: slots,
922            active: true,
923        }
924    }
925
926    fn finish_slot_host_pass(&self, slots: &Rc<SlotsHost>) -> Result<SlotPassOutcome, NodeError> {
927        let finished = {
928            let mut applier = self.core.applier.borrow_dyn();
929            slots.finish_pass(&mut *applier)
930        }?;
931        self.handle_detached_children_in_host(slots, None, finished.detached_root_children)?;
932        self.wake_sites_whose_movable_arrived();
933        self.evict_retained_subtrees_for_host(slots)?;
934        slots.complete_pass_cleanup(&finished.outcome);
935        Ok(finished.outcome)
936    }
937
938    fn wake_sites_whose_movable_arrived(&self) {
939        for host in self.core.shared_state.hosts_awaiting_movables() {
940            self.wake_sites_in_host(&host);
941        }
942    }
943
944    fn wake_sites_in_host(&self, slots: &Rc<SlotsHost>) {
945        let pending = self.core.shared_state.take_pending_movables(slots);
946        if pending.is_empty() {
947            return;
948        }
949        let mut waiting = Vec::new();
950        for site in pending {
951            if !slots.borrow().group_is_active(site.placeholder) {
952                continue;
953            }
954            let retain_key = RetainKey::for_group(None, site.key);
955            if !self.core.shared_state.movable_retained_anywhere(retain_key) {
956                waiting.push(site);
957                continue;
958            }
959            match site.parent_scope.and_then(|id| self.scope_for_id(id)) {
960                Some(scope) => {
961                    scope.force_recompose();
962                    scope.invalidate();
963                }
964                None => log::error!(
965                    "movable content {:?} arrived for a site whose scope is gone",
966                    site.key
967                ),
968            }
969        }
970        self.core.shared_state.keep_pending_movables(slots, waiting);
971    }
972
973    pub(crate) fn forget_movables(&self, ids: &[Key]) -> Result<(), NodeError> {
974        for id in ids {
975            let Some((host, subtree)) = self.core.shared_state.take_retained_movable(*id) else {
976                continue;
977            };
978            self.dispose_detached_subtree_in_host(&host, subtree)?;
979            host.flush_pending_drops();
980        }
981        Ok(())
982    }
983
984    pub(crate) fn parent_stack(&self) -> RefMut<'_, Vec<ParentFrame>> {
985        self.core.parent_stack.borrow_mut()
986    }
987
988    fn current_parent_hint(&self) -> Option<NodeId> {
989        let stack = self.core.parent_stack.borrow();
990        let stack_hint = stack
991            .last()
992            .and_then(|frame| (!frame.synthetic_root).then_some(frame.id));
993        stack_hint.or_else(|| self.core.recompose_parent_hint.get())
994    }
995
996    pub(crate) fn subcompose_stack(&self) -> RefMut<'_, Vec<SubcomposeFrame>> {
997        self.core.subcompose_stack.borrow_mut()
998    }
999
1000    pub(crate) fn commands_mut(&self) -> RefMut<'_, CommandQueue> {
1001        self.core.commands.borrow_mut()
1002    }
1003
1004    pub(crate) fn enqueue_semantics_invalidation(&self, id: NodeId) {
1005        self.commands_mut().push(Command::BubbleDirty {
1006            node_id: id,
1007            bubble: DirtyBubble::SEMANTICS,
1008        });
1009    }
1010
1011    pub(crate) fn scope_stack(&self) -> RefMut<'_, Vec<RecomposeScope>> {
1012        self.core.scope_stack.borrow_mut()
1013    }
1014
1015    fn scope_for_id(&self, scope_id: ScopeId) -> Option<RecomposeScope> {
1016        self.core.shared_state.scope_for_id(scope_id)
1017    }
1018
1019    fn register_scope(&self, scope: &RecomposeScope) {
1020        self.core.shared_state.register_scope(scope);
1021    }
1022
1023    fn remove_scope(&self, scope_id: ScopeId) -> Option<RecomposeScope> {
1024        self.core.shared_state.remove_scope(scope_id)
1025    }
1026
1027    pub(crate) fn local_stack(&self) -> RefMut<'_, LocalStackSnapshot> {
1028        self.core.local_stack.borrow_mut()
1029    }
1030
1031    pub(crate) fn current_local_stack(&self) -> LocalStackSnapshot {
1032        self.core.local_stack.borrow().clone()
1033    }
1034
1035    pub(crate) fn side_effects_mut(&self) -> RefMut<'_, Vec<Box<dyn FnOnce()>>> {
1036        self.core.side_effects.borrow_mut()
1037    }
1038
1039    fn pending_scope_options(&self) -> RefMut<'_, Option<RecomposeOptions>> {
1040        self.core.pending_scope_options.borrow_mut()
1041    }
1042
1043    pub(crate) fn borrow_applier(&self) -> RefMut<'_, dyn Applier> {
1044        self.core.applier.borrow_dyn()
1045    }
1046
1047    /// Records nodes whose retained subtrees a reused subcompose slot just
1048    /// rebound to new content.
1049    ///
1050    /// The rebinding recomposes inline during measure, so every repass it
1051    /// schedules is consumed by the layout pass already running — nothing
1052    /// else survives to tell the scoped scene update these subtrees changed,
1053    /// and a translate-only update would keep their stale layers (measured:
1054    /// a 60pt lazy scroll presented the old row's text at the new row's
1055    /// position). The structural-change set is the one channel drained
1056    /// after layout, so the rebound children ride it.
1057    pub fn record_rebound_slot_children(&self, children: &[NodeId]) {
1058        let mut applier = self.borrow_applier();
1059        for &child in children {
1060            applier.record_structural_change(child);
1061        }
1062    }
1063
1064    /// Registers a virtual node in the Applier.
1065    ///
1066    /// This is used by SubcomposeLayoutNode to register virtual container nodes
1067    /// so that subsequent insert_child commands can find them and attach children.
1068    /// Without this, virtual nodes would only exist in SubcomposeLayoutNodeInner.virtual_nodes
1069    /// and applier.get_mut(virtual_node_id) would fail, breaking child attachment.
1070    pub fn register_virtual_node(
1071        &self,
1072        node_id: NodeId,
1073        node: Box<dyn Node>,
1074    ) -> Result<(), NodeError> {
1075        let mut applier = self.borrow_applier();
1076        applier.insert_with_id(node_id, node)
1077    }
1078
1079    /// Checks if a node has no parent (is a root node).
1080    /// Used by SubcomposeMeasureScope to filter subcompose results.
1081    pub fn node_has_no_parent(&self, node_id: NodeId) -> bool {
1082        let mut applier = self.borrow_applier();
1083        match applier.get_mut(node_id) {
1084            Ok(node) => node.parent().is_none(),
1085            Err(_) => true,
1086        }
1087    }
1088
1089    /// Gets the children of a node from the Applier.
1090    ///
1091    /// This is used by SubcomposeLayoutNode to get children of virtual nodes
1092    /// directly from the Applier, where insert_child commands have been applied.
1093    pub fn get_node_children(&self, node_id: NodeId) -> SmallVec<[NodeId; 8]> {
1094        let mut applier = self.borrow_applier();
1095        match applier.get_mut(node_id) {
1096            Ok(node) => {
1097                let mut children = SmallVec::<[NodeId; 8]>::new();
1098                node.collect_children_into(&mut children);
1099                children
1100            }
1101            Err(_) => SmallVec::<[NodeId; 8]>::new(),
1102        }
1103    }
1104
1105    pub fn nodes_need_measure(&self, node_ids: &[NodeId]) -> bool {
1106        let mut applier = self.borrow_applier();
1107        node_ids.iter().any(|node_id| {
1108            applier
1109                .get_mut(*node_id)
1110                .is_ok_and(|node| node.needs_measure())
1111        })
1112    }
1113
1114    /// Whether any of `node_ids` carries a pending *layout* (placement) repass.
1115    ///
1116    /// Layout-only dirtiness is not a subset of measure dirtiness: a scroll
1117    /// offset change keeps every measured size intact and therefore bubbles
1118    /// `needs_layout` alone. Callers that gate cache reuse on
1119    /// [`Self::nodes_need_measure`] must also consult this, or a node whose
1120    /// *position* changed will replay its stale cached placement forever.
1121    pub fn nodes_need_layout(&self, node_ids: &[NodeId]) -> bool {
1122        let mut applier = self.borrow_applier();
1123        node_ids.iter().any(|node_id| {
1124            applier
1125                .get_mut(*node_id)
1126                .is_ok_and(|node| node.needs_layout())
1127        })
1128    }
1129
1130    /// Records a child node in the current parent frame's expected children list.
1131    ///
1132    /// Used by SubcomposeLayout's `perform_subcompose` to register virtual nodes
1133    /// with the outer composer's parent frame. This ensures that the `pop_parent`
1134    /// call at the end of `subcompose_slot` generates a correct `SyncChildren`
1135    /// command that preserves (rather than removes) the virtual nodes.
1136    ///
1137    /// Without this, `pop_parent` would generate `SyncChildren { expected: [] }`,
1138    /// which removes all virtual nodes and their subtrees from the applier.
1139    pub fn record_subcompose_child(&self, child_id: NodeId) {
1140        let mut parent_stack = self.parent_stack();
1141        if let Some(frame) = parent_stack.last_mut()
1142            && matches!(frame.attach_mode, ParentAttachMode::DeferredSync)
1143        {
1144            if let Some(membership) = frame.new_children_membership.as_mut() {
1145                if membership.insert(child_id) {
1146                    frame.new_children.push(child_id);
1147                }
1148            } else if frame.new_children.len() >= LARGE_DEFERRED_CHILD_TRACKING_THRESHOLD {
1149                let mut membership = HashSet::default();
1150                membership.reserve(frame.new_children.len() + 1);
1151                membership.extend(frame.new_children.iter().copied());
1152                if membership.insert(child_id) {
1153                    frame.new_children.push(child_id);
1154                }
1155                frame.new_children_membership = Some(membership);
1156            } else if !frame.new_children.contains(&child_id) {
1157                frame.new_children.push(child_id);
1158            }
1159        }
1160    }
1161
1162    /// Clears all children of a node in the Applier.
1163    ///
1164    /// This is used by SubcomposeLayoutNode when reusing a virtual node for
1165    /// different content. Without clearing, old children remain attached,
1166    /// causing duplicate/interleaved items in lazy lists after scrolling.
1167    pub fn clear_node_children(&self, node_id: NodeId) {
1168        let mut applier = self.borrow_applier();
1169        if let Ok(node) = applier.get_mut(node_id) {
1170            node.update_children(&[]);
1171        }
1172    }
1173
1174    pub fn install<R>(&self, f: impl FnOnce(&Composer) -> R) -> R {
1175        let _composer_guard = composer_context::enter(self);
1176        runtime::push_active_runtime(&self.core.runtime);
1177        struct Guard;
1178        impl Drop for Guard {
1179            fn drop(&mut self) {
1180                runtime::pop_active_runtime();
1181            }
1182        }
1183        let guard = Guard;
1184        let result = f(self);
1185        drop(guard);
1186        result
1187    }
1188
1189    pub(crate) fn flush_pending_commands_if_large(&self) -> Result<(), NodeError> {
1190        let queued = self.core.commands.borrow().len();
1191        if queued < COMMAND_FLUSH_THRESHOLD {
1192            return Ok(());
1193        }
1194        self.apply_pending_commands()
1195    }
1196
1197    fn resolve_group_entry(
1198        &self,
1199        seed: crate::slot::GroupKeySeed,
1200        parent_scope_id: Option<ScopeId>,
1201    ) -> GroupEntry {
1202        let host = self.active_slots_host();
1203        let key = self.with_slot_session_mut(|slots| slots.reserve_group_key(seed));
1204        let retain_key = RetainKey::for_group(parent_scope_id, key);
1205        let restored = self
1206            .core
1207            .shared_state
1208            .take_retained(&host, retain_key, |subtree| {
1209                self.with_slot_session_mut(|slots| slots.retained_restore_ready(key, subtree))
1210            })
1211            .or_else(|| self.take_movable_from_another_table(&host, retain_key, key));
1212        if restored.is_some() || !key.is_movable() {
1213            return GroupEntry {
1214                key,
1215                restored,
1216                placeholder_for: None,
1217            };
1218        }
1219        let attached_elsewhere = self.movable_attached_elsewhere(&host, key);
1220        if !attached_elsewhere {
1221            return GroupEntry {
1222                key,
1223                restored: None,
1224                placeholder_for: None,
1225            };
1226        }
1227        let id = key.explicit_key.unwrap_or_default();
1228        let placeholder = self.with_slot_session_mut(|slots| {
1229            slots.reserve_group_key(crate::slot::GroupKeySeed::movable_placeholder(id))
1230        });
1231        GroupEntry {
1232            key: placeholder,
1233            restored: None,
1234            placeholder_for: Some(key),
1235        }
1236    }
1237
1238    /// Movable content that was let go by a parent composed in another slot
1239    /// table — a `SubcomposeLayout`'s, or the one a subcomposition owns — is
1240    /// retained there, not here. Bring it over: the table that held it lets
1241    /// go of its anchors, and this one issues its own.
1242    fn take_movable_from_another_table(
1243        &self,
1244        host: &Rc<SlotsHost>,
1245        retain_key: RetainKey,
1246        key: crate::slot::GroupKey,
1247    ) -> Option<crate::slot::DetachedSubtree> {
1248        if !key.is_movable() {
1249            return None;
1250        }
1251        let (source, mut subtree) = self
1252            .core
1253            .shared_state
1254            .take_retained_movable_elsewhere(host, retain_key)?;
1255        source
1256            .borrow_mut()
1257            .invalidate_detached_subtree_anchors(&subtree);
1258        if self.with_slot_session_mut(|slots| slots.retained_restore_ready(key, &mut subtree)) {
1259            return Some(subtree);
1260        }
1261        log::error!(
1262            "movable content {key:?} could not be taken over by the slot table that asked for it"
1263        );
1264        if let Err(error) = self.dispose_detached_subtree_in_host(host, subtree) {
1265            log::error!("disposing movable content that could not move failed: {error}");
1266        }
1267        None
1268    }
1269
1270    /// Whether the movable's content is attached to some parent that is not
1271    /// the one composing, in this slot table or in another.
1272    fn movable_attached_elsewhere(&self, host: &Rc<SlotsHost>, key: crate::slot::GroupKey) -> bool {
1273        if self.with_slot_session_mut(|slots| slots.movable_attached_elsewhere(key)) {
1274            return true;
1275        }
1276        let Some(id) = key.movable_id() else {
1277            return false;
1278        };
1279        self.core
1280            .shared_state
1281            .host_holding_movable(id)
1282            .is_some_and(|holder| !Rc::ptr_eq(&holder, host))
1283    }
1284
1285    fn scope_for_started_group(
1286        &self,
1287        group: crate::slot::ActiveGroupId,
1288        scope_id: Option<ScopeId>,
1289    ) -> RecomposeScope {
1290        if let Some(scope) = scope_id.and_then(|scope_id| self.scope_for_id(scope_id)) {
1291            return scope;
1292        }
1293        let scope = RecomposeScope::new(self.runtime_handle());
1294        self.register_scope(&scope);
1295        self.with_slot_session_mut(|slots| slots.set_group_scope(group, scope.id()));
1296        scope
1297    }
1298
1299    fn enter_group_scope(&self, scope_ref: &RecomposeScope, entry: GroupScopeEntry<'_>) {
1300        let GroupScopeEntry {
1301            parent_scope,
1302            options,
1303            start_kind,
1304            host,
1305            restored_scopes,
1306        } = entry;
1307        let lifetime_owner_scope = if parent_scope.is_none() {
1308            self.core.subcomposition_owner_scope.borrow().clone()
1309        } else {
1310            None
1311        };
1312        scope_ref.reactivate();
1313        scope_ref.set_parent_scope(parent_scope);
1314        scope_ref.set_lifetime_owner_scope(lifetime_owner_scope);
1315        scope_ref.set_retention_mode(options.retention);
1316
1317        if options.force_recompose {
1318            scope_ref.force_recompose();
1319        } else if options.force_reuse {
1320            scope_ref.force_reuse();
1321        }
1322        if matches!(start_kind, GroupStartKind::Restored) {
1323            scope_ref.force_recompose();
1324        }
1325
1326        scope_ref.set_slots_host(host);
1327
1328        {
1329            let mut stack = self.scope_stack();
1330            stack.push(scope_ref.clone());
1331        }
1332
1333        {
1334            let mut stack = self.subcompose_stack();
1335            if let Some(frame) = stack.last_mut() {
1336                frame.scopes.push(scope_ref.clone());
1337            }
1338        }
1339
1340        scope_ref.snapshot_locals(self.current_local_stack());
1341        let parent_hint = self.current_parent_hint();
1342        if let Some(restored_scopes) = restored_scopes {
1343            self.reparent_restored_scopes(scope_ref, &restored_scopes, parent_hint);
1344        }
1345        scope_ref.set_parent_hint(parent_hint);
1346    }
1347
1348    fn reparent_restored_scopes(
1349        &self,
1350        root: &RecomposeScope,
1351        restored_scopes: &[ScopeId],
1352        parent_hint: Option<NodeId>,
1353    ) {
1354        let old_hint = root.parent_hint();
1355        for scope in restored_scopes
1356            .iter()
1357            .filter_map(|scope_id| self.scope_for_id(*scope_id))
1358        {
1359            if scope.parent_hint() == old_hint {
1360                scope.set_parent_hint(parent_hint);
1361            }
1362            scope.reactivate();
1363        }
1364    }
1365
1366    #[inline(never)]
1367    fn with_group_in_active_pass_dyn(
1368        &self,
1369        key: crate::slot::GroupKeySeed,
1370        f: &mut dyn FnMut(&Composer),
1371    ) {
1372        struct GroupGuard {
1373            composer: Composer,
1374            scope: RecomposeScope,
1375        }
1376
1377        impl Drop for GroupGuard {
1378            fn drop(&mut self) {
1379                self.composer
1380                    .close_current_group_body_for_scope(&self.scope);
1381                self.scope.mark_recomposed();
1382                self.composer
1383                    .with_slot_session_mut(|slots| slots.end_group());
1384                if let Err(err) = self.composer.flush_pending_commands_if_large() {
1385                    log::error!("mid-composition command flush failed: {err}");
1386                }
1387            }
1388        }
1389
1390        let parent_scope = self.current_recompose_scope();
1391        let options = self.pending_scope_options().take().unwrap_or_default();
1392        let parent_scope_id = parent_scope.as_ref().map(RecomposeScope::id);
1393        let host = self.active_slots_host();
1394        let GroupEntry {
1395            key: reserved_key,
1396            restored,
1397            placeholder_for,
1398        } = self.resolve_group_entry(key, parent_scope_id);
1399        let restored_scopes = restored
1400            .as_ref()
1401            .map(crate::slot::DetachedSubtree::scope_ids);
1402        let parent_node = self.current_parent_hint();
1403        let (group, anchor, start_scope_id, start_kind) = self.with_slot_session_mut(|slots| {
1404            let GroupStart {
1405                group,
1406                anchor,
1407                scope_id,
1408                kind,
1409            } = slots.begin_group(reserved_key, restored, parent_node);
1410            (group, anchor, scope_id, kind)
1411        });
1412        let scope_ref = self.scope_for_started_group(group, start_scope_id);
1413        self.enter_group_scope(
1414            &scope_ref,
1415            GroupScopeEntry {
1416                parent_scope,
1417                options,
1418                start_kind,
1419                host: &host,
1420                restored_scopes,
1421            },
1422        );
1423        if let Some(movable_key) = placeholder_for {
1424            self.core.shared_state.record_pending_movable(
1425                &host,
1426                PendingMovable {
1427                    key: movable_key,
1428                    placeholder: anchor,
1429                    parent_scope: parent_scope_id,
1430                },
1431            );
1432        }
1433
1434        let guard = GroupGuard {
1435            composer: self.clone(),
1436            scope: scope_ref.clone(),
1437        };
1438        if placeholder_for.is_none() {
1439            self.observe_scope(&scope_ref, || f(self));
1440        }
1441        scope_ref.mark_composed_once();
1442        drop(guard);
1443    }
1444
1445    fn with_group_seed_dyn(&self, key: crate::slot::GroupKeySeed, f: &mut dyn FnMut(&Composer)) {
1446        let host = self.active_slots_host();
1447        if host.has_active_pass() {
1448            self.with_group_in_active_pass_dyn(key, f);
1449            return;
1450        }
1451        self.with_slot_host_pass(host, crate::slot::SlotPassMode::Compose, |composer| {
1452            composer.with_group_in_active_pass_dyn(key, f)
1453        });
1454    }
1455
1456    pub(crate) fn with_group_seed<R>(
1457        &self,
1458        key: crate::slot::GroupKeySeed,
1459        f: impl FnOnce(&Composer) -> R,
1460    ) -> R {
1461        let mut f = Some(f);
1462        let mut result = None;
1463        self.with_group_seed_dyn(key, &mut |composer| {
1464            let f = f.take().expect("group body must run at most once");
1465            result = Some(f(composer));
1466        });
1467        result.expect("group body must run exactly once")
1468    }
1469
1470    pub(crate) fn with_movable_group(&self, id: Key, f: impl FnOnce(&Composer)) {
1471        let mut f = Some(f);
1472        self.with_group_seed_dyn(crate::slot::GroupKeySeed::movable(id), &mut |composer| {
1473            if let Some(f) = f.take() {
1474                f(composer);
1475            }
1476        });
1477    }
1478
1479    pub fn with_group<R>(&self, key: Key, f: impl FnOnce(&Composer) -> R) -> R {
1480        self.with_group_seed(crate::slot::GroupKeySeed::unkeyed(key), f)
1481    }
1482
1483    pub fn cranpose_with_reuse<R>(
1484        &self,
1485        key: Key,
1486        mut options: RecomposeOptions,
1487        f: impl FnOnce(&Composer) -> R,
1488    ) -> R {
1489        options.retention = RetentionMode::RetainWhenInactive;
1490        self.pending_scope_options().replace(options);
1491        self.with_group(key, f)
1492    }
1493
1494    #[track_caller]
1495    pub fn with_key<K: Hash, R>(&self, key: &K, f: impl FnOnce(&Composer) -> R) -> R {
1496        let seed = explicit_group_key_seed(key, std::panic::Location::caller());
1497        self.with_group_seed(seed, f)
1498    }
1499
1500    #[doc(hidden)]
1501    pub fn __branch_group_deferred(&self, key: Key) -> BranchGroupGuard {
1502        BranchGroupGuard {
1503            composer: self.clone(),
1504            fold_token: self.active_slots_host().try_push_branch_fold(key),
1505        }
1506    }
1507
1508    fn dispose_detached_nodes(&self, nodes: impl IntoIterator<Item = NodeId>) {
1509        for node_id in nodes {
1510            self.commands_mut().push(Command::callback(move |applier| {
1511                crate::slot::dispose_detached_node_now(applier, node_id)
1512            }));
1513        }
1514    }
1515
1516    fn deactivate_scope_ids(&self, scope_ids: impl IntoIterator<Item = ScopeId>) {
1517        for scope_id in scope_ids {
1518            if let Some(scope) = self.scope_for_id(scope_id) {
1519                scope.deactivate();
1520            }
1521        }
1522    }
1523
1524    fn dispose_scope_ids(&self, scope_ids: impl IntoIterator<Item = ScopeId>) {
1525        for scope_id in scope_ids {
1526            if let Some(scope) = self.remove_scope(scope_id) {
1527                scope.deactivate();
1528            }
1529        }
1530    }
1531
1532    fn detached_root_parent_commands(
1533        &self,
1534        subtree: &crate::slot::DetachedSubtree,
1535        context: &'static str,
1536    ) -> Result<Vec<(NodeId, Option<NodeId>)>, NodeError> {
1537        let mut root_nodes = Vec::new();
1538        subtree.collect_root_nodes_checked_into(&mut root_nodes, context);
1539        let mut roots = Vec::with_capacity(root_nodes.len());
1540        for root in root_nodes {
1541            let parent_id = {
1542                let mut applier = self.borrow_applier();
1543                applier.get_mut(root)?.parent()
1544            };
1545            roots.push((root, parent_id));
1546        }
1547        Ok(roots)
1548    }
1549
1550    fn retain_detached_subtree_in_host(
1551        &self,
1552        slots_host: &Rc<SlotsHost>,
1553        parent_scope: Option<ScopeId>,
1554        subtree: crate::slot::DetachedSubtree,
1555    ) -> Result<(), NodeError> {
1556        let Some(root_key) = subtree.root_key_checked() else {
1557            log::error!("retention rejected detached subtree without a root group");
1558            self.dispose_detached_subtree_in_host(slots_host, subtree)?;
1559            return Ok(());
1560        };
1561        let root_detaches = self.detached_root_parent_commands(&subtree, "retention")?;
1562        self.deactivate_scope_ids(subtree.scope_ids_iter());
1563        for (root, parent_id) in root_detaches {
1564            if let Some(parent_id) = parent_id {
1565                self.commands_mut().push(Command::DetachChild {
1566                    parent_id,
1567                    child_id: root,
1568                });
1569            }
1570        }
1571        let evicted = self.core.shared_state.insert_retained(
1572            slots_host,
1573            RetainKey::for_group(parent_scope, root_key),
1574            subtree,
1575            root_key.is_movable(),
1576        );
1577        for subtree in evicted {
1578            self.dispose_detached_subtree_in_host(slots_host, subtree)?;
1579        }
1580        Ok(())
1581    }
1582
1583    fn evict_retained_subtrees_for_host(
1584        &self,
1585        slots_host: &Rc<SlotsHost>,
1586    ) -> Result<(), NodeError> {
1587        let evicted = self.core.shared_state.advance_retention_pass(slots_host);
1588        for subtree in evicted {
1589            self.dispose_detached_subtree_in_host(slots_host, subtree)?;
1590        }
1591        Ok(())
1592    }
1593
1594    fn dispose_detached_subtree_in_host(
1595        &self,
1596        slots_host: &Rc<SlotsHost>,
1597        subtree: crate::slot::DetachedSubtree,
1598    ) -> Result<(), NodeError> {
1599        let root_nodes = self
1600            .detached_root_parent_commands(&subtree, "disposal")?
1601            .into_iter()
1602            .map(|(root, _)| root);
1603        self.dispose_scope_ids(subtree.scope_ids_iter());
1604        self.dispose_detached_nodes(root_nodes);
1605        slots_host.with_table_and_lifecycle_mut(|table, lifecycle| {
1606            table.invalidate_detached_subtree_anchors(&subtree);
1607            lifecycle.queue_subtree_disposal(subtree);
1608        });
1609        Ok(())
1610    }
1611
1612    fn handle_detached_children_in_host(
1613        &self,
1614        slots_host: &Rc<SlotsHost>,
1615        parent_scope: Option<ScopeId>,
1616        detached: Vec<crate::slot::DetachedSubtree>,
1617    ) -> Result<(), NodeError> {
1618        for mut subtree in detached {
1619            for movable in subtree.split_off_nested_movables() {
1620                self.retain_detached_subtree_in_host(slots_host, None, movable)?;
1621            }
1622            if subtree
1623                .root_key_checked()
1624                .is_some_and(crate::slot::GroupKey::is_movable)
1625            {
1626                self.retain_detached_subtree_in_host(slots_host, None, subtree)?;
1627                continue;
1628            }
1629            let retention_mode = subtree
1630                .root_scope_id()
1631                .and_then(|scope_id| self.scope_for_id(scope_id))
1632                .map(|scope| scope.retention_mode())
1633                .unwrap_or_default();
1634            match retention_mode {
1635                RetentionMode::DisposeWhenInactive => {
1636                    self.dispose_detached_subtree_in_host(slots_host, subtree)?
1637                }
1638                RetentionMode::RetainWhenInactive => {
1639                    self.retain_detached_subtree_in_host(slots_host, parent_scope, subtree)?
1640                }
1641            }
1642        }
1643        Ok(())
1644    }
1645
1646    fn handle_detached_children(
1647        &self,
1648        parent_scope: Option<ScopeId>,
1649        detached: Vec<crate::slot::DetachedSubtree>,
1650    ) {
1651        let host = self.active_slots_host();
1652        if let Err(err) = self.handle_detached_children_in_host(&host, parent_scope, detached) {
1653            log::error!("detached subtree handling failed while closing a group: {err}");
1654        }
1655    }
1656
1657    fn handle_finished_group_result(
1658        &self,
1659        parent_scope: Option<ScopeId>,
1660        result: FinishGroupResult,
1661    ) {
1662        let FinishGroupResult {
1663            detached_children,
1664            direct_nodes,
1665            root_nodes,
1666            was_skipped,
1667        } = result;
1668        if was_skipped {
1669            self.attach_root_nodes(root_nodes);
1670        }
1671        self.dispose_detached_nodes(direct_nodes);
1672        self.handle_detached_children(parent_scope, detached_children);
1673    }
1674
1675    pub(crate) fn close_current_group_body_for_scope(&self, scope: &RecomposeScope) {
1676        let result = self.with_slot_session_mut(|slots| slots.finish_group_body());
1677        self.handle_finished_group_result(Some(scope.id()), result);
1678        if let Some(popped) = self.scope_stack().pop() {
1679            debug_assert_eq!(
1680                popped.id(),
1681                scope.id(),
1682                "closed scope must match the active scope stack"
1683            );
1684        } else {
1685            log::error!("scope stack underflow while closing scope {}", scope.id());
1686        }
1687    }
1688
1689    #[track_caller]
1690    pub fn remember<T: 'static>(&self, init: impl FnOnce() -> T) -> Owned<T> {
1691        self.remember_at(crate::caller_location_key(), init)
1692    }
1693
1694    #[doc(hidden)]
1695    pub fn remember_at<T: 'static>(
1696        &self,
1697        source: crate::Key,
1698        init: impl FnOnce() -> T,
1699    ) -> Owned<T> {
1700        self.with_slot_session_mut(|slots| {
1701            slots.remember_with_kind(PayloadKind::Remember, source, init)
1702        })
1703    }
1704
1705    #[track_caller]
1706    pub(crate) fn remember_internal<T: 'static>(
1707        &self,
1708        source_salt: crate::Key,
1709        init: impl FnOnce() -> T,
1710    ) -> Owned<T> {
1711        let source = crate::caller_location_key() ^ source_salt;
1712        self.with_slot_session_mut(|slots| {
1713            slots.remember_with_kind(PayloadKind::Internal, source, init)
1714        })
1715    }
1716
1717    #[track_caller]
1718    pub(crate) fn remember_effect<T: Default + 'static>(&self) -> Owned<T> {
1719        let source = crate::caller_location_key();
1720        self.with_slot_session_mut(|slots| slots.remember_effect::<T>(source))
1721    }
1722
1723    #[track_caller]
1724    pub fn use_value_slot<'pass, T: 'static>(
1725        &'pass self,
1726        init: impl FnOnce() -> T,
1727    ) -> ValueSlotHandle<'pass, T> {
1728        let source = crate::caller_location_key();
1729        let slot = self.with_slot_session_mut(|slots| {
1730            slots.value_slot_with_kind(PayloadKind::Internal, source, init)
1731        });
1732        ValueSlotHandle::new(slot)
1733    }
1734
1735    #[doc(hidden)]
1736    #[track_caller]
1737    pub fn __use_param_slot<'pass, T: 'static>(
1738        &'pass self,
1739        init: impl FnOnce() -> T,
1740    ) -> ValueSlotHandle<'pass, T> {
1741        let source = crate::caller_location_key();
1742        let slot = self.with_slot_session_mut(|slots| {
1743            slots.value_slot_with_kind(PayloadKind::Param, source, init)
1744        });
1745        ValueSlotHandle::new(slot)
1746    }
1747
1748    #[doc(hidden)]
1749    #[track_caller]
1750    pub fn __use_return_slot<'pass, T: 'static>(
1751        &'pass self,
1752        init: impl FnOnce() -> T,
1753    ) -> ValueSlotHandle<'pass, T> {
1754        let source = crate::caller_location_key();
1755        let slot = self.with_slot_session_mut(|slots| {
1756            slots.value_slot_with_kind(PayloadKind::Return, source, init)
1757        });
1758        ValueSlotHandle::new(slot)
1759    }
1760
1761    #[doc(hidden)]
1762    pub fn __invalidate_return_consumer_scope(&self) {
1763        let Some(scope) = self.current_recompose_scope() else {
1764            self.request_root_render();
1765            return;
1766        };
1767
1768        if let Some(target) = scope.callback_promotion_target() {
1769            target.invalidate();
1770        } else {
1771            self.request_root_render();
1772        }
1773    }
1774
1775    pub fn with_slot_value<'pass, T: 'static, R>(
1776        &'pass self,
1777        handle: ValueSlotHandle<'pass, T>,
1778        f: impl FnOnce(&T) -> R,
1779    ) -> R {
1780        self.with_slots(|slots| f(slots.read_value(handle.slot())))
1781    }
1782
1783    pub fn with_slot_value_mut<'pass, T: 'static, R>(
1784        &'pass self,
1785        handle: ValueSlotHandle<'pass, T>,
1786        f: impl FnOnce(&mut T) -> R,
1787    ) -> R {
1788        self.with_slots_mut(|slots| f(slots.read_value_mut(handle.slot())))
1789    }
1790
1791    pub fn mutable_state_of<T: Clone + 'static>(&self, initial: T) -> MutableState<T> {
1792        MutableState::with_runtime(initial, self.runtime_handle())
1793    }
1794
1795    pub fn mutable_state_list_of<T, I>(&self, values: I) -> SnapshotStateList<T>
1796    where
1797        T: Clone + 'static,
1798        I: IntoIterator<Item = T>,
1799    {
1800        SnapshotStateList::with_runtime(values, self.runtime_handle())
1801    }
1802
1803    pub fn mutable_state_map_of<K, V, I>(&self, pairs: I) -> SnapshotStateMap<K, V>
1804    where
1805        K: Clone + Eq + Hash + 'static,
1806        V: Clone + 'static,
1807        I: IntoIterator<Item = (K, V)>,
1808    {
1809        SnapshotStateMap::with_runtime(pairs, self.runtime_handle())
1810    }
1811
1812    pub fn read_composition_local<T: Clone + 'static>(&self, local: &CompositionLocal<T>) -> T {
1813        let stack = self.core.local_stack.borrow();
1814        for context in stack.iter().rev() {
1815            if let Some(entry) = context.values.get(&local.key) {
1816                match entry.clone().downcast::<LocalStateEntry<T>>() {
1817                    Ok(typed) => return typed.value(),
1818                    Err(_) => {
1819                        log::error!(
1820                            "composition local entry type mismatch for key {:?}",
1821                            local.key
1822                        );
1823                        return local.default_value();
1824                    }
1825                }
1826            }
1827        }
1828        local.default_value()
1829    }
1830
1831    pub fn read_static_composition_local<T: Clone + 'static>(
1832        &self,
1833        local: &StaticCompositionLocal<T>,
1834    ) -> T {
1835        let stack = self.core.local_stack.borrow();
1836        for context in stack.iter().rev() {
1837            if let Some(entry) = context.values.get(&local.key) {
1838                match entry.clone().downcast::<StaticLocalEntry<T>>() {
1839                    Ok(typed) => return typed.value(),
1840                    Err(_) => {
1841                        log::error!(
1842                            "static composition local entry type mismatch for key {:?}",
1843                            local.key
1844                        );
1845                        return local.default_value();
1846                    }
1847                }
1848            }
1849        }
1850        local.default_value()
1851    }
1852
1853    pub fn current_recompose_scope(&self) -> Option<RecomposeScope> {
1854        self.core.scope_stack.borrow().last().cloned()
1855    }
1856
1857    pub(crate) fn current_state_invalidation_scope(&self) -> Option<RecomposeScope> {
1858        let stack = self.core.scope_stack.borrow();
1859        stack
1860            .iter()
1861            .rev()
1862            .find(|scope| scope.has_recompose_callback())
1863            .cloned()
1864            .or_else(|| stack.last().cloned())
1865    }
1866
1867    pub fn phase(&self) -> crate::Phase {
1868        self.core.phase.get()
1869    }
1870
1871    pub(crate) fn set_phase(&self, phase: crate::Phase) {
1872        self.core.phase.set(phase);
1873    }
1874
1875    pub fn enter_phase(&self, phase: crate::Phase) {
1876        self.set_phase(phase);
1877    }
1878
1879    pub(crate) fn subcompose<R>(
1880        &self,
1881        state: &mut SubcomposeState,
1882        slot_id: SlotId,
1883        content: impl FnOnce(&Composer) -> R,
1884    ) -> (R, Vec<NodeId>) {
1885        match self.phase() {
1886            crate::Phase::Measure | crate::Phase::Layout => {}
1887            current => panic!(
1888                "subcompose() may only be called during measure or layout; current phase: {:?}",
1889                current
1890            ),
1891        }
1892
1893        self.subcompose_stack().push(SubcomposeFrame::default());
1894        let mut guard = SubcomposeStackGuard {
1895            core: self.clone_core(),
1896            leaked: false,
1897        };
1898
1899        let slot_host = state.get_or_create_slots(slot_id);
1900        let (result, _) = self.with_slot_override(slot_host.clone(), |composer| {
1901            composer.with_group(slot_id.raw(), |composer| content(composer))
1902        });
1903
1904        let frame = {
1905            let frame = take_subcompose_frame(&guard.core, "subcompose");
1906            guard.leaked = true;
1907            frame
1908        };
1909        let nodes = frame.nodes;
1910        let scopes = frame.scopes;
1911        state.register_active(slot_id, &nodes, &scopes);
1912        (result, nodes)
1913    }
1914
1915    pub fn subcompose_measurement<R>(
1916        &self,
1917        state: &mut SubcomposeState,
1918        slot_id: SlotId,
1919        content: impl FnOnce(&Composer) -> R,
1920    ) -> (R, Vec<NodeId>) {
1921        let (result, nodes) = self.subcompose(state, slot_id, content);
1922        let roots = nodes
1923            .into_iter()
1924            .filter(|&id| self.node_has_no_parent(id))
1925            .collect();
1926
1927        (result, roots)
1928    }
1929
1930    fn spin_up_subcompose_core(
1931        &self,
1932        slots: &Rc<SlotsHost>,
1933        root: Option<NodeId>,
1934        runtime_handle: &RuntimeHandle,
1935        locals: LocalStackSnapshot,
1936    ) -> Rc<ComposerCore> {
1937        let phase = self.phase();
1938        let shared_state = slots
1939            .runtime_state()
1940            .unwrap_or_else(|| Rc::clone(&self.core.shared_state));
1941        let core = Rc::new(ComposerCore::new(
1942            shared_state,
1943            Rc::clone(slots),
1944            Rc::clone(&self.core.applier),
1945            runtime_handle.clone(),
1946            self.observer(),
1947            root,
1948            InitialParentFrame::RealParent,
1949        ));
1950        core.phase.set(phase);
1951        *core.local_stack.borrow_mut() = locals;
1952        core
1953    }
1954
1955    fn flush_subcompose_pass(
1956        &self,
1957        commands: CommandQueue,
1958        runtime_handle: &RuntimeHandle,
1959        compact_applier: bool,
1960        side_effects: Vec<Box<dyn FnOnce()>>,
1961    ) -> Result<(), NodeError> {
1962        {
1963            let mut applier = self.borrow_applier();
1964            commands.apply(&mut *applier)?;
1965            for update in runtime_handle.take_updates() {
1966                update.apply(&mut *applier)?;
1967            }
1968        }
1969        if compact_applier {
1970            self.core.applier.compact();
1971            self.core.applier.borrow_dyn().clear_recycled_nodes();
1972        }
1973        runtime_handle.drain_ui();
1974        for effect in side_effects {
1975            effect();
1976        }
1977        runtime_handle.drain_ui();
1978        Ok(())
1979    }
1980
1981    pub fn subcompose_in<R>(
1982        &self,
1983        slots: &Rc<SlotsHost>,
1984        root: Option<NodeId>,
1985        f: impl FnOnce(&Composer) -> R,
1986    ) -> Result<R, NodeError> {
1987        let runtime_handle = self.runtime_handle();
1988        let locals = self.current_local_stack();
1989        let core = self.spin_up_subcompose_core(slots, root, &runtime_handle, locals);
1990        let composer = Composer::from_core(core);
1991        let (result, commands, side_effects, compact_applier) = composer.install(|composer| {
1992            let (output, outcome) = composer.try_with_slot_host_pass(
1993                Rc::clone(slots),
1994                crate::slot::SlotPassMode::Compose,
1995                |composer| f(composer),
1996            )?;
1997            let commands = composer.take_commands();
1998            let side_effects = composer.take_side_effects();
1999            Ok((output, commands, side_effects, outcome.compacted))
2000        })?;
2001        self.flush_subcompose_pass(commands, &runtime_handle, compact_applier, side_effects)?;
2002        Ok(result)
2003    }
2004
2005    /// Captures the composition context at the current point so work composed
2006    /// in another slot host inherits both locals and source ownership.
2007    ///
2008    /// A `SubcomposeLayout` captures this while it is being composed and replays
2009    /// it while subcomposing off the measure pass, so content that is
2010    /// subcomposed during layout observes the same composition locals as the
2011    /// `SubcomposeLayout` call site — matching Jetpack Compose, where a
2012    /// subcomposition inherits the composition locals of the layout that
2013    /// created it rather than whatever happens to be in scope during measure
2014    /// (which, after composition unwinds, no longer carries ancestor providers).
2015    pub fn capture_composition_context(&self) -> CapturedCompositionContext {
2016        CapturedCompositionContext {
2017            locals: self.current_local_stack(),
2018            owner_scope: self
2019                .current_recompose_scope()
2020                .map(|scope| scope.downgrade()),
2021        }
2022    }
2023
2024    /// Subcomposes content using an isolated SlotsHost without resetting it.
2025    /// Unlike `subcompose_in`, this preserves existing slot state across calls,
2026    /// allowing efficient reuse during measurement passes. This is critical for
2027    /// lazy lists where items need stable slot positions.
2028    pub fn subcompose_slot<R>(
2029        &self,
2030        slots: &Rc<SlotsHost>,
2031        root: Option<NodeId>,
2032        f: impl FnOnce(&Composer) -> R,
2033    ) -> Result<(R, Vec<RecomposeScope>), NodeError> {
2034        let context = self.capture_composition_context();
2035        self.subcompose_slot_with_context(slots, root, &context, f)
2036    }
2037
2038    /// Like [`Composer::subcompose_slot`], but uses a context captured at the
2039    /// source composition site. This is required for measure-time composition,
2040    /// where the source scope is no longer on the active stack.
2041    pub fn subcompose_slot_with_context<R>(
2042        &self,
2043        slots: &Rc<SlotsHost>,
2044        root: Option<NodeId>,
2045        context: &CapturedCompositionContext,
2046        f: impl FnOnce(&Composer) -> R,
2047    ) -> Result<(R, Vec<RecomposeScope>), NodeError> {
2048        let runtime_handle = self.runtime_handle();
2049        let locals = context.locals.clone();
2050        let core = self.spin_up_subcompose_core(slots, root, &runtime_handle, locals);
2051        *core.subcomposition_owner_scope.borrow_mut() = context
2052            .owner_scope
2053            .as_ref()
2054            .and_then(Weak::upgrade)
2055            .map(|inner| RecomposeScope { inner });
2056        let composer = Composer::from_core(core);
2057        composer.subcompose_stack().push(SubcomposeFrame::default());
2058        let mut guard = SubcomposeStackGuard {
2059            core: composer.clone_core(),
2060            leaked: false,
2061        };
2062        let root_group_key = crate::location_key(file!(), line!(), column!());
2063        let (result, commands, side_effects, compact_applier) = composer.install(|composer| {
2064            let (output, outcome) = composer.try_with_slot_host_pass(
2065                Rc::clone(slots),
2066                crate::slot::SlotPassMode::Compose,
2067                |composer| {
2068                    let output = composer.with_group(root_group_key, |composer| f(composer));
2069                    if root.is_some() {
2070                        composer.pop_parent();
2071                    }
2072                    output
2073                },
2074            )?;
2075            let commands = composer.take_commands();
2076            let side_effects = composer.take_side_effects();
2077            Ok((output, commands, side_effects, outcome.compacted))
2078        })?;
2079        let frame = {
2080            let frame = take_subcompose_frame(&guard.core, "subcompose_slot");
2081            guard.leaked = true;
2082            frame
2083        };
2084
2085        self.flush_subcompose_pass(commands, &runtime_handle, compact_applier, side_effects)?;
2086        Ok((result, frame.scopes))
2087    }
2088
2089    fn attach_root_nodes(&self, root_nodes: Vec<NodeId>) {
2090        for id in root_nodes {
2091            self.attach_to_parent_with_mode(id, true);
2092        }
2093    }
2094
2095    pub fn skip_current_group(&self) {
2096        self.with_slot_session_mut(|slots| slots.skip_group());
2097    }
2098
2099    pub fn runtime_handle(&self) -> RuntimeHandle {
2100        self.core.runtime.clone()
2101    }
2102
2103    pub fn set_recompose_callback<F>(&self, callback: F)
2104    where
2105        F: FnMut(&Composer) + 'static,
2106    {
2107        self.set_recompose_callback_boxed(Box::new(callback));
2108    }
2109
2110    #[inline(never)]
2111    fn set_recompose_callback_boxed(&self, mut callback: Box<dyn FnMut(&Composer)>) {
2112        if let Some(scope) = self.current_recompose_scope() {
2113            let observer = self.observer();
2114            let scope_weak = scope.downgrade();
2115            scope.set_recompose(Box::new(move |composer: &Composer| {
2116                if let Some(inner) = scope_weak.upgrade() {
2117                    let scope_instance = RecomposeScope { inner };
2118                    observer.observe_reads(
2119                        scope_instance.clone(),
2120                        move |scope_ref| scope_ref.invalidate(),
2121                        || {
2122                            callback(composer);
2123                        },
2124                    );
2125                }
2126            }));
2127        }
2128    }
2129
2130    pub fn set_recompose_fn(&self, callback: fn(&Composer)) {
2131        if let Some(scope) = self.current_recompose_scope() {
2132            scope.set_recompose_fn(callback);
2133        }
2134    }
2135
2136    pub fn with_composition_locals<R>(
2137        &self,
2138        provided: Vec<ProvidedValue>,
2139        site: crate::Key,
2140        f: impl FnOnce(&Composer) -> R,
2141    ) -> R {
2142        if provided.is_empty() {
2143            return f(self);
2144        }
2145        let mut context = LocalContext::default();
2146        for value in provided.into_iter().rev() {
2147            if context.values.contains_key(value.key()) {
2148                continue;
2149            }
2150            let (key, entry) = value.into_entry(self, site);
2151            context.values.insert(key, entry);
2152        }
2153        {
2154            let mut stack = self.local_stack();
2155            Rc::make_mut(&mut *stack).push(context);
2156        }
2157        let result = f(self);
2158        {
2159            let mut stack = self.local_stack();
2160            Rc::make_mut(&mut *stack).pop();
2161        }
2162        result
2163    }
2164}