cranpose_core/movable_content.rs
1use std::{
2 cell::Cell,
3 hash::Hash,
4 rc::{Rc, Weak},
5};
6
7use crate::{
8 Composer, Key,
9 composer::{ComposerRuntimeState, MovableLookup},
10 composer_context, current_runtime_handle, hash_key,
11 owned::WeakOwned,
12 with_current_composer,
13};
14
15#[derive(Clone, Copy, PartialEq, Eq)]
16enum MovableOwnerState {
17 NeverShown,
18 ShownInOwnerHost,
19 ShownOutsideOwnerHost,
20 DisposedWithSubtree,
21}
22
23struct RememberedMovable {
24 id: Key,
25 shared_state: Weak<ComposerRuntimeState>,
26 owner_host_key: usize,
27 state: Cell<MovableOwnerState>,
28}
29
30impl Drop for RememberedMovable {
31 fn drop(&mut self) {
32 let owner_host = match self.state.get() {
33 MovableOwnerState::NeverShown | MovableOwnerState::DisposedWithSubtree => return,
34 MovableOwnerState::ShownInOwnerHost => Some(self.owner_host_key),
35 MovableOwnerState::ShownOutsideOwnerHost => None,
36 };
37 if let Some(state) = self.shared_state.upgrade() {
38 state.on_movable_owner_dropped(self.id, owner_host);
39 }
40 }
41}
42
43// Returns the movable id when `payload` is the sole owner of a remembered
44// movable with no live `MovableContent` handles anywhere outside the slot.
45pub(crate) fn sole_owned_movable_id(payload: &dyn std::any::Any) -> Option<Key> {
46 let owned = payload.downcast_ref::<crate::Owned<RememberedMovable>>()?;
47 (owned.strong_count() == 1 && owned.weak_count() == 0).then(|| owned.with(|owner| owner.id))
48}
49
50// Marks a remembered movable whose content is already being disposed inline
51// with its owning subtree, so dropping the owner performs no redundant lookup.
52pub(crate) fn disarm_remembered_movable(payload: &dyn std::any::Any) {
53 if let Some(owned) = payload.downcast_ref::<crate::Owned<RememberedMovable>>() {
54 owned.with(|owner| owner.state.set(MovableOwnerState::DisposedWithSubtree));
55 }
56}
57
58/// Composes `content` under an identity that is `key` alone, the same at
59/// every call site, so the subtree can be emitted from any parent and keep
60/// its remembered values, its running effects and its nodes.
61///
62/// Move content by emitting it under a different parent, in the same pass
63/// or a later one: when the old parent stops emitting it, the subtree is
64/// retained under `key`; when a parent emits it, the retained subtree is
65/// taken back. A site that asks for content still attached elsewhere
66/// composes nothing and is recomposed once the content is retained, so the
67/// order in which the two parents recompose does not matter.
68///
69/// Content is shown at most once. Two live sites with the same key leave
70/// the later one empty. Retained content is kept
71/// until a parent takes it back or [`forget_movable`] releases it, so an
72/// item the app closes for good must be forgotten or its state stays in
73/// memory. A subtree may cross into and out of a `SubcomposeLayout` slot,
74/// whose content lives in a slot table of its own: the table that held it
75/// gives up its anchors and the one taking it over issues new ones.
76#[track_caller]
77pub fn movable<K: Hash>(key: K, content: impl FnOnce()) {
78 let id = hash_key(&key);
79 with_current_composer(|composer| {
80 composer.with_movable_group(id, MovableLookup::AnyHost, |_| content());
81 });
82}
83
84/// Content written once that keeps its identity wherever it is shown.
85///
86/// [`movable`] names content by a key, which means writing the content out
87/// at every parent that might show it and trusting the keys to match. When
88/// the parents are alternatives -- a pane docked in a stack or pulled out
89/// into a window of its own, a tab in a strip or torn into its own window --
90/// that is the same body written twice, and two bodies that must be kept in
91/// step by hand are two bodies that drift.
92///
93/// This hands back the content as a value instead. Write the body once,
94/// remember it, and call [`MovableContent::show`] from whichever parent is
95/// showing it this pass:
96///
97/// ```ignore
98/// let pane = rememberMovableContentOf(move || PaneBody(state));
99/// if docked {
100/// Box(Modifier::empty().offset(0.0, y), BoxSpec::default(), || pane.show());
101/// } else {
102/// Box(Modifier::empty().window(config), BoxSpec::default(), || pane.show());
103/// }
104/// ```
105///
106/// The identity comes from the `remember`, so two calls at one site produce
107/// two distinct pieces of content. The same identity survives recomposition.
108/// Leaving the composition releases the content with the call site. Calling
109/// [`MovableContent::forget`] releases retained content earlier while the call
110/// site stays alive.
111///
112/// Content that must be recognised from another composable that this value
113/// cannot reach uses [`movableContentOf`] instead, which takes a key as the
114/// identity.
115///
116/// Mirrors Jetpack Compose's `movableContentOf`.
117#[expect(non_snake_case, reason = "names follow Compose's casing")]
118#[track_caller]
119pub fn rememberMovableContentOf(content: impl Fn() + 'static) -> MovableContent {
120 crate::composer::enable_movable_hooks();
121 let source = crate::caller_location_key();
122 let (id, owner) = with_current_composer(|composer| {
123 let owned = composer.remember_at(source, || RememberedMovable {
124 id: composer.runtime_handle().next_movable_content_id(),
125 shared_state: composer.shared_state_weak(),
126 owner_host_key: composer.active_slots_host_storage_key(),
127 state: Cell::new(MovableOwnerState::NeverShown),
128 });
129 let id = owned.with(|owner| owner.id);
130 (id, owned.downgrade())
131 });
132 MovableContent {
133 id,
134 content: Rc::new(content),
135 owner: Some(owner),
136 }
137}
138
139/// Movable content whose identity is `key`, the same at every call site.
140///
141/// The keyed twin of [`rememberMovableContentOf`], and the same identity
142/// [`movable`] uses: content shown by this value and content shown by
143/// `movable` under the same key is one piece of content. Reach for this when
144/// the parents that can show it are in different composables, so no single
145/// value can be handed to all of them.
146#[expect(non_snake_case, reason = "names follow Compose's casing")]
147pub fn movableContentOf<K: Hash>(key: K, content: impl Fn() + 'static) -> MovableContent {
148 MovableContent {
149 id: hash_key(&key),
150 content: Rc::new(content),
151 owner: None,
152 }
153}
154
155/// Movable content held as a value. See [`rememberMovableContentOf`].
156#[derive(Clone)]
157pub struct MovableContent {
158 id: Key,
159 content: Rc<dyn Fn()>,
160 owner: Option<WeakOwned<RememberedMovable>>,
161}
162
163impl MovableContent {
164 /// Shows the content here. Calling this from a different parent than
165 /// last pass moves the content, with its remembered values, its running
166 /// effects and its nodes.
167 pub fn show(&self) {
168 let content = Rc::clone(&self.content);
169 let id = self.id;
170 with_current_composer(|composer| {
171 let lookup = self
172 .owner
173 .as_ref()
174 .and_then(|owner| {
175 owner.with(|owner| {
176 let outside =
177 composer.active_slots_host_storage_key() != owner.owner_host_key;
178 let (next, lookup) = match owner.state.get() {
179 MovableOwnerState::NeverShown => (
180 if outside {
181 MovableOwnerState::ShownOutsideOwnerHost
182 } else {
183 MovableOwnerState::ShownInOwnerHost
184 },
185 MovableLookup::FreshUnshown,
186 ),
187 MovableOwnerState::ShownInOwnerHost => {
188 if outside {
189 (
190 MovableOwnerState::ShownOutsideOwnerHost,
191 MovableLookup::AnyHost,
192 )
193 } else {
194 (
195 MovableOwnerState::ShownInOwnerHost,
196 MovableLookup::OwnerHostOnly,
197 )
198 }
199 }
200 MovableOwnerState::ShownOutsideOwnerHost => (
201 MovableOwnerState::ShownOutsideOwnerHost,
202 MovableLookup::AnyHost,
203 ),
204 MovableOwnerState::DisposedWithSubtree => (
205 if outside {
206 MovableOwnerState::ShownOutsideOwnerHost
207 } else {
208 MovableOwnerState::ShownInOwnerHost
209 },
210 MovableLookup::AnyHost,
211 ),
212 };
213 owner.state.set(next);
214 lookup
215 })
216 })
217 .unwrap_or(MovableLookup::AnyHost);
218 composer.with_movable_group(id, lookup, |_| content());
219 });
220 }
221
222 /// Releases the content's state once no parent is showing it, for
223 /// content the application has closed for good. See [`forget_movable`].
224 pub fn forget(&self) {
225 forget_movable_id(self.id);
226 }
227}
228
229impl std::fmt::Debug for MovableContent {
230 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
231 f.debug_struct("MovableContent")
232 .field("id", &self.id)
233 .finish()
234 }
235}
236
237impl PartialEq for MovableContent {
238 fn eq(&self, other: &Self) -> bool {
239 self.id == other.id && Rc::ptr_eq(&self.content, &other.content)
240 }
241}
242
243/// Releases the state of [`movable`] content with identity `key` that no
244/// parent is showing. Call it when the item is closed for good, from an
245/// event handler or inside composition. Content a parent is still showing
246/// is unaffected. Needs a runtime: an active composition or one created on
247/// this thread.
248pub fn forget_movable<K: Hash>(key: K) {
249 let id = hash_key(&key);
250 forget_movable_id(id);
251}
252
253fn forget_movable_id(id: Key) {
254 let runtime = composer_context::try_with_composer(Composer::runtime_handle)
255 .or_else(current_runtime_handle);
256 match runtime {
257 Some(runtime) => runtime.forget_movable(id),
258 None => log::error!("forget_movable called without an active runtime"),
259 }
260}