use std::{
any::Any,
cell::{Cell, RefCell, RefMut},
hash::Hash,
marker::PhantomData,
rc::{Rc, Weak},
};
use smallvec::SmallVec;
use crate::{
Applier, ApplierGuard, ApplierHost, COMMAND_FLUSH_THRESHOLD, Command, CommandQueue,
CompositionLocal, ComputedLocalEntry, DirtyBubble, Key, LocalKey, LocalStackSnapshot,
LocalStateEntry, MutableState, Node, NodeError, NodeId, Owned, ProvidedValue, RecomposeOptions,
RecomposeScope, RecomposeScopeInner, RecycledNode, RuntimeHandle, ScopeId, SlotId,
SlotPassOutcome, SlotTable, SlotsHost, SnapshotStateList, SnapshotStateMap,
StaticCompositionLocal, SubcomposeState, composer_context, runtime,
slot::{FinishGroupResult, GroupStartKind, PayloadKind, RootNodeIds, ValueSlotId},
};
mod composable_group;
mod detach;
mod movable;
mod movable_owners;
mod parent_frame;
mod runtime_state;
mod scope_frame;
mod subcompose_slot;
mod subcompose_stack;
pub use composable_group::{ComposableGroup, ParameterChange};
use movable::{GroupEntry, movable_retain_key};
pub(crate) use movable::{MovableLookup, PendingMovable, enable_movable_hooks};
use movable_owners::{DroppedMovable, MovableOwners};
use parent_frame::{InitialParentFrame, push_root_frame};
pub(crate) use parent_frame::{ParentAttachMode, ParentFrame};
pub(crate) use runtime_state::{ComposerRuntimeState, HostTableDisposal};
pub(crate) use scope_frame::ScopeFrame;
use subcompose_slot::{measure_slot_state, subcompose_slot_at};
use subcompose_stack::{SubcomposeFrame, SubcomposeStack};
pub struct ValueSlotHandle<'pass, T: 'static> {
slot: ValueSlotId,
record: Option<usize>,
_pass: PhantomData<&'pass Composer>,
_value: PhantomData<fn() -> T>,
}
impl<T: 'static> Copy for ValueSlotHandle<'_, T> {}
impl<T: 'static> Clone for ValueSlotHandle<'_, T> {
fn clone(&self) -> Self {
*self
}
}
impl<T: 'static> ValueSlotHandle<'_, T> {
pub(crate) fn new(slot: ValueSlotId, record: Option<usize>) -> Self {
Self {
slot,
record,
_pass: PhantomData,
_value: PhantomData,
}
}
}
fn slots_storage_key(host: &SlotsHost) -> usize {
host.storage_key()
}
fn bind_slots_host_to_runtime_state(
state: &Rc<ComposerRuntimeState>,
host: &Rc<SlotsHost>,
) -> Rc<SlotsHost> {
if host.runtime_state_ptr() == Some(Rc::as_ptr(state)) {
debug_assert!(
state
.host_for_storage_key(host.storage_key())
.is_some_and(|registered| Rc::ptr_eq(®istered, host)),
"a slot host bound to a runtime state must be in its registry"
);
return Rc::clone(host);
}
if host.runtime_state().is_some() {
if host.rebind_orphaned_runtime_state(state) {
state.bind_slots_host(host);
return Rc::clone(host);
}
log::error!(
"slot host already belongs to a different composer runtime state; using a fresh slot host"
);
let replacement = Rc::new(SlotsHost::new(SlotTable::new()));
state.bind_slots_host(&replacement);
return replacement;
}
state.bind_slots_host(host);
Rc::clone(host)
}
struct GroupScopeEntry<'a> {
options: RecomposeOptions,
start_kind: GroupStartKind,
host: &'a SlotsHost,
group: crate::slot::ActiveGroupId,
parent_hint: Option<NodeId>,
}
struct SlotHostPassGuard {
core: Rc<ComposerCore>,
host: Rc<SlotsHost>,
fold_base: usize,
}
impl SlotHostPassGuard {
#[inline(never)]
fn close(&mut self) {
if self.host.has_active_pass() {
self.host.abandon_active_pass();
}
match self.core.slot_hosts.borrow_mut().pop() {
Some(host) if Rc::ptr_eq(&host, &self.host) => {}
Some(_) => {
log::error!("slot host stack mismatch while closing slot host pass");
}
None => {
log::error!("slot host stack underflow while closing slot host pass");
}
}
self.core.branch_folds.end_pass(self.fold_base);
self.core.shared_state.movable_owners.leave_pass_depth();
}
}
impl Drop for SlotHostPassGuard {
fn drop(&mut self) {
self.close();
}
}
fn reparent_restored_scopes(
host: &SlotsHost,
group: crate::slot::ActiveGroupId,
old_hint: Option<NodeId>,
parent_hint: Option<NodeId>,
) {
host.with_write_session(|slots| {
slots.for_each_subtree_scope(group, |scope| {
if scope.parent_hint() == old_hint {
scope.set_parent_hint(parent_hint);
}
scope.reactivate();
});
});
}
const SPARE_COMMAND_QUEUES: usize = 8;
const SPARE_COMMAND_CAPACITY: usize = 1024;
fn spare_commands() -> CommandQueue {
crate::thread_state::try_runtimes(|state| state.spare_commands.borrow_mut().pop())
.flatten()
.unwrap_or_default()
}
#[derive(Default)]
pub(crate) struct ComposerStacks {
slot_hosts: Vec<Rc<SlotsHost>>,
parent_stack: Vec<ParentFrame>,
scope_stack: Vec<ScopeFrame>,
}
const SPARE_STACK_CAPACITY: usize = 256;
fn spare_composer_stacks() -> ComposerStacks {
crate::thread_state::try_runtimes(|state| state.spare_composer_stacks.take())
.flatten()
.unwrap_or_default()
}
impl ComposerStacks {
fn holds_storage(&self) -> bool {
self.slot_hosts.capacity() > 0
|| self.parent_stack.capacity() > 0
|| self.scope_stack.capacity() > 0
}
}
fn recycle_composer_stacks(mut stacks: ComposerStacks) {
let ComposerStacks {
slot_hosts,
parent_stack,
scope_stack,
} = &mut stacks;
if slot_hosts.capacity() > SPARE_STACK_CAPACITY
|| parent_stack.capacity() > SPARE_STACK_CAPACITY
|| scope_stack.capacity() > SPARE_STACK_CAPACITY
{
return;
}
slot_hosts.clear();
parent_stack.clear();
scope_stack.clear();
crate::thread_state::try_runtimes(|state| state.spare_composer_stacks.set(Some(stacks)));
}
pub(crate) fn recycle_commands(commands: CommandQueue) {
if commands.capacity() > SPARE_COMMAND_CAPACITY {
return;
}
crate::thread_state::try_runtimes(|state| {
let mut spare = state.spare_commands.borrow_mut();
if spare.len() < SPARE_COMMAND_QUEUES {
spare.push(commands);
}
});
}
pub(crate) struct LocalFrame {
values: SmallVec<[(LocalKey, Rc<dyn Any>); 2]>,
parent: LocalStackSnapshot,
}
pub(crate) fn provided_entry(stack: &LocalStackSnapshot, key: &LocalKey) -> Option<Rc<dyn Any>> {
let mut frame = stack.as_deref();
while let Some(current) = frame {
if let Some((_, entry)) = current.values.iter().find(|(provided, _)| provided == key) {
return Some(Rc::clone(entry));
}
frame = current.parent.as_deref();
}
None
}
pub(crate) struct ComposerCore {
pub(crate) shared_state: Rc<ComposerRuntimeState>,
pub(crate) branch_folds: Rc<crate::slot::BranchFolds>,
pub(crate) slots: Rc<SlotsHost>,
slot_hosts: RefCell<Vec<Rc<SlotsHost>>>,
pub(crate) applier: Rc<dyn ApplierHost>,
pub(crate) runtime: RuntimeHandle,
pub(crate) parent_stack: RefCell<Vec<ParentFrame>>,
pub(crate) subcompose_stack: RefCell<SubcomposeStack>,
pub(crate) root: Cell<Option<NodeId>>,
pub(crate) commands: RefCell<CommandQueue>,
pub(crate) scope_stack: RefCell<Vec<ScopeFrame>>,
subcomposition_owner_scope: RefCell<Option<RecomposeScope>>,
pub(crate) local_stack: RefCell<LocalStackSnapshot>,
pub(crate) side_effects: RefCell<Vec<Box<dyn FnOnce()>>>,
pub(crate) pending_scope_options: Cell<Option<RecomposeOptions>>,
pub(crate) phase: Cell<crate::Phase>,
pub(crate) recompose_parent_hint: Cell<Option<NodeId>>,
pub(crate) recompose_child_cursor: Cell<crate::recompose::RecomposeChildCursor>,
pub(crate) restarted_scope: RefCell<Option<RecomposeScope>>,
pub(crate) root_render_requested: Cell<bool>,
locals_changed: Cell<bool>,
reused_depth: Cell<u32>,
pub(crate) _not_send: PhantomData<*const ()>,
}
#[derive(Clone, Default)]
pub struct CapturedCompositionContext {
locals: LocalStackSnapshot,
owner_scope: Option<Weak<RecomposeScopeInner>>,
locals_changed: bool,
}
impl CapturedCompositionContext {
pub fn locals_changed(&self) -> bool {
self.locals_changed
}
pub fn owner_chain_deactivation_epoch(&self) -> u64 {
self.owner_scope
.as_ref()
.and_then(Weak::upgrade)
.map_or(0, |inner| {
RecomposeScope { inner }.owner_chain_deactivation_epoch()
})
}
}
fn take_subcompose_frame(core: &ComposerCore, operation: &str) -> SubcomposeFrame {
match core.subcompose_stack.borrow_mut().pop() {
Some(frame) => frame,
None => {
log::error!("subcompose stack underflow while finishing {operation}");
SubcomposeFrame::default()
}
}
}
struct SubcomposeStackGuard {
core: Rc<ComposerCore>,
leaked: bool,
}
impl Drop for SubcomposeStackGuard {
fn drop(&mut self) {
if !self.leaked {
self.core.subcompose_stack.borrow_mut().pop();
}
}
}
impl Drop for ComposerCore {
fn drop(&mut self) {
let commands = std::mem::take(self.commands.get_mut());
if commands.len() == 0 && commands.capacity() > 0 {
recycle_commands(commands);
}
let stacks = self.take_stacks();
if stacks.holds_storage() {
recycle_composer_stacks(stacks);
}
}
}
impl ComposerCore {
fn new(parts: ComposerParts) -> Self {
let ComposerParts {
shared_state,
slots,
applier,
runtime,
root,
initial_parent_frame,
} = parts;
let ComposerStacks {
slot_hosts,
mut parent_stack,
scope_stack,
} = spare_composer_stacks();
push_root_frame(&mut parent_stack, root, initial_parent_frame);
Self {
branch_folds: Rc::clone(&shared_state.branch_folds),
shared_state,
slots,
slot_hosts: RefCell::new(slot_hosts),
applier,
runtime,
parent_stack: RefCell::new(parent_stack),
subcompose_stack: RefCell::default(),
root: Cell::new(root),
commands: RefCell::new(spare_commands()),
scope_stack: RefCell::new(scope_stack),
subcomposition_owner_scope: RefCell::new(None),
local_stack: RefCell::new(None),
side_effects: RefCell::new(Vec::new()),
pending_scope_options: Cell::new(None),
phase: Cell::new(crate::Phase::Compose),
recompose_parent_hint: Cell::new(None),
recompose_child_cursor: Cell::new(crate::recompose::RecomposeChildCursor::Unknown),
restarted_scope: RefCell::new(None),
root_render_requested: Cell::new(false),
locals_changed: Cell::new(false),
reused_depth: Cell::new(0),
_not_send: PhantomData,
}
}
fn take_stacks(&mut self) -> ComposerStacks {
let mut stacks = ComposerStacks {
slot_hosts: std::mem::take(self.slot_hosts.get_mut()),
parent_stack: std::mem::take(self.parent_stack.get_mut()),
scope_stack: std::mem::take(self.scope_stack.get_mut()),
};
stacks.slot_hosts.clear();
stacks.parent_stack.clear();
stacks.scope_stack.clear();
stacks
}
fn restart(&mut self, parts: ComposerParts) {
let Self {
shared_state,
branch_folds,
slots,
slot_hosts,
applier,
runtime,
parent_stack,
subcompose_stack,
root,
commands,
scope_stack,
subcomposition_owner_scope,
local_stack,
side_effects,
pending_scope_options,
phase,
recompose_parent_hint,
recompose_child_cursor,
restarted_scope,
root_render_requested,
locals_changed,
reused_depth,
_not_send: _,
} = self;
if !Rc::ptr_eq(shared_state, &parts.shared_state) {
*branch_folds = Rc::clone(&parts.shared_state.branch_folds);
*shared_state = parts.shared_state;
}
*slots = parts.slots;
*applier = parts.applier;
*runtime = parts.runtime;
slot_hosts.get_mut().clear();
let parent_stack = parent_stack.get_mut();
parent_stack.clear();
push_root_frame(parent_stack, parts.root, parts.initial_parent_frame);
subcompose_stack.get_mut().clear();
root.set(parts.root);
let commands = commands.get_mut();
if commands.len() > 0 || commands.capacity() == 0 {
*commands = spare_commands();
}
scope_stack.get_mut().clear();
*subcomposition_owner_scope.get_mut() = None;
*local_stack.get_mut() = None;
side_effects.get_mut().clear();
pending_scope_options.set(None);
phase.set(crate::Phase::Compose);
recompose_parent_hint.set(None);
recompose_child_cursor.set(crate::recompose::RecomposeChildCursor::Unknown);
*restarted_scope.get_mut() = None;
root_render_requested.set(false);
locals_changed.set(false);
reused_depth.set(0);
}
fn park(&mut self) {
self.slot_hosts.get_mut().clear();
self.parent_stack.get_mut().clear();
self.scope_stack.get_mut().clear();
self.subcompose_stack.get_mut().clear();
*self.subcomposition_owner_scope.get_mut() = None;
*self.local_stack.get_mut() = None;
self.side_effects.get_mut().clear();
}
}
#[derive(Clone, Copy)]
struct SubcomposeSite<'a> {
applier: &'a Rc<dyn ApplierHost>,
runtime: &'a RuntimeHandle,
phase: crate::Phase,
locals_changed: bool,
}
impl SubcomposeSite<'_> {
fn spin_up_core(
self,
shared_state: Rc<ComposerRuntimeState>,
slots: &Rc<SlotsHost>,
root: Option<NodeId>,
locals: LocalStackSnapshot,
) -> Rc<ComposerCore> {
let core = Rc::new(ComposerCore::new(ComposerParts {
shared_state,
slots: Rc::clone(slots),
applier: Rc::clone(self.applier),
runtime: self.runtime.clone(),
root,
initial_parent_frame: InitialParentFrame::RealParent,
}));
core.phase.set(self.phase);
core.locals_changed.set(self.locals_changed);
*core.local_stack.borrow_mut() = locals;
core
}
fn flush(
self,
mut commands: CommandQueue,
compact_applier: bool,
side_effects: Vec<Box<dyn FnOnce()>>,
) -> Result<(), NodeError> {
{
let mut applier = self.applier.borrow_dyn();
commands.apply(&mut *applier)?;
for update in self.runtime.take_updates() {
update.apply(&mut *applier)?;
}
}
recycle_commands(commands);
if compact_applier {
self.applier.compact();
self.applier.borrow_dyn().clear_recycled_nodes();
}
composer_context::without_composer(|| {
for effect in side_effects {
effect();
}
});
Ok(())
}
}
struct ComposerParts {
shared_state: Rc<ComposerRuntimeState>,
slots: Rc<SlotsHost>,
applier: Rc<dyn ApplierHost>,
runtime: RuntimeHandle,
root: Option<NodeId>,
initial_parent_frame: InitialParentFrame,
}
#[derive(Clone)]
pub struct Composer {
pub(crate) core: Rc<ComposerCore>,
}
#[doc(hidden)]
pub struct BranchGroupGuard<'a> {
folds: &'a crate::slot::BranchFolds,
token: crate::slot::FoldToken,
}
impl BranchGroupGuard<'_> {
#[doc(hidden)]
#[inline]
pub fn advance(&mut self, key: Key) {
self.folds.advance(&mut self.token, key);
}
}
impl Drop for BranchGroupGuard<'_> {
#[inline]
fn drop(&mut self) {
self.folds.close(self.token);
}
}
#[doc(hidden)]
pub struct ScopedBranchGroupGuard {
open: std::mem::ManuallyDrop<Option<ScopedBranchGroup>>,
}
struct ScopedBranchGroup {
folds: Rc<crate::slot::BranchFolds>,
token: crate::slot::FoldToken,
}
#[doc(hidden)]
#[inline]
pub fn __branch_group_scope_deferred(key: Key) -> ScopedBranchGroupGuard {
let open = composer_context::with_current_core(|core| ScopedBranchGroup {
token: core.branch_folds.push(key),
folds: Rc::clone(&core.branch_folds),
});
ScopedBranchGroupGuard {
open: std::mem::ManuallyDrop::new(open),
}
}
#[doc(hidden)]
#[inline]
pub fn __branch_group_scope_advance(guard: &mut ScopedBranchGroupGuard, key: Key) {
if let Some(group) = guard.open.as_mut() {
group.folds.advance(&mut group.token, key);
}
}
impl Drop for ScopedBranchGroupGuard {
#[inline(always)]
fn drop(&mut self) {
if let Some(group) = self.open.take() {
close_scoped_branch_group(group);
}
}
}
#[inline(never)]
fn close_scoped_branch_group(group: ScopedBranchGroup) {
group.folds.close(group.token);
}
pub(crate) enum EmittedNode {
Fresh(Box<dyn Node>),
Recycled(RecycledNode),
}
impl Composer {
pub(crate) fn new_with_shared_state(
shared_state: Rc<ComposerRuntimeState>,
slots: Rc<SlotsHost>,
applier: Rc<dyn ApplierHost>,
runtime: RuntimeHandle,
root: Option<NodeId>,
) -> Self {
Self::new_with_shared_state_with_parent_frame(
shared_state,
slots,
applier,
runtime,
root,
InitialParentFrame::SyntheticRoot,
)
}
fn new_with_shared_state_with_parent_frame(
shared_state: Rc<ComposerRuntimeState>,
slots: Rc<SlotsHost>,
applier: Rc<dyn ApplierHost>,
runtime: RuntimeHandle,
root: Option<NodeId>,
initial_parent_frame: InitialParentFrame,
) -> Self {
shared_state.bind_applier_host(&applier);
let slots = bind_slots_host_to_runtime_state(&shared_state, &slots);
let core = Rc::new(ComposerCore::new(ComposerParts {
shared_state,
slots,
applier,
runtime,
root,
initial_parent_frame,
}));
Self { core }
}
pub(crate) fn for_pass(
parked: Option<Self>,
shared_state: Rc<ComposerRuntimeState>,
slots: Rc<SlotsHost>,
applier: Rc<dyn ApplierHost>,
runtime: RuntimeHandle,
root: Option<NodeId>,
) -> Self {
let Some(mut composer) = parked.filter(|parked| Rc::strong_count(&parked.core) == 1) else {
return Self::new_with_shared_state(shared_state, slots, applier, runtime, root);
};
let Some(core) = Rc::get_mut(&mut composer.core) else {
return Self::new_with_shared_state(shared_state, slots, applier, runtime, root);
};
shared_state.bind_applier_host(&applier);
let slots = bind_slots_host_to_runtime_state(&shared_state, &slots);
core.restart(ComposerParts {
shared_state,
slots,
applier,
runtime,
root,
initial_parent_frame: InitialParentFrame::SyntheticRoot,
});
composer
}
pub(crate) fn park(mut self) -> Option<Self> {
Rc::get_mut(&mut self.core)?.park();
Some(self)
}
pub fn new(
slots: Rc<SlotsHost>,
applier: Rc<dyn ApplierHost>,
runtime: RuntimeHandle,
root: Option<NodeId>,
) -> Self {
Self::new_with_shared_state_with_parent_frame(
slots
.runtime_state()
.unwrap_or_else(|| Rc::new(ComposerRuntimeState::default())),
slots,
applier,
runtime,
root,
InitialParentFrame::RealParent,
)
}
pub(crate) fn from_core(core: Rc<ComposerCore>) -> Self {
Self { core }
}
pub(crate) fn clone_core(&self) -> Rc<ComposerCore> {
Rc::clone(&self.core)
}
pub(crate) fn request_root_render(&self) {
self.core.root_render_requested.set(true);
}
pub(crate) fn take_root_render_request(&self) -> bool {
self.core.root_render_requested.replace(false)
}
pub fn active_slots_host(&self) -> Rc<SlotsHost> {
self.core
.slot_hosts
.borrow()
.last()
.cloned()
.unwrap_or_else(|| Rc::clone(&self.core.slots))
}
fn with_active_slots_host<R>(&self, f: impl FnOnce(&SlotsHost) -> R) -> R {
let hosts = self.core.slot_hosts.borrow();
f(hosts.last().unwrap_or(&self.core.slots))
}
pub(crate) fn with_slots<R>(&self, f: impl FnOnce(&SlotTable) -> R) -> R {
self.with_active_slots_host(|host| f(&host.borrow()))
}
pub(crate) fn with_slots_mut<R>(&self, f: impl FnOnce(&mut SlotTable) -> R) -> R {
self.with_active_slots_host(|host| f(&mut host.borrow_mut()))
}
pub(crate) fn with_slot_session_mut<R>(
&self,
f: impl FnOnce(&mut crate::slot::SlotWriteSession<'_>) -> R,
) -> R {
self.with_active_slots_host(|host| host.with_write_session(f))
}
pub(crate) fn try_with_slot_host_pass<R>(
&self,
slots: &Rc<SlotsHost>,
mode: crate::slot::SlotPassMode,
f: impl FnOnce(&Self) -> R,
) -> Result<(R, SlotPassOutcome), NodeError> {
let guard = self.begin_slot_host_pass(slots, mode);
let result = f(self);
let outcome = self.finish_slot_host_pass(&guard.host)?;
drop(guard);
Ok((result, outcome))
}
pub(crate) fn with_slot_host_pass<R>(
&self,
slots: Rc<SlotsHost>,
mode: crate::slot::SlotPassMode,
f: impl FnOnce(&Self) -> R,
) -> (R, SlotPassOutcome) {
let guard = self.begin_slot_host_pass(&slots, mode);
let result = f(self);
let outcome = self
.finish_slot_host_pass(&guard.host)
.unwrap_or_else(|err| {
log::error!("slot host pass finalization failed: {err}");
SlotPassOutcome::default()
});
drop(guard);
(result, outcome)
}
pub(crate) fn with_slot_override<R>(
&self,
slots: Rc<SlotsHost>,
f: impl FnOnce(&Self) -> R,
) -> (R, SlotPassOutcome) {
self.with_slot_host_pass(slots, crate::slot::SlotPassMode::Compose, f)
}
#[inline(never)]
fn begin_slot_host_pass(
&self,
slots: &Rc<SlotsHost>,
mode: crate::slot::SlotPassMode,
) -> SlotHostPassGuard {
let slots = bind_slots_host_to_runtime_state(&self.core.shared_state, slots);
self.core.shared_state.movable_owners.enter_pass_depth();
let fold_base = self.core.branch_folds.len();
slots.begin_pass(mode, &self.core.branch_folds);
{
let mut stack = self.core.slot_hosts.borrow_mut();
if let Some(parent) = stack.last()
&& !Rc::ptr_eq(parent, &slots)
{
parent.note_nested_host(&slots);
}
stack.push(Rc::clone(&slots));
}
SlotHostPassGuard {
core: self.clone_core(),
host: slots,
fold_base,
}
}
fn finish_slot_host_pass(&self, slots: &SlotsHost) -> Result<SlotPassOutcome, NodeError> {
let finished = {
let mut applier = self.core.applier.borrow_dyn();
slots.finish_pass(&mut *applier)
}?;
if !finished.detached_root_children.is_empty() {
self.core.handle_detached_children_in_host(
slots,
None,
finished.detached_root_children,
)?;
}
self.core.evict_retained_subtrees_for_host(slots)?;
self.settle_pass_movables(slots)?;
slots.complete_pass_cleanup(&finished.outcome);
Ok(finished.outcome)
}
pub(crate) fn parent_stack(&self) -> RefMut<'_, Vec<ParentFrame>> {
self.core.parent_stack.borrow_mut()
}
pub(crate) fn current_parent_hint(&self) -> Option<NodeId> {
let stack = self.core.parent_stack.borrow();
let stack_hint = stack
.last()
.and_then(|frame| (!frame.synthetic_root).then_some(frame.id));
stack_hint.or_else(|| self.core.recompose_parent_hint.get())
}
pub(crate) fn subcompose_stack(&self) -> RefMut<'_, SubcomposeStack> {
self.core.subcompose_stack.borrow_mut()
}
pub(crate) fn commands_mut(&self) -> RefMut<'_, CommandQueue> {
self.core.commands.borrow_mut()
}
pub(crate) fn enqueue_semantics_invalidation(&self, id: NodeId) {
self.commands_mut().push(Command::BubbleDirty {
node_id: id,
bubble: DirtyBubble::SEMANTICS,
});
}
pub(crate) fn scope_stack(&self) -> RefMut<'_, Vec<ScopeFrame>> {
self.core.scope_stack.borrow_mut()
}
pub(crate) fn local_stack(&self) -> RefMut<'_, LocalStackSnapshot> {
self.core.local_stack.borrow_mut()
}
pub(crate) fn current_local_stack(&self) -> LocalStackSnapshot {
self.core.local_stack.borrow().clone()
}
pub(crate) fn side_effects_mut(&self) -> RefMut<'_, Vec<Box<dyn FnOnce()>>> {
self.core.side_effects.borrow_mut()
}
pub(crate) fn borrow_applier(&self) -> ApplierGuard<'_, dyn Applier> {
self.core.applier.borrow_dyn()
}
pub fn record_rebound_slot_children(&self, children: &[NodeId]) {
let mut applier = self.borrow_applier();
for &child in children {
applier.record_structural_change(child);
}
}
pub fn create_virtual_node(&self, node: Box<dyn Node>) -> NodeId {
debug_assert!(node.is_virtual(), "a virtual node reports `is_virtual`");
let mut applier = self.borrow_applier();
let node_id = applier.create(node);
if let Ok(node) = applier.get_mut(node_id) {
node.set_node_id(node_id);
}
node_id
}
pub fn dispose_subcomposed_nodes(
&self,
disposal: crate::subcompose::SubcomposeDisposal,
) -> Result<(), NodeError> {
if disposal.nodes.is_empty() && disposal.slot_hosts.is_empty() {
return Ok(());
}
self.apply_pending_commands()?;
Self::dispose_measure_subcomposed_nodes(&self.core.applier, disposal)
}
pub fn dispose_measure_subcomposed_nodes(
applier: &Rc<dyn ApplierHost>,
disposal: crate::subcompose::SubcomposeDisposal,
) -> Result<(), NodeError> {
if disposal.nodes.is_empty() && disposal.slot_hosts.is_empty() {
return Ok(());
}
let disposal = crate::NodeDisposal::from_subcomposed(disposal, &*applier.borrow_dyn());
applier.dispose_nodes(disposal)
}
pub fn node_has_no_parent(&self, node_id: NodeId) -> bool {
let mut applier = self.borrow_applier();
match applier.get_mut(node_id) {
Ok(node) => node.parent().is_none(),
Err(_) => true,
}
}
pub fn node_parent(&self, node_id: NodeId) -> Result<Option<NodeId>, NodeError> {
self.borrow_applier()
.get_mut(node_id)
.map(|node| node.parent())
}
pub fn get_node_children(&self, node_id: NodeId) -> SmallVec<[NodeId; 8]> {
let mut applier = self.borrow_applier();
match applier.get_mut(node_id) {
Ok(node) => {
let mut children = SmallVec::<[NodeId; 8]>::new();
node.collect_children_into(&mut children);
children
}
Err(_) => SmallVec::<[NodeId; 8]>::new(),
}
}
pub fn visit_node_children(&self, node_id: NodeId, mut visit: impl FnMut(NodeId, bool)) {
let applier = self.borrow_applier();
let Ok(node) = applier.get_ref(node_id) else {
return;
};
node.for_each_child(&mut |child| {
let needs_relayout = applier.get_ref(child).is_ok_and(Node::layout_dirty);
visit(child, needs_relayout);
});
}
pub fn nodes_need_relayout(&self, node_ids: impl IntoIterator<Item = NodeId>) -> bool {
let applier = self.borrow_applier();
node_ids
.into_iter()
.any(|node_id| applier.get_ref(node_id).is_ok_and(Node::layout_dirty))
}
pub fn clear_node_children(&self, node_id: NodeId) {
let mut applier = self.borrow_applier();
if let Ok(node) = applier.get_mut(node_id) {
node.update_children(&[]);
}
}
pub fn install<R>(&self, f: impl FnOnce(&Self) -> R) -> R {
let _composer_guard = composer_context::enter(self);
runtime::push_active_runtime(&self.core.runtime);
struct Guard;
impl Drop for Guard {
fn drop(&mut self) {
runtime::pop_active_runtime();
}
}
let guard = Guard;
let result = f(self);
drop(guard);
result
}
pub(crate) fn flush_pending_commands_if_large(&self) -> Result<(), NodeError> {
let queued = self.core.commands.borrow().len();
if queued < COMMAND_FLUSH_THRESHOLD {
return Ok(());
}
self.apply_pending_commands()
}
#[doc(hidden)]
pub fn __branch_group_deferred(&self, key: Key) -> BranchGroupGuard<'_> {
let folds = &*self.core.branch_folds;
BranchGroupGuard {
token: folds.push(key),
folds,
}
}
fn handle_finished_group_result(
&self,
host: &Rc<SlotsHost>,
parent_scope: Option<ScopeId>,
result: FinishGroupResult,
) {
let FinishGroupResult {
detached_children,
direct_nodes,
root_nodes,
was_skipped,
} = result;
if was_skipped {
self.attach_root_nodes(root_nodes);
}
if !detached_children.is_empty()
&& let Err(err) =
self.core
.handle_detached_children_in_host(host, parent_scope, detached_children)
{
log::error!("detached subtree handling failed while closing a group: {err}");
}
self.core.dispose_detached_nodes(&direct_nodes);
}
pub(crate) fn close_current_group_body_for_scope(&self, scope: &RecomposeScope) {
self.close_group_body(&self.active_slots_host(), scope);
}
fn close_group_body(&self, host: &Rc<SlotsHost>, scope: &RecomposeScope) {
#[expect(
clippy::redundant_closure_for_method_calls,
reason = "the method path is not general over the session lifetime"
)]
let result = host.with_write_session(|slots| slots.finish_group_body_changes());
self.close_finished_group(host, Some(scope), result);
}
fn close_finished_group(
&self,
host: &Rc<SlotsHost>,
scope: Option<&RecomposeScope>,
result: Option<FinishGroupResult>,
) {
if let Some(result) = result {
self.handle_finished_group_result(host, scope.map(RecomposeScope::id), result);
}
self.pop_closed_scope();
}
#[track_caller]
pub fn remember<T: 'static>(&self, init: impl FnOnce() -> T) -> Owned<T> {
self.remember_at(crate::caller_location_key(), init)
}
#[doc(hidden)]
pub fn remember_at<T: 'static>(&self, source: Key, init: impl FnOnce() -> T) -> Owned<T> {
self.with_slot_session_mut(|slots| {
slots.remember_with_kind(PayloadKind::Remember, source, init)
})
}
#[track_caller]
pub(crate) fn remember_internal<T: 'static>(
&self,
source_salt: Key,
init: impl FnOnce() -> T,
) -> Owned<T> {
let source = crate::caller_location_key().scoped(source_salt);
self.with_slot_session_mut(|slots| {
slots.remember_with_kind(PayloadKind::Internal, source, init)
})
}
#[track_caller]
pub(crate) fn remember_effect<T: Default + 'static>(&self, site: Key) -> Owned<T> {
self.with_slot_session_mut(|slots| slots.remember_effect::<T>(site))
}
#[track_caller]
pub fn use_value_slot<T: 'static>(&self, init: impl FnOnce() -> T) -> ValueSlotHandle<'_, T> {
let source = crate::caller_location_key();
let (slot, record) = self.with_slot_session_mut(|slots| {
slots.located_value_slot(PayloadKind::Internal, source, init)
});
ValueSlotHandle::new(slot, record)
}
#[doc(hidden)]
pub fn __use_param_slot<T: 'static>(
&self,
source: Key,
init: impl FnOnce() -> T,
) -> ValueSlotHandle<'_, T> {
let (slot, record) = self.with_slot_session_mut(|slots| {
slots.located_value_slot(PayloadKind::Param, source, init)
});
ValueSlotHandle::new(slot, record)
}
#[doc(hidden)]
pub fn __update_param_slot<T: 'static, R>(
&self,
source: Key,
init: impl FnOnce() -> T,
update: impl FnOnce(&mut T) -> R,
) -> (ValueSlotHandle<'_, T>, R) {
self.update_value_slot(PayloadKind::Param, source, init, update)
}
#[doc(hidden)]
pub fn __update_return_slot<T: 'static, R>(
&self,
source: Key,
init: impl FnOnce() -> T,
read: impl FnOnce(&mut T) -> R,
) -> (ValueSlotHandle<'_, T>, R) {
self.update_value_slot(PayloadKind::Return, source, init, read)
}
fn update_value_slot<T: 'static, R>(
&self,
kind: PayloadKind,
source: Key,
init: impl FnOnce() -> T,
update: impl FnOnce(&mut T) -> R,
) -> (ValueSlotHandle<'_, T>, R) {
self.with_slot_session_mut(|slots| {
let (slot, record, value) = slots.value_slot_and_value(kind, source, init);
(ValueSlotHandle::new(slot, record), update(value))
})
}
#[doc(hidden)]
#[track_caller]
pub fn __use_return_slot<T: 'static>(
&self,
init: impl FnOnce() -> T,
) -> ValueSlotHandle<'_, T> {
let source = crate::caller_location_key();
let (slot, record) = self.with_slot_session_mut(|slots| {
slots.located_value_slot(PayloadKind::Return, source, init)
});
ValueSlotHandle::new(slot, record)
}
#[doc(hidden)]
pub fn __invalidate_return_consumer_scope(&self) {
let Some(scope) = self.current_recompose_scope() else {
self.request_root_render();
return;
};
if let Some(target) = scope.callback_promotion_target() {
target.invalidate();
} else {
self.request_root_render();
}
}
pub fn with_slot_value<'pass, T: 'static, R>(
&'pass self,
handle: ValueSlotHandle<'pass, T>,
f: impl FnOnce(&T) -> R,
) -> R {
self.with_slots(|slots| f(slots.value_at(handle.slot, handle.record)))
}
pub fn with_slot_value_mut<'pass, T: 'static, R>(
&'pass self,
handle: ValueSlotHandle<'pass, T>,
f: impl FnOnce(&mut T) -> R,
) -> R {
self.with_slots_mut(|slots| f(slots.value_at_mut(handle.slot, handle.record)))
}
pub fn mutable_state_of<T: Clone + 'static>(&self, initial: T) -> MutableState<T> {
MutableState::with_runtime(initial, self.runtime_handle())
}
pub fn mutable_state_list_of<T, I>(&self, values: I) -> SnapshotStateList<T>
where
T: Clone + 'static,
I: IntoIterator<Item = T>,
{
SnapshotStateList::with_runtime(values, self.runtime_handle())
}
pub fn mutable_state_map_of<K, V, I>(&self, pairs: I) -> SnapshotStateMap<K, V>
where
K: Clone + Eq + Hash + 'static,
V: Clone + 'static,
I: IntoIterator<Item = (K, V)>,
{
SnapshotStateMap::with_runtime(pairs, self.runtime_handle())
}
pub fn read_composition_local<T: Clone + 'static>(&self, local: &CompositionLocal<T>) -> T {
self.read_provided(
&local.key,
|entry: &LocalStateEntry<T>| entry.value(),
|entry: &ComputedLocalEntry<T>| entry.value(),
)
.unwrap_or_else(|| local.default_value())
}
pub fn read_static_composition_local<T: Clone + 'static>(
&self,
local: &StaticCompositionLocal<T>,
) -> T {
let provided = local.provided_under(&self.core.local_stack.borrow());
provided.unwrap_or_else(|deferred| deferred.value(local))
}
fn read_provided<V: 'static, C: 'static, T>(
&self,
key: &LocalKey,
value: impl FnOnce(&V) -> T,
computed: impl FnOnce(&C) -> T,
) -> Option<T> {
let entry = provided_entry(&self.core.local_stack.borrow(), key)?;
match entry.downcast::<V>() {
Ok(entry) => Some(value(&entry)),
Err(entry) => entry
.downcast::<C>()
.inspect_err(|_| key.report_type_mismatch())
.ok()
.map(|entry| computed(&entry)),
}
}
pub(crate) fn restarted_scope(&self) -> Option<RecomposeScope> {
self.core.restarted_scope.borrow().clone()
}
pub fn phase(&self) -> crate::Phase {
self.core.phase.get()
}
pub(crate) fn set_phase(&self, phase: crate::Phase) {
self.core.phase.set(phase);
}
pub fn enter_phase(&self, phase: crate::Phase) {
self.set_phase(phase);
}
pub(crate) fn subcompose<R>(
&self,
state: &mut SubcomposeState,
slot_id: SlotId,
content: impl FnOnce(&Self) -> R,
) -> (R, Vec<NodeId>) {
match self.phase() {
crate::Phase::Measure | crate::Phase::Layout => {}
current => panic!(
"subcompose() may only be called during measure or layout; current phase: {current:?}"
),
}
self.subcompose_stack().push(SubcomposeFrame::default());
let mut guard = SubcomposeStackGuard {
core: self.clone_core(),
leaked: false,
};
let slot_host = state.get_or_create_slots(slot_id);
let (result, _) = self.with_slot_override(slot_host, |composer| {
composer.with_group(Key(slot_id.raw()), |composer| content(composer))
});
let frame = {
let frame = take_subcompose_frame(&guard.core, "subcompose");
guard.leaked = true;
frame
};
let nodes = frame.nodes;
let scopes = frame.scopes;
state.register_active(slot_id, &nodes, &scopes);
(result, nodes)
}
pub fn subcompose_measurement<R>(
&self,
state: &mut SubcomposeState,
slot_id: SlotId,
content: impl FnOnce(&Self) -> R,
) -> (R, Vec<NodeId>) {
let (result, nodes) = self.subcompose(state, slot_id, content);
let roots = nodes
.into_iter()
.filter(|&id| self.node_has_no_parent(id))
.collect();
(result, roots)
}
fn subcompose_site(&self) -> SubcomposeSite<'_> {
SubcomposeSite {
applier: &self.core.applier,
runtime: &self.core.runtime,
phase: self.phase(),
locals_changed: self.core.locals_changed.get(),
}
}
pub fn subcompose_in<R>(
&self,
slots: &Rc<SlotsHost>,
root: Option<NodeId>,
f: impl FnOnce(&Self) -> R,
) -> Result<R, NodeError> {
let _teardown = runtime::enter_state_teardown_scope();
let site = self.subcompose_site();
let shared_state = slots
.runtime_state()
.unwrap_or_else(|| Rc::clone(&self.core.shared_state));
let core = site.spin_up_core(shared_state, slots, root, self.current_local_stack());
let composer = Self::from_core(core);
let (result, commands, side_effects, compact_applier) = composer.install(|composer| {
let (output, outcome) = composer.try_with_slot_host_pass(
slots,
crate::slot::SlotPassMode::Compose,
|composer| f(composer),
)?;
let commands = composer.take_commands();
let side_effects = composer.take_side_effects();
Ok((output, commands, side_effects, outcome.compacted))
})?;
site.flush(commands, compact_applier, side_effects)?;
Ok(result)
}
pub fn capture_composition_context(&self) -> CapturedCompositionContext {
CapturedCompositionContext {
locals: self.current_local_stack(),
owner_scope: self
.current_recompose_scope()
.map(|scope| scope.downgrade()),
locals_changed: self.core.locals_changed.get(),
}
}
pub fn with_captured_locals<R>(
&self,
context: &CapturedCompositionContext,
f: impl FnOnce(&Self) -> R,
) -> R {
let parent = self.current_local_stack();
self.local_stack().clone_from(&context.locals);
let result = self.with_locals_changed(context.locals_changed, f);
*self.local_stack() = parent;
result
}
pub fn with_locals_changed<R>(&self, changed: bool, f: impl FnOnce(&Self) -> R) -> R {
let outer = self.core.locals_changed.get();
self.core.locals_changed.set(outer || changed);
let result = f(self);
self.core.locals_changed.set(outer);
result
}
pub fn subcompose_slot<R>(
&self,
slots: &Rc<SlotsHost>,
root: Option<NodeId>,
f: impl FnOnce(&Self) -> R,
) -> Result<(R, Vec<RecomposeScope>), NodeError> {
let context = self.capture_composition_context();
self.subcompose_slot_with_context(slots, root, &context, f)
}
pub fn subcompose_slot_with_context<R>(
&self,
slots: &Rc<SlotsHost>,
root: Option<NodeId>,
context: &CapturedCompositionContext,
f: impl FnOnce(&Self) -> R,
) -> Result<(R, Vec<RecomposeScope>), NodeError> {
subcompose_slot_at(
self.subcompose_site(),
|| Rc::clone(&self.core.shared_state),
slots,
root,
context,
f,
)
}
pub fn subcompose_measure_slot<R>(
applier: &Rc<dyn ApplierHost>,
runtime: &RuntimeHandle,
slots: &Rc<SlotsHost>,
root: NodeId,
context: &CapturedCompositionContext,
f: impl FnOnce(&Self) -> R,
) -> Result<(R, Vec<RecomposeScope>), NodeError> {
let site = SubcomposeSite {
applier,
runtime,
phase: crate::Phase::Measure,
locals_changed: false,
};
let new_state = || measure_slot_state(applier, context);
subcompose_slot_at(site, new_state, slots, Some(root), context, f)
}
fn attach_root_nodes(&self, root_nodes: RootNodeIds) {
for id in root_nodes {
self.attach_to_parent(id);
}
}
pub fn skip_current_group(&self) {
#[expect(
clippy::redundant_closure_for_method_calls,
reason = "the method path is not general over the session lifetime"
)]
self.with_slot_session_mut(|slots| slots.skip_group());
}
pub fn runtime_handle(&self) -> RuntimeHandle {
self.core.runtime.clone()
}
pub fn set_recompose_callback<F>(&self, callback: F)
where
F: FnMut(&Self) + 'static,
{
if let Some(scope) = self.current_recompose_scope() {
scope.set_recompose_callback(callback);
}
}
pub fn set_recompose_fn(&self, callback: fn(&Self)) {
if let Some(scope) = self.current_recompose_scope() {
scope.set_recompose_fn(callback);
}
}
pub fn with_composition_locals<R>(
&self,
provided: impl IntoIterator<Item = ProvidedValue>,
site: Key,
f: impl FnOnce(&Self) -> R,
) -> R {
let provided: SmallVec<[ProvidedValue; 2]> = provided.into_iter().collect();
if provided.is_empty() {
return f(self);
}
let mut values = SmallVec::<[(LocalKey, Rc<dyn Any>); 2]>::new();
let mut static_changed = false;
for value in provided.into_iter().rev() {
if values.iter().any(|(key, _)| key == value.key()) {
continue;
}
let (key, entry, changed) = value.into_entry(self, site);
static_changed |= changed;
values.push((key, entry));
}
let parent = self.current_local_stack();
*self.local_stack() = Some(Rc::new(LocalFrame {
values,
parent: parent.clone(),
}));
let result = self.with_locals_changed(static_changed, f);
*self.local_stack() = parent;
result
}
}