use std::{cell::Cell, hash::Hash, rc::Rc};
use super::{GroupScopeEntry, PendingMovable, SlotHostPassGuard, scope_frame};
use crate::{
BodyRun, Composer, Key, RecomposeOptions, RecomposeScope, RetentionMode, SlotsHost,
explicit_group_key_seed, slot::GroupStart,
};
#[doc(hidden)]
pub struct ComposableGroup<'a> {
composer: &'a Composer,
host: Rc<SlotsHost>,
scope: Option<RecomposeScope>,
pass: Option<SlotHostPassGuard>,
runs_body: bool,
forces_content: bool,
completed: bool,
body: Cell<Body>,
}
#[doc(hidden)]
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum ParameterChange {
Unchanged,
Changed,
}
impl From<bool> for ParameterChange {
fn from(changed: bool) -> Self {
if changed {
Self::Changed
} else {
Self::Unchanged
}
}
}
#[derive(Clone, Copy)]
enum Body {
Runs,
Skipped,
Paused,
}
impl ComposableGroup<'_> {
pub fn should_recompose(&self) -> bool {
match &self.scope {
Some(scope) => scope.should_recompose(),
None => self.composer.deferred_scope_forced(),
}
}
#[inline]
pub fn set_recompose_fn(&self, body: fn(&Composer)) {
match &self.scope {
Some(scope) => scope.set_recompose_fn(body),
None => self.composer.set_deferred_recompose_fn(body),
}
}
fn has_composed_once(&self) -> bool {
match &self.scope {
Some(scope) => scope.has_composed_once(),
None => self.composer.deferred_scope_composed_once(),
}
}
pub fn skip(&self) {
self.body.set(Body::Skipped);
}
pub fn should_execute(&self, change: ParameterChange, recompose: fn(&Composer)) -> bool {
self.set_recompose_fn(recompose);
match self.body.get() {
Body::Paused => false,
_ if change == ParameterChange::Unchanged && self.has_composed_once() => {
self.body.set(Body::Skipped);
false
}
_ => true,
}
}
#[cold]
#[inline(never)]
fn close_paused(&self, scope: &RecomposeScope) {
scope.end_reads(BodyRun::Skipped);
self.composer
.close_group_in_active_pass(&self.host, Some(scope), None);
self.composer.hold_paused(scope);
}
#[inline]
pub fn close(mut self) {
self.completed = true;
}
}
impl Drop for ComposableGroup<'_> {
fn drop(&mut self) {
let body = self.body.get();
match (body, &self.scope) {
(Body::Paused, Some(scope)) => self.close_paused(scope),
_ => {
let made_by_body = self
.scope
.is_none()
.then(|| self.composer.scope_made_by_body())
.flatten();
let scope = self
.scope
.as_ref()
.or_else(|| made_by_body.as_ref().map(|(_, scope)| scope));
if let Some(scope) = scope {
if self.completed {
scope.mark_composed_once();
}
let ran = matches!(body, Body::Runs) & self.completed & self.runs_body;
scope.end_reads(BodyRun::from(ran));
}
if matches!(body, Body::Skipped) {
self.composer
.close_skipped_group_in_active_pass(&self.host, scope);
} else {
let store = made_by_body.as_ref().map(|(group, scope)| {
scope.set_slots_host(&self.host);
(*group, scope)
});
self.composer
.close_group_in_active_pass(&self.host, scope, store);
}
}
}
if self.forces_content {
self.composer.leave_forced_content();
}
if let Some(mut pass) = self.pass.take() {
if self.completed
&& let Err(err) = self.composer.finish_slot_host_pass(&pass.host)
{
log::error!("slot host pass finalization failed: {err}");
}
pass.close();
}
}
}
#[expect(clippy::multiple_inherent_impl, reason = "one file per concern")]
impl Composer {
fn scope_for_started_group(
&self,
host: &SlotsHost,
group: crate::slot::ActiveGroupId,
scope: Option<RecomposeScope>,
) -> RecomposeScope {
if let Some(scope) = scope {
return scope;
}
let scope = RecomposeScope::new(self.runtime_handle());
host.with_write_session(|slots| slots.set_group_scope(group, scope.clone()));
if self.core.shared_state.pausing.is_holding() {
self.hold_scope(&scope);
}
scope
}
#[inline(never)]
fn open_group_in_active_pass(
&self,
host: &Rc<SlotsHost>,
key: crate::slot::GroupKeySeed,
) -> (Option<RecomposeScope>, bool, bool) {
let options = self.core.pending_scope_options.take().unwrap_or_default();
let parent_node = self.current_parent_hint();
let (
GroupStart {
group,
anchor,
scope,
kind,
},
placeholder_for,
) = self.start_group(host, key, parent_node);
if scope.is_none()
&& !key.exact
&& placeholder_for.is_none()
&& scope_frame::may_defer(options, kind)
&& self.defers_scopes_here()
{
self.push_deferred_scope((group, anchor), kind, parent_node);
return (None, true, false);
}
let scope_ref = self.scope_for_started_group(host, group, scope);
if let Some(movable_key) = placeholder_for {
let parent_scope = {
let mut stack = self.scope_stack();
let top = stack.len().checked_sub(1);
top.map(|top| self.frame_scope(&mut stack, top).downgrade())
};
self.core.shared_state.record_pending_movable(
host,
PendingMovable {
key: movable_key,
placeholder: anchor,
parent_scope,
},
);
}
let forces_content = self.enter_group_scope(
&scope_ref,
&GroupScopeEntry {
options,
start_kind: kind,
host,
group,
parent_hint: parent_node,
},
);
(Some(scope_ref), placeholder_for.is_none(), forces_content)
}
#[inline(never)]
fn close_group_in_active_pass(
&self,
host: &Rc<SlotsHost>,
scope: Option<&RecomposeScope>,
store: Option<(crate::slot::ActiveGroupId, &RecomposeScope)>,
) {
let result = host.with_write_session(|slots| {
let result = slots.finish_group_body_changes();
if let Some((group, made)) = store {
slots.set_group_scope(group, made.clone());
}
slots.end_group();
result
});
self.close_finished_group(host, scope, result);
self.settle_closed_group(scope);
}
#[inline(never)]
fn close_skipped_group_in_active_pass(
&self,
host: &Rc<SlotsHost>,
scope: Option<&RecomposeScope>,
) {
host.with_write_session(|slots| slots.skip_and_end_group(|id| self.attach_to_parent(id)));
self.pop_closed_scope();
self.settle_closed_group(scope);
}
fn settle_closed_group(&self, scope: Option<&RecomposeScope>) {
if let Some(scope) = scope {
scope.mark_recomposed();
}
if let Err(err) = self.flush_pending_commands_if_large() {
log::error!("mid-composition command flush failed: {err}");
}
}
#[inline(never)]
fn open_group(&self, key: crate::slot::GroupKeySeed) -> ComposableGroup<'_> {
let host = self.active_slots_host();
let (host, pass) = if host.has_active_pass() {
(host, None)
} else {
let pass = self.begin_slot_host_pass(&host, crate::slot::SlotPassMode::Compose);
(self.active_slots_host(), Some(pass))
};
let (scope, runs_body, forces_content) = self.open_group_in_active_pass(&host, key);
if let Some(scope) = &scope {
scope.begin_reads();
}
ComposableGroup {
composer: self,
host,
scope,
pass,
runs_body,
forces_content,
completed: false,
body: Cell::new(Body::Runs),
}
}
#[doc(hidden)]
pub fn __open_composable_group(&self, key: Key) -> ComposableGroup<'_> {
self.current_recompose_scope();
self.open_group(crate::slot::GroupKeySeed::unkeyed(key))
}
#[doc(hidden)]
pub fn __open_pausable_group(&self, key: Key) -> ComposableGroup<'_> {
let group = self.open_group(crate::slot::GroupKeySeed::unkeyed(key));
if self.core.shared_state.pausing.is_holding()
&& let Some(scope) = &group.scope
&& self.pauses_first_body(scope)
{
group.body.set(Body::Paused);
}
group
}
pub(crate) fn with_group_seed<R>(
&self,
key: crate::slot::GroupKeySeed,
f: impl FnOnce(&Self) -> R,
) -> R {
let group = self.open_group(key);
debug_assert!(group.runs_body, "only movable content waits for a body");
let result = f(self);
group.close();
result
}
pub(crate) fn with_movable_group(&self, id: Key, f: impl FnOnce(&Self)) {
let group = self.open_group(crate::slot::GroupKeySeed::movable(id));
if group.runs_body {
f(self);
}
group.close();
}
pub fn with_group<R>(&self, key: Key, f: impl FnOnce(&Self) -> R) -> R {
self.with_group_seed(crate::slot::GroupKeySeed::unkeyed(key), f)
}
pub fn cranpose_with_reuse<R>(
&self,
key: Key,
mut options: RecomposeOptions,
f: impl FnOnce(&Self) -> R,
) -> R {
options.retention = RetentionMode::RetainWhenInactive;
self.core.pending_scope_options.set(Some(options));
self.with_group(key, f)
}
#[track_caller]
pub fn with_key<K: Hash, R>(&self, key: &K, f: impl FnOnce(&Self) -> R) -> R {
let seed = explicit_group_key_seed(key, std::panic::Location::caller());
self.with_group_seed(seed, f)
}
}