cranpose_core/
callbacks.rs1use std::{
2 cell::{Cell, RefCell},
3 rc::Rc,
4};
5
6use crate::{Composer, ComposerCore, Key, RecomposeScope, ValueSlotHandle, composer_context};
7
8pub struct ParamState<T> {
11 pub(crate) value: Option<T>,
12}
13
14pub trait SharedParam {
17 fn same_allocation(&self, other: &Self) -> bool;
19}
20
21impl<T: ?Sized> SharedParam for Rc<T> {
22 fn same_allocation(&self, other: &Self) -> bool {
23 Self::ptr_eq(self, other)
24 }
25}
26
27impl<T: ?Sized> SharedParam for std::sync::Arc<T> {
28 fn same_allocation(&self, other: &Self) -> bool {
29 Self::ptr_eq(self, other)
30 }
31}
32
33impl<T> ParamState<T> {
34 pub fn update_fields(
39 &mut self,
40 fresh: impl FnOnce() -> T,
41 refresh: impl FnOnce(&mut T) -> bool,
42 ) -> bool {
43 match self.value.as_mut() {
44 Some(stored) => refresh(stored),
45 None => {
46 self.value = Some(fresh());
47 true
48 }
49 }
50 }
51
52 pub fn value(&self) -> Option<T>
54 where
55 T: Clone,
56 {
57 self.value.clone()
58 }
59}
60
61pub struct ParamReturnState<T, R> {
64 params: ParamState<T>,
65 returned: Option<R>,
66}
67
68impl<T, R> ParamReturnState<T, R> {
69 pub fn update_fields(
71 &mut self,
72 fresh: impl FnOnce() -> T,
73 refresh: impl FnOnce(&mut T) -> bool,
74 ) -> bool {
75 self.params.update_fields(fresh, refresh)
76 }
77
78 pub fn value(&self) -> Option<T>
80 where
81 T: Clone,
82 {
83 self.params.value()
84 }
85
86 pub fn returned(&self) -> Option<R>
88 where
89 R: Clone,
90 {
91 self.returned.clone()
92 }
93
94 pub fn store_return(&mut self, value: R) {
96 self.returned = Some(value);
97 }
98}
99
100impl<T, R> Default for ParamReturnState<T, R> {
101 fn default() -> Self {
102 Self {
103 params: ParamState::default(),
104 returned: None,
105 }
106 }
107}
108
109pub fn refresh_param<T: PartialEq + Clone>(stored: &mut T, new: &T) -> bool {
112 if stored == new {
113 return false;
114 }
115 stored.clone_from(new);
116 true
117}
118
119pub fn store_param<T: Clone>(stored: &mut T, new: &T) -> bool {
124 stored.clone_from(new);
125 true
126}
127
128pub fn refresh_shared_param<T: SharedParam + PartialEq + Clone>(stored: &mut T, new: &T) -> bool {
132 if stored.same_allocation(new) || stored == new {
133 return false;
134 }
135 stored.clone_from(new);
136 true
137}
138
139pub struct ParamSlot<T> {
142 val: RefCell<Option<T>>,
143}
144
145impl<T> Default for ParamSlot<T> {
146 fn default() -> Self {
147 Self {
148 val: RefCell::new(None),
149 }
150 }
151}
152
153impl<T> ParamSlot<T> {
154 pub fn set(&self, v: T) {
156 *self.val.borrow_mut() = Some(v);
157 }
158
159 pub fn take(&self) -> Option<T> {
161 self.val.borrow_mut().take()
162 }
163}
164
165type CallbackScopeCell = RefCell<Option<RecomposeScope>>;
166
167struct CallbackShared<F: ?Sized> {
170 owner: CallbackOwner,
171 callback: RefCell<Option<Box<F>>>,
172}
173
174#[derive(Default)]
177struct CallbackOwner {
178 creator_scope: CallbackScopeCell,
180 renders: Cell<bool>,
182}
183
184struct CallbackEntry {
187 _scope: Option<CallbackScopeGuard>,
188}
189
190impl CallbackOwner {
191 #[inline(never)]
196 fn enter(&self) -> Option<CallbackEntry> {
197 if !callback_owner_is_active(&self.creator_scope) {
198 return None;
199 }
200 if !self.renders.get()
201 && (composer_context::has_composer() || !crate::in_applied_snapshot())
202 {
203 self.renders.set(true);
204 }
205 let scope = self.creator_scope.borrow().clone().and_then(|scope| {
206 composer_context::current_composer()
207 .map(|composer| CallbackScopeGuard::push(&composer, scope))
208 });
209 Some(CallbackEntry { _scope: scope })
210 }
211}
212
213struct CallbackScopeGuard {
214 core: Rc<ComposerCore>,
215}
216
217impl CallbackScopeGuard {
218 fn push(composer: &Composer, scope: RecomposeScope) -> Self {
219 composer
220 .core
221 .scope_stack
222 .borrow_mut()
223 .push(crate::composer::ScopeFrame::Made(scope));
224 Self {
225 core: composer.clone_core(),
226 }
227 }
228}
229
230impl Drop for CallbackScopeGuard {
231 fn drop(&mut self) {
232 self.core.scope_stack.borrow_mut().pop();
233 }
234}
235
236fn callback_owner_is_active(scope: &CallbackScopeCell) -> bool {
237 scope
238 .borrow()
239 .as_ref()
240 .is_none_or(RecomposeScope::is_effectively_active)
241}
242
243fn callback_owner_scope(composer: &Composer) -> Option<RecomposeScope> {
244 composer.current_recompose_scope()
245}
246
247pub struct CallbackHolder<F: ?Sized + 'static = dyn FnMut()> {
250 shared: Rc<CallbackShared<F>>,
251}
252
253impl<F: ?Sized + 'static> CallbackHolder<F> {
254 pub fn new() -> Self {
256 Self::default()
257 }
258
259 pub fn update_boxed(&self, callback: Box<F>) {
263 *self.shared.callback.borrow_mut() = Some(callback);
264 *self.shared.owner.creator_scope.borrow_mut() =
265 composer_context::try_with_composer(callback_owner_scope).flatten();
266 }
267
268 pub fn renders(&self) -> bool {
272 self.shared.owner.renders.get()
273 }
274
275 pub fn forwarder(&self) -> CallbackForwarder<F> {
277 CallbackForwarder {
278 shared: Rc::clone(&self.shared),
279 }
280 }
281
282 #[doc(hidden)]
286 pub fn __hold(
287 composer: &Composer,
288 source: Key,
289 callback: Box<F>,
290 ) -> (ValueSlotHandle<'_, Self>, bool) {
291 composer.__update_param_slot(source, Self::new, |holder: &mut Self| {
292 holder.update_boxed(callback);
293 holder.renders()
294 })
295 }
296
297 #[doc(hidden)]
300 pub fn __slot(composer: &Composer, source: Key) -> ValueSlotHandle<'_, Self> {
301 composer.__use_param_slot(source, Self::new)
302 }
303
304 #[doc(hidden)]
306 pub fn __forwarder<'pass>(
307 composer: &'pass Composer,
308 slot: ValueSlotHandle<'pass, Self>,
309 ) -> CallbackForwarder<F> {
310 composer.with_slot_value(slot, Self::forwarder)
311 }
312}
313
314impl<F: ?Sized + 'static> Clone for CallbackHolder<F> {
315 fn clone(&self) -> Self {
316 Self {
317 shared: Rc::clone(&self.shared),
318 }
319 }
320}
321
322impl CallbackHolder {
323 pub fn update(&self, callback: impl FnMut() + 'static) {
325 self.update_boxed(Box::new(callback));
326 }
327
328 pub fn clone_rc(&self) -> impl Fn() + 'static + use<> {
330 let forwarder = self.forwarder();
331 move || forwarder.call(|callback| callback())
332 }
333}
334
335impl<F: ?Sized + 'static> Default for CallbackHolder<F> {
336 fn default() -> Self {
337 Self {
338 shared: Rc::new(CallbackShared {
339 owner: CallbackOwner::default(),
340 callback: RefCell::new(None),
341 }),
342 }
343 }
344}
345
346pub struct CallbackForwarder<F: ?Sized + 'static> {
349 shared: Rc<CallbackShared<F>>,
350}
351
352impl<F: ?Sized + 'static> CallbackForwarder<F> {
353 pub fn call(&self, call: impl FnOnce(&mut F)) {
356 let Some(_entry) = self.shared.owner.enter() else {
357 return;
358 };
359 if let Some(callback) = self.shared.callback.borrow_mut().as_mut() {
360 call(callback);
361 }
362 }
363}
364
365impl<F: ?Sized + 'static> Clone for CallbackForwarder<F> {
366 fn clone(&self) -> Self {
367 Self {
368 shared: Rc::clone(&self.shared),
369 }
370 }
371}
372
373pub struct ReturnSlot<T> {
376 value: Option<T>,
377}
378
379impl<T: Clone> ReturnSlot<T> {
380 pub fn store(&mut self, value: T) {
382 self.value = Some(value);
383 }
384
385 pub fn get(&self) -> Option<T> {
387 self.value.clone()
388 }
389}
390
391impl<T> Default for ParamState<T> {
392 fn default() -> Self {
393 Self { value: None }
394 }
395}
396
397impl<T> Default for ReturnSlot<T> {
398 fn default() -> Self {
399 Self { value: None }
400 }
401}
402
403#[cfg(test)]
404#[path = "tests/callbacks_callback_holder_tests.rs"]
405mod callback_holder_tests;
406
407#[cfg(test)]
408#[path = "tests/callbacks_param_state_tests.rs"]
409mod param_state_tests;