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, ApplierGuard, ApplierHost, COMMAND_FLUSH_THRESHOLD, ChildList, Command,
13 CommandQueue, CompositionLocal, ComputedLocalEntry, DirtyBubble, Key, LocalKey,
14 LocalStackSnapshot, LocalStateEntry, MutableState, Node, NodeError, NodeId, Owned,
15 ProvidedValue, RecomposeOptions, RecomposeScope, RecomposeScopeInner, RecycledNode,
16 RetentionMode, RuntimeHandle, ScopeId, SlotId, SlotPassOutcome, SlotTable, SlotsHost,
17 SnapshotStateList, SnapshotStateMap, StaticCompositionLocal, SubcomposeState, composer_context,
18 retention::RetainKey,
19 runtime,
20 slot::{FinishGroupResult, GroupStart, GroupStartKind, PayloadKind, RootNodeIds, ValueSlotId},
21};
22
23mod composable_group;
24mod runtime_state;
25mod scope_frame;
26mod subcompose_slot;
27pub use composable_group::{ComposableGroup, ParameterChange};
28pub(crate) use runtime_state::ComposerRuntimeState;
29pub(crate) use scope_frame::ScopeFrame;
30use subcompose_slot::{measure_slot_state, subcompose_slot_at};
31
32pub struct ValueSlotHandle<'pass, T: 'static> {
35 slot: ValueSlotId,
36 record: Option<usize>,
37 _pass: PhantomData<&'pass Composer>,
38 _value: PhantomData<fn() -> T>,
39}
40
41impl<T: 'static> Copy for ValueSlotHandle<'_, T> {}
42
43impl<T: 'static> Clone for ValueSlotHandle<'_, T> {
44 fn clone(&self) -> Self {
45 *self
46 }
47}
48
49impl<T: 'static> ValueSlotHandle<'_, T> {
50 pub(crate) fn new(slot: ValueSlotId, record: Option<usize>) -> Self {
51 Self {
52 slot,
53 record,
54 _pass: PhantomData,
55 _value: PhantomData,
56 }
57 }
58}
59
60fn slots_storage_key(host: &Rc<SlotsHost>) -> usize {
61 host.storage_key()
62}
63
64fn bind_slots_host_to_runtime_state(
65 state: &Rc<ComposerRuntimeState>,
66 host: &Rc<SlotsHost>,
67) -> Rc<SlotsHost> {
68 if host.runtime_state_ptr() == Some(Rc::as_ptr(state)) {
71 debug_assert!(
72 state
73 .host_for_storage_key(host.storage_key())
74 .is_some_and(|registered| Rc::ptr_eq(®istered, host)),
75 "a slot host bound to a runtime state must be in its registry"
76 );
77 return Rc::clone(host);
78 }
79 if host.runtime_state().is_some() {
80 if host.rebind_orphaned_runtime_state(state) {
81 state.bind_slots_host(host);
82 return Rc::clone(host);
83 }
84 log::error!(
85 "slot host already belongs to a different composer runtime state; using a fresh slot host"
86 );
87 let replacement = Rc::new(SlotsHost::new(SlotTable::new()));
88 state.bind_slots_host(&replacement);
89 return replacement;
90 }
91 state.bind_slots_host(host);
92 Rc::clone(host)
93}
94
95struct GroupEntry {
96 key: crate::slot::GroupKey,
97 restored: Option<Box<crate::slot::DetachedSubtree>>,
99 placeholder_for: Option<crate::slot::GroupKey>,
100}
101
102struct GroupScopeEntry<'a> {
103 options: RecomposeOptions,
104 start_kind: GroupStartKind,
105 host: &'a SlotsHost,
106 group: crate::slot::ActiveGroupId,
107 parent_hint: Option<NodeId>,
108}
109
110struct SlotHostPassGuard {
111 core: Rc<ComposerCore>,
112 host: Rc<SlotsHost>,
113 fold_base: usize,
115 active: bool,
116}
117
118impl SlotHostPassGuard {
119 fn close(&mut self) {
120 if !self.active {
121 return;
122 }
123 if self.host.has_active_pass() {
124 self.host.abandon_active_pass();
125 }
126 match self.core.slot_hosts.borrow_mut().pop() {
127 Some(host) if Rc::ptr_eq(&host, &self.host) => {}
128 Some(_) => {
129 log::error!("slot host stack mismatch while closing slot host pass");
130 }
131 None => {
132 log::error!("slot host stack underflow while closing slot host pass");
133 }
134 }
135 self.core.branch_folds.end_pass(self.fold_base);
136 self.active = false;
137 }
138}
139
140impl Drop for SlotHostPassGuard {
141 fn drop(&mut self) {
142 self.close();
143 }
144}
145
146pub(crate) struct PendingMovable {
147 pub(crate) key: crate::slot::GroupKey,
148 pub(crate) placeholder: AnchorId,
149 pub(crate) parent_scope: Option<Weak<RecomposeScopeInner>>,
150}
151
152fn reparent_restored_scopes(
153 host: &SlotsHost,
154 group: crate::slot::ActiveGroupId,
155 old_hint: Option<NodeId>,
156 parent_hint: Option<NodeId>,
157) {
158 host.with_write_session(|slots| {
159 slots.for_each_subtree_scope(group, |scope| {
160 if scope.parent_hint() == old_hint {
161 scope.set_parent_hint(parent_hint);
162 }
163 scope.reactivate();
164 });
165 });
166}
167
168fn movable_retain_key(id: Key) -> RetainKey {
169 RetainKey::for_group(
170 None,
171 crate::slot::GroupKey::new(crate::slot::MOVABLE_STATIC_KEY, Some(id), 0),
172 )
173}
174
175const SPARE_COMMAND_QUEUES: usize = 8;
177
178const SPARE_COMMAND_CAPACITY: usize = 1024;
181
182fn spare_commands() -> CommandQueue {
183 crate::thread_state::try_runtimes(|state| state.spare_commands.borrow_mut().pop())
184 .flatten()
185 .unwrap_or_default()
186}
187
188#[derive(Default)]
191pub(crate) struct ComposerStacks {
192 slot_hosts: Vec<Rc<SlotsHost>>,
193 parent_stack: Vec<ParentFrame>,
194 scope_stack: Vec<ScopeFrame>,
195}
196
197const SPARE_STACK_CAPACITY: usize = 256;
200
201fn spare_composer_stacks() -> ComposerStacks {
202 crate::thread_state::try_runtimes(|state| state.spare_composer_stacks.take())
203 .flatten()
204 .unwrap_or_default()
205}
206
207impl ComposerStacks {
208 fn holds_storage(&self) -> bool {
209 self.slot_hosts.capacity() > 0
210 || self.parent_stack.capacity() > 0
211 || self.scope_stack.capacity() > 0
212 }
213}
214
215fn recycle_composer_stacks(mut stacks: ComposerStacks) {
217 let ComposerStacks {
218 slot_hosts,
219 parent_stack,
220 scope_stack,
221 } = &mut stacks;
222 if slot_hosts.capacity() > SPARE_STACK_CAPACITY
223 || parent_stack.capacity() > SPARE_STACK_CAPACITY
224 || scope_stack.capacity() > SPARE_STACK_CAPACITY
225 {
226 return;
227 }
228 slot_hosts.clear();
229 parent_stack.clear();
230 scope_stack.clear();
231 crate::thread_state::try_runtimes(|state| state.spare_composer_stacks.set(Some(stacks)));
232}
233
234pub(crate) fn recycle_commands(commands: CommandQueue) {
236 if commands.capacity() > SPARE_COMMAND_CAPACITY {
237 return;
238 }
239 crate::thread_state::try_runtimes(|state| {
240 let mut spare = state.spare_commands.borrow_mut();
241 if spare.len() < SPARE_COMMAND_QUEUES {
242 spare.push(commands);
243 }
244 });
245}
246
247pub(crate) struct ParentFrame {
248 pub(crate) id: NodeId,
249 pub(crate) previous: ChildList,
250 pub(crate) new_children: ChildList,
251 pub(crate) attach_mode: ParentAttachMode,
252 pub(crate) synthetic_root: bool,
253}
254
255#[derive(Clone, Copy)]
256pub(crate) enum InitialParentFrame {
257 SyntheticRoot,
258 RealParent,
259}
260
261#[derive(Clone, Copy, Debug, PartialEq, Eq)]
262pub(crate) enum ParentAttachMode {
263 ImmediateAppend,
264 DeferredSync,
265}
266
267#[derive(Default)]
268pub(crate) struct SubcomposeFrame {
269 pub(crate) nodes: Vec<NodeId>,
270 pub(crate) scopes: Vec<RecomposeScope>,
271}
272
273pub(crate) struct LocalFrame {
276 values: SmallVec<[(LocalKey, Rc<dyn Any>); 2]>,
277 parent: LocalStackSnapshot,
278}
279
280pub(crate) fn provided_entry(stack: &LocalStackSnapshot, key: &LocalKey) -> Option<Rc<dyn Any>> {
282 let mut frame = stack.as_deref();
283 while let Some(current) = frame {
284 if let Some((_, entry)) = current.values.iter().find(|(provided, _)| provided == key) {
285 return Some(Rc::clone(entry));
286 }
287 frame = current.parent.as_deref();
288 }
289 None
290}
291
292pub(crate) struct ComposerCore {
293 pub(crate) shared_state: Rc<ComposerRuntimeState>,
294 pub(crate) branch_folds: Rc<crate::slot::BranchFolds>,
297 pub(crate) slots: Rc<SlotsHost>,
298 slot_hosts: RefCell<Vec<Rc<SlotsHost>>>,
299 pub(crate) applier: Rc<dyn ApplierHost>,
300 pub(crate) runtime: RuntimeHandle,
301 pub(crate) parent_stack: RefCell<Vec<ParentFrame>>,
302 pub(crate) subcompose_stack: RefCell<Vec<SubcomposeFrame>>,
303 pub(crate) root: Cell<Option<NodeId>>,
304 pub(crate) commands: RefCell<CommandQueue>,
305 pub(crate) scope_stack: RefCell<Vec<ScopeFrame>>,
306 subcomposition_owner_scope: RefCell<Option<RecomposeScope>>,
307 pub(crate) local_stack: RefCell<LocalStackSnapshot>,
308 pub(crate) side_effects: RefCell<Vec<Box<dyn FnOnce()>>>,
309 pub(crate) pending_scope_options: Cell<Option<RecomposeOptions>>,
310 pub(crate) phase: Cell<crate::Phase>,
311 pub(crate) recompose_parent_hint: Cell<Option<NodeId>>,
312 pub(crate) recompose_child_cursor: Cell<crate::recompose::RecomposeChildCursor>,
313 pub(crate) restarted_scope: RefCell<Option<RecomposeScope>>,
317 pub(crate) root_render_requested: Cell<bool>,
318 locals_changed: Cell<bool>,
321 reused_depth: Cell<u32>,
324 pub(crate) _not_send: PhantomData<*const ()>,
325}
326
327#[derive(Clone, Default)]
331pub struct CapturedCompositionContext {
332 locals: LocalStackSnapshot,
333 owner_scope: Option<Weak<RecomposeScopeInner>>,
334 locals_changed: bool,
335}
336
337impl CapturedCompositionContext {
338 pub fn locals_changed(&self) -> bool {
343 self.locals_changed
344 }
345
346 pub fn owner_chain_deactivation_epoch(&self) -> u64 {
350 self.owner_scope
351 .as_ref()
352 .and_then(Weak::upgrade)
353 .map_or(0, |inner| {
354 RecomposeScope { inner }.owner_chain_deactivation_epoch()
355 })
356 }
357}
358
359fn take_subcompose_frame(core: &ComposerCore, operation: &str) -> SubcomposeFrame {
360 match core.subcompose_stack.borrow_mut().pop() {
361 Some(frame) => frame,
362 None => {
363 log::error!("subcompose stack underflow while finishing {operation}");
364 SubcomposeFrame::default()
365 }
366 }
367}
368
369struct SubcomposeStackGuard {
370 core: Rc<ComposerCore>,
371 leaked: bool,
372}
373
374impl Drop for SubcomposeStackGuard {
375 fn drop(&mut self) {
376 if !self.leaked {
377 self.core.subcompose_stack.borrow_mut().pop();
378 }
379 }
380}
381
382impl Drop for ComposerCore {
383 fn drop(&mut self) {
386 let commands = std::mem::take(self.commands.get_mut());
387 if commands.len() == 0 && commands.capacity() > 0 {
388 recycle_commands(commands);
389 }
390 let stacks = self.take_stacks();
391 if stacks.holds_storage() {
392 recycle_composer_stacks(stacks);
393 }
394 }
395}
396
397impl ComposerCore {
398 fn new(parts: ComposerParts) -> Self {
399 let ComposerParts {
400 shared_state,
401 slots,
402 applier,
403 runtime,
404 root,
405 initial_parent_frame,
406 } = parts;
407 let ComposerStacks {
408 slot_hosts,
409 mut parent_stack,
410 scope_stack,
411 } = spare_composer_stacks();
412 push_root_frame(&mut parent_stack, root, initial_parent_frame);
413 Self {
414 branch_folds: Rc::clone(&shared_state.branch_folds),
415 shared_state,
416 slots,
417 slot_hosts: RefCell::new(slot_hosts),
418 applier,
419 runtime,
420 parent_stack: RefCell::new(parent_stack),
421 subcompose_stack: RefCell::new(Vec::new()),
422 root: Cell::new(root),
423 commands: RefCell::new(spare_commands()),
424 scope_stack: RefCell::new(scope_stack),
425 subcomposition_owner_scope: RefCell::new(None),
426 local_stack: RefCell::new(None),
427 side_effects: RefCell::new(Vec::new()),
428 pending_scope_options: Cell::new(None),
429 phase: Cell::new(crate::Phase::Compose),
430 recompose_parent_hint: Cell::new(None),
431 recompose_child_cursor: Cell::new(crate::recompose::RecomposeChildCursor::Unknown),
432 restarted_scope: RefCell::new(None),
433 root_render_requested: Cell::new(false),
434 locals_changed: Cell::new(false),
435 reused_depth: Cell::new(0),
436 _not_send: PhantomData,
437 }
438 }
439
440 fn take_stacks(&mut self) -> ComposerStacks {
442 let mut stacks = ComposerStacks {
443 slot_hosts: std::mem::take(self.slot_hosts.get_mut()),
444 parent_stack: std::mem::take(self.parent_stack.get_mut()),
445 scope_stack: std::mem::take(self.scope_stack.get_mut()),
446 };
447 stacks.slot_hosts.clear();
448 stacks.parent_stack.clear();
449 stacks.scope_stack.clear();
450 stacks
451 }
452
453 fn restart(&mut self, parts: ComposerParts) {
457 let Self {
458 shared_state,
459 branch_folds,
460 slots,
461 slot_hosts,
462 applier,
463 runtime,
464 parent_stack,
465 subcompose_stack,
466 root,
467 commands,
468 scope_stack,
469 subcomposition_owner_scope,
470 local_stack,
471 side_effects,
472 pending_scope_options,
473 phase,
474 recompose_parent_hint,
475 recompose_child_cursor,
476 restarted_scope,
477 root_render_requested,
478 locals_changed,
479 reused_depth,
480 _not_send: _,
481 } = self;
482 if !Rc::ptr_eq(shared_state, &parts.shared_state) {
483 *branch_folds = Rc::clone(&parts.shared_state.branch_folds);
484 *shared_state = parts.shared_state;
485 }
486 *slots = parts.slots;
487 *applier = parts.applier;
488 *runtime = parts.runtime;
489 slot_hosts.get_mut().clear();
490 let parent_stack = parent_stack.get_mut();
491 parent_stack.clear();
492 push_root_frame(parent_stack, parts.root, parts.initial_parent_frame);
493 subcompose_stack.get_mut().clear();
494 root.set(parts.root);
495 let commands = commands.get_mut();
496 if commands.len() > 0 || commands.capacity() == 0 {
497 *commands = spare_commands();
498 }
499 scope_stack.get_mut().clear();
500 *subcomposition_owner_scope.get_mut() = None;
501 *local_stack.get_mut() = None;
502 side_effects.get_mut().clear();
503 pending_scope_options.set(None);
504 phase.set(crate::Phase::Compose);
505 recompose_parent_hint.set(None);
506 recompose_child_cursor.set(crate::recompose::RecomposeChildCursor::Unknown);
507 *restarted_scope.get_mut() = None;
508 root_render_requested.set(false);
509 locals_changed.set(false);
510 reused_depth.set(0);
511 }
512
513 fn park(&mut self) {
516 self.slot_hosts.get_mut().clear();
517 self.parent_stack.get_mut().clear();
518 self.scope_stack.get_mut().clear();
519 self.subcompose_stack.get_mut().clear();
520 *self.subcomposition_owner_scope.get_mut() = None;
521 *self.local_stack.get_mut() = None;
522 self.side_effects.get_mut().clear();
523 }
524}
525
526fn push_root_frame(
528 parent_stack: &mut Vec<ParentFrame>,
529 root: Option<NodeId>,
530 initial_parent_frame: InitialParentFrame,
531) {
532 if let Some(root_id) = root {
533 parent_stack.push(ParentFrame {
534 id: root_id,
535 previous: ChildList::new(),
536 new_children: ChildList::new(),
537 attach_mode: ParentAttachMode::DeferredSync,
538 synthetic_root: matches!(initial_parent_frame, InitialParentFrame::SyntheticRoot),
539 });
540 }
541}
542
543#[derive(Clone, Copy)]
547struct SubcomposeSite<'a> {
548 applier: &'a Rc<dyn ApplierHost>,
549 runtime: &'a RuntimeHandle,
550 phase: crate::Phase,
551 locals_changed: bool,
552}
553
554impl SubcomposeSite<'_> {
555 fn spin_up_core(
558 self,
559 shared_state: Rc<ComposerRuntimeState>,
560 slots: &Rc<SlotsHost>,
561 root: Option<NodeId>,
562 locals: LocalStackSnapshot,
563 ) -> Rc<ComposerCore> {
564 let core = Rc::new(ComposerCore::new(ComposerParts {
565 shared_state,
566 slots: Rc::clone(slots),
567 applier: Rc::clone(self.applier),
568 runtime: self.runtime.clone(),
569 root,
570 initial_parent_frame: InitialParentFrame::RealParent,
571 }));
572 core.phase.set(self.phase);
573 core.locals_changed.set(self.locals_changed);
574 *core.local_stack.borrow_mut() = locals;
575 core
576 }
577
578 fn flush(
583 self,
584 mut commands: CommandQueue,
585 compact_applier: bool,
586 side_effects: Vec<Box<dyn FnOnce()>>,
587 ) -> Result<(), NodeError> {
588 {
589 let mut applier = self.applier.borrow_dyn();
590 commands.apply(&mut *applier)?;
591 for update in self.runtime.take_updates() {
592 update.apply(&mut *applier)?;
593 }
594 }
595 recycle_commands(commands);
596 if compact_applier {
597 self.applier.compact();
598 self.applier.borrow_dyn().clear_recycled_nodes();
599 }
600 composer_context::without_composer(|| {
601 for effect in side_effects {
602 effect();
603 }
604 });
605 Ok(())
606 }
607}
608
609struct ComposerParts {
612 shared_state: Rc<ComposerRuntimeState>,
613 slots: Rc<SlotsHost>,
614 applier: Rc<dyn ApplierHost>,
615 runtime: RuntimeHandle,
616 root: Option<NodeId>,
617 initial_parent_frame: InitialParentFrame,
618}
619
620#[derive(Clone)]
624pub struct Composer {
625 pub(crate) core: Rc<ComposerCore>,
626}
627
628#[doc(hidden)]
631pub struct BranchGroupGuard<'a> {
632 folds: &'a crate::slot::BranchFolds,
633 token: crate::slot::FoldToken,
634}
635
636impl BranchGroupGuard<'_> {
637 #[doc(hidden)]
640 #[inline]
641 pub fn advance(&mut self, key: Key) {
642 self.folds.advance(&mut self.token, key);
643 }
644}
645
646impl Drop for BranchGroupGuard<'_> {
647 #[inline]
648 fn drop(&mut self) {
649 self.folds.close(self.token);
650 }
651}
652
653#[doc(hidden)]
660pub struct ScopedBranchGroupGuard {
661 open: std::mem::ManuallyDrop<Option<ScopedBranchGroup>>,
664}
665
666struct ScopedBranchGroup {
668 folds: Rc<crate::slot::BranchFolds>,
669 token: crate::slot::FoldToken,
670}
671
672#[doc(hidden)]
675#[inline]
676pub fn __branch_group_scope_deferred(key: Key) -> ScopedBranchGroupGuard {
677 let open = composer_context::with_current_core(|core| ScopedBranchGroup {
678 token: core.branch_folds.push(key),
679 folds: Rc::clone(&core.branch_folds),
680 });
681 ScopedBranchGroupGuard {
682 open: std::mem::ManuallyDrop::new(open),
683 }
684}
685
686#[doc(hidden)]
691#[inline]
692pub fn __branch_group_scope_advance(guard: &mut ScopedBranchGroupGuard, key: Key) {
693 if let Some(group) = guard.open.as_mut() {
694 group.folds.advance(&mut group.token, key);
695 }
696}
697
698impl Drop for ScopedBranchGroupGuard {
699 #[inline(always)]
700 fn drop(&mut self) {
701 if let Some(group) = self.open.take() {
702 close_scoped_branch_group(group);
703 }
704 }
705}
706
707#[inline(never)]
708fn close_scoped_branch_group(group: ScopedBranchGroup) {
709 group.folds.close(group.token);
710}
711
712pub(crate) enum EmittedNode {
713 Fresh(Box<dyn Node>),
714 Recycled(RecycledNode),
715}
716
717impl Composer {
718 pub(crate) fn new_with_shared_state(
719 shared_state: Rc<ComposerRuntimeState>,
720 slots: Rc<SlotsHost>,
721 applier: Rc<dyn ApplierHost>,
722 runtime: RuntimeHandle,
723 root: Option<NodeId>,
724 ) -> Self {
725 Self::new_with_shared_state_with_parent_frame(
726 shared_state,
727 slots,
728 applier,
729 runtime,
730 root,
731 InitialParentFrame::SyntheticRoot,
732 )
733 }
734
735 fn new_with_shared_state_with_parent_frame(
736 shared_state: Rc<ComposerRuntimeState>,
737 slots: Rc<SlotsHost>,
738 applier: Rc<dyn ApplierHost>,
739 runtime: RuntimeHandle,
740 root: Option<NodeId>,
741 initial_parent_frame: InitialParentFrame,
742 ) -> Self {
743 shared_state.bind_applier_host(&applier);
744 let slots = bind_slots_host_to_runtime_state(&shared_state, &slots);
745 let core = Rc::new(ComposerCore::new(ComposerParts {
746 shared_state,
747 slots,
748 applier,
749 runtime,
750 root,
751 initial_parent_frame,
752 }));
753 Self { core }
754 }
755
756 pub(crate) fn for_pass(
760 parked: Option<Self>,
761 shared_state: Rc<ComposerRuntimeState>,
762 slots: Rc<SlotsHost>,
763 applier: Rc<dyn ApplierHost>,
764 runtime: RuntimeHandle,
765 root: Option<NodeId>,
766 ) -> Self {
767 let Some(mut composer) = parked.filter(|parked| Rc::strong_count(&parked.core) == 1) else {
768 return Self::new_with_shared_state(shared_state, slots, applier, runtime, root);
769 };
770 let Some(core) = Rc::get_mut(&mut composer.core) else {
771 return Self::new_with_shared_state(shared_state, slots, applier, runtime, root);
772 };
773 shared_state.bind_applier_host(&applier);
774 let slots = bind_slots_host_to_runtime_state(&shared_state, &slots);
775 core.restart(ComposerParts {
776 shared_state,
777 slots,
778 applier,
779 runtime,
780 root,
781 initial_parent_frame: InitialParentFrame::SyntheticRoot,
782 });
783 composer
784 }
785
786 pub(crate) fn park(mut self) -> Option<Self> {
790 Rc::get_mut(&mut self.core)?.park();
791 Some(self)
792 }
793
794 pub fn new(
797 slots: Rc<SlotsHost>,
798 applier: Rc<dyn ApplierHost>,
799 runtime: RuntimeHandle,
800 root: Option<NodeId>,
801 ) -> Self {
802 Self::new_with_shared_state_with_parent_frame(
803 slots
804 .runtime_state()
805 .unwrap_or_else(|| Rc::new(ComposerRuntimeState::default())),
806 slots,
807 applier,
808 runtime,
809 root,
810 InitialParentFrame::RealParent,
811 )
812 }
813
814 pub(crate) fn from_core(core: Rc<ComposerCore>) -> Self {
815 Self { core }
816 }
817
818 pub(crate) fn clone_core(&self) -> Rc<ComposerCore> {
819 Rc::clone(&self.core)
820 }
821
822 pub(crate) fn request_root_render(&self) {
823 self.core.root_render_requested.set(true);
824 }
825
826 pub(crate) fn take_root_render_request(&self) -> bool {
827 self.core.root_render_requested.replace(false)
828 }
829
830 pub fn active_slots_host(&self) -> Rc<SlotsHost> {
833 self.core
834 .slot_hosts
835 .borrow()
836 .last()
837 .cloned()
838 .unwrap_or_else(|| Rc::clone(&self.core.slots))
839 }
840
841 fn with_active_slots_host<R>(&self, f: impl FnOnce(&SlotsHost) -> R) -> R {
842 let hosts = self.core.slot_hosts.borrow();
843 f(hosts.last().unwrap_or(&self.core.slots))
844 }
845
846 pub(crate) fn with_slots<R>(&self, f: impl FnOnce(&SlotTable) -> R) -> R {
847 self.with_active_slots_host(|host| f(&host.borrow()))
848 }
849
850 pub(crate) fn with_slots_mut<R>(&self, f: impl FnOnce(&mut SlotTable) -> R) -> R {
851 self.with_active_slots_host(|host| f(&mut host.borrow_mut()))
852 }
853
854 pub(crate) fn with_slot_session_mut<R>(
855 &self,
856 f: impl FnOnce(&mut crate::slot::SlotWriteSession<'_>) -> R,
857 ) -> R {
858 self.with_active_slots_host(|host| host.with_write_session(f))
859 }
860
861 pub(crate) fn try_with_slot_host_pass<R>(
862 &self,
863 slots: Rc<SlotsHost>,
864 mode: crate::slot::SlotPassMode,
865 f: impl FnOnce(&Self) -> R,
866 ) -> Result<(R, SlotPassOutcome), NodeError> {
867 let mut guard = self.begin_slot_host_pass(&slots, mode);
868 let result = f(self);
869 let outcome = self.finish_slot_host_pass(&guard.host)?;
870 guard.close();
871 Ok((result, outcome))
872 }
873
874 pub(crate) fn with_slot_host_pass<R>(
875 &self,
876 slots: Rc<SlotsHost>,
877 mode: crate::slot::SlotPassMode,
878 f: impl FnOnce(&Self) -> R,
879 ) -> (R, SlotPassOutcome) {
880 let mut guard = self.begin_slot_host_pass(&slots, mode);
881 let result = f(self);
882 let outcome = match self.finish_slot_host_pass(&guard.host) {
883 Ok(outcome) => outcome,
884 Err(err) => {
885 log::error!("slot host pass finalization failed: {err}");
886 SlotPassOutcome::default()
887 }
888 };
889 guard.close();
890 (result, outcome)
891 }
892
893 pub(crate) fn with_slot_override<R>(
894 &self,
895 slots: Rc<SlotsHost>,
896 f: impl FnOnce(&Self) -> R,
897 ) -> (R, SlotPassOutcome) {
898 self.with_slot_host_pass(slots, crate::slot::SlotPassMode::Compose, f)
899 }
900
901 fn begin_slot_host_pass(
902 &self,
903 slots: &Rc<SlotsHost>,
904 mode: crate::slot::SlotPassMode,
905 ) -> SlotHostPassGuard {
906 let slots = bind_slots_host_to_runtime_state(&self.core.shared_state, slots);
907 let fold_base = self.core.branch_folds.len();
908 slots.begin_pass(mode, &self.core.branch_folds);
909 {
910 let mut stack = self.core.slot_hosts.borrow_mut();
911 if let Some(parent) = stack.last()
912 && !Rc::ptr_eq(parent, &slots)
913 {
914 parent.note_nested_host(&slots);
915 }
916 stack.push(Rc::clone(&slots));
917 }
918 SlotHostPassGuard {
919 core: self.clone_core(),
920 host: slots,
921 fold_base,
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.as_ref().and_then(RecomposeScope::upgrade) {
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 pub(crate) 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<ScopeFrame>> {
1012 self.core.scope_stack.borrow_mut()
1013 }
1014
1015 pub(crate) fn local_stack(&self) -> RefMut<'_, LocalStackSnapshot> {
1016 self.core.local_stack.borrow_mut()
1017 }
1018
1019 pub(crate) fn current_local_stack(&self) -> LocalStackSnapshot {
1020 self.core.local_stack.borrow().clone()
1021 }
1022
1023 pub(crate) fn side_effects_mut(&self) -> RefMut<'_, Vec<Box<dyn FnOnce()>>> {
1024 self.core.side_effects.borrow_mut()
1025 }
1026
1027 pub(crate) fn borrow_applier(&self) -> ApplierGuard<'_, dyn Applier> {
1028 self.core.applier.borrow_dyn()
1029 }
1030
1031 pub fn record_rebound_slot_children(&self, children: &[NodeId]) {
1042 let mut applier = self.borrow_applier();
1043 for &child in children {
1044 applier.record_structural_change(child);
1045 }
1046 }
1047
1048 pub fn create_virtual_node(&self, node: Box<dyn Node>) -> NodeId {
1051 debug_assert!(node.is_virtual(), "a virtual node reports `is_virtual`");
1052 let mut applier = self.borrow_applier();
1053 let node_id = applier.create(node);
1054 if let Ok(node) = applier.get_mut(node_id) {
1055 node.set_node_id(node_id);
1056 }
1057 node_id
1058 }
1059
1060 pub fn dispose_subcomposed_nodes(
1072 &self,
1073 disposal: crate::subcompose::SubcomposeDisposal,
1074 ) -> Result<(), NodeError> {
1075 if disposal.nodes.is_empty() && disposal.slot_hosts.is_empty() {
1076 return Ok(());
1077 }
1078 self.apply_pending_commands()?;
1079 Self::dispose_measure_subcomposed_nodes(&self.core.applier, disposal)
1080 }
1081
1082 pub fn dispose_measure_subcomposed_nodes(
1086 applier: &Rc<dyn ApplierHost>,
1087 disposal: crate::subcompose::SubcomposeDisposal,
1088 ) -> Result<(), NodeError> {
1089 if disposal.nodes.is_empty() && disposal.slot_hosts.is_empty() {
1090 return Ok(());
1091 }
1092 let disposal = crate::NodeDisposal::from_subcomposed(disposal, &*applier.borrow_dyn());
1093 applier.dispose_nodes(disposal)
1094 }
1095
1096 pub fn node_has_no_parent(&self, node_id: NodeId) -> bool {
1099 let mut applier = self.borrow_applier();
1100 match applier.get_mut(node_id) {
1101 Ok(node) => node.parent().is_none(),
1102 Err(_) => true,
1103 }
1104 }
1105
1106 pub fn node_parent(&self, node_id: NodeId) -> Result<Option<NodeId>, NodeError> {
1110 self.borrow_applier()
1111 .get_mut(node_id)
1112 .map(|node| node.parent())
1113 }
1114
1115 pub fn get_node_children(&self, node_id: NodeId) -> SmallVec<[NodeId; 8]> {
1120 let mut applier = self.borrow_applier();
1121 match applier.get_mut(node_id) {
1122 Ok(node) => {
1123 let mut children = SmallVec::<[NodeId; 8]>::new();
1124 node.collect_children_into(&mut children);
1125 children
1126 }
1127 Err(_) => SmallVec::<[NodeId; 8]>::new(),
1128 }
1129 }
1130
1131 pub fn visit_node_children(&self, node_id: NodeId, mut visit: impl FnMut(NodeId, bool)) {
1137 let applier = self.borrow_applier();
1138 let Ok(node) = applier.get_ref(node_id) else {
1139 return;
1140 };
1141 node.for_each_child(&mut |child| {
1142 let needs_relayout = applier.get_ref(child).is_ok_and(Node::layout_dirty);
1143 visit(child, needs_relayout);
1144 });
1145 }
1146
1147 pub fn nodes_need_relayout(&self, node_ids: impl IntoIterator<Item = NodeId>) -> bool {
1156 let applier = self.borrow_applier();
1157 node_ids
1158 .into_iter()
1159 .any(|node_id| applier.get_ref(node_id).is_ok_and(Node::layout_dirty))
1160 }
1161
1162 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(&Self) -> R) -> R {
1177 let _composer_guard = composer_context::enter(self);
1178 runtime::push_active_runtime(&self.core.runtime);
1179 struct Guard;
1180 impl Drop for Guard {
1181 fn drop(&mut self) {
1182 runtime::pop_active_runtime();
1183 }
1184 }
1185 let guard = Guard;
1186 let result = f(self);
1187 drop(guard);
1188 result
1189 }
1190
1191 pub(crate) fn flush_pending_commands_if_large(&self) -> Result<(), NodeError> {
1192 let queued = self.core.commands.borrow().len();
1193 if queued < COMMAND_FLUSH_THRESHOLD {
1194 return Ok(());
1195 }
1196 self.apply_pending_commands()
1197 }
1198
1199 fn resolve_group_entry(
1200 &self,
1201 host: &Rc<SlotsHost>,
1202 seed: crate::slot::GroupKeySeed,
1203 parent_scope_id: Option<ScopeId>,
1204 ) -> GroupEntry {
1205 let key = host.with_write_session(|slots| slots.reserve_group_key(seed));
1206 let retain_key = RetainKey::for_group(parent_scope_id, key);
1207 let restored = self
1208 .core
1209 .shared_state
1210 .take_retained(host, retain_key, |subtree| {
1211 host.with_write_session(|slots| slots.retained_restore_ready(key, subtree))
1212 })
1213 .or_else(|| self.take_movable_from_another_table(host, retain_key, key))
1214 .map(Box::new);
1215 if restored.is_some() || !key.is_movable() {
1216 return GroupEntry {
1217 key,
1218 restored,
1219 placeholder_for: None,
1220 };
1221 }
1222 let attached_elsewhere = self.movable_attached_elsewhere(host, key);
1223 if !attached_elsewhere {
1224 return GroupEntry {
1225 key,
1226 restored: None,
1227 placeholder_for: None,
1228 };
1229 }
1230 let id = key.explicit_key.unwrap_or_default();
1231 let placeholder = host.with_write_session(|slots| {
1232 slots.reserve_group_key(crate::slot::GroupKeySeed::movable_placeholder(id))
1233 });
1234 GroupEntry {
1235 key: placeholder,
1236 restored: None,
1237 placeholder_for: Some(key),
1238 }
1239 }
1240
1241 fn take_movable_from_another_table(
1246 &self,
1247 host: &Rc<SlotsHost>,
1248 retain_key: RetainKey,
1249 key: crate::slot::GroupKey,
1250 ) -> Option<crate::slot::DetachedSubtree> {
1251 if !key.is_movable() {
1252 return None;
1253 }
1254 let (source, mut subtree) = self
1255 .core
1256 .shared_state
1257 .take_retained_movable_elsewhere(host, retain_key)?;
1258 source
1259 .borrow_mut()
1260 .invalidate_detached_subtree_anchors(&subtree);
1261 if host.with_write_session(|slots| slots.retained_restore_ready(key, &mut subtree)) {
1262 return Some(subtree);
1263 }
1264 log::error!(
1265 "movable content {key:?} could not be taken over by the slot table that asked for it"
1266 );
1267 if let Err(error) = self.dispose_detached_subtree_in_host(host, subtree) {
1268 log::error!("disposing movable content that could not move failed: {error}");
1269 }
1270 None
1271 }
1272
1273 fn movable_attached_elsewhere(&self, host: &Rc<SlotsHost>, key: crate::slot::GroupKey) -> bool {
1276 if host.with_write_session(|slots| slots.movable_attached_elsewhere(key)) {
1277 return true;
1278 }
1279 let Some(id) = key.movable_id() else {
1280 return false;
1281 };
1282 self.core
1283 .shared_state
1284 .host_holding_movable(id)
1285 .is_some_and(|holder| !Rc::ptr_eq(&holder, host))
1286 }
1287
1288 fn start_group(
1289 &self,
1290 host: &Rc<SlotsHost>,
1291 seed: crate::slot::GroupKeySeed,
1292 parent_node: Option<NodeId>,
1293 ) -> (
1294 GroupStart<crate::slot::ActiveGroupId>,
1295 Option<crate::slot::GroupKey>,
1296 ) {
1297 if !self.core.shared_state.retains_any() {
1298 let started = host.with_write_session(|slots| {
1299 let key = slots.reserve_group_key(seed);
1300 (!key.is_movable()).then(|| slots.begin_group(key, None, parent_node))
1301 });
1302 if let Some(started) = started {
1303 return (started, None);
1304 }
1305 }
1306 let parent_scope_id = {
1308 let mut stack = self.scope_stack();
1309 let top = stack.len().checked_sub(1);
1310 top.map(|top| self.frame_scope(&mut stack, top).id())
1311 };
1312 let GroupEntry {
1313 key,
1314 restored,
1315 placeholder_for,
1316 } = self.resolve_group_entry(host, seed, parent_scope_id);
1317 let started =
1318 host.with_write_session(|slots| slots.begin_group(key, restored, parent_node));
1319 (started, placeholder_for)
1320 }
1321
1322 #[doc(hidden)]
1323 pub fn __branch_group_deferred(&self, key: Key) -> BranchGroupGuard<'_> {
1324 let folds = &*self.core.branch_folds;
1325 BranchGroupGuard {
1326 token: folds.push(key),
1327 folds,
1328 }
1329 }
1330
1331 fn dispose_detached_nodes(&self, nodes: impl IntoIterator<Item = NodeId>) {
1332 for node_id in nodes {
1333 self.commands_mut().push(Command::callback(move |applier| {
1334 crate::slot::dispose_detached_node_now(applier, node_id)
1335 }));
1336 }
1337 }
1338
1339 fn detached_root_parent_commands(
1340 &self,
1341 subtree: &crate::slot::DetachedSubtree,
1342 context: &'static str,
1343 ) -> Result<Vec<(NodeId, Option<NodeId>)>, NodeError> {
1344 let mut root_nodes = Vec::new();
1345 subtree.collect_root_nodes_checked_into(&mut root_nodes, context);
1346 let mut roots = Vec::with_capacity(root_nodes.len());
1347 for root in root_nodes {
1348 let parent_id = {
1349 let mut applier = self.borrow_applier();
1350 applier.get_mut(root)?.parent()
1351 };
1352 roots.push((root, parent_id));
1353 }
1354 Ok(roots)
1355 }
1356
1357 fn retain_detached_subtree_in_host(
1358 &self,
1359 slots_host: &Rc<SlotsHost>,
1360 parent_scope: Option<ScopeId>,
1361 subtree: crate::slot::DetachedSubtree,
1362 ) -> Result<(), NodeError> {
1363 let Some(root_key) = subtree.root_key_checked() else {
1364 log::error!("retention rejected detached subtree without a root group");
1365 self.dispose_detached_subtree_in_host(slots_host, subtree)?;
1366 return Ok(());
1367 };
1368 let root_detaches = self.detached_root_parent_commands(&subtree, "retention")?;
1369 subtree.scopes().for_each(RecomposeScope::deactivate);
1370 for (root, parent_id) in root_detaches {
1371 if let Some(parent_id) = parent_id {
1372 self.commands_mut().push(Command::DetachChild {
1373 parent_id,
1374 child_id: root,
1375 });
1376 }
1377 }
1378 let evicted = self.core.shared_state.insert_retained(
1379 slots_host,
1380 RetainKey::for_group(parent_scope, root_key),
1381 subtree,
1382 root_key.is_movable(),
1383 );
1384 for subtree in evicted {
1385 self.dispose_detached_subtree_in_host(slots_host, subtree)?;
1386 }
1387 Ok(())
1388 }
1389
1390 fn evict_retained_subtrees_for_host(
1391 &self,
1392 slots_host: &Rc<SlotsHost>,
1393 ) -> Result<(), NodeError> {
1394 let evicted = self.core.shared_state.advance_retention_pass(slots_host);
1395 for subtree in evicted {
1396 self.dispose_detached_subtree_in_host(slots_host, subtree)?;
1397 }
1398 Ok(())
1399 }
1400
1401 fn dispose_detached_subtree_in_host(
1402 &self,
1403 slots_host: &Rc<SlotsHost>,
1404 subtree: crate::slot::DetachedSubtree,
1405 ) -> Result<(), NodeError> {
1406 let root_nodes = self
1407 .detached_root_parent_commands(&subtree, "disposal")?
1408 .into_iter()
1409 .map(|(root, _)| root);
1410 subtree.scopes().for_each(RecomposeScope::deactivate);
1411 self.dispose_detached_nodes(root_nodes);
1412 slots_host.with_table_and_lifecycle_mut(|table, lifecycle| {
1413 table.invalidate_detached_subtree_anchors(&subtree);
1414 lifecycle.queue_subtree_disposal(subtree);
1415 });
1416 Ok(())
1417 }
1418
1419 fn handle_detached_children_in_host(
1420 &self,
1421 slots_host: &Rc<SlotsHost>,
1422 parent_scope: Option<ScopeId>,
1423 detached: Vec<crate::slot::DetachedSubtree>,
1424 ) -> Result<(), NodeError> {
1425 for mut subtree in detached {
1426 for movable in subtree.split_off_nested_movables() {
1427 self.retain_detached_subtree_in_host(slots_host, None, movable)?;
1428 }
1429 if subtree
1430 .root_key_checked()
1431 .is_some_and(crate::slot::GroupKey::is_movable)
1432 {
1433 self.retain_detached_subtree_in_host(slots_host, None, subtree)?;
1434 continue;
1435 }
1436 let retention_mode = subtree
1437 .root_scope()
1438 .map(RecomposeScope::retention_mode)
1439 .unwrap_or_default();
1440 match retention_mode {
1441 RetentionMode::DisposeWhenInactive => {
1442 self.dispose_detached_subtree_in_host(slots_host, subtree)?;
1443 }
1444 RetentionMode::RetainWhenInactive => {
1445 self.retain_detached_subtree_in_host(slots_host, parent_scope, subtree)?;
1446 }
1447 }
1448 }
1449 Ok(())
1450 }
1451
1452 fn handle_finished_group_result(
1453 &self,
1454 host: &Rc<SlotsHost>,
1455 parent_scope: Option<ScopeId>,
1456 result: FinishGroupResult,
1457 ) {
1458 let FinishGroupResult {
1459 detached_children,
1460 direct_nodes,
1461 root_nodes,
1462 was_skipped,
1463 } = result;
1464 if was_skipped {
1465 self.attach_root_nodes(root_nodes);
1466 }
1467 self.dispose_detached_nodes(direct_nodes);
1468 if detached_children.is_empty() {
1469 return;
1470 }
1471 if let Err(err) =
1472 self.handle_detached_children_in_host(host, parent_scope, detached_children)
1473 {
1474 log::error!("detached subtree handling failed while closing a group: {err}");
1475 }
1476 }
1477
1478 pub(crate) fn close_current_group_body_for_scope(&self, scope: &RecomposeScope) {
1479 self.close_group_body(&self.active_slots_host(), scope);
1480 }
1481
1482 fn close_group_body(&self, host: &Rc<SlotsHost>, scope: &RecomposeScope) {
1483 #[expect(
1484 clippy::redundant_closure_for_method_calls,
1485 reason = "the method path is not general over the session lifetime"
1486 )]
1487 let result = host.with_write_session(|slots| slots.finish_group_body_changes());
1488 self.close_finished_group(host, Some(scope), result);
1489 }
1490
1491 fn close_finished_group(
1494 &self,
1495 host: &Rc<SlotsHost>,
1496 scope: Option<&RecomposeScope>,
1497 result: Option<FinishGroupResult>,
1498 ) {
1499 if let Some(result) = result {
1500 self.handle_finished_group_result(host, scope.map(RecomposeScope::id), result);
1501 }
1502 self.pop_closed_scope();
1503 }
1504
1505 #[track_caller]
1508 pub fn remember<T: 'static>(&self, init: impl FnOnce() -> T) -> Owned<T> {
1509 self.remember_at(crate::caller_location_key(), init)
1510 }
1511
1512 #[doc(hidden)]
1513 pub fn remember_at<T: 'static>(&self, source: Key, init: impl FnOnce() -> T) -> Owned<T> {
1514 self.with_slot_session_mut(|slots| {
1515 slots.remember_with_kind(PayloadKind::Remember, source, init)
1516 })
1517 }
1518
1519 #[track_caller]
1520 pub(crate) fn remember_internal<T: 'static>(
1521 &self,
1522 source_salt: Key,
1523 init: impl FnOnce() -> T,
1524 ) -> Owned<T> {
1525 let source = crate::caller_location_key().scoped(source_salt);
1526 self.with_slot_session_mut(|slots| {
1527 slots.remember_with_kind(PayloadKind::Internal, source, init)
1528 })
1529 }
1530
1531 #[track_caller]
1532 pub(crate) fn remember_effect<T: Default + 'static>(&self, site: Key) -> Owned<T> {
1535 self.with_slot_session_mut(|slots| slots.remember_effect::<T>(site))
1536 }
1537
1538 #[track_caller]
1541 pub fn use_value_slot<T: 'static>(&self, init: impl FnOnce() -> T) -> ValueSlotHandle<'_, T> {
1542 let source = crate::caller_location_key();
1543 let (slot, record) = self.with_slot_session_mut(|slots| {
1544 slots.located_value_slot(PayloadKind::Internal, source, init)
1545 });
1546 ValueSlotHandle::new(slot, record)
1547 }
1548
1549 #[doc(hidden)]
1550 pub fn __use_param_slot<T: 'static>(
1551 &self,
1552 source: Key,
1553 init: impl FnOnce() -> T,
1554 ) -> ValueSlotHandle<'_, T> {
1555 let (slot, record) = self.with_slot_session_mut(|slots| {
1556 slots.located_value_slot(PayloadKind::Param, source, init)
1557 });
1558 ValueSlotHandle::new(slot, record)
1559 }
1560
1561 #[doc(hidden)]
1564 pub fn __update_param_slot<T: 'static, R>(
1565 &self,
1566 source: Key,
1567 init: impl FnOnce() -> T,
1568 update: impl FnOnce(&mut T) -> R,
1569 ) -> (ValueSlotHandle<'_, T>, R) {
1570 self.update_value_slot(PayloadKind::Param, source, init, update)
1571 }
1572
1573 #[doc(hidden)]
1576 pub fn __update_return_slot<T: 'static, R>(
1577 &self,
1578 source: Key,
1579 init: impl FnOnce() -> T,
1580 read: impl FnOnce(&mut T) -> R,
1581 ) -> (ValueSlotHandle<'_, T>, R) {
1582 self.update_value_slot(PayloadKind::Return, source, init, read)
1583 }
1584
1585 fn update_value_slot<T: 'static, R>(
1586 &self,
1587 kind: PayloadKind,
1588 source: Key,
1589 init: impl FnOnce() -> T,
1590 update: impl FnOnce(&mut T) -> R,
1591 ) -> (ValueSlotHandle<'_, T>, R) {
1592 self.with_slot_session_mut(|slots| {
1593 let (slot, record, value) = slots.value_slot_and_value(kind, source, init);
1594 (ValueSlotHandle::new(slot, record), update(value))
1595 })
1596 }
1597
1598 #[doc(hidden)]
1599 #[track_caller]
1600 pub fn __use_return_slot<T: 'static>(
1601 &self,
1602 init: impl FnOnce() -> T,
1603 ) -> ValueSlotHandle<'_, T> {
1604 let source = crate::caller_location_key();
1605 let (slot, record) = self.with_slot_session_mut(|slots| {
1606 slots.located_value_slot(PayloadKind::Return, source, init)
1607 });
1608 ValueSlotHandle::new(slot, record)
1609 }
1610
1611 #[doc(hidden)]
1612 pub fn __invalidate_return_consumer_scope(&self) {
1613 let Some(scope) = self.current_recompose_scope() else {
1614 self.request_root_render();
1615 return;
1616 };
1617
1618 if let Some(target) = scope.callback_promotion_target() {
1619 target.invalidate();
1620 } else {
1621 self.request_root_render();
1622 }
1623 }
1624
1625 pub fn with_slot_value<'pass, T: 'static, R>(
1627 &'pass self,
1628 handle: ValueSlotHandle<'pass, T>,
1629 f: impl FnOnce(&T) -> R,
1630 ) -> R {
1631 self.with_slots(|slots| f(slots.value_at(handle.slot, handle.record)))
1632 }
1633
1634 pub fn with_slot_value_mut<'pass, T: 'static, R>(
1636 &'pass self,
1637 handle: ValueSlotHandle<'pass, T>,
1638 f: impl FnOnce(&mut T) -> R,
1639 ) -> R {
1640 self.with_slots_mut(|slots| f(slots.value_at_mut(handle.slot, handle.record)))
1641 }
1642
1643 pub fn mutable_state_of<T: Clone + 'static>(&self, initial: T) -> MutableState<T> {
1646 MutableState::with_runtime(initial, self.runtime_handle())
1647 }
1648
1649 pub fn mutable_state_list_of<T, I>(&self, values: I) -> SnapshotStateList<T>
1652 where
1653 T: Clone + 'static,
1654 I: IntoIterator<Item = T>,
1655 {
1656 SnapshotStateList::with_runtime(values, self.runtime_handle())
1657 }
1658
1659 pub fn mutable_state_map_of<K, V, I>(&self, pairs: I) -> SnapshotStateMap<K, V>
1662 where
1663 K: Clone + Eq + Hash + 'static,
1664 V: Clone + 'static,
1665 I: IntoIterator<Item = (K, V)>,
1666 {
1667 SnapshotStateMap::with_runtime(pairs, self.runtime_handle())
1668 }
1669
1670 pub fn read_composition_local<T: Clone + 'static>(&self, local: &CompositionLocal<T>) -> T {
1673 self.read_provided(
1674 &local.key,
1675 |entry: &LocalStateEntry<T>| entry.value(),
1676 |entry: &ComputedLocalEntry<T>| entry.value(),
1677 )
1678 .unwrap_or_else(|| local.default_value())
1679 }
1680
1681 pub fn read_static_composition_local<T: Clone + 'static>(
1684 &self,
1685 local: &StaticCompositionLocal<T>,
1686 ) -> T {
1687 let provided = local.provided_under(&self.core.local_stack.borrow());
1688 provided.unwrap_or_else(|deferred| deferred.value(local))
1689 }
1690
1691 fn read_provided<V: 'static, C: 'static, T>(
1695 &self,
1696 key: &LocalKey,
1697 value: impl FnOnce(&V) -> T,
1698 computed: impl FnOnce(&C) -> T,
1699 ) -> Option<T> {
1700 let entry = provided_entry(&self.core.local_stack.borrow(), key)?;
1701 match entry.downcast::<V>() {
1702 Ok(entry) => Some(value(&entry)),
1703 Err(entry) => entry
1704 .downcast::<C>()
1705 .inspect_err(|_| key.report_type_mismatch())
1706 .ok()
1707 .map(|entry| computed(&entry)),
1708 }
1709 }
1710
1711 pub(crate) fn restarted_scope(&self) -> Option<RecomposeScope> {
1714 self.core.restarted_scope.borrow().clone()
1715 }
1716
1717 pub fn phase(&self) -> crate::Phase {
1719 self.core.phase.get()
1720 }
1721
1722 pub(crate) fn set_phase(&self, phase: crate::Phase) {
1723 self.core.phase.set(phase);
1724 }
1725
1726 pub fn enter_phase(&self, phase: crate::Phase) {
1728 self.set_phase(phase);
1729 }
1730
1731 pub(crate) fn subcompose<R>(
1732 &self,
1733 state: &mut SubcomposeState,
1734 slot_id: SlotId,
1735 content: impl FnOnce(&Self) -> R,
1736 ) -> (R, Vec<NodeId>) {
1737 match self.phase() {
1738 crate::Phase::Measure | crate::Phase::Layout => {}
1739 current => panic!(
1740 "subcompose() may only be called during measure or layout; current phase: {current:?}"
1741 ),
1742 }
1743
1744 self.subcompose_stack().push(SubcomposeFrame::default());
1745 let mut guard = SubcomposeStackGuard {
1746 core: self.clone_core(),
1747 leaked: false,
1748 };
1749
1750 let slot_host = state.get_or_create_slots(slot_id);
1751 let (result, _) = self.with_slot_override(slot_host, |composer| {
1752 composer.with_group(Key(slot_id.raw()), |composer| content(composer))
1753 });
1754
1755 let frame = {
1756 let frame = take_subcompose_frame(&guard.core, "subcompose");
1757 guard.leaked = true;
1758 frame
1759 };
1760 let nodes = frame.nodes;
1761 let scopes = frame.scopes;
1762 state.register_active(slot_id, &nodes, &scopes);
1763 (result, nodes)
1764 }
1765
1766 pub fn subcompose_measurement<R>(
1769 &self,
1770 state: &mut SubcomposeState,
1771 slot_id: SlotId,
1772 content: impl FnOnce(&Self) -> R,
1773 ) -> (R, Vec<NodeId>) {
1774 let (result, nodes) = self.subcompose(state, slot_id, content);
1775 let roots = nodes
1776 .into_iter()
1777 .filter(|&id| self.node_has_no_parent(id))
1778 .collect();
1779
1780 (result, roots)
1781 }
1782
1783 fn subcompose_site(&self) -> SubcomposeSite<'_> {
1785 SubcomposeSite {
1786 applier: &self.core.applier,
1787 runtime: &self.core.runtime,
1788 phase: self.phase(),
1789 locals_changed: self.core.locals_changed.get(),
1790 }
1791 }
1792
1793 pub fn subcompose_in<R>(
1797 &self,
1798 slots: &Rc<SlotsHost>,
1799 root: Option<NodeId>,
1800 f: impl FnOnce(&Self) -> R,
1801 ) -> Result<R, NodeError> {
1802 let _teardown = runtime::enter_state_teardown_scope();
1803 let site = self.subcompose_site();
1804 let shared_state = slots
1805 .runtime_state()
1806 .unwrap_or_else(|| Rc::clone(&self.core.shared_state));
1807 let core = site.spin_up_core(shared_state, slots, root, self.current_local_stack());
1808 let composer = Self::from_core(core);
1809 let (result, commands, side_effects, compact_applier) = composer.install(|composer| {
1810 let (output, outcome) = composer.try_with_slot_host_pass(
1811 Rc::clone(slots),
1812 crate::slot::SlotPassMode::Compose,
1813 |composer| f(composer),
1814 )?;
1815 let commands = composer.take_commands();
1816 let side_effects = composer.take_side_effects();
1817 Ok((output, commands, side_effects, outcome.compacted))
1818 })?;
1819 site.flush(commands, compact_applier, side_effects)?;
1820 Ok(result)
1821 }
1822
1823 pub fn capture_composition_context(&self) -> CapturedCompositionContext {
1834 CapturedCompositionContext {
1835 locals: self.current_local_stack(),
1836 owner_scope: self
1837 .current_recompose_scope()
1838 .map(|scope| scope.downgrade()),
1839 locals_changed: self.core.locals_changed.get(),
1840 }
1841 }
1842
1843 pub fn with_captured_locals<R>(
1848 &self,
1849 context: &CapturedCompositionContext,
1850 f: impl FnOnce(&Self) -> R,
1851 ) -> R {
1852 let parent = self.current_local_stack();
1853 self.local_stack().clone_from(&context.locals);
1854 let result = self.with_locals_changed(context.locals_changed, f);
1855 *self.local_stack() = parent;
1856 result
1857 }
1858
1859 pub fn with_locals_changed<R>(&self, changed: bool, f: impl FnOnce(&Self) -> R) -> R {
1863 let outer = self.core.locals_changed.get();
1864 self.core.locals_changed.set(outer || changed);
1865 let result = f(self);
1866 self.core.locals_changed.set(outer);
1867 result
1868 }
1869
1870 pub fn subcompose_slot<R>(
1875 &self,
1876 slots: &Rc<SlotsHost>,
1877 root: Option<NodeId>,
1878 f: impl FnOnce(&Self) -> R,
1879 ) -> Result<(R, Vec<RecomposeScope>), NodeError> {
1880 let context = self.capture_composition_context();
1881 self.subcompose_slot_with_context(slots, root, &context, f)
1882 }
1883
1884 pub fn subcompose_slot_with_context<R>(
1888 &self,
1889 slots: &Rc<SlotsHost>,
1890 root: Option<NodeId>,
1891 context: &CapturedCompositionContext,
1892 f: impl FnOnce(&Self) -> R,
1893 ) -> Result<(R, Vec<RecomposeScope>), NodeError> {
1894 subcompose_slot_at(
1895 self.subcompose_site(),
1896 || Rc::clone(&self.core.shared_state),
1897 slots,
1898 root,
1899 context,
1900 f,
1901 )
1902 }
1903
1904 pub fn subcompose_measure_slot<R>(
1909 applier: &Rc<dyn ApplierHost>,
1910 runtime: &RuntimeHandle,
1911 slots: &Rc<SlotsHost>,
1912 root: NodeId,
1913 context: &CapturedCompositionContext,
1914 f: impl FnOnce(&Self) -> R,
1915 ) -> Result<(R, Vec<RecomposeScope>), NodeError> {
1916 let site = SubcomposeSite {
1917 applier,
1918 runtime,
1919 phase: crate::Phase::Measure,
1920 locals_changed: false,
1921 };
1922 let new_state = || measure_slot_state(applier, context);
1923 subcompose_slot_at(site, new_state, slots, Some(root), context, f)
1924 }
1925
1926 fn attach_root_nodes(&self, root_nodes: RootNodeIds) {
1927 for id in root_nodes {
1928 self.attach_to_parent(id);
1929 }
1930 }
1931
1932 pub fn skip_current_group(&self) {
1935 #[expect(
1936 clippy::redundant_closure_for_method_calls,
1937 reason = "the method path is not general over the session lifetime"
1938 )]
1939 self.with_slot_session_mut(|slots| slots.skip_group());
1940 }
1941
1942 pub fn runtime_handle(&self) -> RuntimeHandle {
1944 self.core.runtime.clone()
1945 }
1946
1947 pub fn set_recompose_callback<F>(&self, callback: F)
1950 where
1951 F: FnMut(&Self) + 'static,
1952 {
1953 if let Some(scope) = self.current_recompose_scope() {
1954 scope.set_recompose_callback(callback);
1955 }
1956 }
1957
1958 pub fn set_recompose_fn(&self, callback: fn(&Self)) {
1960 if let Some(scope) = self.current_recompose_scope() {
1961 scope.set_recompose_fn(callback);
1962 }
1963 }
1964
1965 pub fn with_composition_locals<R>(
1968 &self,
1969 provided: impl IntoIterator<Item = ProvidedValue>,
1970 site: Key,
1971 f: impl FnOnce(&Self) -> R,
1972 ) -> R {
1973 let provided: SmallVec<[ProvidedValue; 2]> = provided.into_iter().collect();
1974 if provided.is_empty() {
1975 return f(self);
1976 }
1977 let mut values = SmallVec::<[(LocalKey, Rc<dyn Any>); 2]>::new();
1978 let mut static_changed = false;
1979 for value in provided.into_iter().rev() {
1980 if values.iter().any(|(key, _)| key == value.key()) {
1981 continue;
1982 }
1983 let (key, entry, changed) = value.into_entry(self, site);
1984 static_changed |= changed;
1985 values.push((key, entry));
1986 }
1987 let parent = self.current_local_stack();
1988 *self.local_stack() = Some(Rc::new(LocalFrame {
1989 values,
1990 parent: parent.clone(),
1991 }));
1992 let result = self.with_locals_changed(static_changed, f);
1993 *self.local_stack() = parent;
1994 result
1995 }
1996}