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, RecomposeOptions, RecomposeScope, RetentionMode, SlotsHost,
6    explicit_group_key_seed, 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(mut pass) = self.pass.take() {
171            if 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            pass.close();
177        }
178    }
179}
180
181#[expect(clippy::multiple_inherent_impl, reason = "one file per concern")]
182impl Composer {
183    fn scope_for_started_group(
184        &self,
185        host: &SlotsHost,
186        group: crate::slot::ActiveGroupId,
187        scope: Option<RecomposeScope>,
188    ) -> RecomposeScope {
189        if let Some(scope) = scope {
190            return scope;
191        }
192        let scope = RecomposeScope::new(self.runtime_handle());
193        host.with_write_session(|slots| slots.set_group_scope(group, scope.clone()));
194        if self.core.shared_state.pausing.is_holding() {
195            self.hold_scope(&scope);
196        }
197        scope
198    }
199
200    // Opens a group; returns its scope, `None` for one whose body makes it
201    // when it first needs one, whether its body runs and whether it forces
202    // the groups below it to run theirs.
203    #[inline(never)]
204    fn open_group_in_active_pass(
205        &self,
206        host: &Rc<SlotsHost>,
207        key: crate::slot::GroupKeySeed,
208    ) -> (Option<RecomposeScope>, bool, bool) {
209        let options = self.core.pending_scope_options.take().unwrap_or_default();
210        let parent_node = self.current_parent_hint();
211        let (
212            GroupStart {
213                group,
214                anchor,
215                scope,
216                kind,
217            },
218            placeholder_for,
219        ) = self.start_group(host, key, parent_node);
220        // Movable content keeps its scope, which a move reparents its
221        // scopes from.
222        if scope.is_none()
223            && !key.exact
224            && placeholder_for.is_none()
225            && scope_frame::may_defer(options, kind)
226            && self.defers_scopes_here()
227        {
228            self.push_deferred_scope((group, anchor), kind, parent_node);
229            return (None, true, false);
230        }
231        let scope_ref = self.scope_for_started_group(host, group, scope);
232        if let Some(movable_key) = placeholder_for {
233            let parent_scope = {
234                let mut stack = self.scope_stack();
235                let top = stack.len().checked_sub(1);
236                top.map(|top| self.frame_scope(&mut stack, top).downgrade())
237            };
238            self.core.shared_state.record_pending_movable(
239                host,
240                PendingMovable {
241                    key: movable_key,
242                    placeholder: anchor,
243                    parent_scope,
244                },
245            );
246        }
247        let forces_content = self.enter_group_scope(
248            &scope_ref,
249            &GroupScopeEntry {
250                options,
251                start_kind: kind,
252                host,
253                group,
254                parent_hint: parent_node,
255            },
256        );
257        (Some(scope_ref), placeholder_for.is_none(), forces_content)
258    }
259
260    // Closes a group whose body ran: `store` is the scope its body made,
261    // which goes into the group's record.
262    #[inline(never)]
263    fn close_group_in_active_pass(
264        &self,
265        host: &Rc<SlotsHost>,
266        scope: Option<&RecomposeScope>,
267        store: Option<(crate::slot::ActiveGroupId, &RecomposeScope)>,
268    ) {
269        let result = host.with_write_session(|slots| {
270            let result = slots.finish_group_body_changes();
271            if let Some((group, made)) = store {
272                slots.set_group_scope(group, made.clone());
273            }
274            slots.end_group();
275            result
276        });
277        self.close_finished_group(host, scope, result);
278        self.settle_closed_group(scope);
279    }
280
281    // Closes a group whose body was skipped, in one slot session: its root
282    // nodes stay attached where they were.
283    #[inline(never)]
284    fn close_skipped_group_in_active_pass(
285        &self,
286        host: &Rc<SlotsHost>,
287        scope: Option<&RecomposeScope>,
288    ) {
289        // Attaching a node reaches the parent stack and the applier, never
290        // the slot table the session holds.
291        host.with_write_session(|slots| slots.skip_and_end_group(|id| self.attach_to_parent(id)));
292        self.pop_closed_scope();
293        self.settle_closed_group(scope);
294    }
295
296    fn settle_closed_group(&self, scope: Option<&RecomposeScope>) {
297        if let Some(scope) = scope {
298            scope.mark_recomposed();
299        }
300        if let Err(err) = self.flush_pending_commands_if_large() {
301            log::error!("mid-composition command flush failed: {err}");
302        }
303    }
304
305    #[inline(never)]
306    fn open_group(&self, key: crate::slot::GroupKeySeed) -> ComposableGroup<'_> {
307        let host = self.active_slots_host();
308        let (host, pass) = if host.has_active_pass() {
309            (host, None)
310        } else {
311            let pass = self.begin_slot_host_pass(&host, crate::slot::SlotPassMode::Compose);
312            (self.active_slots_host(), Some(pass))
313        };
314        let (scope, runs_body, forces_content) = self.open_group_in_active_pass(&host, key);
315        if let Some(scope) = &scope {
316            scope.begin_reads();
317        }
318        ComposableGroup {
319            composer: self,
320            host,
321            scope,
322            pass,
323            runs_body,
324            forces_content,
325            completed: false,
326            body: Cell::new(Body::Runs),
327        }
328    }
329
330    #[doc(hidden)]
331    pub fn __open_composable_group(&self, key: Key) -> ComposableGroup<'_> {
332        // A composable that returns a value invalidates its caller's scope
333        // when a recomposition of its own returns another one.
334        self.current_recompose_scope();
335        self.open_group(crate::slot::GroupKeySeed::unkeyed(key))
336    }
337
338    // Opens the group of a composable that returns nothing: in pausable
339    // content past the frame's budget, its first body waits.
340    #[doc(hidden)]
341    pub fn __open_pausable_group(&self, key: Key) -> ComposableGroup<'_> {
342        let group = self.open_group(crate::slot::GroupKeySeed::unkeyed(key));
343        if self.core.shared_state.pausing.is_holding()
344            && let Some(scope) = &group.scope
345            && self.pauses_first_body(scope)
346        {
347            group.body.set(Body::Paused);
348        }
349        group
350    }
351
352    pub(crate) fn with_group_seed<R>(
353        &self,
354        key: crate::slot::GroupKeySeed,
355        f: impl FnOnce(&Self) -> R,
356    ) -> R {
357        let group = self.open_group(key);
358        debug_assert!(group.runs_body, "only movable content waits for a body");
359        let result = f(self);
360        group.close();
361        result
362    }
363
364    pub(crate) fn with_movable_group(&self, id: Key, f: impl FnOnce(&Self)) {
365        let group = self.open_group(crate::slot::GroupKeySeed::movable(id));
366        if group.runs_body {
367            f(self);
368        }
369        group.close();
370    }
371
372    /// Runs `f` in a group identified by `key`. Slots and nodes that `f` creates belong to the
373    /// group.
374    pub fn with_group<R>(&self, key: Key, f: impl FnOnce(&Self) -> R) -> R {
375        self.with_group_seed(crate::slot::GroupKeySeed::unkeyed(key), f)
376    }
377
378    /// Runs `f` in a group identified by `key` that is retained when it leaves the composition,
379    /// with the recompose `options` applied to its scope. A retained group returns with its state
380    /// and nodes when `key` is composed again.
381    pub fn cranpose_with_reuse<R>(
382        &self,
383        key: Key,
384        mut options: RecomposeOptions,
385        f: impl FnOnce(&Self) -> R,
386    ) -> R {
387        options.retention = RetentionMode::RetainWhenInactive;
388        self.core.pending_scope_options.set(Some(options));
389        self.with_group(key, f)
390    }
391
392    /// Runs `f` in a group identified by the hash of `key`, so state and nodes follow the key when
393    /// siblings move. Compose's `key`.
394    #[track_caller]
395    pub fn with_key<K: Hash, R>(&self, key: &K, f: impl FnOnce(&Self) -> R) -> R {
396        let seed = explicit_group_key_seed(key, std::panic::Location::caller());
397        self.with_group_seed(seed, f)
398    }
399}