Skip to main content

cranpose_core/composer/
composable_group.rs

1use std::{cell::Cell, hash::Hash, rc::Rc};
2
3use super::{GroupScopeEntry, PendingMovable, SlotHostPassGuard, scope_frame};
4use crate::{
5    BodyRun, Composer, Key, NodeId, RecomposeOptions, RecomposeScope, RetentionMode, ScopeId,
6    SlotsHost, explicit_group_key_seed, retention::RetainKey, slot::GroupStart,
7};
8
9/// A group a composable call opened; [`ComposableGroup::close`] ends it
10/// after the call's body.
11#[doc(hidden)]
12pub struct ComposableGroup<'a> {
13    composer: &'a Composer,
14    host: Rc<SlotsHost>,
15    // The group's scope when it opened with one; `None` for a group whose
16    // body makes its scope when it first needs one.
17    scope: Option<RecomposeScope>,
18    pass: Option<SlotHostPassGuard>,
19    runs_body: bool,
20    // Whether the group composes reused content, under which every group
21    // runs its body.
22    forces_content: bool,
23    completed: bool,
24    body: Cell<Body>,
25}
26
27/// Whether a composable call's parameters changed since its body last ran,
28/// or its scope asks to recompose.
29#[doc(hidden)]
30#[derive(Clone, Copy, PartialEq, Eq)]
31pub enum ParameterChange {
32    /// Nothing the body reads as a parameter changed.
33    Unchanged,
34    /// A parameter changed or the scope asks to recompose.
35    Changed,
36}
37
38impl From<bool> for ParameterChange {
39    fn from(changed: bool) -> Self {
40        if changed {
41            Self::Changed
42        } else {
43            Self::Unchanged
44        }
45    }
46}
47
48// What a composable call does with its group's body.
49#[derive(Clone, Copy)]
50enum Body {
51    Runs,
52    // What the body composed last stays.
53    Skipped,
54    // The first body waits for a later frame, in pausable content.
55    Paused,
56}
57
58impl ComposableGroup<'_> {
59    /// Whether the group's body runs whatever its parameters: its scope asks
60    /// to recompose, or the content around it runs every body.
61    pub fn should_recompose(&self) -> bool {
62        match &self.scope {
63            Some(scope) => scope.should_recompose(),
64            None => self.composer.deferred_scope_forced(),
65        }
66    }
67
68    /// Registers `body` as the function that recomposes the group's scope,
69    /// as [`Composer::set_recompose_fn`] does for the current scope: a plain
70    /// function needs no box and no call shim.
71    #[inline]
72    pub fn set_recompose_fn(&self, body: fn(&Composer)) {
73        match &self.scope {
74            Some(scope) => scope.set_recompose_fn(body),
75            None => self.composer.set_deferred_recompose_fn(body),
76        }
77    }
78
79    // Whether the group composed before.
80    fn has_composed_once(&self) -> bool {
81        match &self.scope {
82            Some(scope) => scope.has_composed_once(),
83            None => self.composer.deferred_scope_composed_once(),
84        }
85    }
86
87    /// Skips the group's body: what it composed last stays. The call
88    /// composes nothing more in the group before closing it.
89    pub fn skip(&self) {
90        self.body.set(Body::Skipped);
91    }
92
93    /// Registers `recompose` as the function that recomposes the group's scope,
94    /// as [`Self::set_recompose_fn`] does, and answers whether the call runs
95    /// its body: `change` says whether a parameter changed or the scope asks
96    /// to recompose. A body that does not run keeps what it composed
97    /// last, or, for a group that opened in pausable content past the
98    /// frame's budget, waits for a later frame. When the body does not run,
99    /// the call composes nothing more in the group before closing it.
100    /// Compose's `Composer.shouldExecute`.
101    pub fn should_execute(&self, change: ParameterChange, recompose: fn(&Composer)) -> bool {
102        self.set_recompose_fn(recompose);
103        match self.body.get() {
104            Body::Paused => false,
105            _ if change == ParameterChange::Unchanged && self.has_composed_once() => {
106                self.body.set(Body::Skipped);
107                false
108            }
109            _ => true,
110        }
111    }
112
113    // Closes a group whose first body waits for a later frame: its scope has
114    // not composed once and stays invalid until the body runs.
115    #[cold]
116    #[inline(never)]
117    fn close_paused(&self, scope: &RecomposeScope) {
118        scope.end_reads(BodyRun::Skipped);
119        self.composer
120            .close_group_in_active_pass(&self.host, Some(scope), None);
121        self.composer.hold_paused(scope);
122    }
123
124    /// Ends the group after its body composed.
125    #[inline]
126    pub fn close(mut self) {
127        self.completed = true;
128    }
129}
130
131impl Drop for ComposableGroup<'_> {
132    fn drop(&mut self) {
133        let body = self.body.get();
134        match (body, &self.scope) {
135            (Body::Paused, Some(scope)) => self.close_paused(scope),
136            _ => {
137                // The scope the group opened with, or one its body made.
138                let made_by_body = self
139                    .scope
140                    .is_none()
141                    .then(|| self.composer.scope_made_by_body())
142                    .flatten();
143                let scope = self
144                    .scope
145                    .as_ref()
146                    .or_else(|| made_by_body.as_ref().map(|(_, scope)| scope));
147                if let Some(scope) = scope {
148                    if self.completed {
149                        scope.mark_composed_once();
150                    }
151                    let ran = matches!(body, Body::Runs) & self.completed & self.runs_body;
152                    scope.end_reads(BodyRun::from(ran));
153                }
154                if matches!(body, Body::Skipped) {
155                    self.composer
156                        .close_skipped_group_in_active_pass(&self.host, scope);
157                } else {
158                    let store = made_by_body.as_ref().map(|(group, scope)| {
159                        scope.set_slots_host(&self.host);
160                        (*group, scope)
161                    });
162                    self.composer
163                        .close_group_in_active_pass(&self.host, scope, store);
164                }
165            }
166        }
167        if self.forces_content {
168            self.composer.leave_forced_content();
169        }
170        if let Some(pass) = self.pass.take()
171            && self.completed
172            && let Err(err) = self.composer.finish_slot_host_pass(&pass.host)
173        {
174            log::error!("slot host pass finalization failed: {err}");
175        }
176    }
177}
178
179enum RetentionParent {
180    Root,
181    Scope(ScopeId),
182    Deferred,
183}
184
185#[expect(clippy::multiple_inherent_impl, reason = "one file per concern")]
186impl Composer {
187    fn scope_for_started_group(
188        &self,
189        host: &SlotsHost,
190        group: crate::slot::ActiveGroupId,
191        scope: Option<RecomposeScope>,
192    ) -> RecomposeScope {
193        if let Some(scope) = scope {
194            return scope;
195        }
196        let scope = RecomposeScope::new(self.runtime_handle());
197        host.with_write_session(|slots| slots.set_group_scope(group, scope.clone()));
198        if self.core.shared_state.pausing.is_holding() {
199            self.hold_scope(&scope);
200        }
201        scope
202    }
203
204    fn retention_parent(&self) -> RetentionParent {
205        match self.core.scope_stack.borrow().last() {
206            None => RetentionParent::Root,
207            Some(frame) => match frame.scope() {
208                Some(scope) => RetentionParent::Scope(scope.id()),
209                None => RetentionParent::Deferred,
210            },
211        }
212    }
213
214    fn begin_fresh_group(
215        host: &Rc<SlotsHost>,
216        seed: crate::slot::GroupKeySeed,
217        parent_node: Option<NodeId>,
218    ) -> GroupStart<crate::slot::ActiveGroupId> {
219        host.with_write_session(|slots| {
220            let key = slots.reserve_group_key(seed);
221            slots.begin_group(key, None, parent_node)
222        })
223    }
224
225    fn start_group(
226        &self,
227        host: &Rc<SlotsHost>,
228        seed: crate::slot::GroupKeySeed,
229        parent_node: Option<NodeId>,
230    ) -> GroupStart<crate::slot::ActiveGroupId> {
231        if !self.core.shared_state.retains_any() {
232            return Self::begin_fresh_group(host, seed, parent_node);
233        }
234        let parent_scope_id = match self.retention_parent() {
235            RetentionParent::Root => None,
236            RetentionParent::Scope(id) => Some(id),
237            // A deferred parent has never held a scope id, so no retained
238            // group can be keyed under it.
239            RetentionParent::Deferred => return Self::begin_fresh_group(host, seed, parent_node),
240        };
241        let key = host.with_write_session(|slots| slots.reserve_group_key(seed));
242        let retain_key = RetainKey::for_group(parent_scope_id, key);
243        let restored = self
244            .core
245            .shared_state
246            .take_retained(host, retain_key, key)
247            .map(Box::new);
248        host.with_write_session(|slots| slots.begin_group(key, restored, parent_node))
249    }
250
251    fn start_movable_group(
252        &self,
253        host: &Rc<SlotsHost>,
254        id: Key,
255        parent_node: Option<NodeId>,
256        lookup: super::MovableLookup,
257    ) -> (
258        GroupStart<crate::slot::ActiveGroupId>,
259        Option<crate::slot::GroupKey>,
260    ) {
261        let seed = crate::slot::GroupKeySeed::movable(id);
262        if lookup == super::MovableLookup::FreshUnshown {
263            return (Self::begin_fresh_group(host, seed, parent_node), None);
264        }
265        let key = host.with_write_session(|slots| slots.reserve_group_key(seed));
266        let super::GroupEntry {
267            key,
268            restored,
269            placeholder_for,
270        } = self.resolve_movable_group_entry(host, key, lookup);
271        let started =
272            host.with_write_session(|slots| slots.begin_group(key, restored, parent_node));
273        (started, placeholder_for)
274    }
275
276    // Opens a group; returns its scope, `None` for one whose body makes it
277    // when it first needs one, and whether it forces the groups below it to
278    // run theirs.
279    #[inline(never)]
280    fn open_group_in_active_pass(
281        &self,
282        host: &Rc<SlotsHost>,
283        key: crate::slot::GroupKeySeed,
284    ) -> (Option<RecomposeScope>, bool) {
285        let options = self.core.pending_scope_options.take().unwrap_or_default();
286        let parent_node = self.current_parent_hint();
287        let GroupStart {
288            group,
289            anchor,
290            scope,
291            kind,
292        } = self.start_group(host, key, parent_node);
293        if scope.is_none()
294            && !key.exact
295            && scope_frame::may_defer(options, kind)
296            && self.defers_scopes_here()
297        {
298            self.push_deferred_scope((group, anchor), kind, parent_node);
299            return (None, false);
300        }
301        let scope_ref = self.scope_for_started_group(host, group, scope);
302        let forces_content = self.enter_group_scope(
303            &scope_ref,
304            &GroupScopeEntry {
305                options,
306                start_kind: kind,
307                host,
308                group,
309                parent_hint: parent_node,
310            },
311        );
312        (Some(scope_ref), forces_content)
313    }
314
315    #[inline(never)]
316    fn open_movable_group_in_active_pass(
317        &self,
318        host: &Rc<SlotsHost>,
319        id: Key,
320        lookup: super::MovableLookup,
321    ) -> (Option<RecomposeScope>, bool, bool) {
322        let options = self.core.pending_scope_options.take().unwrap_or_default();
323        let parent_node = self.current_parent_hint();
324        let (
325            GroupStart {
326                group,
327                anchor,
328                scope,
329                kind,
330            },
331            placeholder_for,
332        ) = self.start_movable_group(host, id, parent_node, lookup);
333        let scope_ref = self.scope_for_started_group(host, group, scope);
334        if let Some(movable_key) = placeholder_for {
335            let parent_scope = {
336                let mut stack = self.scope_stack();
337                let top = stack.len().checked_sub(1);
338                top.map(|top| self.frame_scope(&mut stack, top).downgrade())
339            };
340            self.core.shared_state.record_pending_movable(
341                host,
342                PendingMovable {
343                    key: movable_key,
344                    placeholder: anchor,
345                    parent_scope,
346                    woken: false,
347                },
348            );
349        }
350        let forces_content = self.enter_group_scope(
351            &scope_ref,
352            &GroupScopeEntry {
353                options,
354                start_kind: kind,
355                host,
356                group,
357                parent_hint: parent_node,
358            },
359        );
360        (Some(scope_ref), placeholder_for.is_none(), forces_content)
361    }
362
363    // Closes a group whose body ran: `store` is the scope its body made,
364    // which goes into the group's record.
365    #[inline(never)]
366    fn close_group_in_active_pass(
367        &self,
368        host: &Rc<SlotsHost>,
369        scope: Option<&RecomposeScope>,
370        store: Option<(crate::slot::ActiveGroupId, &RecomposeScope)>,
371    ) {
372        let result = host.with_write_session(|slots| {
373            let result = slots.finish_group_body_changes();
374            if let Some((group, made)) = store {
375                slots.set_group_scope(group, made.clone());
376            }
377            slots.end_group();
378            result
379        });
380        self.close_finished_group(host, scope, result);
381        self.settle_closed_group(scope);
382    }
383
384    // Closes a group whose body was skipped, in one slot session: its root
385    // nodes stay attached where they were.
386    #[inline(never)]
387    fn close_skipped_group_in_active_pass(
388        &self,
389        host: &Rc<SlotsHost>,
390        scope: Option<&RecomposeScope>,
391    ) {
392        // Attaching a node reaches the parent stack and the applier, never
393        // the slot table the session holds.
394        host.with_write_session(|slots| slots.skip_and_end_group(|id| self.attach_to_parent(id)));
395        self.pop_closed_scope();
396        self.settle_closed_group(scope);
397    }
398
399    fn settle_closed_group(&self, scope: Option<&RecomposeScope>) {
400        if let Some(scope) = scope {
401            scope.mark_recomposed();
402        }
403        if let Err(err) = self.flush_pending_commands_if_large() {
404            log::error!("mid-composition command flush failed: {err}");
405        }
406    }
407
408    #[inline]
409    fn acquire_pass_host(&self) -> (Rc<SlotsHost>, Option<SlotHostPassGuard>) {
410        let host = self.active_slots_host();
411        if host.has_active_pass() {
412            (host, None)
413        } else {
414            let pass = self.begin_slot_host_pass(&host, crate::slot::SlotPassMode::Compose);
415            (self.active_slots_host(), Some(pass))
416        }
417    }
418
419    #[inline]
420    fn finish_open_group(
421        &self,
422        host: Rc<SlotsHost>,
423        pass: Option<SlotHostPassGuard>,
424        scope: Option<RecomposeScope>,
425        runs_body: bool,
426        forces_content: bool,
427    ) -> ComposableGroup<'_> {
428        if let Some(scope) = &scope {
429            scope.begin_reads();
430        }
431        ComposableGroup {
432            composer: self,
433            host,
434            scope,
435            pass,
436            runs_body,
437            forces_content,
438            completed: false,
439            body: Cell::new(Body::Runs),
440        }
441    }
442
443    #[inline(never)]
444    fn open_group(&self, key: crate::slot::GroupKeySeed) -> ComposableGroup<'_> {
445        let (host, pass) = self.acquire_pass_host();
446        let (scope, forces_content) = self.open_group_in_active_pass(&host, key);
447        self.finish_open_group(host, pass, scope, true, forces_content)
448    }
449
450    fn open_movable_group(&self, id: Key, lookup: super::MovableLookup) -> ComposableGroup<'_> {
451        super::movable::enable_movable_hooks();
452        let (host, pass) = self.acquire_pass_host();
453        let (scope, runs_body, forces_content) =
454            self.open_movable_group_in_active_pass(&host, id, lookup);
455        self.finish_open_group(host, pass, scope, runs_body, forces_content)
456    }
457
458    #[doc(hidden)]
459    pub fn __open_composable_group(&self, key: Key) -> ComposableGroup<'_> {
460        // A composable that returns a value invalidates its caller's scope
461        // when a recomposition of its own returns another one.
462        self.current_recompose_scope();
463        self.open_group(crate::slot::GroupKeySeed::unkeyed(key))
464    }
465
466    // Opens the group of a composable that returns nothing: in pausable
467    // content past the frame's budget, its first body waits.
468    #[doc(hidden)]
469    pub fn __open_pausable_group(&self, key: Key) -> ComposableGroup<'_> {
470        let group = self.open_group(crate::slot::GroupKeySeed::unkeyed(key));
471        if self.core.shared_state.pausing.is_holding()
472            && let Some(scope) = &group.scope
473            && self.pauses_first_body(scope)
474        {
475            group.body.set(Body::Paused);
476        }
477        group
478    }
479
480    pub(crate) fn with_group_seed<R>(
481        &self,
482        key: crate::slot::GroupKeySeed,
483        f: impl FnOnce(&Self) -> R,
484    ) -> R {
485        let group = self.open_group(key);
486        debug_assert!(group.runs_body, "only movable content waits for a body");
487        let result = f(self);
488        group.close();
489        result
490    }
491
492    pub(crate) fn with_movable_group(
493        &self,
494        id: Key,
495        lookup: super::MovableLookup,
496        f: impl FnOnce(&Self),
497    ) {
498        let group = self.open_movable_group(id, lookup);
499        if group.runs_body {
500            f(self);
501        }
502        group.close();
503    }
504
505    /// Runs `f` in a group identified by `key`. Slots and nodes that `f` creates belong to the
506    /// group.
507    pub fn with_group<R>(&self, key: Key, f: impl FnOnce(&Self) -> R) -> R {
508        self.with_group_seed(crate::slot::GroupKeySeed::unkeyed(key), f)
509    }
510
511    /// Runs `f` in a group identified by `key` that is retained when it leaves the composition,
512    /// with the recompose `options` applied to its scope. A retained group returns with its state
513    /// and nodes when `key` is composed again.
514    pub fn cranpose_with_reuse<R>(
515        &self,
516        key: Key,
517        mut options: RecomposeOptions,
518        f: impl FnOnce(&Self) -> R,
519    ) -> R {
520        options.retention = RetentionMode::RetainWhenInactive;
521        self.core.pending_scope_options.set(Some(options));
522        self.with_group(key, f)
523    }
524
525    /// Runs `f` in a group identified by the hash of `key`, so state and nodes follow the key when
526    /// siblings move. Compose's `key`.
527    #[track_caller]
528    pub fn with_key<K: Hash, R>(&self, key: &K, f: impl FnOnce(&Self) -> R) -> R {
529        let seed = explicit_group_key_seed(key, std::panic::Location::caller());
530        self.with_group_seed(seed, f)
531    }
532}