Skip to main content

waft_widgets/widgets/
restoration.rs

1//! Flutter counterpart: `widgets/restoration.dart`.
2//!
3//! The widget-side of state restoration: the scopes that carry a [`RestorationBucket`] down
4//! the tree, the [`RestorableProperty`] a [`State`] stores its data in, and the
5//! [`RestorationMixin`] that ties the two together.
6
7use std::fmt::{self, Debug};
8use std::rc::Rc;
9
10use indexmap::IndexMap;
11use waft_foundation::{
12    App, ChangeNotifier, ChangeNotifierData, Handle, HandleId, ListenableObject, Listener,
13    OptionRetained, Ref, Retained,
14};
15pub use waft_services::RestorationBucket;
16use waft_services::{RestorationData, RestorationManager};
17
18use crate::framework::{
19    BuildContext, InheritedWidget, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
20};
21use crate::widgets::basic::SizedBox;
22
23/// The typed handle for an erased id. Free: nothing is looked up; `get` checks the slot.
24fn resolve<T: 'static>(id: HandleId) -> Handle<T> {
25    Handle::from_id(id)
26}
27
28// ---------------------------------------------------------------------------------------------
29// RestorationScope
30
31/// Creates a new scope for restoration IDs used by descendant widgets to claim
32/// [`RestorationBucket`]s.
33///
34/// A restoration scope inserts a [`RestorationBucket`] into the widget tree, which descendant
35/// widgets can access via [`RestorationScope::of`]. It is uncommon for descendants to directly
36/// store data in this bucket. Instead, descendant widgets should consider storing their own
37/// restoration data in a child bucket claimed with [`RestorationBucket::claim_child`] from the
38/// bucket provided by this scope.
39///
40/// The bucket inserted into the widget tree by this scope has been claimed from the
41/// surrounding [`RestorationScope`] using the provided
42/// [`restoration_id`](Self::restoration_id). If the [`RestorationScope`] is moved to a
43/// different part of the widget tree under a different [`RestorationScope`], the bucket owned
44/// by this scope with all its children and the data contained in them is moved to the new
45/// scope as well.
46///
47/// This widget will not make a [`RestorationBucket`] available to descendants if
48/// [`restoration_id`](Self::restoration_id) is `None` or when there is no surrounding
49/// restoration scope to claim a bucket from. In this case, descendant widgets invoking
50/// [`RestorationScope::of`] will receive `None` as a return value indicating that no bucket is
51/// available for storing restoration data. This will turn off state restoration for the widget
52/// subtree.
53///
54/// See also:
55///
56///  * [`RootRestorationScope`], which inserts the root bucket provided by the
57///    [`RestorationManager`] into the widget tree and makes it accessible for descendants via
58///    [`RestorationScope::of`].
59///  * [`UnmanagedRestorationScope`], which inserts a provided [`RestorationBucket`] into the
60///    widget tree and makes it accessible for descendants via [`RestorationScope::of`].
61///  * [`RestorationMixin`], which may be used in [`State`] objects to manage the restoration
62///    data of a [`StatefulWidget`] instead of manually interacting with [`RestorationScope`]s
63///    and [`RestorationBucket`]s.
64///  * [`RestorationManager`], which describes the basic concepts of state restoration.
65#[derive(Debug)]
66pub struct RestorationScope {
67    /// See [`StatefulWidget::key`].
68    pub key: Option<KeyRef>,
69    /// The widget below this widget in the tree.
70    pub child: WidgetRef,
71    /// The restoration ID used by this widget to obtain a child bucket from the surrounding
72    /// [`RestorationScope`].
73    ///
74    /// The child bucket obtained from the surrounding scope is made available to descendant
75    /// widgets via [`RestorationScope::of`].
76    ///
77    /// If this is `None`, [`RestorationScope::of`] invoked by descendants will return `None`,
78    /// which effectively turns off state restoration for this subtree.
79    pub restoration_id: Option<String>,
80}
81
82impl RestorationScope {
83    /// Creates a [`RestorationScope`].
84    ///
85    /// Providing `None` as the `restoration_id` turns off state restoration for the `child`
86    /// and its descendants.
87    #[cfg_attr(debug_assertions, track_caller)]
88    pub fn new<K>(restoration_id: Option<String>, child: impl IntoWidget<K>) -> RestorationScope {
89        RestorationScope {
90            key: None,
91            child: child.into_widget(),
92            restoration_id,
93        }
94    }
95
96    /// Dart `RestorationScope(key:)`.
97    pub fn key(mut self, key: KeyRef) -> RestorationScope {
98        self.key = Some(key);
99        self
100    }
101
102    /// Returns the [`RestorationBucket`] inserted into the widget tree by the closest ancestor
103    /// [`RestorationScope`] of `context`.
104    ///
105    /// To avoid accidentally overwriting data already stored in the bucket by its owner, data
106    /// should not be stored directly in the bucket returned by this method. Instead, consider
107    /// claiming a child bucket from the returned bucket (via
108    /// [`RestorationBucket::claim_child`]) and store the restoration data in that child.
109    ///
110    /// This method returns `None` if state restoration is turned off for this subtree.
111    ///
112    /// Calling this method will create a dependency on the closest [`RestorationScope`] in the
113    /// `context`, if there is one.
114    ///
115    /// See also:
116    ///
117    ///  * [`RestorationScope::of`], which is similar to this method, but panics if no
118    ///    [`RestorationScope`] ancestor is found.
119    pub fn maybe_of(app: &mut App, context: BuildContext) -> Option<Handle<RestorationBucket>> {
120        context
121            .depend_on_inherited_widget_of_exact_type::<UnmanagedRestorationScope>(app)
122            .and_then(|scope| scope.bucket.handle())
123    }
124
125    /// Returns the [`RestorationBucket`] inserted into the widget tree by the closest ancestor
126    /// [`RestorationScope`] of `context`.
127    ///
128    /// To avoid accidentally overwriting data already stored in the bucket by its owner, data
129    /// should not be stored directly in the bucket returned by this method. Instead, consider
130    /// claiming a child bucket from the returned bucket (via
131    /// [`RestorationBucket::claim_child`]) and store the restoration data in that child.
132    ///
133    /// This method panics if state restoration is turned off for this subtree.
134    ///
135    /// Calling this method will create a dependency on the closest [`RestorationScope`] in the
136    /// `context`.
137    ///
138    /// See also:
139    ///
140    ///  * [`RestorationScope::maybe_of`], which is similar to this method, but returns `None`
141    ///    if no [`RestorationScope`] ancestor is found.
142    pub fn of(app: &mut App, context: BuildContext) -> Handle<RestorationBucket> {
143        Self::maybe_of(app, context).expect(
144            "RestorationScope.of() was called with a context that does not contain a \
145             RestorationScope widget.\n\
146             No RestorationScope widget ancestor could be found starting from the context that \
147             was passed to RestorationScope.of(). This can happen because you are using a \
148             widget that looks for a RestorationScope ancestor, but no such ancestor exists.\n\
149             State restoration must be enabled for a RestorationScope to exist. This can be \
150             done by wrapping the widget tree in a RootRestorationScope.",
151        )
152    }
153}
154
155impl StatefulWidget for RestorationScope {
156    type State = RestorationScopeState;
157
158    fn key(&self) -> Option<&KeyRef> {
159        self.key.as_ref()
160    }
161
162    fn create_state(&self) -> RestorationScopeState {
163        RestorationScopeState {
164            state: StateData::new(),
165            restoration: RestorationMixinData::new(),
166        }
167    }
168}
169
170/// Dart's `_RestorationScopeState`.
171pub struct RestorationScopeState {
172    state: StateData<RestorationScope>,
173    restoration: RestorationMixinData,
174}
175
176impl RestorationMixin for RestorationScopeState {
177    crate::restoration_mixin_accessors!();
178
179    fn restoration_id(self: Handle<Self>, app: &App) -> Option<&str> {
180        self.widget(app).restoration_id.as_deref()
181    }
182
183    fn restore_state(
184        self: Handle<Self>,
185        app: &mut App,
186        old_bucket: Option<Handle<RestorationBucket>>,
187        initial_restore: bool,
188    ) {
189        // Nothing to do.
190        // The bucket gets injected into the widget tree in the build method.
191        let _ = (app, old_bucket, initial_restore);
192    }
193}
194
195impl State for RestorationScopeState {
196    type Widget = RestorationScope;
197    crate::state_accessors!();
198
199    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
200        self.did_change_dependencies_restoration(app);
201    }
202
203    fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &RestorationScope) {
204        self.did_update_restoration_id(app);
205    }
206
207    fn dispose(self: Handle<Self>, app: &mut App) {
208        self.dispose_restoration(app);
209    }
210
211    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
212        // `bucket` is provided by the RestorationMixin.
213        let bucket = self.restoration_mixin_data(app).bucket.clone();
214        let child = self.widget(app).child.clone();
215        UnmanagedRestorationScope::new(child)
216            .bucket(bucket)
217            .into_widget()
218    }
219}
220
221// ---------------------------------------------------------------------------------------------
222// UnmanagedRestorationScope
223
224/// Inserts a provided [`RestorationBucket`] into the widget tree and makes it available to
225/// descendants via [`RestorationScope::of`].
226///
227/// A restoration scope inserts a [`RestorationBucket`] into the widget tree, which descendant
228/// widgets can access via [`RestorationScope::of`]. It is uncommon for descendants to directly
229/// store data in this bucket. Instead, descendant widgets should consider storing their own
230/// restoration data in a child bucket claimed with [`RestorationBucket::claim_child`] from the
231/// bucket provided by this scope.
232///
233/// If [`bucket`](Self::bucket) is `None`, no restoration bucket is made available to descendant
234/// widgets ([`RestorationScope::of`] invoked from a descendant will return `None`). This
235/// effectively turns off state restoration for the subtree because no bucket for storing
236/// restoration data is made available.
237///
238/// See also:
239///
240///  * [`RestorationScope`], which inserts a bucket obtained from a surrounding restoration
241///    scope into the widget tree and makes it accessible for descendants via
242///    [`RestorationScope::of`].
243///  * [`RootRestorationScope`], which inserts the root bucket provided by the
244///    [`RestorationManager`] into the widget tree and makes it accessible for descendants via
245///    [`RestorationScope::of`].
246///  * [`RestorationMixin`], which may be used in [`State`] objects to manage the restoration
247///    data of a [`StatefulWidget`] instead of manually interacting with [`RestorationScope`]s
248///    and [`RestorationBucket`]s.
249///  * [`RestorationManager`], which describes the basic concepts of state restoration.
250#[derive(Debug)]
251pub struct UnmanagedRestorationScope {
252    /// See [`InheritedWidget::key`].
253    pub key: Option<KeyRef>,
254    /// The [`RestorationBucket`] that this widget will insert into the widget tree.
255    ///
256    /// Descendant widgets may obtain this bucket via [`RestorationScope::of`].
257    pub bucket: Option<Ref<RestorationBucket>>,
258    /// The widget below this widget in the tree.
259    pub child: WidgetRef,
260}
261
262impl UnmanagedRestorationScope {
263    /// Creates an [`UnmanagedRestorationScope`].
264    ///
265    /// When [`bucket`](Self::bucket) is `None` state restoration is turned off for the `child`
266    /// and its descendants.
267    #[cfg_attr(debug_assertions, track_caller)]
268    pub fn new<K>(child: impl IntoWidget<K>) -> UnmanagedRestorationScope {
269        UnmanagedRestorationScope {
270            key: None,
271            bucket: None,
272            child: child.into_widget(),
273        }
274    }
275
276    /// Dart `UnmanagedRestorationScope(key:)`.
277    pub fn key(mut self, key: KeyRef) -> UnmanagedRestorationScope {
278        self.key = Some(key);
279        self
280    }
281
282    /// Dart `UnmanagedRestorationScope(bucket:)`; `None` turns off state restoration for the
283    /// subtree.
284    pub fn bucket(mut self, bucket: Option<Ref<RestorationBucket>>) -> UnmanagedRestorationScope {
285        self.bucket = bucket;
286        self
287    }
288}
289
290impl InheritedWidget for UnmanagedRestorationScope {
291    fn key(&self) -> Option<&KeyRef> {
292        self.key.as_ref()
293    }
294
295    fn child(&self) -> &WidgetRef {
296        &self.child
297    }
298
299    fn update_should_notify(&self, old_widget: &UnmanagedRestorationScope) -> bool {
300        old_widget.bucket != self.bucket
301    }
302}
303
304// ---------------------------------------------------------------------------------------------
305// RootRestorationScope
306
307/// Inserts a child bucket of [`RestorationManager::root_bucket`] into the widget tree and makes
308/// it available to descendants via [`RestorationScope::of`].
309///
310/// This widget is usually used near the root of the widget tree to enable the state restoration
311/// functionality for the application. For all other use cases, consider using a regular
312/// [`RestorationScope`] instead.
313///
314/// The exact behavior of this widget depends on its ancestors: When the [`RootRestorationScope`]
315/// does not find an ancestor restoration bucket via [`RestorationScope::of`] it will claim a
316/// child bucket from the root restoration bucket ([`RestorationManager::root_bucket`]) using the
317/// provided [`restoration_id`](Self::restoration_id) and inserts that bucket into the widget
318/// tree where descendants may access it via [`RestorationScope::of`]. If the
319/// [`RootRestorationScope`] finds a non-`None` ancestor restoration bucket via
320/// [`RestorationScope::of`] it will behave like a regular [`RestorationScope`] instead: It will
321/// claim a child bucket from that ancestor and insert that child into the widget tree.
322///
323/// Unlike the [`RestorationScope`] widget, the [`RootRestorationScope`] will guarantee that
324/// descendants have a bucket available for storing restoration data as long as
325/// [`restoration_id`](Self::restoration_id) is not `None` and [`RestorationManager`] is able to
326/// provide a root bucket. In other words, it will force-enable state restoration for the subtree
327/// if [`restoration_id`](Self::restoration_id) is not `None`.
328///
329/// If [`restoration_id`](Self::restoration_id) is `None`, no bucket is made available to
330/// descendants, which effectively turns off state restoration for this subtree.
331///
332/// See also:
333///
334///  * [`RestorationScope`], which inserts a bucket obtained from a surrounding restoration
335///    scope into the widget tree and makes it accessible for descendants via
336///    [`RestorationScope::of`].
337///  * [`UnmanagedRestorationScope`], which inserts a provided [`RestorationBucket`] into the
338///    widget tree and makes it accessible for descendants via [`RestorationScope::of`].
339///  * [`RestorationMixin`], which may be used in [`State`] objects to manage the restoration
340///    data of a [`StatefulWidget`] instead of manually interacting with [`RestorationScope`]s
341///    and [`RestorationBucket`]s.
342///  * [`RestorationManager`], which describes the basic concepts of state restoration.
343#[derive(Debug)]
344pub struct RootRestorationScope {
345    /// See [`StatefulWidget::key`].
346    pub key: Option<KeyRef>,
347    /// The widget below this widget in the tree.
348    pub child: WidgetRef,
349    /// The restoration ID used to identify the child bucket that this widget will insert into
350    /// the tree.
351    ///
352    /// If this is `None`, no bucket is made available to descendants and state restoration for
353    /// the subtree is essentially turned off.
354    pub restoration_id: Option<String>,
355}
356
357impl RootRestorationScope {
358    /// Creates a [`RootRestorationScope`].
359    ///
360    /// Providing `None` as the `restoration_id` turns off state restoration for the `child` and
361    /// its descendants.
362    #[cfg_attr(debug_assertions, track_caller)]
363    pub fn new<K>(
364        restoration_id: Option<String>,
365        child: impl IntoWidget<K>,
366    ) -> RootRestorationScope {
367        RootRestorationScope {
368            key: None,
369            child: child.into_widget(),
370            restoration_id,
371        }
372    }
373
374    /// Dart `RootRestorationScope(key:)`.
375    pub fn key(mut self, key: KeyRef) -> RootRestorationScope {
376        self.key = Some(key);
377        self
378    }
379}
380
381impl StatefulWidget for RootRestorationScope {
382    type State = RootRestorationScopeState;
383
384    fn key(&self) -> Option<&KeyRef> {
385        self.key.as_ref()
386    }
387
388    fn create_state(&self) -> RootRestorationScopeState {
389        RootRestorationScopeState {
390            state: StateData::new(),
391            ok_to_render_blank_container: None,
392            root_bucket_valid: false,
393            root_bucket: None,
394            ancestor_bucket: None,
395            is_loading_root_bucket: false,
396        }
397    }
398}
399
400/// Dart's `_RootRestorationScopeState`.
401pub struct RootRestorationScopeState {
402    state: StateData<RootRestorationScope>,
403    ok_to_render_blank_container: Option<bool>,
404    root_bucket_valid: bool,
405    root_bucket: Option<Ref<RestorationBucket>>,
406    ancestor_bucket: Option<Ref<RestorationBucket>>,
407    is_loading_root_bucket: bool,
408}
409
410impl RootRestorationScopeState {
411    fn needs_root_bucket_inserted(self: Handle<Self>, app: &App) -> bool {
412        app.get(self).ancestor_bucket.is_none()
413    }
414
415    fn is_waiting_for_root_bucket(self: Handle<Self>, app: &App) -> bool {
416        self.widget(app).restoration_id.is_some()
417            && self.needs_root_bucket_inserted(app)
418            && !app.get(self).root_bucket_valid
419    }
420
421    /// Dart's `_loadRootBucketIfNecessary`.
422    ///
423    /// [`RestorationManager::root_bucket`] answers within the call, so what Dart runs from the
424    /// future's continuation runs here inline.
425    fn load_root_bucket_if_necessary(self: Handle<Self>, app: &mut App) {
426        if self.is_waiting_for_root_bucket(app) && !app.get(self).is_loading_root_bucket {
427            app.get_mut(self).is_loading_root_bucket = true;
428            let manager = RestorationManager::instance(app);
429            let bucket = manager.root_bucket(app).map(|bucket| bucket.keep(app));
430            app.get_mut(self).is_loading_root_bucket = false;
431            if self.mounted(app) {
432                manager.add_listener(
433                    app,
434                    Listener::handle_method(self, Self::replace_root_bucket),
435                );
436                self.set_state(app, |state| {
437                    state.root_bucket = bucket;
438                    state.root_bucket_valid = true;
439                    state.ok_to_render_blank_container = Some(false);
440                });
441            }
442        }
443    }
444
445    /// Dart's `_replaceRootBucket`: the [`RestorationManager`] listener that picks up newly
446    /// provided restoration data.
447    fn replace_root_bucket(self: Handle<Self>, app: &mut App) {
448        app.get_mut(self).root_bucket_valid = false;
449        app.get_mut(self).root_bucket = None;
450        let manager = RestorationManager::instance(app);
451        manager.remove_listener(
452            app,
453            &Listener::handle_method(self, Self::replace_root_bucket),
454        );
455        self.load_root_bucket_if_necessary(app);
456        // Ensure that load finished synchronously.
457        debug_assert!(!self.is_waiting_for_root_bucket(app));
458    }
459}
460
461impl State for RootRestorationScopeState {
462    type Widget = RootRestorationScope;
463    crate::state_accessors!();
464
465    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
466        let context = self.context(app);
467        let ancestor_bucket =
468            RestorationScope::maybe_of(app, context).map(|bucket| bucket.keep(app));
469        app.get_mut(self).ancestor_bucket = ancestor_bucket;
470        self.load_root_bucket_if_necessary(app);
471        if app.get(self).ok_to_render_blank_container.is_none() {
472            let ok_to_render_blank_container =
473                self.widget(app).restoration_id.is_some() && self.needs_root_bucket_inserted(app);
474            app.get_mut(self).ok_to_render_blank_container = Some(ok_to_render_blank_container);
475        }
476    }
477
478    fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &RootRestorationScope) {
479        self.load_root_bucket_if_necessary(app);
480    }
481
482    fn dispose(self: Handle<Self>, app: &mut App) {
483        if app.get(self).root_bucket_valid {
484            let manager = RestorationManager::instance(app);
485            manager.remove_listener(
486                app,
487                &Listener::handle_method(self, Self::replace_root_bucket),
488            );
489        }
490    }
491
492    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
493        let ok_to_render_blank_container = app
494            .get(self)
495            .ok_to_render_blank_container
496            .expect("didChangeDependencies runs before the first build");
497        if ok_to_render_blank_container && self.is_waiting_for_root_bucket(app) {
498            return SizedBox::shrink().into_widget();
499        }
500
501        let this = app.get(self);
502        let bucket = this
503            .ancestor_bucket
504            .clone()
505            .or_else(|| this.root_bucket.clone());
506        let restoration_id = self.widget(app).restoration_id.clone();
507        let child = self.widget(app).child.clone();
508        UnmanagedRestorationScope::new(RestorationScope::new(restoration_id, child))
509            .bucket(bucket)
510            .into_widget()
511    }
512}
513
514// ---------------------------------------------------------------------------------------------
515// RestorableProperty
516
517/// The framework's part of a [`RestorableProperty`]: the ID and owner it is registered under.
518pub struct RestorablePropertyData {
519    // ID under which the property has been registered with the RestorationMixin.
520    restoration_id: Option<String>,
521    owner: Option<AnyRestorationMixin>,
522    disposed: bool,
523}
524
525impl RestorablePropertyData {
526    /// A property that is not registered with any [`RestorationMixin`].
527    pub fn new() -> RestorablePropertyData {
528        RestorablePropertyData {
529            restoration_id: None,
530            owner: None,
531            disposed: false,
532        }
533    }
534}
535
536impl Default for RestorablePropertyData {
537    fn default() -> RestorablePropertyData {
538        RestorablePropertyData::new()
539    }
540}
541
542/// The accessors [`RestorableProperty`] asks for, for a struct whose bag is the field
543/// `property`.
544#[macro_export]
545macro_rules! restorable_property_accessors {
546    () => {
547        fn restorable_property_data(
548            self: ::waft_foundation::Handle<Self>,
549            app: &::waft_foundation::App,
550        ) -> &$crate::RestorablePropertyData {
551            &app.get(self).property
552        }
553
554        fn restorable_property_data_mut(
555            self: ::waft_foundation::Handle<Self>,
556            app: &mut ::waft_foundation::App,
557        ) -> &mut $crate::RestorablePropertyData {
558            &mut app.get_mut(self).property
559        }
560    };
561}
562
563/// Manages an object of type [`Value`](Self::Value), whose value a [`State`] object wants to
564/// have restored during state restoration.
565///
566/// The property wraps an object of type [`Value`](Self::Value). It knows how to store its value
567/// in the restoration data and it knows how to re-instantiate that object from the information
568/// it previously stored in the restoration data.
569///
570/// The knowledge of how to store the wrapped object in the restoration data is encoded in the
571/// [`to_primitives`](Self::to_primitives) method and the knowledge of how to re-instantiate the
572/// object from that data is encoded in the [`from_primitives`](Self::from_primitives) method. At
573/// a later point in time (which may be after the application restarted), the data obtained from
574/// [`to_primitives`](Self::to_primitives) may be handed back to the property's
575/// [`from_primitives`](Self::from_primitives) method to restore it to the previous state
576/// described by that data.
577///
578/// A [`RestorableProperty`] needs to be registered to a [`RestorationMixin`] using a restoration
579/// ID that is unique within the mixin. The [`RestorationMixin`] provides and manages the
580/// [`RestorationBucket`], in which the data returned by [`to_primitives`](Self::to_primitives)
581/// is stored.
582///
583/// Whenever the value returned by [`to_primitives`](Self::to_primitives) (or the
584/// [`enabled`](Self::enabled) getter) changes, the [`RestorableProperty`] must call
585/// `notify_listeners`. This will trigger the [`RestorationMixin`] to update the data it has
586/// stored for the property in its [`RestorationBucket`] to the latest information returned by
587/// [`to_primitives`](Self::to_primitives).
588///
589/// When the property is registered with the [`RestorationMixin`], the mixin checks whether there
590/// is any restoration data available for the property. If data is available, the mixin calls
591/// [`from_primitives`](Self::from_primitives) on the property, which must return an object that
592/// matches the object the property wrapped when the provided restoration data was obtained from
593/// [`to_primitives`](Self::to_primitives). If no restoration data is available to restore the
594/// property's wrapped object from, the mixin calls
595/// [`create_default_value`](Self::create_default_value). The value returned by either of those
596/// methods is then handed to the property's [`init_with_value`](Self::init_with_value) method.
597///
598/// Usually, implementors of [`RestorableProperty`] hold on to the value provided to them in
599/// [`init_with_value`](Self::init_with_value) and make it accessible to the [`State`] object
600/// that owns the property. This base trait, however, has no opinion about what to do with the
601/// value provided to [`init_with_value`](Self::init_with_value).
602///
603/// The [`RestorationMixin`] may call
604/// [`from_primitives`](Self::from_primitives) / [`create_default_value`](Self::create_default_value)
605/// followed by [`init_with_value`](Self::init_with_value) multiple times throughout the life of
606/// a [`RestorableProperty`]: Whenever new restoration data is made available to the
607/// [`RestorationMixin`] the property is registered with, the cycle repeats. Whenever
608/// [`init_with_value`](Self::init_with_value) is called, the property should forget the old
609/// value it was wrapping and re-initialize itself with the newly provided value.
610///
611/// In a typical use case, a [`RestorableProperty`] is instantiated to initialize a member
612/// variable of a [`State`] object or within `State::init_state`. It is then registered to a
613/// [`RestorationMixin`] in [`RestorationMixin::restore_state`] and later
614/// [`dispose`](Self::dispose)d in `State::dispose`.
615///
616/// See also:
617///
618///  * [`RestorableValue`](crate::RestorableValue), which is a [`RestorableProperty`] that makes
619///    the wrapped value accessible to the owning [`State`] object via a `value` getter and
620///    setter.
621///  * [`RestorationMixin`], to which a [`RestorableProperty`] must be registered.
622///  * [`RestorationManager`], which describes how state restoration works.
623pub trait RestorableProperty: ChangeNotifier + Sized + 'static {
624    /// The object this property wraps; Dart's type argument `T`.
625    type Value;
626
627    /// The registration with a [`RestorationMixin`], held under the field `property`
628    /// ([`restorable_property_accessors!`](crate::restorable_property_accessors)).
629    fn restorable_property_data(self: Handle<Self>, app: &App) -> &RestorablePropertyData;
630
631    /// See [`restorable_property_data`](Self::restorable_property_data).
632    fn restorable_property_data_mut(
633        self: Handle<Self>,
634        app: &mut App,
635    ) -> &mut RestorablePropertyData;
636
637    /// Called by the [`RestorationMixin`] if no restoration data is available to restore the
638    /// value of the property from, to obtain the default value for the property.
639    ///
640    /// The method returns the default value that the property should wrap if no restoration
641    /// data is available. After this is called, [`init_with_value`](Self::init_with_value) will
642    /// be called with this method's return value.
643    ///
644    /// The method may be called multiple times throughout the life of the
645    /// [`RestorableProperty`]. Whenever new restoration data has been provided to the
646    /// [`RestorationMixin`] the property is registered to, either this method or
647    /// [`from_primitives`](Self::from_primitives) is called before
648    /// [`init_with_value`](Self::init_with_value) is invoked.
649    fn create_default_value(self: Handle<Self>, app: &mut App) -> Self::Value;
650
651    /// Called by the [`RestorationMixin`] to convert the `data` previously retrieved from
652    /// [`to_primitives`](Self::to_primitives) back into an object of type
653    /// [`Value`](Self::Value) that this property should wrap.
654    ///
655    /// The object returned by this method is passed to
656    /// [`init_with_value`](Self::init_with_value) to restore the value that this property is
657    /// wrapping to the value described by the provided `data`.
658    ///
659    /// The method may be called multiple times throughout the life of the
660    /// [`RestorableProperty`]. Whenever new restoration data has been provided to the
661    /// [`RestorationMixin`] the property is registered to, either this method or
662    /// [`create_default_value`](Self::create_default_value) is called before
663    /// [`init_with_value`](Self::init_with_value) is invoked.
664    fn from_primitives(self: Handle<Self>, app: &mut App, data: &RestorationData) -> Self::Value;
665
666    /// Called by the [`RestorationMixin`] with the `value` returned by either
667    /// [`create_default_value`](Self::create_default_value) or
668    /// [`from_primitives`](Self::from_primitives) to set the value that this property currently
669    /// wraps.
670    ///
671    /// This method may be called multiple times throughout the life of the
672    /// [`RestorableProperty`] whenever new restoration data has been provided to the
673    /// [`RestorationMixin`] the property is registered to. When it is called, the property
674    /// should forget its previous value and re-initialize itself to the newly provided `value`.
675    fn init_with_value(self: Handle<Self>, app: &mut App, value: Self::Value);
676
677    /// Called by the [`RestorationMixin`] to retrieve the information that this property wants
678    /// to store in the restoration data.
679    ///
680    /// The information returned by this method may be handed back to the property in a call to
681    /// [`from_primitives`](Self::from_primitives) at a later point in time (possibly after the
682    /// application restarted) to restore the value that the property is currently wrapping.
683    ///
684    /// When the value returned by this method changes, the property must call
685    /// `notify_listeners`. The [`RestorationMixin`] will invoke this method whenever the
686    /// property's listeners are notified.
687    fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData;
688
689    /// Whether the object currently returned by [`to_primitives`](Self::to_primitives) should
690    /// be included in the restoration state.
691    ///
692    /// When this returns false, no information is included in the restoration data for this
693    /// property and the property will be initialized to its default value (obtained from
694    /// [`create_default_value`](Self::create_default_value)) the next time that restoration
695    /// data is used for state restoration.
696    ///
697    /// Whenever the value returned by this getter changes, `notify_listeners` must be called.
698    /// When the value changes from true to false, the information last retrieved from
699    /// [`to_primitives`](Self::to_primitives) is removed from the restoration data. When it
700    /// changes from false to true, [`to_primitives`](Self::to_primitives) is invoked to add the
701    /// latest restoration information provided by this property to the restoration data.
702    fn enabled(self: Handle<Self>, app: &App) -> bool {
703        let _ = (self, app);
704        true
705    }
706
707    /// Dart's `RestorableProperty.dispose` body. An override that runs `super.dispose()`
708    /// calls this.
709    fn dispose_property(self: Handle<Self>, app: &mut App) {
710        debug_assert!(ChangeNotifierData::debug_assert_not_disposed(
711            app.get(self).change_notifier_data()
712        ));
713        if let Some(owner) = self.restorable_property_data(app).owner {
714            owner.unregister(app, self.as_property());
715        }
716        ChangeNotifierData::dispose(app, self);
717        self.restorable_property_data_mut(app).disposed = true;
718        self.did_dispose(app);
719    }
720
721    /// Discards any resources used by the property, unregistering it from its owner.
722    fn dispose(self: Handle<Self>, app: &mut App) {
723        self.dispose_property(app);
724    }
725
726    /// Runs at the end of [`dispose`](Self::dispose): what a Dart override does after its
727    /// `super.dispose()` call.
728    fn did_dispose(self: Handle<Self>, app: &mut App) {
729        let _ = (self, app);
730    }
731
732    /// The [`State`] object that this property is registered with.
733    ///
734    /// Must only be called when [`is_registered`](Self::is_registered) is true.
735    fn state(self: Handle<Self>, app: &App) -> AnyRestorationMixin {
736        debug_assert!(self.is_registered(app));
737        self.restorable_property_data(app)
738            .owner
739            .expect("a registered property has an owner")
740    }
741
742    /// Whether this property is currently registered with a [`RestorationMixin`].
743    fn is_registered(self: Handle<Self>, app: &App) -> bool {
744        debug_assert!(ChangeNotifierData::debug_assert_not_disposed(
745            app.get(self).change_notifier_data()
746        ));
747        self.restorable_property_data(app).restoration_id.is_some()
748    }
749
750    /// This property as the erased [`AnyRestorableProperty`] — what to pass where a Dart API
751    /// takes a `RestorableProperty<Object?>`.
752    fn as_property(self: Handle<Self>) -> AnyRestorableProperty {
753        AnyRestorableProperty {
754            id: self.id(),
755            vtable: const { &RestorablePropertyVTable::of::<Self>() },
756        }
757    }
758}
759
760/// The type-erased handle's slots for one [`RestorableProperty`] implementor.
761struct RestorablePropertyVTable {
762    type_name: fn() -> &'static str,
763    data: fn(&App, HandleId) -> &RestorablePropertyData,
764    data_mut: fn(&mut App, HandleId) -> &mut RestorablePropertyData,
765    restore: fn(&mut App, HandleId, Option<&RestorationData>),
766    to_primitives: fn(&App, HandleId) -> RestorationData,
767    enabled: fn(&App, HandleId) -> bool,
768    add_listener: fn(&mut App, HandleId, Listener),
769    remove_listener: fn(&mut App, HandleId, &Listener),
770}
771
772impl RestorablePropertyVTable {
773    /// The table for one property type.
774    const fn of<P: RestorableProperty>() -> RestorablePropertyVTable {
775        RestorablePropertyVTable {
776            type_name: std::any::type_name::<P>,
777            data: |app, id| P::restorable_property_data(resolve(id), app),
778            data_mut: |app, id| P::restorable_property_data_mut(resolve(id), app),
779            restore: |app, id, data| {
780                let property: Handle<P> = resolve(id);
781                let value = match data {
782                    Some(data) => P::from_primitives(property, app, data),
783                    None => P::create_default_value(property, app),
784                };
785                P::init_with_value(property, app, value);
786            },
787            to_primitives: |app, id| P::to_primitives(resolve(id), app),
788            enabled: |app, id| P::enabled(resolve(id), app),
789            add_listener: |app, id, listener| {
790                ListenableObject::add_listener(resolve::<P>(id), app, listener)
791            },
792            remove_listener: |app, id, listener| {
793                ListenableObject::remove_listener(resolve::<P>(id), app, listener)
794            },
795        }
796    }
797}
798
799/// Erased [`RestorableProperty`]: one identity and a static vtable, the fat pointer rustc
800/// cannot build for an arena id. No lease.
801///
802/// This is what Dart's `RestorableProperty<Object?>` becomes — the type a [`RestorationMixin`]
803/// keeps its registered properties as. The property itself stays in the [`App`] under its own
804/// type, and [`downcast`](Self::downcast) gets the typed handle back.
805///
806/// Equality is Dart's `==` on an object reference: two handles are equal exactly when they address
807/// the same property.
808#[derive(Clone, Copy)]
809pub struct AnyRestorableProperty {
810    id: HandleId,
811    vtable: &'static RestorablePropertyVTable,
812}
813
814/// A field Dart types as the erased object, kept: AnyRestorableProperty with its count.
815pub type RestorablePropertyRef = Retained<AnyRestorableProperty>;
816
817waft_foundation::erased_handle!(AnyRestorableProperty: RestorableProperty => RestorableProperty::as_property);
818
819impl Debug for AnyRestorableProperty {
820    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
821        write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
822    }
823}
824
825impl AnyRestorableProperty {
826    /// The arena id behind this handle.
827    pub fn id(self) -> HandleId {
828        self.id
829    }
830
831    /// Dart's `property as T`: the typed handle when this property is a `T`, else `None`.
832    pub fn downcast<T: 'static>(self, app: &App) -> Option<Handle<T>> {
833        app.handle::<T>(self.id)
834    }
835
836    fn data(self, app: &App) -> &RestorablePropertyData {
837        (self.vtable.data)(app, self.id)
838    }
839
840    fn data_mut(self, app: &mut App) -> &mut RestorablePropertyData {
841        (self.vtable.data_mut)(app, self.id)
842    }
843
844    /// The ID under which the property is registered with its owner.
845    pub fn restoration_id(self, app: &App) -> Option<&str> {
846        self.data(app).restoration_id.as_deref()
847    }
848
849    /// The [`RestorationMixin`] this property is registered with; Dart's `_owner`.
850    pub fn owner(self, app: &App) -> Option<AnyRestorationMixin> {
851        self.data(app).owner
852    }
853
854    /// See [`RestorableProperty::is_registered`].
855    pub fn is_registered(self, app: &App) -> bool {
856        self.data(app).restoration_id.is_some()
857    }
858
859    /// Whether [`RestorableProperty::dispose`] has run.
860    pub fn disposed(self, app: &App) -> bool {
861        self.data(app).disposed
862    }
863
864    /// See [`RestorableProperty::enabled`].
865    pub fn enabled(self, app: &App) -> bool {
866        (self.vtable.enabled)(app, self.id)
867    }
868
869    /// See [`RestorableProperty::to_primitives`].
870    pub fn to_primitives(self, app: &App) -> RestorationData {
871        (self.vtable.to_primitives)(app, self.id)
872    }
873
874    /// Dart's `property.initWithValue(data != null ? property.fromPrimitives(data) : property.createDefaultValue())`.
875    ///
876    /// `None` is Dart's "no serialized value for this property"; a stored
877    /// [`RestorationData::Null`] arrives as `Some`.
878    pub fn restore(self, app: &mut App, data: Option<&RestorationData>) {
879        (self.vtable.restore)(app, self.id, data);
880    }
881
882    /// See [`Listenable::add_listener`](waft_foundation::Listenable::add_listener).
883    pub fn add_listener(self, app: &mut App, listener: Listener) {
884        (self.vtable.add_listener)(app, self.id, listener);
885    }
886
887    /// See [`Listenable::remove_listener`](waft_foundation::Listenable::remove_listener).
888    pub fn remove_listener(self, app: &mut App, listener: &Listener) {
889        (self.vtable.remove_listener)(app, self.id, listener);
890    }
891
892    /// Dart's `RestorableProperty._register`.
893    fn register(self, app: &mut App, restoration_id: &str, owner: AnyRestorationMixin) {
894        let data = self.data_mut(app);
895        data.restoration_id = Some(restoration_id.to_string());
896        data.owner = Some(owner);
897    }
898
899    /// Dart's `RestorableProperty._unregister`.
900    fn unregister(self, app: &mut App) {
901        let data = self.data_mut(app);
902        debug_assert!(data.restoration_id.is_some());
903        debug_assert!(data.owner.is_some());
904        data.restoration_id = None;
905        data.owner = None;
906    }
907}
908
909// ---------------------------------------------------------------------------------------------
910// RestorationMixin
911
912/// Dart's private members of `RestorationMixin`; a [`State`] using the mixin carries this bag
913/// under the field `restoration`.
914pub struct RestorationMixinData {
915    bucket: Option<Ref<RestorationBucket>>,
916    // Maps properties to their listeners.
917    properties: IndexMap<RestorablePropertyRef, Listener>,
918    debug_properties_waiting_for_reregistration: Option<Vec<RestorablePropertyRef>>,
919    first_restore_pending: bool,
920    current_parent: Option<Ref<RestorationBucket>>,
921}
922
923impl RestorationMixinData {
924    /// A state that has not claimed a bucket yet.
925    pub fn new() -> RestorationMixinData {
926        RestorationMixinData {
927            bucket: None,
928            properties: IndexMap::new(),
929            debug_properties_waiting_for_reregistration: None,
930            first_restore_pending: true,
931            current_parent: None,
932        }
933    }
934}
935
936impl Default for RestorationMixinData {
937    fn default() -> RestorationMixinData {
938        RestorationMixinData::new()
939    }
940}
941
942/// The accessors [`RestorationMixin`] asks for, for a state whose bag is the field
943/// `restoration`.
944#[macro_export]
945macro_rules! restoration_mixin_accessors {
946    () => {
947        fn restoration_mixin_data(
948            self: ::waft_foundation::Handle<Self>,
949            app: &::waft_foundation::App,
950        ) -> &$crate::RestorationMixinData {
951            &app.get(self).restoration
952        }
953
954        fn restoration_mixin_data_mut(
955            self: ::waft_foundation::Handle<Self>,
956            app: &mut ::waft_foundation::App,
957        ) -> &mut $crate::RestorationMixinData {
958            &mut app.get_mut(self).restoration
959        }
960    };
961}
962
963/// Manages the restoration data for a [`State`] object of a [`StatefulWidget`].
964///
965/// Restoration data can be serialized out and, at a later point in time, be used to restore the
966/// stateful members in the [`State`] object to the same values they had when the data was
967/// generated.
968///
969/// This trait organizes the restoration data of a [`State`] object in
970/// [`RestorableProperty`]s. All the information that the [`State`] object wants to get restored
971/// during state restoration needs to be saved in a [`RestorableProperty`]. For example, to
972/// restore the count value in a counter app, that value should be stored in a member of type
973/// [`RestorableInt`](crate::RestorableInt) instead of a plain `i64` member.
974///
975/// The mixin ensures that the current values of the [`RestorableProperty`]s are serialized as
976/// part of the restoration state. It is up to the [`State`] to ensure that the data stored in
977/// the properties is always up to date. When the widget is restored from previously generated
978/// restoration data, the values of the [`RestorableProperty`]s are automatically restored to the
979/// values they had when the restoration data was serialized out.
980///
981/// Within a [`State`] that uses this mixin, [`RestorableProperty`]s are usually instantiated to
982/// initialize member variables. Users of the mixin must implement
983/// [`restore_state`](Self::restore_state) and register their previously instantiated
984/// [`RestorableProperty`]s in this method by calling
985/// [`register_for_restoration`](Self::register_for_restoration). The mixin calls this method for
986/// the first time right after `State::init_state`. After registration, the values stored in the
987/// property have either been restored to their previous value or - if no restoration data for
988/// restoring is available - they are initialized with a property-specific default value. At the
989/// end of a [`State`] object's life cycle, all restorable properties must be disposed in
990/// `State::dispose`.
991///
992/// In addition to being invoked right after `State::init_state`,
993/// [`restore_state`](Self::restore_state) is invoked again when new restoration data has been
994/// provided to the mixin. When this happens, the [`State`] object must re-register all
995/// properties with [`register_for_restoration`](Self::register_for_restoration) again to restore
996/// them to their previous values as described by the new restoration data. All initialization
997/// logic that depends on the current value of a restorable property should be included in the
998/// [`restore_state`](Self::restore_state) method to ensure it re-executes when the properties
999/// are restored to a different value during the life time of the [`State`] object.
1000///
1001/// Internally, the mixin stores the restoration data from all registered properties in a
1002/// [`RestorationBucket`] claimed from the surrounding [`RestorationScope`] using the
1003/// [`State`]-provided [`restoration_id`](Self::restoration_id). The
1004/// [`restoration_id`](Self::restoration_id) must be unique in the surrounding
1005/// [`RestorationScope`]. State restoration is disabled for the [`State`] object using this mixin
1006/// if [`restoration_id`](Self::restoration_id) is `None` or when there is no surrounding
1007/// [`RestorationScope`]. In that case, the values of the registered properties will not be
1008/// restored during state restoration.
1009///
1010/// The [`RestorationBucket`] used to store the registered properties is available via the
1011/// [`bucket`](Self::bucket) getter. Interacting directly with the bucket is uncommon, but the
1012/// [`State`] object may make this bucket available for its descendants to claim child buckets
1013/// from. For that, the [`bucket`](Self::bucket) is injected into the widget tree in
1014/// `State::build` with the help of an [`UnmanagedRestorationScope`].
1015///
1016/// The [`bucket`](Self::bucket) getter returns `None` if state restoration is turned off. If
1017/// state restoration is turned on or off during the lifetime of the widget (e.g. because
1018/// [`restoration_id`](Self::restoration_id) changes from `None` to non-`None`) the value
1019/// returned by the getter will also change. The mixin calls
1020/// [`did_toggle_bucket`](Self::did_toggle_bucket) on itself to notify the [`State`] object about
1021/// this change. Implementing that method is not necessary as long as the [`State`] object does
1022/// not directly interact with the [`bucket`](Self::bucket).
1023///
1024/// Whenever the value returned by [`restoration_id`](Self::restoration_id) changes,
1025/// [`did_update_restoration_id`](Self::did_update_restoration_id) must be called.
1026///
1027/// The [`State`] using this trait calls
1028/// [`did_change_dependencies_restoration`](Self::did_change_dependencies_restoration) from its
1029/// `State::did_change_dependencies`,
1030/// [`did_update_restoration_id`](Self::did_update_restoration_id) from its
1031/// `State::did_update_widget`, and [`dispose_restoration`](Self::dispose_restoration) from its
1032/// `State::dispose`, where Dart's mixin body would run.
1033///
1034/// See also:
1035///
1036///  * [`RestorableProperty`], which is the base trait for all restoration properties managed by
1037///    this mixin.
1038///  * [`RestorationManager`], which describes how state restoration works.
1039///  * [`RestorationScope`], which creates a new namespace for restoration IDs in the widget
1040///    tree.
1041pub trait RestorationMixin: State + Sized + 'static {
1042    /// Dart's `RestorationMixin` fields, held under the field `restoration`
1043    /// ([`restoration_mixin_accessors!`](crate::restoration_mixin_accessors)).
1044    fn restoration_mixin_data(self: Handle<Self>, app: &App) -> &RestorationMixinData;
1045
1046    /// See [`restoration_mixin_data`](Self::restoration_mixin_data).
1047    fn restoration_mixin_data_mut(self: Handle<Self>, app: &mut App) -> &mut RestorationMixinData;
1048
1049    /// The restoration ID used for the [`RestorationBucket`] in which the mixin will store the
1050    /// restoration data of all registered properties.
1051    ///
1052    /// The restoration ID is used to claim a child bucket from the surrounding
1053    /// [`RestorationScope`] (accessed via [`RestorationScope::of`]) and the ID must be unique in
1054    /// that scope (otherwise the end of the frame panics in debug mode).
1055    ///
1056    /// State restoration for this mixin is turned off when this getter returns `None` or when
1057    /// there is no surrounding [`RestorationScope`] available. When state restoration is turned
1058    /// off, the values of the registered properties cannot be restored.
1059    ///
1060    /// Whenever the value returned by this getter changes,
1061    /// [`did_update_restoration_id`](Self::did_update_restoration_id) must be called.
1062    ///
1063    /// The restoration ID returned by this getter is often a field of the [`StatefulWidget`]
1064    /// that this [`State`] object is associated with.
1065    fn restoration_id(self: Handle<Self>, app: &App) -> Option<&str>;
1066
1067    /// The [`RestorationBucket`] used for the restoration data of the [`RestorableProperty`]s
1068    /// registered to this mixin.
1069    ///
1070    /// The bucket has been claimed from the surrounding [`RestorationScope`] using
1071    /// [`restoration_id`](Self::restoration_id).
1072    ///
1073    /// The getter returns `None` if state restoration is turned off. When state restoration is
1074    /// turned on or off during the lifetime of this mixin (and hence the return value of this
1075    /// getter switches between `None` and non-`None`)
1076    /// [`did_toggle_bucket`](Self::did_toggle_bucket) is called.
1077    ///
1078    /// Interacting directly with this bucket is uncommon. However, the bucket may be injected
1079    /// into the widget tree in the [`State`]'s `build` method using an
1080    /// [`UnmanagedRestorationScope`]. That allows descendants to claim child buckets from this
1081    /// bucket for their own restoration needs.
1082    fn bucket(self: Handle<Self>, app: &App) -> Option<Handle<RestorationBucket>> {
1083        self.restoration_mixin_data(app).bucket.handle()
1084    }
1085
1086    /// Called to initialize or restore the [`RestorableProperty`]s used by the [`State`] object.
1087    ///
1088    /// This method is always invoked at least once right after `State::init_state` to register
1089    /// the [`RestorableProperty`]s with the mixin even when state restoration is turned off or
1090    /// no restoration data is available for this [`State`] object.
1091    ///
1092    /// Typically, [`register_for_restoration`](Self::register_for_restoration) is called from
1093    /// this method to register all [`RestorableProperty`]s used by the [`State`] object with the
1094    /// mixin. The registration will either restore the property's value to the value described
1095    /// by the restoration data, if available, or, if no restoration data is available,
1096    /// initialize it to a property-specific default value.
1097    ///
1098    /// The method is called again whenever new restoration data (in the form of a new
1099    /// [`bucket`](Self::bucket)) has been provided to the mixin. When that happens, the
1100    /// [`State`] object must re-register all previously registered properties, which will
1101    /// restore their values to the value described by the new restoration data.
1102    ///
1103    /// Since the method may change the value of the registered properties when new restoration
1104    /// state is provided, all initialization logic that depends on a specific value of a
1105    /// [`RestorableProperty`] should be included in this method.
1106    ///
1107    /// The first time the method is invoked, the provided `old_bucket` argument is always
1108    /// `None`. In subsequent calls triggered by new restoration data in the form of a new
1109    /// bucket, the argument given is the previous value of [`bucket`](Self::bucket).
1110    fn restore_state(
1111        self: Handle<Self>,
1112        app: &mut App,
1113        old_bucket: Option<Handle<RestorationBucket>>,
1114        initial_restore: bool,
1115    );
1116
1117    /// Called when [`bucket`](Self::bucket) switches between `None` and non-`None` values.
1118    ///
1119    /// [`State`] objects that wish to directly interact with the bucket may implement this
1120    /// method to store additional values in the bucket when one becomes available or to save
1121    /// values stored in a bucket elsewhere when the bucket goes away. This is uncommon and
1122    /// storing those values in [`RestorableProperty`]s should be considered instead.
1123    ///
1124    /// The `old_bucket` is provided to the method when the [`bucket`](Self::bucket) getter
1125    /// changes from non-`None` to `None`. The `old_bucket` argument is `None` when the
1126    /// [`bucket`](Self::bucket) changes from `None` to non-`None`.
1127    ///
1128    /// See also:
1129    ///
1130    ///  * [`restore_state`](Self::restore_state), which is called when the
1131    ///    [`bucket`](Self::bucket) changes from one non-`None` value to another non-`None`
1132    ///    value.
1133    fn did_toggle_bucket(
1134        self: Handle<Self>,
1135        app: &mut App,
1136        old_bucket: Option<Handle<RestorationBucket>>,
1137    ) {
1138        let _ = old_bucket;
1139        // When a bucket is replaced, `restore_state` is called instead.
1140        debug_assert!(
1141            self.bucket(app)
1142                .is_none_or(|bucket| !bucket.is_replacing(app))
1143        );
1144    }
1145
1146    /// Registers a [`RestorableProperty`] for state restoration.
1147    ///
1148    /// The registration associates the provided `property` with the provided `restoration_id`.
1149    /// If restoration data is available for the provided `restoration_id`, the property's value
1150    /// is restored to the value described by the restoration data. If no restoration data is
1151    /// available, the property will be initialized to a property-specific default value.
1152    ///
1153    /// Each property within a [`State`] object must be registered under a unique ID. Only
1154    /// registered properties will have their values restored during state restoration.
1155    ///
1156    /// Typically, this method is called from within [`restore_state`](Self::restore_state) to
1157    /// register all restorable properties of the owning [`State`] object. However, if a given
1158    /// [`RestorableProperty`] is only needed when certain conditions are met within the
1159    /// [`State`], this method may also be called at any time after
1160    /// [`restore_state`](Self::restore_state) has been invoked for the first time.
1161    ///
1162    /// A property that has been registered outside of [`restore_state`](Self::restore_state)
1163    /// must be re-registered within [`restore_state`](Self::restore_state) the next time that
1164    /// method is called unless it has been unregistered with
1165    /// [`unregister_from_restoration`](Self::unregister_from_restoration).
1166    fn register_for_restoration(
1167        self: Handle<Self>,
1168        app: &mut App,
1169        property: AnyRestorableProperty,
1170        restoration_id: &str,
1171    ) {
1172        if cfg!(debug_assertions) {
1173            let doing_restore = self.debug_doing_restore(app);
1174            let registered_id = property.restoration_id(app).map(str::to_string);
1175            assert!(
1176                registered_id.is_none()
1177                    || (doing_restore && registered_id.as_deref() == Some(restoration_id)),
1178                "Property is already registered under {registered_id:?}."
1179            );
1180            let id_taken = self
1181                .restoration_mixin_data(app)
1182                .properties
1183                .keys()
1184                .any(|other| other.restoration_id(app) == Some(restoration_id));
1185            assert!(
1186                doing_restore || !id_taken,
1187                "\"{restoration_id}\" is already registered to another property."
1188            );
1189        }
1190
1191        let has_serialized_value = self
1192            .bucket(app)
1193            .is_some_and(|bucket| bucket.contains(app, restoration_id));
1194        let serialized_value = has_serialized_value
1195            .then(|| {
1196                self.bucket(app)
1197                    .expect("a serialized value implies a bucket")
1198                    .read(app, restoration_id)
1199            })
1200            .flatten();
1201
1202        if !property.is_registered(app) {
1203            property.register(app, restoration_id, self.as_restoration_mixin());
1204            let listener = Listener::new(move |app| {
1205                if self.bucket(app).is_none() {
1206                    return;
1207                }
1208                self.update_property(app, property);
1209            });
1210            property.add_listener(app, listener.clone());
1211            let kept = property.keep(app);
1212            self.restoration_mixin_data_mut(app)
1213                .properties
1214                .insert(kept, listener);
1215        }
1216
1217        debug_assert!(
1218            property.restoration_id(app) == Some(restoration_id)
1219                && property.owner(app) == Some(self.as_restoration_mixin())
1220                && self
1221                    .restoration_mixin_data(app)
1222                    .properties
1223                    .contains_key(&property)
1224        );
1225
1226        property.restore(app, serialized_value.as_ref());
1227        if !has_serialized_value && property.enabled(app) && self.bucket(app).is_some() {
1228            self.update_property(app, property);
1229        }
1230
1231        if cfg!(debug_assertions)
1232            && let Some(waiting) = self
1233                .restoration_mixin_data_mut(app)
1234                .debug_properties_waiting_for_reregistration
1235                .as_mut()
1236        {
1237            waiting.retain(|other| other != property);
1238        }
1239    }
1240
1241    /// Unregisters a [`RestorableProperty`] from state restoration.
1242    ///
1243    /// The value of the `property` is removed from the restoration data and it will not be
1244    /// restored if that data is used in a future state restoration.
1245    ///
1246    /// Calling this method is uncommon, but may be necessary if the data of a
1247    /// [`RestorableProperty`] is only relevant when the [`State`] object is in a certain state.
1248    fn unregister_from_restoration(
1249        self: Handle<Self>,
1250        app: &mut App,
1251        property: AnyRestorableProperty,
1252    ) {
1253        debug_assert!(property.owner(app) == Some(self.as_restoration_mixin()));
1254        let restoration_id = property
1255            .restoration_id(app)
1256            .expect("a registered property has an ID")
1257            .to_string();
1258        if let Some(bucket) = self.restoration_mixin_data(app).bucket.handle() {
1259            bucket.remove(app, &restoration_id);
1260        }
1261        self.unregister(app, property);
1262    }
1263
1264    /// Must be called when the value returned by [`restoration_id`](Self::restoration_id)
1265    /// changes.
1266    ///
1267    /// The [`State`] calls this from its `State::did_update_widget`, where Dart's mixin body
1268    /// would run; a change in [`restoration_id`](Self::restoration_id) that no widget update
1269    /// caused must call it directly.
1270    fn did_update_restoration_id(self: Handle<Self>, app: &mut App) {
1271        // There's nothing to do if:
1272        //  - We don't have a parent to claim a bucket from.
1273        //  - Our current bucket already uses the provided restoration ID.
1274        //  - There's a restore pending, which means that did_change_dependencies will be
1275        //    called and we handle the rename there.
1276        let bucket_keeps_id =
1277            self.bucket(app).map(|bucket| bucket.restoration_id(app)) == self.restoration_id(app);
1278        if self.restoration_mixin_data(app).current_parent.is_none()
1279            || bucket_keeps_id
1280            || self.restore_pending(app)
1281        {
1282            return;
1283        }
1284
1285        let old_bucket = self.bucket(app);
1286        let current_parent = self.restoration_mixin_data(app).current_parent.handle();
1287        let did_replace_bucket = self.update_bucket_if_necessary(app, current_parent, false);
1288        if did_replace_bucket {
1289            debug_assert!(old_bucket != self.bucket(app));
1290            debug_assert!(self.bucket(app).is_none() || old_bucket.is_none());
1291            if let Some(old_bucket) = old_bucket {
1292                old_bucket.dispose(app);
1293            }
1294        }
1295    }
1296
1297    /// Whether [`restore_state`](Self::restore_state) will be called at the beginning of the
1298    /// next build phase.
1299    ///
1300    /// Returns true when new restoration data has been provided to the mixin, but the registered
1301    /// [`RestorableProperty`]s have not been restored to their new values (as described by the
1302    /// new restoration data) yet. The properties will get the values restored when
1303    /// [`restore_state`](Self::restore_state) is invoked at the beginning of the next build
1304    /// cycle.
1305    ///
1306    /// While this is true, [`bucket`](Self::bucket) will also still return the old bucket with
1307    /// the old restoration data. It will update to the new bucket with the new data just before
1308    /// [`restore_state`](Self::restore_state) is invoked.
1309    fn restore_pending(self: Handle<Self>, app: &mut App) -> bool {
1310        if self.restoration_mixin_data(app).first_restore_pending {
1311            return true;
1312        }
1313        if self.restoration_id(app).is_none() {
1314            return false;
1315        }
1316        let context = self.context(app);
1317        let potential_new_parent = RestorationScope::maybe_of(app, context);
1318        potential_new_parent != self.restoration_mixin_data(app).current_parent.handle()
1319            && potential_new_parent.is_some_and(|parent| parent.is_replacing(app))
1320    }
1321
1322    /// Dart's `RestorationMixin.didChangeDependencies`, called by the [`State`] from its own
1323    /// `State::did_change_dependencies`.
1324    fn did_change_dependencies_restoration(self: Handle<Self>, app: &mut App) {
1325        let old_bucket = self.bucket(app);
1326        let needs_restore = self.restore_pending(app);
1327        let context = self.context(app);
1328        let current_parent = RestorationScope::maybe_of(app, context);
1329        let kept_parent = current_parent.map(|parent| parent.keep(app));
1330        self.restoration_mixin_data_mut(app).current_parent = kept_parent;
1331
1332        let did_replace_bucket =
1333            self.update_bucket_if_necessary(app, current_parent, needs_restore);
1334
1335        if needs_restore {
1336            self.do_restore(app, old_bucket);
1337        }
1338        if did_replace_bucket {
1339            debug_assert!(old_bucket != self.bucket(app));
1340            if let Some(old_bucket) = old_bucket {
1341                old_bucket.dispose(app);
1342            }
1343        }
1344    }
1345
1346    /// Dart's `RestorationMixin.dispose`, called by the [`State`] from its own `State::dispose`.
1347    fn dispose_restoration(self: Handle<Self>, app: &mut App) {
1348        let properties: Vec<(AnyRestorableProperty, Listener)> = self
1349            .restoration_mixin_data(app)
1350            .properties
1351            .iter()
1352            .map(|(property, listener)| (property.handle(), listener.clone()))
1353            .collect();
1354        for (property, listener) in properties {
1355            if !property.disposed(app) {
1356                property.remove_listener(app, &listener);
1357            }
1358        }
1359        if let Some(bucket) = self.restoration_mixin_data(app).bucket.handle() {
1360            bucket.dispose(app);
1361        }
1362        self.restoration_mixin_data_mut(app).bucket = None;
1363    }
1364
1365    /// This state as the erased [`AnyRestorationMixin`] — what a [`RestorableProperty`] keeps as
1366    /// its owner.
1367    fn as_restoration_mixin(self: Handle<Self>) -> AnyRestorationMixin {
1368        AnyRestorationMixin {
1369            id: self.id(),
1370            vtable: const { &RestorationMixinVTable::of::<Self>() },
1371        }
1372    }
1373
1374    /// Dart's `_debugDoingRestore`.
1375    fn debug_doing_restore(self: Handle<Self>, app: &App) -> bool {
1376        self.restoration_mixin_data(app)
1377            .debug_properties_waiting_for_reregistration
1378            .is_some()
1379    }
1380
1381    /// Dart's `_doRestore`.
1382    fn do_restore(
1383        self: Handle<Self>,
1384        app: &mut App,
1385        old_bucket: Option<Handle<RestorationBucket>>,
1386    ) {
1387        if cfg!(debug_assertions) {
1388            let registered: Vec<RestorablePropertyRef> = self
1389                .restoration_mixin_data(app)
1390                .properties
1391                .keys()
1392                .cloned()
1393                .collect();
1394            self.restoration_mixin_data_mut(app)
1395                .debug_properties_waiting_for_reregistration = Some(registered);
1396        }
1397
1398        let initial_restore = self.restoration_mixin_data(app).first_restore_pending;
1399        self.restore_state(app, old_bucket, initial_restore);
1400        self.restoration_mixin_data_mut(app).first_restore_pending = false;
1401
1402        if cfg!(debug_assertions) {
1403            let waiting = self
1404                .restoration_mixin_data_mut(app)
1405                .debug_properties_waiting_for_reregistration
1406                .take()
1407                .expect("set just above");
1408            let missing: Vec<String> = waiting
1409                .iter()
1410                .map(|property| format!(" * {:?}", property.restoration_id(app)))
1411                .collect();
1412            assert!(
1413                missing.is_empty(),
1414                "Previously registered RestorableProperties must be re-registered in \
1415                 \"restore_state\". The RestorableProperties with the following IDs were not \
1416                 re-registered when \"restore_state\" was called:\n{}",
1417                missing.join("\n")
1418            );
1419        }
1420    }
1421
1422    /// Dart's `_updateBucketIfNecessary`. Returns true if [`bucket`](Self::bucket) has been
1423    /// replaced with a new bucket; it is the responsibility of the caller to dispose the old
1424    /// bucket when this returns true.
1425    fn update_bucket_if_necessary(
1426        self: Handle<Self>,
1427        app: &mut App,
1428        parent: Option<Handle<RestorationBucket>>,
1429        restore_pending: bool,
1430    ) -> bool {
1431        let restoration_id = self.restoration_id(app).map(str::to_string);
1432        let (Some(restoration_id), Some(parent)) = (restoration_id, parent) else {
1433            let did_replace = self.set_new_bucket_if_necessary(app, None, restore_pending);
1434            debug_assert!(self.bucket(app).is_none());
1435            return did_replace;
1436        };
1437
1438        if restore_pending || self.bucket(app).is_none() {
1439            let debug_owner: Option<Rc<dyn Debug>> = cfg!(debug_assertions)
1440                .then(|| Rc::new(self.as_restoration_mixin()) as Rc<dyn Debug>);
1441            let new_bucket = parent.claim_child(app, &restoration_id, debug_owner);
1442            let new_handle = new_bucket.handle();
1443            let did_replace =
1444                self.set_new_bucket_if_necessary(app, Some(new_bucket), restore_pending);
1445            debug_assert!(self.bucket(app) == Some(new_handle));
1446            return did_replace;
1447        }
1448
1449        // We have an existing bucket, make sure it has the right parent and id.
1450        debug_assert!(!restore_pending);
1451        let bucket = self
1452            .restoration_mixin_data(app)
1453            .bucket
1454            .clone()
1455            .expect("checked just above");
1456        bucket.rename(app, &restoration_id);
1457        parent.adopt_child(app, &bucket);
1458        false
1459    }
1460
1461    /// Dart's `_setNewBucketIfNecessary`. Returns true if [`bucket`](Self::bucket) has been
1462    /// replaced with a new bucket; it is the responsibility of the caller to dispose the old
1463    /// bucket when this returns true.
1464    fn set_new_bucket_if_necessary(
1465        self: Handle<Self>,
1466        app: &mut App,
1467        new_bucket: Option<Ref<RestorationBucket>>,
1468        restore_pending: bool,
1469    ) -> bool {
1470        if new_bucket.handle() == self.bucket(app) {
1471            return false;
1472        }
1473        let old_bucket = self.bucket(app);
1474        self.restoration_mixin_data_mut(app).bucket = new_bucket;
1475        if !restore_pending {
1476            // Write the current property values into the new bucket to persist them.
1477            if self.bucket(app).is_some() {
1478                let properties: Vec<AnyRestorableProperty> = self
1479                    .restoration_mixin_data(app)
1480                    .properties
1481                    .keys()
1482                    .map(Retained::handle)
1483                    .collect();
1484                for property in properties {
1485                    self.update_property(app, property);
1486                }
1487            }
1488            self.did_toggle_bucket(app, old_bucket);
1489        }
1490        true
1491    }
1492
1493    /// Dart's `_updateProperty`.
1494    fn update_property(self: Handle<Self>, app: &mut App, property: AnyRestorableProperty) {
1495        let Some(bucket) = self.bucket(app) else {
1496            return;
1497        };
1498        let restoration_id = property
1499            .restoration_id(app)
1500            .expect("a registered property has an ID")
1501            .to_string();
1502        if property.enabled(app) {
1503            let value = property.to_primitives(app);
1504            bucket.write(app, &restoration_id, value);
1505        } else {
1506            bucket.remove(app, &restoration_id);
1507        }
1508    }
1509
1510    /// Dart's `RestorationMixin._unregister`.
1511    fn unregister(self: Handle<Self>, app: &mut App, property: AnyRestorableProperty) {
1512        let listener = self
1513            .restoration_mixin_data_mut(app)
1514            .properties
1515            .shift_remove(&property)
1516            .expect("the property is registered with this mixin");
1517        if cfg!(debug_assertions)
1518            && let Some(waiting) = self
1519                .restoration_mixin_data_mut(app)
1520                .debug_properties_waiting_for_reregistration
1521                .as_mut()
1522        {
1523            waiting.retain(|other| other != property);
1524        }
1525        property.remove_listener(app, &listener);
1526        property.unregister(app);
1527    }
1528}
1529
1530/// The type-erased handle's slots for one [`RestorationMixin`] implementor.
1531struct RestorationMixinVTable {
1532    type_name: fn() -> &'static str,
1533    unregister: fn(&mut App, HandleId, AnyRestorableProperty),
1534    bucket: fn(&App, HandleId) -> Option<Handle<RestorationBucket>>,
1535    context: fn(&App, HandleId) -> BuildContext,
1536    mounted: fn(&App, HandleId) -> bool,
1537}
1538
1539impl RestorationMixinVTable {
1540    /// The table for one state type.
1541    const fn of<M: RestorationMixin>() -> RestorationMixinVTable {
1542        RestorationMixinVTable {
1543            type_name: std::any::type_name::<M>,
1544            unregister: |app, id, property| M::unregister(resolve(id), app, property),
1545            bucket: |app, id| M::bucket(resolve(id), app),
1546            context: |app, id| M::context(resolve(id), app),
1547            mounted: |app, id| M::mounted(resolve(id), app),
1548        }
1549    }
1550}
1551
1552/// Erased [`RestorationMixin`]: the [`State`] a [`RestorableProperty`] is registered with.
1553///
1554/// This is what Dart's `RestorationMixin? _owner` and `State get state` become; the state itself
1555/// stays in the [`App`] under its own type, and [`downcast`](Self::downcast) gets the typed
1556/// handle back.
1557///
1558/// Equality is Dart's `==` on an object reference: two handles are equal exactly when they address
1559/// the same state.
1560#[derive(Clone, Copy)]
1561pub struct AnyRestorationMixin {
1562    id: HandleId,
1563    vtable: &'static RestorationMixinVTable,
1564}
1565
1566impl PartialEq for AnyRestorationMixin {
1567    fn eq(&self, other: &AnyRestorationMixin) -> bool {
1568        self.id == other.id
1569    }
1570}
1571
1572impl Eq for AnyRestorationMixin {}
1573
1574impl std::hash::Hash for AnyRestorationMixin {
1575    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1576        self.id.hash(state);
1577    }
1578}
1579
1580impl Debug for AnyRestorationMixin {
1581    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1582        write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
1583    }
1584}
1585
1586impl AnyRestorationMixin {
1587    /// The arena id behind this handle.
1588    pub fn id(self) -> HandleId {
1589        self.id
1590    }
1591
1592    /// Dart's `state as T`: the typed handle when this state is a `T`, else `None`.
1593    pub fn downcast<T: 'static>(self, app: &App) -> Option<Handle<T>> {
1594        app.handle::<T>(self.id)
1595    }
1596
1597    /// See [`RestorationMixin::bucket`].
1598    pub fn bucket(self, app: &App) -> Option<Handle<RestorationBucket>> {
1599        (self.vtable.bucket)(app, self.id)
1600    }
1601
1602    /// See `State::context`.
1603    pub fn context(self, app: &App) -> BuildContext {
1604        (self.vtable.context)(app, self.id)
1605    }
1606
1607    /// See `State::mounted`.
1608    pub fn mounted(self, app: &App) -> bool {
1609        (self.vtable.mounted)(app, self.id)
1610    }
1611
1612    fn unregister(self, app: &mut App, property: AnyRestorableProperty) {
1613        (self.vtable.unregister)(app, self.id, property);
1614    }
1615}
1616
1617#[cfg(test)]
1618mod tests {
1619    use std::cell::RefCell;
1620    use waft_foundation::Ref;
1621
1622    use waft_services::RestorationMap;
1623
1624    use super::*;
1625    use crate::framework::{GlobalKey, StatelessWidget};
1626    use crate::testing::{WidgetTester, test_widgets};
1627    use crate::widgets::restoration_properties::{RestorableInt, RestorableValue};
1628
1629    fn map<const N: usize>(entries: [(&str, RestorationData); N]) -> RestorationMap {
1630        entries
1631            .into_iter()
1632            .map(|(key, value)| (RestorationData::from(key), value))
1633            .collect()
1634    }
1635
1636    /// The raw map of a bucket that stores these values.
1637    fn values<const N: usize>(entries: [(&str, RestorationData); N]) -> RestorationMap {
1638        map([("v", map(entries).into())])
1639    }
1640
1641    /// The raw map of a bucket whose only content is one child.
1642    fn child(restoration_id: &str, data: RestorationMap) -> RestorationMap {
1643        map([("c", map([(restoration_id, data.into())]).into())])
1644    }
1645
1646    /// The value stored down `path`, e.g. `["c", "app", "v", "count"]`.
1647    fn at<'a>(data: &'a RestorationMap, path: &[&str]) -> Option<&'a RestorationData> {
1648        let (last, parents) = path.split_last()?;
1649        let mut map = data;
1650        for key in parents {
1651            map = map.get(&RestorationData::from(*key))?.as_map()?;
1652        }
1653        map.get(&RestorationData::from(*last))
1654    }
1655
1656    /// What a [`BucketProbe`] saw, in build order.
1657    type SeenBuckets = Rc<RefCell<Vec<Option<Handle<RestorationBucket>>>>>;
1658
1659    /// Reads [`RestorationScope::maybe_of`] on every build and logs the bucket it saw.
1660    #[derive(Debug)]
1661    struct BucketProbe {
1662        seen: SeenBuckets,
1663    }
1664
1665    impl StatelessWidget for BucketProbe {
1666        fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
1667            let bucket = RestorationScope::maybe_of(app, context);
1668            self.seen.borrow_mut().push(bucket);
1669            SizedBox::shrink().into_widget()
1670        }
1671    }
1672
1673    fn probe() -> (WidgetRef, SeenBuckets) {
1674        let seen = Rc::new(RefCell::new(Vec::new()));
1675        let probe = BucketProbe {
1676            seen: Rc::clone(&seen),
1677        }
1678        .into_widget();
1679        (probe, seen)
1680    }
1681
1682    /// A `State` that keeps its count in a [`RestorableInt`].
1683    #[derive(Debug)]
1684    struct Counter {
1685        key: Option<KeyRef>,
1686        restoration_id: Option<String>,
1687    }
1688
1689    impl StatefulWidget for Counter {
1690        type State = CounterState;
1691
1692        fn key(&self) -> Option<&KeyRef> {
1693            self.key.as_ref()
1694        }
1695
1696        fn create_state(&self) -> CounterState {
1697            CounterState {
1698                state: StateData::new(),
1699                restoration: RestorationMixinData::new(),
1700                count: None,
1701                restores: 0,
1702            }
1703        }
1704    }
1705
1706    struct CounterState {
1707        state: StateData<Counter>,
1708        restoration: RestorationMixinData,
1709        count: Option<Ref<RestorableInt>>,
1710        restores: usize,
1711    }
1712
1713    impl CounterState {
1714        fn count(self: Handle<Self>, app: &App) -> Handle<RestorableInt> {
1715            app.get(self).count.handle().expect("restore_state ran")
1716        }
1717    }
1718
1719    impl RestorationMixin for CounterState {
1720        crate::restoration_mixin_accessors!();
1721
1722        fn restoration_id(self: Handle<Self>, app: &App) -> Option<&str> {
1723            self.widget(app).restoration_id.as_deref()
1724        }
1725
1726        fn restore_state(
1727            self: Handle<Self>,
1728            app: &mut App,
1729            _old_bucket: Option<Handle<RestorationBucket>>,
1730            _initial_restore: bool,
1731        ) {
1732            app.get_mut(self).restores += 1;
1733            let count = match app.get(self).count.handle() {
1734                Some(count) => count,
1735                None => {
1736                    let count = RestorableInt::new(app, 0);
1737                    let handle = count.handle();
1738                    app.get_mut(self).count = Some(count);
1739                    handle
1740                }
1741            };
1742            self.register_for_restoration(app, count.as_property(), "count");
1743        }
1744    }
1745
1746    impl State for CounterState {
1747        type Widget = Counter;
1748        crate::state_accessors!();
1749
1750        fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
1751            self.did_change_dependencies_restoration(app);
1752        }
1753
1754        fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &Counter) {
1755            self.did_update_restoration_id(app);
1756        }
1757
1758        fn dispose(self: Handle<Self>, app: &mut App) {
1759            self.dispose_restoration(app);
1760        }
1761
1762        fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
1763            let _ = app;
1764            SizedBox::shrink().into_widget()
1765        }
1766    }
1767
1768    /// Dart's `tester.pumpWidget(child)` on a tester whose host restores `data`.
1769    fn mount<K>(data: Option<RestorationMap>, child: impl IntoWidget<K>) -> WidgetTester {
1770        let mut tester = WidgetTester::restoring(data);
1771        tester.pump_widget(child);
1772        tester
1773    }
1774
1775    fn counter_state(tester: &WidgetTester, key: &GlobalKey) -> Handle<CounterState> {
1776        key.current_state::<CounterState>(&tester.cell.borrow())
1777            .expect("the counter is in the tree")
1778    }
1779
1780    /// The value the host was last handed down `path`.
1781    fn sent_at(tester: &WidgetTester, path: &[&str]) -> Option<RestorationData> {
1782        let sent = tester.restoration_data().expect("serialized");
1783        at(&sent, path).cloned()
1784    }
1785
1786    fn counter(key: &GlobalKey, restoration_id: &str) -> Counter {
1787        Counter {
1788            key: Some(key.clone().into()),
1789            restoration_id: Some(restoration_id.to_string()),
1790        }
1791    }
1792
1793    fn app_scope<K>(child: impl IntoWidget<K>) -> RootRestorationScope {
1794        RootRestorationScope::new(Some("app".to_string()), child)
1795    }
1796
1797    #[test]
1798    fn the_root_scope_hands_the_hosts_root_bucket_down() {
1799        let (probe, seen) = probe();
1800        let tester = mount(
1801            Some(child("app", values([("count", 42i64.into())]))),
1802            app_scope(probe),
1803        );
1804
1805        let bucket = seen.borrow()[0].expect("the host enabled restoration");
1806        let mut app = tester.cell.borrow_mut();
1807        assert_eq!(bucket.restoration_id(&app), "app");
1808        assert_eq!(bucket.read(&mut app, "count"), Some(42i64.into()));
1809    }
1810
1811    #[test]
1812    fn the_root_scope_hands_nothing_down_without_a_restoration_id() {
1813        let (probe, seen) = probe();
1814        let _tester = mount(None, RootRestorationScope::new(None, probe));
1815
1816        assert_eq!(seen.borrow().as_slice(), [None]);
1817    }
1818
1819    #[test]
1820    fn a_restoration_scope_claims_the_child_bucket_named_by_its_id() {
1821        let (probe, seen) = probe();
1822        let tester = mount(
1823            Some(child(
1824                "app",
1825                child("greeting", values([("hello", "world".into())])),
1826            )),
1827            app_scope(RestorationScope::new(Some("greeting".to_string()), probe)),
1828        );
1829
1830        let bucket = seen.borrow()[0].expect("the scope claimed a bucket");
1831        let mut app = tester.cell.borrow_mut();
1832        assert_eq!(bucket.restoration_id(&app), "greeting");
1833        assert_eq!(bucket.read(&mut app, "hello"), Some("world".into()));
1834    }
1835
1836    #[test]
1837    fn a_restoration_scope_without_an_id_turns_restoration_off_for_its_subtree() {
1838        let (probe, seen) = probe();
1839        let _tester = mount(None, app_scope(RestorationScope::new(None, probe)));
1840
1841        assert_eq!(seen.borrow().as_slice(), [None]);
1842    }
1843
1844    #[test]
1845    fn a_registered_property_is_restored_from_the_hosts_data() {
1846        let key = GlobalKey::new();
1847        let tester = mount(
1848            Some(child(
1849                "app",
1850                child("counter", values([("count", 7i64.into())])),
1851            )),
1852            app_scope(counter(&key, "counter")),
1853        );
1854
1855        let state = counter_state(&tester, &key);
1856        let app = tester.cell.borrow();
1857        assert_eq!(app.get(state).restores, 1);
1858        let count = state.count(&app);
1859        assert_eq!(*count.value(&app), 7);
1860    }
1861
1862    #[test]
1863    fn a_property_with_no_stored_value_takes_its_default_and_writes_it_out() {
1864        let key = GlobalKey::new();
1865        let mut tester = mount(None, app_scope(counter(&key, "counter")));
1866
1867        let state = counter_state(&tester, &key);
1868        {
1869            let app = tester.cell.borrow();
1870            assert_eq!(*state.count(&app).value(&app), 0);
1871        }
1872
1873        tester.pump();
1874        assert_eq!(
1875            sent_at(&tester, &["c", "app", "c", "counter", "v", "count"]),
1876            Some(0i64.into())
1877        );
1878    }
1879
1880    #[test]
1881    fn a_changed_property_reaches_the_host_at_the_end_of_the_frame() {
1882        let key = GlobalKey::new();
1883        let mut tester = mount(
1884            Some(child(
1885                "app",
1886                child("counter", values([("count", 7i64.into())])),
1887            )),
1888            app_scope(counter(&key, "counter")),
1889        );
1890        tester.pump();
1891        let path = ["c", "app", "c", "counter", "v", "count"];
1892        assert_eq!(sent_at(&tester, &path), Some(7i64.into()));
1893
1894        let state = counter_state(&tester, &key);
1895        // Inside `setState`, as Dart's cases change a property, which asks for the frame.
1896        tester.update(|app| {
1897            state.count(app).set_value(app, 9);
1898            state.set_state(app, |_| {});
1899        });
1900        assert_eq!(
1901            sent_at(&tester, &path),
1902            Some(7i64.into()),
1903            "the write waits for the end of the frame"
1904        );
1905
1906        tester.pump();
1907        assert_eq!(sent_at(&tester, &path), Some(9i64.into()));
1908    }
1909
1910    #[test]
1911    fn did_update_restoration_id_moves_the_bucket_and_its_data() {
1912        let key = GlobalKey::new();
1913        let mut tester = mount(
1914            Some(child(
1915                "app",
1916                child("counter", values([("count", 7i64.into())])),
1917            )),
1918            app_scope(counter(&key, "counter")),
1919        );
1920        let state = counter_state(&tester, &key);
1921        let bucket = state
1922            .bucket(&tester.cell.borrow())
1923            .expect("the counter claimed a bucket");
1924
1925        tester.pump_widget(app_scope(counter(&key, "renamed")));
1926
1927        {
1928            let app = tester.cell.borrow();
1929            assert_eq!(app.get(state).restores, 1, "a rename does not re-restore");
1930            assert_eq!(
1931                state.bucket(&app),
1932                Some(bucket),
1933                "the same bucket moved to the new ID"
1934            );
1935            assert_eq!(bucket.restoration_id(&app), "renamed");
1936            assert_eq!(*state.count(&app).value(&app), 7);
1937        }
1938
1939        tester.pump();
1940        assert_eq!(
1941            sent_at(&tester, &["c", "app", "c", "renamed", "v", "count"]),
1942            Some(7i64.into())
1943        );
1944        assert_eq!(sent_at(&tester, &["c", "app", "c", "counter"]), None);
1945    }
1946
1947    #[test]
1948    fn new_data_from_the_host_restores_the_registered_properties_again() {
1949        let key = GlobalKey::new();
1950        let mut tester = mount(
1951            Some(child(
1952                "app",
1953                child("counter", values([("count", 7i64.into())])),
1954            )),
1955            app_scope(counter(&key, "counter")),
1956        );
1957        let state = counter_state(&tester, &key);
1958        {
1959            let app = tester.cell.borrow();
1960            assert_eq!(*state.count(&app).value(&app), 7);
1961        }
1962
1963        tester.update(|app| {
1964            let manager = RestorationManager::instance(app);
1965            manager.handle_restoration_update_from_engine(
1966                app,
1967                true,
1968                Some(child(
1969                    "app",
1970                    child("counter", values([("count", 21i64.into())])),
1971                )),
1972            );
1973        });
1974        tester.pump();
1975
1976        let app = tester.cell.borrow();
1977        assert_eq!(app.get(state).restores, 2);
1978        assert_eq!(*state.count(&app).value(&app), 21);
1979    }
1980
1981    #[test]
1982    fn a_state_without_a_surrounding_scope_gets_no_bucket() {
1983        let key = GlobalKey::new();
1984        let tester = mount(None, counter(&key, "counter"));
1985
1986        let state = counter_state(&tester, &key);
1987        let app = tester.cell.borrow();
1988        assert_eq!(state.bucket(&app), None);
1989        assert_eq!(*state.count(&app).value(&app), 0);
1990    }
1991
1992    #[test]
1993    fn of_panics_outside_any_restoration_scope() {
1994        test_widgets(|tester| {
1995            let key = GlobalKey::new();
1996            tester.pump_widget(SizedBox::shrink().key(key.clone().into()));
1997            let context = key
1998                .current_context(&tester.cell.borrow())
1999                .expect("the box is mounted");
2000            let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2001                tester.update(|app| RestorationScope::of(app, context))
2002            }));
2003            assert!(panic.is_err());
2004        });
2005    }
2006}