Skip to main content

waft_widgets/widgets/
restoration_properties.rs

1//! Flutter counterpart: `widgets/restoration_properties.dart`.
2//!
3//! The [`RestorableProperty`] implementations a [`State`](crate::State) registers with a
4//! [`RestorationMixin`](crate::RestorationMixin): the value bases and the concrete properties
5//! for the primitives, [`DateTime`], and enums.
6
7use std::fmt::Debug;
8
9use waft_foundation::{
10    App, ChangeNotifier, ChangeNotifierData, DateTime, Handle, Listenable, Listener,
11};
12use waft_services::{RestorationData, TextEditingValue};
13
14use crate::widgets::editable_text::{TextEditingController, TextEditingControllerLeaf};
15use crate::widgets::restoration::{RestorableProperty, RestorablePropertyData};
16use waft_foundation::Ref;
17
18// ---------------------------------------------------------------------------------------------
19// RestorableValue
20
21/// Dart's private `_value` of `RestorableValue`; a property carries this bag under the field
22/// `value`.
23pub struct RestorableValueData<T> {
24    value: Option<T>,
25}
26
27impl<T> RestorableValueData<T> {
28    /// A property whose [`init_with_value`](RestorableProperty::init_with_value) has not run.
29    pub fn new() -> RestorableValueData<T> {
30        RestorableValueData { value: None }
31    }
32}
33
34impl<T> Default for RestorableValueData<T> {
35    fn default() -> RestorableValueData<T> {
36        RestorableValueData::new()
37    }
38}
39
40/// The accessors [`RestorableValue`] asks for, for a property whose bag is the field `value`.
41#[macro_export]
42macro_rules! restorable_value_accessors {
43    () => {
44        fn restorable_value_data(
45            self: ::waft_foundation::Handle<Self>,
46            app: &::waft_foundation::App,
47        ) -> &$crate::RestorableValueData<Self::Value> {
48            &app.get(self).value
49        }
50
51        fn restorable_value_data_mut(
52            self: ::waft_foundation::Handle<Self>,
53            app: &mut ::waft_foundation::App,
54        ) -> &mut $crate::RestorableValueData<Self::Value> {
55            &mut app.get_mut(self).value
56        }
57    };
58}
59
60/// A [`RestorableProperty`] that makes the wrapped value accessible to the owning
61/// [`State`](crate::State) object via the [`value`](Self::value) getter and
62/// [`set_value`](Self::set_value) setter.
63///
64/// Whenever a new value is set, [`did_update_value`](Self::did_update_value) is called.
65/// Implementors should call `notify_listeners` from that method if the new value changes what
66/// [`to_primitives`](RestorableProperty::to_primitives) returns.
67///
68/// ## Creating an implementor
69///
70/// ```text
71/// pub struct RestorableDuration {
72///     change_notifier: ChangeNotifierData,
73///     property: RestorablePropertyData,
74///     value: RestorableValueData<Duration>,
75/// }
76///
77/// impl RestorableProperty for RestorableDuration {
78///     type Value = Duration;
79///     crate::restorable_property_accessors!();
80///
81///     fn create_default_value(self: Handle<Self>, _app: &mut App) -> Duration {
82///         Duration::ZERO
83///     }
84///
85///     fn from_primitives(self: Handle<Self>, _app: &mut App, data: &RestorationData) -> Duration {
86///         Duration::from_micros(data.as_int().unwrap_or(0) as u64)
87///     }
88///
89///     fn init_with_value(self: Handle<Self>, app: &mut App, value: Duration) {
90///         RestorableValue::init_with_value(self, app, value)
91///     }
92///
93///     fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
94///         RestorationData::Int(RestorableValue::value(self, app).as_micros() as i64)
95///     }
96/// }
97///
98/// impl RestorableValue for RestorableDuration {
99///     crate::restorable_value_accessors!();
100///
101///     fn did_update_value(self: Handle<Self>, app: &mut App, old_value: Option<Duration>) {
102///         if old_value != Some(*RestorableValue::value(self, app)) {
103///             self.notify_listeners(app);
104///         }
105///     }
106/// }
107/// ```
108///
109/// See also:
110///
111///  * [`RestorableProperty`], which is the base trait of this trait.
112///  * [`RestorationMixin`](crate::RestorationMixin), to which a [`RestorableValue`] needs to be
113///    registered in order to work.
114pub trait RestorableValue: RestorableProperty<Value: Clone + PartialEq> {
115    /// Dart's `RestorableValue._value`, held under the field `value`
116    /// ([`restorable_value_accessors!`](crate::restorable_value_accessors)).
117    fn restorable_value_data(self: Handle<Self>, app: &App) -> &RestorableValueData<Self::Value>;
118
119    /// See [`restorable_value_data`](Self::restorable_value_data).
120    fn restorable_value_data_mut(
121        self: Handle<Self>,
122        app: &mut App,
123    ) -> &mut RestorableValueData<Self::Value>;
124
125    /// The current value stored in this property.
126    ///
127    /// A representation of the current value is stored in the restoration data. During state
128    /// restoration, the property will restore the value to what it was when the restoration
129    /// data it is getting restored from was collected.
130    ///
131    /// The value can only be accessed after the property has been registered with a
132    /// [`RestorationMixin`](crate::RestorationMixin) by calling
133    /// [`register_for_restoration`](crate::RestorationMixin::register_for_restoration).
134    fn value(self: Handle<Self>, app: &App) -> &Self::Value {
135        debug_assert!(RestorableProperty::is_registered(self, app));
136        self.restorable_value_data(app)
137            .value
138            .as_ref()
139            .expect("init_with_value runs at registration")
140    }
141
142    /// Replaces [`value`](Self::value), calling
143    /// [`did_update_value`](Self::did_update_value) when it changes.
144    fn set_value(self: Handle<Self>, app: &mut App, new_value: Self::Value) {
145        debug_assert!(RestorableProperty::is_registered(self, app));
146        debug_assert!(self.debug_assert_valid_value(app, &new_value));
147        if self.restorable_value_data(app).value.as_ref() != Some(&new_value) {
148            let old_value = self.restorable_value_data_mut(app).value.replace(new_value);
149            RestorableValue::did_update_value(self, app, old_value);
150        }
151    }
152
153    /// Dart's `RestorableValue.initWithValue`: the value the
154    /// [`RestorationMixin`](crate::RestorationMixin) restored or defaulted becomes
155    /// [`value`](Self::value).
156    fn init_with_value(self: Handle<Self>, app: &mut App, value: Self::Value) {
157        self.restorable_value_data_mut(app).value = Some(value);
158    }
159
160    /// Called whenever a new value is assigned to [`value`](Self::value).
161    ///
162    /// The new value can be read with the regular [`value`](Self::value) getter and the previous
163    /// value is provided as `old_value`.
164    ///
165    /// Implementors should call `notify_listeners` from this method, if the new value changes
166    /// what [`to_primitives`](RestorableProperty::to_primitives) returns.
167    fn did_update_value(self: Handle<Self>, app: &mut App, old_value: Option<Self::Value>);
168
169    /// Checks what Dart asserts inside a `set value` override before running the inherited
170    /// setter; [`RestorableEnum`] and [`RestorableEnumN`] check membership in their `values`.
171    ///
172    /// Call it inside a `debug_assert!`, as Dart calls it inside an `assert`.
173    fn debug_assert_valid_value(self: Handle<Self>, app: &App, new_value: &Self::Value) -> bool {
174        let _ = (self, app, new_value);
175        true
176    }
177}
178
179// ---------------------------------------------------------------------------------------------
180// The primitive value bases
181
182/// A value that is stored in the restoration data as one [`RestorationData`]; Dart's cast
183/// `serialized as T` in `_RestorablePrimitiveValueN.fromPrimitives`.
184///
185/// Implemented for the primitives a [`RestorationBucket`](crate::RestorationBucket) can hold and
186/// for `Option` of each of them, which is the nullable half of Dart's primitive property pairs.
187pub trait RestorablePrimitive: Clone + PartialEq + 'static {
188    /// Dart's `serialized as T`; panics when the stored data is of another kind, which is what
189    /// Dart's failing cast does.
190    fn from_restoration_data(data: &RestorationData) -> Self;
191
192    /// The value as it is stored in the restoration data.
193    fn to_restoration_data(&self) -> RestorationData;
194}
195
196impl RestorablePrimitive for bool {
197    fn from_restoration_data(data: &RestorationData) -> bool {
198        data.as_bool()
199            .expect("the restoration data of a bool property is a bool")
200    }
201
202    fn to_restoration_data(&self) -> RestorationData {
203        RestorationData::Bool(*self)
204    }
205}
206
207impl RestorablePrimitive for i64 {
208    fn from_restoration_data(data: &RestorationData) -> i64 {
209        data.as_int()
210            .expect("the restoration data of an int property is an int")
211    }
212
213    fn to_restoration_data(&self) -> RestorationData {
214        RestorationData::Int(*self)
215    }
216}
217
218impl RestorablePrimitive for f64 {
219    fn from_restoration_data(data: &RestorationData) -> f64 {
220        data.as_double()
221            .expect("the restoration data of a double property is a double")
222    }
223
224    fn to_restoration_data(&self) -> RestorationData {
225        RestorationData::Double(*self)
226    }
227}
228
229impl RestorablePrimitive for String {
230    fn from_restoration_data(data: &RestorationData) -> String {
231        data.as_str()
232            .expect("the restoration data of a String property is a String")
233            .to_string()
234    }
235
236    fn to_restoration_data(&self) -> RestorationData {
237        RestorationData::String(self.clone())
238    }
239}
240
241impl<T: RestorablePrimitive> RestorablePrimitive for Option<T> {
242    fn from_restoration_data(data: &RestorationData) -> Option<T> {
243        (!data.is_null()).then(|| T::from_restoration_data(data))
244    }
245
246    fn to_restoration_data(&self) -> RestorationData {
247        self.as_ref()
248            .map_or(RestorationData::Null, T::to_restoration_data)
249    }
250}
251
252/// Dart's `T extends num`: the numeric values a [`RestorableNum`] may wrap.
253pub trait RestorableNumValue: RestorablePrimitive {}
254
255impl RestorableNumValue for i64 {}
256
257impl RestorableNumValue for f64 {}
258
259/// Dart's private `_defaultValue` of `_RestorablePrimitiveValueN`; a primitive property carries
260/// this bag under the field `primitive`.
261pub struct RestorablePrimitiveValueData<T> {
262    default_value: T,
263}
264
265impl<T> RestorablePrimitiveValueData<T> {
266    /// The bag holding the value the property falls back to.
267    pub fn new(default_value: T) -> RestorablePrimitiveValueData<T> {
268        RestorablePrimitiveValueData { default_value }
269    }
270}
271
272/// The accessors [`RestorablePrimitiveValueN`] asks for, for a property whose bag is the field
273/// `primitive`.
274#[macro_export]
275macro_rules! restorable_primitive_value_accessors {
276    () => {
277        fn restorable_primitive_value_data(
278            self: ::waft_foundation::Handle<Self>,
279            app: &::waft_foundation::App,
280        ) -> &$crate::RestorablePrimitiveValueData<Self::Value> {
281            &app.get(self).primitive
282        }
283
284        fn restorable_primitive_value_data_mut(
285            self: ::waft_foundation::Handle<Self>,
286            app: &mut ::waft_foundation::App,
287        ) -> &mut $crate::RestorablePrimitiveValueData<Self::Value> {
288            &mut app.get_mut(self).primitive
289        }
290    };
291}
292
293/// Dart's `_RestorablePrimitiveValueN<T extends Object?>`: the shared bodies of every property
294/// that stores its value as a single primitive, nullable values included.
295///
296/// See [`RestorablePrimitiveValue`] for the non-nullable half of the pair.
297pub trait RestorablePrimitiveValueN: RestorableValue<Value: RestorablePrimitive> {
298    /// Dart's `_RestorablePrimitiveValueN._defaultValue`, held under the field `primitive`
299    /// ([`restorable_primitive_value_accessors!`](crate::restorable_primitive_value_accessors)).
300    fn restorable_primitive_value_data(
301        self: Handle<Self>,
302        app: &App,
303    ) -> &RestorablePrimitiveValueData<Self::Value>;
304
305    /// See [`restorable_primitive_value_data`](Self::restorable_primitive_value_data).
306    fn restorable_primitive_value_data_mut(
307        self: Handle<Self>,
308        app: &mut App,
309    ) -> &mut RestorablePrimitiveValueData<Self::Value>;
310
311    /// Dart's `_RestorablePrimitiveValueN.createDefaultValue`.
312    fn create_default_value(self: Handle<Self>, app: &mut App) -> Self::Value {
313        self.restorable_primitive_value_data(app)
314            .default_value
315            .clone()
316    }
317
318    /// Dart's `_RestorablePrimitiveValueN.didUpdateValue`.
319    fn did_update_value(self: Handle<Self>, app: &mut App, old_value: Option<Self::Value>) {
320        let _ = old_value;
321        self.notify_listeners(app);
322    }
323
324    /// Dart's `_RestorablePrimitiveValueN.fromPrimitives`.
325    fn from_primitives(self: Handle<Self>, app: &mut App, data: &RestorationData) -> Self::Value {
326        let _ = app;
327        Self::Value::from_restoration_data(data)
328    }
329
330    /// Dart's `_RestorablePrimitiveValueN.toPrimitives`.
331    fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
332        RestorableValue::value(self, app).to_restoration_data()
333    }
334}
335
336/// Dart's `_RestorablePrimitiveValue<T extends Object>`: the non-nullable half of the primitive
337/// property pairs.
338///
339/// Dart's overrides only narrow [`RestorablePrimitiveValueN`]'s nullable types and assert that
340/// the stored data is not null; here the value type is already non-nullable and
341/// [`RestorablePrimitive::from_restoration_data`] carries the assert, so the trait adds no body
342/// of its own.
343pub trait RestorablePrimitiveValue: RestorablePrimitiveValueN {}
344
345// ---------------------------------------------------------------------------------------------
346// The primitive properties
347
348/// A [`RestorableProperty`] that knows how to store and restore a number.
349///
350/// The current value of this property is stored in the restoration data. During state
351/// restoration the property is restored to the value it had when the restoration data it is
352/// getting restored from was collected.
353///
354/// If no restoration data is available, the value is initialized to the `default_value` given in
355/// the constructor.
356///
357/// Instead of using the more generic [`RestorableNum`] directly, consider using one of the more
358/// specific aliases ([`RestorableDouble`] to store an `f64` and [`RestorableInt`] to store an
359/// `i64`).
360///
361/// See also:
362///
363///  * [`RestorableNumN`] for the nullable version of this property.
364pub struct RestorableNum<T: RestorableNumValue> {
365    change_notifier: ChangeNotifierData,
366    property: RestorablePropertyData,
367    value: RestorableValueData<T>,
368    primitive: RestorablePrimitiveValueData<T>,
369}
370
371impl<T: RestorableNumValue> RestorableNum<T> {
372    /// Creates a [`RestorableNum`].
373    ///
374    /// If no restoration data is available to restore the value in this property from, the
375    /// property will be initialized with the provided `default_value`.
376    pub fn new(app: &mut App, default_value: T) -> Ref<RestorableNum<T>> {
377        app.create(RestorableNum {
378            change_notifier: ChangeNotifierData::new(),
379            property: RestorablePropertyData::new(),
380            value: RestorableValueData::new(),
381            primitive: RestorablePrimitiveValueData::new(default_value),
382        })
383    }
384}
385
386impl<T: RestorableNumValue> ChangeNotifier for RestorableNum<T> {
387    fn change_notifier_data(&self) -> &ChangeNotifierData {
388        &self.change_notifier
389    }
390
391    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
392        &mut self.change_notifier
393    }
394}
395
396impl<T: RestorableNumValue> RestorableProperty for RestorableNum<T> {
397    type Value = T;
398    crate::restorable_property_accessors!();
399
400    fn create_default_value(self: Handle<Self>, app: &mut App) -> T {
401        RestorablePrimitiveValueN::create_default_value(self, app)
402    }
403
404    fn from_primitives(self: Handle<Self>, app: &mut App, data: &RestorationData) -> T {
405        RestorablePrimitiveValueN::from_primitives(self, app, data)
406    }
407
408    fn init_with_value(self: Handle<Self>, app: &mut App, value: T) {
409        RestorableValue::init_with_value(self, app, value);
410    }
411
412    fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
413        RestorablePrimitiveValueN::to_primitives(self, app)
414    }
415}
416
417impl<T: RestorableNumValue> RestorableValue for RestorableNum<T> {
418    crate::restorable_value_accessors!();
419
420    fn did_update_value(self: Handle<Self>, app: &mut App, old_value: Option<T>) {
421        RestorablePrimitiveValueN::did_update_value(self, app, old_value);
422    }
423}
424
425impl<T: RestorableNumValue> RestorablePrimitiveValueN for RestorableNum<T> {
426    crate::restorable_primitive_value_accessors!();
427}
428
429impl<T: RestorableNumValue> RestorablePrimitiveValue for RestorableNum<T> {}
430
431/// A [`RestorableProperty`] that knows how to store and restore an `f64`; Dart's
432/// `RestorableDouble`, which adds nothing to [`RestorableNum`] but the name.
433///
434/// See also:
435///
436///  * [`RestorableDoubleN`] for the nullable version of this property.
437pub type RestorableDouble = RestorableNum<f64>;
438
439/// A [`RestorableProperty`] that knows how to store and restore an `i64`; Dart's
440/// `RestorableInt`, which adds nothing to [`RestorableNum`] but the name.
441///
442/// See also:
443///
444///  * [`RestorableIntN`] for the nullable version of this property.
445pub type RestorableInt = RestorableNum<i64>;
446
447/// A [`RestorableProperty`] that knows how to store and restore a `String`.
448///
449/// The current value of this property is stored in the restoration data. During state
450/// restoration the property is restored to the value it had when the restoration data it is
451/// getting restored from was collected.
452///
453/// If no restoration data is available, the value is initialized to the `default_value` given in
454/// the constructor.
455///
456/// See also:
457///
458///  * [`RestorableStringN`] for the nullable version of this property.
459pub struct RestorableString {
460    change_notifier: ChangeNotifierData,
461    property: RestorablePropertyData,
462    value: RestorableValueData<String>,
463    primitive: RestorablePrimitiveValueData<String>,
464}
465
466impl RestorableString {
467    /// Creates a [`RestorableString`].
468    ///
469    /// If no restoration data is available to restore the value in this property from, the
470    /// property will be initialized with the provided `default_value`.
471    pub fn new(app: &mut App, default_value: impl Into<String>) -> Ref<RestorableString> {
472        app.create(RestorableString {
473            change_notifier: ChangeNotifierData::new(),
474            property: RestorablePropertyData::new(),
475            value: RestorableValueData::new(),
476            primitive: RestorablePrimitiveValueData::new(default_value.into()),
477        })
478    }
479}
480
481impl ChangeNotifier for RestorableString {
482    fn change_notifier_data(&self) -> &ChangeNotifierData {
483        &self.change_notifier
484    }
485
486    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
487        &mut self.change_notifier
488    }
489}
490
491impl RestorableProperty for RestorableString {
492    type Value = String;
493    crate::restorable_property_accessors!();
494
495    fn create_default_value(self: Handle<Self>, app: &mut App) -> String {
496        RestorablePrimitiveValueN::create_default_value(self, app)
497    }
498
499    fn from_primitives(self: Handle<Self>, app: &mut App, data: &RestorationData) -> String {
500        RestorablePrimitiveValueN::from_primitives(self, app, data)
501    }
502
503    fn init_with_value(self: Handle<Self>, app: &mut App, value: String) {
504        RestorableValue::init_with_value(self, app, value);
505    }
506
507    fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
508        RestorablePrimitiveValueN::to_primitives(self, app)
509    }
510}
511
512impl RestorableValue for RestorableString {
513    crate::restorable_value_accessors!();
514
515    fn did_update_value(self: Handle<Self>, app: &mut App, old_value: Option<String>) {
516        RestorablePrimitiveValueN::did_update_value(self, app, old_value);
517    }
518}
519
520impl RestorablePrimitiveValueN for RestorableString {
521    crate::restorable_primitive_value_accessors!();
522}
523
524impl RestorablePrimitiveValue for RestorableString {}
525
526/// A [`RestorableProperty`] that knows how to store and restore a `bool`.
527///
528/// The current value of this property is stored in the restoration data. During state
529/// restoration the property is restored to the value it had when the restoration data it is
530/// getting restored from was collected.
531///
532/// If no restoration data is available, the value is initialized to the `default_value` given in
533/// the constructor.
534///
535/// See also:
536///
537///  * [`RestorableBoolN`] for the nullable version of this property.
538pub struct RestorableBool {
539    change_notifier: ChangeNotifierData,
540    property: RestorablePropertyData,
541    value: RestorableValueData<bool>,
542    primitive: RestorablePrimitiveValueData<bool>,
543}
544
545impl RestorableBool {
546    /// Creates a [`RestorableBool`].
547    ///
548    /// If no restoration data is available to restore the value in this property from, the
549    /// property will be initialized with the provided `default_value`.
550    pub fn new(app: &mut App, default_value: bool) -> Ref<RestorableBool> {
551        app.create(RestorableBool {
552            change_notifier: ChangeNotifierData::new(),
553            property: RestorablePropertyData::new(),
554            value: RestorableValueData::new(),
555            primitive: RestorablePrimitiveValueData::new(default_value),
556        })
557    }
558}
559
560impl ChangeNotifier for RestorableBool {
561    fn change_notifier_data(&self) -> &ChangeNotifierData {
562        &self.change_notifier
563    }
564
565    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
566        &mut self.change_notifier
567    }
568}
569
570impl RestorableProperty for RestorableBool {
571    type Value = bool;
572    crate::restorable_property_accessors!();
573
574    fn create_default_value(self: Handle<Self>, app: &mut App) -> bool {
575        RestorablePrimitiveValueN::create_default_value(self, app)
576    }
577
578    fn from_primitives(self: Handle<Self>, app: &mut App, data: &RestorationData) -> bool {
579        RestorablePrimitiveValueN::from_primitives(self, app, data)
580    }
581
582    fn init_with_value(self: Handle<Self>, app: &mut App, value: bool) {
583        RestorableValue::init_with_value(self, app, value);
584    }
585
586    fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
587        RestorablePrimitiveValueN::to_primitives(self, app)
588    }
589}
590
591impl RestorableValue for RestorableBool {
592    crate::restorable_value_accessors!();
593
594    fn did_update_value(self: Handle<Self>, app: &mut App, old_value: Option<bool>) {
595        RestorablePrimitiveValueN::did_update_value(self, app, old_value);
596    }
597}
598
599impl RestorablePrimitiveValueN for RestorableBool {
600    crate::restorable_primitive_value_accessors!();
601}
602
603impl RestorablePrimitiveValue for RestorableBool {}
604
605/// A [`RestorableProperty`] that knows how to store and restore a `bool` that is nullable.
606///
607/// The current value of this property is stored in the restoration data. During state
608/// restoration the property is restored to the value it had when the restoration data it is
609/// getting restored from was collected.
610///
611/// If no restoration data is available, the value is initialized to the `default_value` given in
612/// the constructor.
613///
614/// See also:
615///
616///  * [`RestorableBool`] for the non-nullable version of this property.
617pub struct RestorableBoolN {
618    change_notifier: ChangeNotifierData,
619    property: RestorablePropertyData,
620    value: RestorableValueData<Option<bool>>,
621    primitive: RestorablePrimitiveValueData<Option<bool>>,
622}
623
624impl RestorableBoolN {
625    /// Creates a [`RestorableBoolN`].
626    ///
627    /// If no restoration data is available to restore the value in this property from, the
628    /// property will be initialized with the provided `default_value`.
629    pub fn new(app: &mut App, default_value: Option<bool>) -> Ref<RestorableBoolN> {
630        app.create(RestorableBoolN {
631            change_notifier: ChangeNotifierData::new(),
632            property: RestorablePropertyData::new(),
633            value: RestorableValueData::new(),
634            primitive: RestorablePrimitiveValueData::new(default_value),
635        })
636    }
637}
638
639impl ChangeNotifier for RestorableBoolN {
640    fn change_notifier_data(&self) -> &ChangeNotifierData {
641        &self.change_notifier
642    }
643
644    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
645        &mut self.change_notifier
646    }
647}
648
649impl RestorableProperty for RestorableBoolN {
650    type Value = Option<bool>;
651    crate::restorable_property_accessors!();
652
653    fn create_default_value(self: Handle<Self>, app: &mut App) -> Option<bool> {
654        RestorablePrimitiveValueN::create_default_value(self, app)
655    }
656
657    fn from_primitives(self: Handle<Self>, app: &mut App, data: &RestorationData) -> Option<bool> {
658        RestorablePrimitiveValueN::from_primitives(self, app, data)
659    }
660
661    fn init_with_value(self: Handle<Self>, app: &mut App, value: Option<bool>) {
662        RestorableValue::init_with_value(self, app, value);
663    }
664
665    fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
666        RestorablePrimitiveValueN::to_primitives(self, app)
667    }
668}
669
670impl RestorableValue for RestorableBoolN {
671    crate::restorable_value_accessors!();
672
673    fn did_update_value(self: Handle<Self>, app: &mut App, old_value: Option<Option<bool>>) {
674        RestorablePrimitiveValueN::did_update_value(self, app, old_value);
675    }
676}
677
678impl RestorablePrimitiveValueN for RestorableBoolN {
679    crate::restorable_primitive_value_accessors!();
680}
681
682/// A [`RestorableProperty`] that knows how to store and restore a number that is nullable.
683///
684/// The current value of this property is stored in the restoration data. During state
685/// restoration the property is restored to the value it had when the restoration data it is
686/// getting restored from was collected.
687///
688/// If no restoration data is available, the value is initialized to the `default_value` given in
689/// the constructor.
690///
691/// Instead of using the more generic [`RestorableNumN`] directly, consider using one of the more
692/// specific aliases ([`RestorableDoubleN`] to store an `f64` and [`RestorableIntN`] to store an
693/// `i64`).
694///
695/// See also:
696///
697///  * [`RestorableNum`] for the non-nullable version of this property.
698pub struct RestorableNumN<T: RestorableNumValue> {
699    change_notifier: ChangeNotifierData,
700    property: RestorablePropertyData,
701    value: RestorableValueData<Option<T>>,
702    primitive: RestorablePrimitiveValueData<Option<T>>,
703}
704
705impl<T: RestorableNumValue> RestorableNumN<T> {
706    /// Creates a [`RestorableNumN`].
707    ///
708    /// If no restoration data is available to restore the value in this property from, the
709    /// property will be initialized with the provided `default_value`.
710    pub fn new(app: &mut App, default_value: Option<T>) -> Ref<RestorableNumN<T>> {
711        app.create(RestorableNumN {
712            change_notifier: ChangeNotifierData::new(),
713            property: RestorablePropertyData::new(),
714            value: RestorableValueData::new(),
715            primitive: RestorablePrimitiveValueData::new(default_value),
716        })
717    }
718}
719
720impl<T: RestorableNumValue> ChangeNotifier for RestorableNumN<T> {
721    fn change_notifier_data(&self) -> &ChangeNotifierData {
722        &self.change_notifier
723    }
724
725    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
726        &mut self.change_notifier
727    }
728}
729
730impl<T: RestorableNumValue> RestorableProperty for RestorableNumN<T> {
731    type Value = Option<T>;
732    crate::restorable_property_accessors!();
733
734    fn create_default_value(self: Handle<Self>, app: &mut App) -> Option<T> {
735        RestorablePrimitiveValueN::create_default_value(self, app)
736    }
737
738    fn from_primitives(self: Handle<Self>, app: &mut App, data: &RestorationData) -> Option<T> {
739        RestorablePrimitiveValueN::from_primitives(self, app, data)
740    }
741
742    fn init_with_value(self: Handle<Self>, app: &mut App, value: Option<T>) {
743        RestorableValue::init_with_value(self, app, value);
744    }
745
746    fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
747        RestorablePrimitiveValueN::to_primitives(self, app)
748    }
749}
750
751impl<T: RestorableNumValue> RestorableValue for RestorableNumN<T> {
752    crate::restorable_value_accessors!();
753
754    fn did_update_value(self: Handle<Self>, app: &mut App, old_value: Option<Option<T>>) {
755        RestorablePrimitiveValueN::did_update_value(self, app, old_value);
756    }
757}
758
759impl<T: RestorableNumValue> RestorablePrimitiveValueN for RestorableNumN<T> {
760    crate::restorable_primitive_value_accessors!();
761}
762
763/// A [`RestorableProperty`] that knows how to store and restore an `f64` that is nullable;
764/// Dart's `RestorableDoubleN`, which adds nothing to [`RestorableNumN`] but the name.
765///
766/// See also:
767///
768///  * [`RestorableDouble`] for the non-nullable version of this property.
769pub type RestorableDoubleN = RestorableNumN<f64>;
770
771/// A [`RestorableProperty`] that knows how to store and restore an `i64` that is nullable;
772/// Dart's `RestorableIntN`, which adds nothing to [`RestorableNumN`] but the name.
773///
774/// See also:
775///
776///  * [`RestorableInt`] for the non-nullable version of this property.
777pub type RestorableIntN = RestorableNumN<i64>;
778
779/// A [`RestorableProperty`] that knows how to store and restore a `String` that is nullable.
780///
781/// The current value of this property is stored in the restoration data. During state
782/// restoration the property is restored to the value it had when the restoration data it is
783/// getting restored from was collected.
784///
785/// If no restoration data is available, the value is initialized to the `default_value` given in
786/// the constructor.
787///
788/// See also:
789///
790///  * [`RestorableString`] for the non-nullable version of this property.
791pub struct RestorableStringN {
792    change_notifier: ChangeNotifierData,
793    property: RestorablePropertyData,
794    value: RestorableValueData<Option<String>>,
795    primitive: RestorablePrimitiveValueData<Option<String>>,
796}
797
798impl RestorableStringN {
799    /// Creates a [`RestorableStringN`].
800    ///
801    /// If no restoration data is available to restore the value in this property from, the
802    /// property will be initialized with the provided `default_value`.
803    pub fn new(app: &mut App, default_value: Option<String>) -> Ref<RestorableStringN> {
804        app.create(RestorableStringN {
805            change_notifier: ChangeNotifierData::new(),
806            property: RestorablePropertyData::new(),
807            value: RestorableValueData::new(),
808            primitive: RestorablePrimitiveValueData::new(default_value),
809        })
810    }
811}
812
813impl ChangeNotifier for RestorableStringN {
814    fn change_notifier_data(&self) -> &ChangeNotifierData {
815        &self.change_notifier
816    }
817
818    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
819        &mut self.change_notifier
820    }
821}
822
823impl RestorableProperty for RestorableStringN {
824    type Value = Option<String>;
825    crate::restorable_property_accessors!();
826
827    fn create_default_value(self: Handle<Self>, app: &mut App) -> Option<String> {
828        RestorablePrimitiveValueN::create_default_value(self, app)
829    }
830
831    fn from_primitives(
832        self: Handle<Self>,
833        app: &mut App,
834        data: &RestorationData,
835    ) -> Option<String> {
836        RestorablePrimitiveValueN::from_primitives(self, app, data)
837    }
838
839    fn init_with_value(self: Handle<Self>, app: &mut App, value: Option<String>) {
840        RestorableValue::init_with_value(self, app, value);
841    }
842
843    fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
844        RestorablePrimitiveValueN::to_primitives(self, app)
845    }
846}
847
848impl RestorableValue for RestorableStringN {
849    crate::restorable_value_accessors!();
850
851    fn did_update_value(self: Handle<Self>, app: &mut App, old_value: Option<Option<String>>) {
852        RestorablePrimitiveValueN::did_update_value(self, app, old_value);
853    }
854}
855
856impl RestorablePrimitiveValueN for RestorableStringN {
857    crate::restorable_primitive_value_accessors!();
858}
859
860// ---------------------------------------------------------------------------------------------
861// RestorableDateTime
862
863/// A [`RestorableValue`] that knows how to save and restore a [`DateTime`].
864///
865/// The current value of this property is stored in the restoration data as the milliseconds
866/// since the epoch. During state restoration the property is restored to the value it had when
867/// the restoration data it is getting restored from was collected.
868///
869/// If no restoration data is available, the value is initialized to the `default_value` given in
870/// the constructor.
871pub struct RestorableDateTime {
872    change_notifier: ChangeNotifierData,
873    property: RestorablePropertyData,
874    value: RestorableValueData<DateTime>,
875    default_value: DateTime,
876}
877
878impl RestorableDateTime {
879    /// Creates a [`RestorableDateTime`].
880    ///
881    /// If no restoration data is available to restore the value in this property from, the
882    /// property will be initialized with the provided `default_value`.
883    pub fn new(app: &mut App, default_value: DateTime) -> Ref<RestorableDateTime> {
884        app.create(RestorableDateTime {
885            change_notifier: ChangeNotifierData::new(),
886            property: RestorablePropertyData::new(),
887            value: RestorableValueData::new(),
888            default_value,
889        })
890    }
891}
892
893impl ChangeNotifier for RestorableDateTime {
894    fn change_notifier_data(&self) -> &ChangeNotifierData {
895        &self.change_notifier
896    }
897
898    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
899        &mut self.change_notifier
900    }
901}
902
903impl RestorableProperty for RestorableDateTime {
904    type Value = DateTime;
905    crate::restorable_property_accessors!();
906
907    fn create_default_value(self: Handle<Self>, app: &mut App) -> DateTime {
908        app.get(self).default_value
909    }
910
911    fn from_primitives(self: Handle<Self>, _app: &mut App, data: &RestorationData) -> DateTime {
912        DateTime::from_milliseconds_since_epoch(
913            data.as_int()
914                .expect("the restoration data of a DateTime property is an int"),
915            false,
916        )
917    }
918
919    fn init_with_value(self: Handle<Self>, app: &mut App, value: DateTime) {
920        RestorableValue::init_with_value(self, app, value);
921    }
922
923    fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
924        RestorationData::Int(RestorableValue::value(self, app).milliseconds_since_epoch())
925    }
926}
927
928impl RestorableValue for RestorableDateTime {
929    crate::restorable_value_accessors!();
930
931    fn did_update_value(self: Handle<Self>, app: &mut App, old_value: Option<DateTime>) {
932        let _ = old_value;
933        self.notify_listeners(app);
934    }
935}
936
937/// A [`RestorableValue`] that knows how to save and restore a [`DateTime`] that is nullable.
938///
939/// The current value of this property is stored in the restoration data as the milliseconds
940/// since the epoch. During state restoration the property is restored to the value it had when
941/// the restoration data it is getting restored from was collected.
942///
943/// If no restoration data is available, the value is initialized to the `default_value` given in
944/// the constructor.
945pub struct RestorableDateTimeN {
946    change_notifier: ChangeNotifierData,
947    property: RestorablePropertyData,
948    value: RestorableValueData<Option<DateTime>>,
949    default_value: Option<DateTime>,
950}
951
952impl RestorableDateTimeN {
953    /// Creates a [`RestorableDateTimeN`].
954    ///
955    /// If no restoration data is available to restore the value in this property from, the
956    /// property will be initialized with the provided `default_value`.
957    pub fn new(app: &mut App, default_value: Option<DateTime>) -> Ref<RestorableDateTimeN> {
958        app.create(RestorableDateTimeN {
959            change_notifier: ChangeNotifierData::new(),
960            property: RestorablePropertyData::new(),
961            value: RestorableValueData::new(),
962            default_value,
963        })
964    }
965}
966
967impl ChangeNotifier for RestorableDateTimeN {
968    fn change_notifier_data(&self) -> &ChangeNotifierData {
969        &self.change_notifier
970    }
971
972    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
973        &mut self.change_notifier
974    }
975}
976
977impl RestorableProperty for RestorableDateTimeN {
978    type Value = Option<DateTime>;
979    crate::restorable_property_accessors!();
980
981    fn create_default_value(self: Handle<Self>, app: &mut App) -> Option<DateTime> {
982        app.get(self).default_value
983    }
984
985    fn from_primitives(
986        self: Handle<Self>,
987        _app: &mut App,
988        data: &RestorationData,
989    ) -> Option<DateTime> {
990        data.as_int()
991            .map(|milliseconds| DateTime::from_milliseconds_since_epoch(milliseconds, false))
992    }
993
994    fn init_with_value(self: Handle<Self>, app: &mut App, value: Option<DateTime>) {
995        RestorableValue::init_with_value(self, app, value);
996    }
997
998    fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
999        RestorableValue::value(self, app).map_or(RestorationData::Null, |value| {
1000            RestorationData::Int(value.milliseconds_since_epoch())
1001        })
1002    }
1003}
1004
1005impl RestorableValue for RestorableDateTimeN {
1006    crate::restorable_value_accessors!();
1007
1008    fn did_update_value(self: Handle<Self>, app: &mut App, old_value: Option<Option<DateTime>>) {
1009        let _ = old_value;
1010        self.notify_listeners(app);
1011    }
1012}
1013
1014// ---------------------------------------------------------------------------------------------
1015// RestorableEnum
1016
1017/// Dart's `EnumName.name`: the variant's name, which is what a derived `Debug` prints.
1018fn enum_name<T: Debug>(value: &T) -> String {
1019    format!("{value:?}")
1020}
1021
1022/// A [`RestorableProperty`] that knows how to store and restore an enum.
1023///
1024/// The current value of this property is stored in the restoration data. During state
1025/// restoration the property is restored to the value it had when the restoration data it is
1026/// getting restored from was collected.
1027///
1028/// If no restoration data is available, the value is initialized to the `default_value` given in
1029/// the constructor.
1030///
1031/// The values are serialized using the name of the variant, obtained from its `Debug`.
1032///
1033/// The set of values the property may represent is [`values`](Self::values), which the
1034/// constructor takes.
1035///
1036/// See also:
1037///
1038///  * [`RestorableEnumN`], which knows how to store and restore nullable enums.
1039pub struct RestorableEnum<T: Copy + Debug + PartialEq + 'static> {
1040    change_notifier: ChangeNotifierData,
1041    property: RestorablePropertyData,
1042    value: RestorableValueData<T>,
1043    default_value: T,
1044    values: Vec<T>,
1045}
1046
1047impl<T: Copy + Debug + PartialEq + 'static> RestorableEnum<T> {
1048    /// Creates a [`RestorableEnum`].
1049    ///
1050    /// If no restoration data is available to restore the value in this property from, the
1051    /// property will be initialized with the provided `default_value`.
1052    pub fn new(
1053        app: &mut App,
1054        default_value: T,
1055        values: impl IntoIterator<Item = T>,
1056    ) -> Ref<RestorableEnum<T>> {
1057        let values: Vec<T> = values.into_iter().collect();
1058        assert!(
1059            values.contains(&default_value),
1060            "Default value {default_value:?} not found in the values: {values:?}"
1061        );
1062        app.create(RestorableEnum {
1063            change_notifier: ChangeNotifierData::new(),
1064            property: RestorablePropertyData::new(),
1065            value: RestorableValueData::new(),
1066            default_value,
1067            values,
1068        })
1069    }
1070
1071    /// The set of values that this [`RestorableEnum`] may represent.
1072    ///
1073    /// This supplies the enum values that are serialized and restored. If a value is
1074    /// encountered that is not in this set,
1075    /// [`from_primitives`](RestorableProperty::from_primitives) asserts when restoring.
1076    ///
1077    /// It is typically every variant of the enum type.
1078    pub fn values(self: Handle<Self>, app: &App) -> &[T] {
1079        &app.get(self).values
1080    }
1081
1082    /// See [`values`](Self::values).
1083    pub fn set_values(self: Handle<Self>, app: &mut App, values: impl IntoIterator<Item = T>) {
1084        app.get_mut(self).values = values.into_iter().collect();
1085    }
1086}
1087
1088impl<T: Copy + Debug + PartialEq + 'static> ChangeNotifier for RestorableEnum<T> {
1089    fn change_notifier_data(&self) -> &ChangeNotifierData {
1090        &self.change_notifier
1091    }
1092
1093    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
1094        &mut self.change_notifier
1095    }
1096}
1097
1098impl<T: Copy + Debug + PartialEq + 'static> RestorableProperty for RestorableEnum<T> {
1099    type Value = T;
1100    crate::restorable_property_accessors!();
1101
1102    fn create_default_value(self: Handle<Self>, app: &mut App) -> T {
1103        app.get(self).default_value
1104    }
1105
1106    fn from_primitives(self: Handle<Self>, app: &mut App, data: &RestorationData) -> T {
1107        if let Some(name) = data.as_str() {
1108            if let Some(allowed) = app
1109                .get(self)
1110                .values
1111                .iter()
1112                .find(|value| enum_name(value) == name)
1113            {
1114                return *allowed;
1115            }
1116            debug_assert!(
1117                false,
1118                "Attempted to restore an unknown enum value \"{name}\" that is not in the valid \
1119                 set of enum values: {:?}",
1120                app.get(self).values
1121            );
1122        }
1123        app.get(self).default_value
1124    }
1125
1126    fn init_with_value(self: Handle<Self>, app: &mut App, value: T) {
1127        RestorableValue::init_with_value(self, app, value);
1128    }
1129
1130    fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
1131        RestorationData::String(enum_name(RestorableValue::value(self, app)))
1132    }
1133}
1134
1135impl<T: Copy + Debug + PartialEq + 'static> RestorableValue for RestorableEnum<T> {
1136    crate::restorable_value_accessors!();
1137
1138    fn did_update_value(self: Handle<Self>, app: &mut App, old_value: Option<T>) {
1139        let _ = old_value;
1140        self.notify_listeners(app);
1141    }
1142
1143    fn debug_assert_valid_value(self: Handle<Self>, app: &App, new_value: &T) -> bool {
1144        assert!(
1145            app.get(self).values.contains(new_value),
1146            "Attempted to set an unknown enum value \"{new_value:?}\" that is not in the valid \
1147             set of enum values: {:?}",
1148            app.get(self).values
1149        );
1150        true
1151    }
1152}
1153
1154/// A [`RestorableProperty`] that knows how to store and restore an enum that is nullable.
1155///
1156/// The current value of this property is stored in the restoration data. During state
1157/// restoration the property is restored to the value it had when the restoration data it is
1158/// getting restored from was collected.
1159///
1160/// If no restoration data is available, the value is initialized to the `default_value` given in
1161/// the constructor.
1162///
1163/// The values are serialized using the name of the variant, obtained from its `Debug`.
1164///
1165/// The set of non-`None` values the property may represent is [`values`](Self::values), which
1166/// the constructor takes; since [`RestorableEnumN`] allows `None`, that is a valid value too
1167/// even though it does not appear in the set.
1168///
1169/// See also:
1170///
1171///  * [`RestorableEnum`], which knows how to store and restore non-nullable enums.
1172pub struct RestorableEnumN<T: Copy + Debug + PartialEq + 'static> {
1173    change_notifier: ChangeNotifierData,
1174    property: RestorablePropertyData,
1175    value: RestorableValueData<Option<T>>,
1176    default_value: Option<T>,
1177    values: Vec<T>,
1178}
1179
1180impl<T: Copy + Debug + PartialEq + 'static> RestorableEnumN<T> {
1181    /// Creates a [`RestorableEnumN`].
1182    ///
1183    /// If no restoration data is available to restore the value in this property from, the
1184    /// property will be initialized with the provided `default_value`.
1185    pub fn new(
1186        app: &mut App,
1187        default_value: Option<T>,
1188        values: impl IntoIterator<Item = T>,
1189    ) -> Ref<RestorableEnumN<T>> {
1190        let values: Vec<T> = values.into_iter().collect();
1191        assert!(
1192            default_value.is_none_or(|default| values.contains(&default)),
1193            "Default value {default_value:?} not found in the values: {values:?}"
1194        );
1195        app.create(RestorableEnumN {
1196            change_notifier: ChangeNotifierData::new(),
1197            property: RestorablePropertyData::new(),
1198            value: RestorableValueData::new(),
1199            default_value,
1200            values,
1201        })
1202    }
1203
1204    /// The set of non-`None` values that this [`RestorableEnumN`] may represent.
1205    ///
1206    /// This supplies the enum values that are serialized and restored. If a value is
1207    /// encountered that is neither `None` nor in this set,
1208    /// [`from_primitives`](RestorableProperty::from_primitives) asserts when restoring.
1209    ///
1210    /// It is typically every variant of the enum type.
1211    pub fn values(self: Handle<Self>, app: &App) -> &[T] {
1212        &app.get(self).values
1213    }
1214
1215    /// See [`values`](Self::values).
1216    pub fn set_values(self: Handle<Self>, app: &mut App, values: impl IntoIterator<Item = T>) {
1217        app.get_mut(self).values = values.into_iter().collect();
1218    }
1219}
1220
1221impl<T: Copy + Debug + PartialEq + 'static> ChangeNotifier for RestorableEnumN<T> {
1222    fn change_notifier_data(&self) -> &ChangeNotifierData {
1223        &self.change_notifier
1224    }
1225
1226    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
1227        &mut self.change_notifier
1228    }
1229}
1230
1231impl<T: Copy + Debug + PartialEq + 'static> RestorableProperty for RestorableEnumN<T> {
1232    type Value = Option<T>;
1233    crate::restorable_property_accessors!();
1234
1235    fn create_default_value(self: Handle<Self>, app: &mut App) -> Option<T> {
1236        app.get(self).default_value
1237    }
1238
1239    fn from_primitives(self: Handle<Self>, app: &mut App, data: &RestorationData) -> Option<T> {
1240        if data.is_null() {
1241            return None;
1242        }
1243        if let Some(name) = data.as_str() {
1244            if let Some(allowed) = app
1245                .get(self)
1246                .values
1247                .iter()
1248                .find(|value| enum_name(value) == name)
1249            {
1250                return Some(*allowed);
1251            }
1252            debug_assert!(
1253                false,
1254                "Attempted to set an unknown enum value \"{name}\" that is not null, or in the \
1255                 valid set of enum values: {:?}",
1256                app.get(self).values
1257            );
1258        }
1259        app.get(self).default_value
1260    }
1261
1262    fn init_with_value(self: Handle<Self>, app: &mut App, value: Option<T>) {
1263        RestorableValue::init_with_value(self, app, value);
1264    }
1265
1266    fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
1267        RestorableValue::value(self, app)
1268            .as_ref()
1269            .map_or(RestorationData::Null, |value| {
1270                RestorationData::String(enum_name(value))
1271            })
1272    }
1273}
1274
1275impl<T: Copy + Debug + PartialEq + 'static> RestorableValue for RestorableEnumN<T> {
1276    crate::restorable_value_accessors!();
1277
1278    fn did_update_value(self: Handle<Self>, app: &mut App, old_value: Option<Option<T>>) {
1279        let _ = old_value;
1280        self.notify_listeners(app);
1281    }
1282
1283    fn debug_assert_valid_value(self: Handle<Self>, app: &App, new_value: &Option<T>) -> bool {
1284        assert!(
1285            new_value.is_none_or(|value| app.get(self).values.contains(&value)),
1286            "Attempted to set an unknown enum value \"{new_value:?}\" that is not null, or in \
1287             the valid set of enum values: {:?}",
1288            app.get(self).values
1289        );
1290        true
1291    }
1292}
1293
1294// ---------------------------------------------------------------------------------------------
1295// RestorableListenable and RestorableChangeNotifier
1296
1297/// Dart's private `_value` of `RestorableListenable`; a listenable property carries this bag
1298/// under the field `listenable`.
1299pub struct RestorableListenableData<T> {
1300    value: Option<T>,
1301}
1302
1303impl<T> RestorableListenableData<T> {
1304    /// A property whose [`init_with_value`](RestorableProperty::init_with_value) has not run.
1305    pub fn new() -> RestorableListenableData<T> {
1306        RestorableListenableData { value: None }
1307    }
1308}
1309
1310impl<T> Default for RestorableListenableData<T> {
1311    fn default() -> RestorableListenableData<T> {
1312        RestorableListenableData::new()
1313    }
1314}
1315
1316/// The accessors [`RestorableListenable`] asks for, for a property whose bag is the field
1317/// `listenable`.
1318#[macro_export]
1319macro_rules! restorable_listenable_accessors {
1320    () => {
1321        fn restorable_listenable_data(
1322            self: ::waft_foundation::Handle<Self>,
1323            app: &::waft_foundation::App,
1324        ) -> &$crate::RestorableListenableData<Self::Value> {
1325            &app.get(self).listenable
1326        }
1327
1328        fn restorable_listenable_data_mut(
1329            self: ::waft_foundation::Handle<Self>,
1330            app: &mut ::waft_foundation::App,
1331        ) -> &mut $crate::RestorableListenableData<Self::Value> {
1332            &mut app.get_mut(self).listenable
1333        }
1334    };
1335}
1336
1337/// A base for a [`RestorableProperty`] that stores and restores a
1338/// [`Listenable`](waft_foundation::Listenable).
1339///
1340/// This trait may be used to implement a [`RestorableProperty`] for a listenable whose
1341/// information it needs to store in the restoration data changes whenever the listenable
1342/// notifies its listeners.
1343///
1344/// The [`RestorationMixin`](crate::RestorationMixin) this property is registered with will call
1345/// [`to_primitives`](RestorableProperty::to_primitives) whenever the wrapped listenable notifies
1346/// its listeners, to update the information that this property has stored in the restoration
1347/// data.
1348pub trait RestorableListenable: RestorableProperty<Value: Listenable + Clone + 'static> {
1349    /// Dart's `RestorableListenable._value`, held under the field `listenable`
1350    /// ([`restorable_listenable_accessors!`](crate::restorable_listenable_accessors)).
1351    fn restorable_listenable_data(
1352        self: Handle<Self>,
1353        app: &App,
1354    ) -> &RestorableListenableData<Self::Value>;
1355
1356    /// See [`restorable_listenable_data`](Self::restorable_listenable_data).
1357    fn restorable_listenable_data_mut(
1358        self: Handle<Self>,
1359        app: &mut App,
1360    ) -> &mut RestorableListenableData<Self::Value>;
1361
1362    /// The listenable stored in this property.
1363    ///
1364    /// A representation of its current value is stored in the restoration data. During state
1365    /// restoration, the listenable returned by this getter will be restored to the state it had
1366    /// when the restoration data the property is getting restored from was collected.
1367    ///
1368    /// The value can only be accessed after the property has been registered with a
1369    /// [`RestorationMixin`](crate::RestorationMixin) by calling
1370    /// [`register_for_restoration`](crate::RestorationMixin::register_for_restoration).
1371    fn value(self: Handle<Self>, app: &App) -> Self::Value {
1372        debug_assert!(RestorableProperty::is_registered(self, app));
1373        self.restorable_listenable_data(app)
1374            .value
1375            .clone()
1376            .expect("init_with_value runs at registration")
1377    }
1378
1379    /// Dart's `RestorableListenable.initWithValue`: the old listenable is dropped and this
1380    /// property listens to the new one.
1381    fn init_with_value(self: Handle<Self>, app: &mut App, value: Self::Value) {
1382        let listener = self.notification_listener();
1383        if let Some(old_value) = self.restorable_listenable_data(app).value.clone() {
1384            old_value.remove_listener(app, &listener);
1385        }
1386        self.restorable_listenable_data_mut(app).value = Some(value.clone());
1387        value.add_listener(app, listener);
1388    }
1389
1390    /// Dart's `RestorableListenable.dispose`.
1391    fn dispose(self: Handle<Self>, app: &mut App) {
1392        RestorableProperty::dispose_property(self, app);
1393        let listener = self.notification_listener();
1394        if let Some(value) = self.restorable_listenable_data(app).value.clone() {
1395            value.remove_listener(app, &listener);
1396        }
1397    }
1398
1399    /// Dart's `notifyListeners` tear-off: the listener this property keeps on its value.
1400    fn notification_listener(self: Handle<Self>) -> Listener {
1401        Listener::handle_method(self, Self::forward_notification)
1402    }
1403
1404    /// The body behind [`notification_listener`](Self::notification_listener).
1405    fn forward_notification(self: Handle<Self>, app: &mut App) {
1406        self.notify_listeners(app);
1407    }
1408}
1409
1410/// A base for a [`RestorableProperty`] that stores and restores a
1411/// [`ChangeNotifier`](waft_foundation::ChangeNotifier).
1412///
1413/// This trait may be used to implement a [`RestorableProperty`] for a change notifier whose
1414/// information it needs to store in the restoration data changes whenever the notifier notifies
1415/// its listeners.
1416///
1417/// The [`RestorationMixin`](crate::RestorationMixin) this property is registered with will call
1418/// [`to_primitives`](RestorableProperty::to_primitives) whenever the wrapped notifier notifies
1419/// its listeners, to update the information that this property has stored in the restoration
1420/// data.
1421///
1422/// Furthermore, the property will dispose the wrapped notifier when either the property itself
1423/// is disposed or its value is replaced with another notifier.
1424pub trait RestorableChangeNotifier: RestorableListenable {
1425    /// Dart's `_value!.dispose()`: how the wrapped notifier is discarded.
1426    fn dispose_value(self: Handle<Self>, app: &mut App, value: Self::Value);
1427
1428    /// Dart's `RestorableChangeNotifier.initWithValue`.
1429    fn init_with_value(self: Handle<Self>, app: &mut App, value: Self::Value) {
1430        self.dispose_old_value(app);
1431        RestorableListenable::init_with_value(self, app, value);
1432    }
1433
1434    /// Dart's `RestorableChangeNotifier.dispose`.
1435    fn dispose(self: Handle<Self>, app: &mut App) {
1436        self.dispose_old_value(app);
1437        RestorableListenable::dispose(self, app);
1438    }
1439
1440    /// Dart's `_disposeOldValue`.
1441    fn dispose_old_value(self: Handle<Self>, app: &mut App) {
1442        if let Some(value) = self.restorable_listenable_data(app).value.clone() {
1443            // Scheduling a microtask for dispose to give other entities a chance to remove
1444            // their listeners first.
1445            app.schedule_microtask(Listener::new(move |app| {
1446                Self::dispose_value(self, app, value.clone());
1447            }));
1448        }
1449    }
1450}
1451
1452/// A [`RestorableProperty`] that knows how to store and restore a
1453/// [`TextEditingController`].
1454///
1455/// The [`TextEditingController`] is accessible via the [`value`](RestorableListenable::value)
1456/// getter. During state restoration, the property will restore
1457/// [`TextEditingController::text_value`] to the value it had when the restoration data it is
1458/// getting restored from was collected.
1459pub struct RestorableTextEditingController {
1460    change_notifier: ChangeNotifierData,
1461    property: RestorablePropertyData,
1462    listenable: RestorableListenableData<Ref<TextEditingController>>,
1463    initial_value: TextEditingValue,
1464}
1465
1466impl RestorableTextEditingController {
1467    /// Creates a [`RestorableTextEditingController`].
1468    ///
1469    /// This constructor treats a missing `text` argument as if it were the empty string.
1470    pub fn new(app: &mut App) -> Ref<RestorableTextEditingController> {
1471        Self::from_value(app, TextEditingValue::EMPTY)
1472    }
1473
1474    /// Dart `RestorableTextEditingController(text:)`.
1475    pub fn text(app: &mut App, text: impl Into<String>) -> Ref<RestorableTextEditingController> {
1476        Self::from_value(app, TextEditingValue::new().text(text))
1477    }
1478
1479    /// Creates a [`RestorableTextEditingController`] from an initial [`TextEditingValue`].
1480    pub fn from_value(
1481        app: &mut App,
1482        value: TextEditingValue,
1483    ) -> Ref<RestorableTextEditingController> {
1484        app.create(RestorableTextEditingController {
1485            change_notifier: ChangeNotifierData::new(),
1486            property: RestorablePropertyData::new(),
1487            listenable: RestorableListenableData::new(),
1488            initial_value: value,
1489        })
1490    }
1491}
1492
1493impl ChangeNotifier for RestorableTextEditingController {
1494    fn change_notifier_data(&self) -> &ChangeNotifierData {
1495        &self.change_notifier
1496    }
1497
1498    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
1499        &mut self.change_notifier
1500    }
1501}
1502
1503impl RestorableProperty for RestorableTextEditingController {
1504    type Value = Ref<TextEditingController>;
1505    crate::restorable_property_accessors!();
1506
1507    fn create_default_value(self: Handle<Self>, app: &mut App) -> Ref<TextEditingController> {
1508        let initial_value = app.get(self).initial_value.clone();
1509        TextEditingController::from_value(app, Some(initial_value))
1510    }
1511
1512    fn from_primitives(
1513        self: Handle<Self>,
1514        app: &mut App,
1515        data: &RestorationData,
1516    ) -> Ref<TextEditingController> {
1517        TextEditingController::new(app).text(
1518            app,
1519            data.as_str()
1520                .expect("RestorableTextEditingController stores a String"),
1521        )
1522    }
1523
1524    fn init_with_value(self: Handle<Self>, app: &mut App, value: Ref<TextEditingController>) {
1525        RestorableChangeNotifier::init_with_value(self, app, value);
1526    }
1527
1528    fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
1529        RestorationData::String(
1530            RestorableListenable::value(self, app)
1531                .text_value(app)
1532                .to_string(),
1533        )
1534    }
1535
1536    fn dispose(self: Handle<Self>, app: &mut App) {
1537        RestorableChangeNotifier::dispose(self, app);
1538    }
1539}
1540
1541impl RestorableListenable for RestorableTextEditingController {
1542    crate::restorable_listenable_accessors!();
1543}
1544
1545impl RestorableChangeNotifier for RestorableTextEditingController {
1546    fn dispose_value(self: Handle<Self>, app: &mut App, value: Ref<TextEditingController>) {
1547        value.dispose(app);
1548    }
1549}
1550
1551#[cfg(test)]
1552mod tests {
1553    use std::rc::Rc;
1554    use waft_foundation::AppCell;
1555
1556    use waft_foundation::{Handle, OptionRetained};
1557    use waft_services::{RestorationBucket, RestorationManager, RestorationMap};
1558
1559    use super::*;
1560    use crate::framework::{BuildContext, GlobalKey, KeyRef, StateData, StatefulWidget, WidgetRef};
1561    use crate::test_harness::Harness;
1562    use crate::widgets::basic::SizedBox;
1563    use crate::widgets::restoration::{
1564        RestorationMixin, RestorationMixinData, RootRestorationScope,
1565    };
1566    use crate::{IntoWidget, State};
1567
1568    #[derive(Clone, Copy, Debug, PartialEq)]
1569    enum Direction {
1570        Up,
1571        Down,
1572    }
1573
1574    const DIRECTIONS: [Direction; 2] = [Direction::Up, Direction::Down];
1575
1576    fn map<const N: usize>(entries: [(&str, RestorationData); N]) -> RestorationMap {
1577        entries
1578            .into_iter()
1579            .map(|(key, value)| (RestorationData::from(key), value))
1580            .collect()
1581    }
1582
1583    /// The raw map of a bucket that stores these values.
1584    fn values<const N: usize>(entries: [(&str, RestorationData); N]) -> RestorationMap {
1585        map([("v", map(entries).into())])
1586    }
1587
1588    /// The raw map of a bucket whose only content is one child.
1589    fn child(restoration_id: &str, data: RestorationMap) -> RestorationMap {
1590        map([("c", map([(restoration_id, data.into())]).into())])
1591    }
1592
1593    /// One property of every kind, so a single registration exercises them all.
1594    #[derive(Clone)]
1595    struct Properties {
1596        int: Ref<RestorableInt>,
1597        double: Ref<RestorableDouble>,
1598        string: Ref<RestorableString>,
1599        boolean: Ref<RestorableBool>,
1600        int_n: Ref<RestorableIntN>,
1601        double_n: Ref<RestorableDoubleN>,
1602        string_n: Ref<RestorableStringN>,
1603        bool_n: Ref<RestorableBoolN>,
1604        date_time: Ref<RestorableDateTime>,
1605        date_time_n: Ref<RestorableDateTimeN>,
1606        direction: Ref<RestorableEnum<Direction>>,
1607        direction_n: Ref<RestorableEnumN<Direction>>,
1608    }
1609
1610    impl Properties {
1611        fn new(app: &mut App) -> Properties {
1612            Properties {
1613                int: RestorableInt::new(app, 1),
1614                double: RestorableDouble::new(app, 1.5),
1615                string: RestorableString::new(app, "one"),
1616                boolean: RestorableBool::new(app, true),
1617                int_n: RestorableIntN::new(app, Some(2)),
1618                double_n: RestorableDoubleN::new(app, None),
1619                string_n: RestorableStringN::new(app, None),
1620                bool_n: RestorableBoolN::new(app, Some(false)),
1621                date_time: RestorableDateTime::new(
1622                    app,
1623                    DateTime::from_milliseconds_since_epoch(1000, false),
1624                ),
1625                date_time_n: RestorableDateTimeN::new(app, None),
1626                direction: RestorableEnum::new(app, Direction::Up, DIRECTIONS),
1627                direction_n: RestorableEnumN::new(app, None, DIRECTIONS),
1628            }
1629        }
1630
1631        fn register(self, state: Handle<BagState>, app: &mut App) {
1632            state.register_for_restoration(app, self.int.as_property(), "int");
1633            state.register_for_restoration(app, self.double.as_property(), "double");
1634            state.register_for_restoration(app, self.string.as_property(), "string");
1635            state.register_for_restoration(app, self.boolean.as_property(), "bool");
1636            state.register_for_restoration(app, self.int_n.as_property(), "int-n");
1637            state.register_for_restoration(app, self.double_n.as_property(), "double-n");
1638            state.register_for_restoration(app, self.string_n.as_property(), "string-n");
1639            state.register_for_restoration(app, self.bool_n.as_property(), "bool-n");
1640            state.register_for_restoration(app, self.date_time.as_property(), "date-time");
1641            state.register_for_restoration(app, self.date_time_n.as_property(), "date-time-n");
1642            state.register_for_restoration(app, self.direction.as_property(), "direction");
1643            state.register_for_restoration(app, self.direction_n.as_property(), "direction-n");
1644        }
1645    }
1646
1647    #[derive(Debug)]
1648    struct Bag {
1649        key: Option<KeyRef>,
1650    }
1651
1652    impl StatefulWidget for Bag {
1653        type State = BagState;
1654
1655        fn key(&self) -> Option<&KeyRef> {
1656            self.key.as_ref()
1657        }
1658
1659        fn create_state(&self) -> BagState {
1660            BagState {
1661                state: StateData::new(),
1662                restoration: RestorationMixinData::new(),
1663                properties: None,
1664            }
1665        }
1666    }
1667
1668    struct BagState {
1669        state: StateData<Bag>,
1670        restoration: RestorationMixinData,
1671        properties: Option<Properties>,
1672    }
1673
1674    impl RestorationMixin for BagState {
1675        crate::restoration_mixin_accessors!();
1676
1677        fn restoration_id(self: Handle<Self>, _app: &App) -> Option<&str> {
1678            Some("bag")
1679        }
1680
1681        fn restore_state(
1682            self: Handle<Self>,
1683            app: &mut App,
1684            _old_bucket: Option<Handle<RestorationBucket>>,
1685            _initial_restore: bool,
1686        ) {
1687            let properties = match app.get(self).properties.clone() {
1688                Some(properties) => properties,
1689                None => {
1690                    let properties = Properties::new(app);
1691                    app.get_mut(self).properties = Some(properties.clone());
1692                    properties
1693                }
1694            };
1695            properties.register(self, app);
1696        }
1697    }
1698
1699    impl State for BagState {
1700        type Widget = Bag;
1701        crate::state_accessors!();
1702
1703        fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
1704            self.did_change_dependencies_restoration(app);
1705        }
1706
1707        fn dispose(self: Handle<Self>, app: &mut App) {
1708            self.dispose_restoration(app);
1709        }
1710
1711        fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
1712            let _ = app;
1713            SizedBox::shrink().into_widget()
1714        }
1715    }
1716
1717    /// A mounted [`Bag`] under a root scope holding `data`.
1718    struct Fixture {
1719        cell: Rc<AppCell>,
1720        properties: Properties,
1721        bucket: Handle<RestorationBucket>,
1722    }
1723
1724    impl Fixture {
1725        fn mount(data: Option<RestorationMap>) -> Fixture {
1726            let cell = AppCell::new();
1727            let mut app = cell.borrow_mut();
1728            let manager = RestorationManager::instance(&mut app);
1729            manager.handle_restoration_update_from_engine(&mut app, true, data);
1730            let key = GlobalKey::new();
1731            let harness = Harness::mount(
1732                &mut app,
1733                RootRestorationScope::new(
1734                    Some("app".to_string()),
1735                    Bag {
1736                        key: Some(key.clone().into()),
1737                    },
1738                )
1739                .into_widget(),
1740            );
1741            harness.pump(&mut app);
1742            let state = harness
1743                .owner
1744                .global_key_element(&app, &key)
1745                .expect("the bag is in the tree")
1746                .state_handle::<BagState>(&app)
1747                .expect("a BagState");
1748            let properties = app
1749                .get(state)
1750                .properties
1751                .clone()
1752                .expect("restore_state ran");
1753            let bucket = state.bucket(&app).expect("the bag claimed a bucket");
1754            drop(app);
1755            Fixture {
1756                cell,
1757                properties,
1758                bucket,
1759            }
1760        }
1761
1762        fn stored(&mut self, restoration_id: &str) -> Option<RestorationData> {
1763            self.bucket
1764                .read(&mut self.cell.borrow_mut(), restoration_id)
1765        }
1766    }
1767
1768    /// The data a [`Fixture`] restores from when every property carries a non-default value.
1769    fn filled() -> Option<RestorationMap> {
1770        Some(child(
1771            "app",
1772            child(
1773                "bag",
1774                values([
1775                    ("int", 7i64.into()),
1776                    ("double", 2.5f64.into()),
1777                    ("string", "seven".into()),
1778                    ("bool", false.into()),
1779                    ("int-n", RestorationData::Null),
1780                    ("double-n", 0.5f64.into()),
1781                    ("string-n", "maybe".into()),
1782                    ("bool-n", RestorationData::Null),
1783                    ("date-time", 2000i64.into()),
1784                    ("date-time-n", 3000i64.into()),
1785                    ("direction", "Down".into()),
1786                    ("direction-n", "Up".into()),
1787                ]),
1788            ),
1789        ))
1790    }
1791
1792    #[test]
1793    fn a_property_with_no_stored_value_takes_the_default_it_was_created_with() {
1794        let fixture = Fixture::mount(None);
1795        let properties = fixture.properties.clone();
1796        let app = &mut fixture.cell.borrow_mut();
1797
1798        assert_eq!(*properties.int.value(app), 1);
1799        assert_eq!(*properties.double.value(app), 1.5);
1800        assert_eq!(properties.string.value(app), "one");
1801        assert!(*properties.boolean.value(app));
1802        assert_eq!(*properties.int_n.value(app), Some(2));
1803        assert_eq!(*properties.double_n.value(app), None);
1804        assert_eq!(*properties.string_n.value(app), None);
1805        assert_eq!(*properties.bool_n.value(app), Some(false));
1806        assert_eq!(
1807            *properties.date_time.value(app),
1808            DateTime::from_milliseconds_since_epoch(1000, false)
1809        );
1810        assert_eq!(*properties.date_time_n.value(app), None);
1811        assert_eq!(*properties.direction.value(app), Direction::Up);
1812        assert_eq!(*properties.direction_n.value(app), None);
1813    }
1814
1815    #[test]
1816    fn a_default_value_is_written_into_the_bucket_at_registration() {
1817        let mut fixture = Fixture::mount(None);
1818
1819        assert_eq!(fixture.stored("int"), Some(1i64.into()));
1820        assert_eq!(fixture.stored("double"), Some(1.5f64.into()));
1821        assert_eq!(fixture.stored("string"), Some("one".into()));
1822        assert_eq!(fixture.stored("bool"), Some(true.into()));
1823        assert_eq!(fixture.stored("int-n"), Some(2i64.into()));
1824        assert_eq!(fixture.stored("double-n"), Some(RestorationData::Null));
1825        assert_eq!(fixture.stored("string-n"), Some(RestorationData::Null));
1826        assert_eq!(fixture.stored("bool-n"), Some(false.into()));
1827        assert_eq!(fixture.stored("date-time"), Some(1000i64.into()));
1828        assert_eq!(fixture.stored("date-time-n"), Some(RestorationData::Null));
1829        assert_eq!(fixture.stored("direction"), Some("Up".into()));
1830        assert_eq!(fixture.stored("direction-n"), Some(RestorationData::Null));
1831    }
1832
1833    #[test]
1834    fn every_property_restores_the_value_the_data_describes() {
1835        let fixture = Fixture::mount(filled());
1836        let properties = fixture.properties.clone();
1837        let app = &mut fixture.cell.borrow_mut();
1838
1839        assert_eq!(*properties.int.value(app), 7);
1840        assert_eq!(*properties.double.value(app), 2.5);
1841        assert_eq!(properties.string.value(app), "seven");
1842        assert!(!*properties.boolean.value(app));
1843        assert_eq!(*properties.int_n.value(app), None);
1844        assert_eq!(*properties.double_n.value(app), Some(0.5));
1845        assert_eq!(properties.string_n.value(app).as_deref(), Some("maybe"));
1846        assert_eq!(*properties.bool_n.value(app), None);
1847        assert_eq!(
1848            *properties.date_time.value(app),
1849            DateTime::from_milliseconds_since_epoch(2000, false)
1850        );
1851        assert_eq!(
1852            *properties.date_time_n.value(app),
1853            Some(DateTime::from_milliseconds_since_epoch(3000, false))
1854        );
1855        assert_eq!(*properties.direction.value(app), Direction::Down);
1856        assert_eq!(*properties.direction_n.value(app), Some(Direction::Up));
1857    }
1858
1859    #[test]
1860    fn a_new_value_is_written_back_as_the_data_it_was_restored_from() {
1861        let mut fixture = Fixture::mount(filled());
1862        let properties = fixture.properties.clone();
1863        {
1864            let app = &mut fixture.cell.borrow_mut();
1865            properties.int.set_value(app, 8);
1866            properties.double.set_value(app, 3.5);
1867            properties.string.set_value(app, "eight".to_string());
1868            properties.boolean.set_value(app, true);
1869            properties.int_n.set_value(app, Some(9));
1870            properties.double_n.set_value(app, None);
1871            properties.string_n.set_value(app, Some("nine".to_string()));
1872            properties.bool_n.set_value(app, Some(true));
1873            let date_time = DateTime::from_milliseconds_since_epoch(4000, false);
1874            properties.date_time.set_value(app, date_time);
1875            properties.date_time_n.set_value(app, None);
1876            properties.direction.set_value(app, Direction::Up);
1877            properties.direction_n.set_value(app, Some(Direction::Down));
1878        }
1879
1880        assert_eq!(fixture.stored("int"), Some(8i64.into()));
1881        assert_eq!(fixture.stored("double"), Some(3.5f64.into()));
1882        assert_eq!(fixture.stored("string"), Some("eight".into()));
1883        assert_eq!(fixture.stored("bool"), Some(true.into()));
1884        assert_eq!(fixture.stored("int-n"), Some(9i64.into()));
1885        assert_eq!(fixture.stored("double-n"), Some(RestorationData::Null));
1886        assert_eq!(fixture.stored("string-n"), Some("nine".into()));
1887        assert_eq!(fixture.stored("bool-n"), Some(true.into()));
1888        assert_eq!(fixture.stored("date-time"), Some(4000i64.into()));
1889        assert_eq!(fixture.stored("date-time-n"), Some(RestorationData::Null));
1890        assert_eq!(fixture.stored("direction"), Some("Up".into()));
1891        assert_eq!(fixture.stored("direction-n"), Some("Down".into()));
1892    }
1893
1894    #[test]
1895    fn setting_the_value_it_already_has_writes_nothing() {
1896        let fixture = Fixture::mount(filled());
1897        let int = fixture.properties.int.clone();
1898        let notified = Rc::new(std::cell::Cell::new(0usize));
1899        let seen = Rc::clone(&notified);
1900        int.add_listener(
1901            &mut fixture.cell.borrow_mut(),
1902            Listener::new(move |_app| seen.set(seen.get() + 1)),
1903        );
1904
1905        int.set_value(&mut fixture.cell.borrow_mut(), 7);
1906        assert_eq!(notified.get(), 0, "the value did not change");
1907
1908        int.set_value(&mut fixture.cell.borrow_mut(), 8);
1909        assert_eq!(notified.get(), 1);
1910    }
1911
1912    #[test]
1913    fn an_unregistered_property_is_removed_from_the_data() {
1914        let mut fixture = Fixture::mount(filled());
1915        let int = fixture.properties.int.clone();
1916        let state = int.state(&fixture.cell.borrow());
1917        let bag = state
1918            .downcast::<BagState>(&fixture.cell.borrow())
1919            .expect("the owner is the bag");
1920        bag.unregister_from_restoration(&mut fixture.cell.borrow_mut(), int.as_property());
1921
1922        assert_eq!(fixture.stored("int"), None);
1923        assert!(!int.as_property().is_registered(&fixture.cell.borrow()));
1924    }
1925
1926    #[test]
1927    fn restorable_text_editing_controller_create_default_value_holds_initial_text() {
1928        let cell = AppCell::new();
1929        let mut app = cell.borrow_mut();
1930        let property = RestorableTextEditingController::from_value(
1931            &mut app,
1932            TextEditingValue::new().text("hello"),
1933        );
1934        let controller = RestorableProperty::create_default_value(property.handle(), &mut app);
1935        assert_eq!(controller.text_value(&app), "hello");
1936        let restored = RestorableProperty::from_primitives(
1937            property.handle(),
1938            &mut app,
1939            &RestorationData::String("hello".into()),
1940        );
1941        assert_eq!(restored.text_value(&app), "hello");
1942    }
1943
1944    #[derive(Debug)]
1945    struct Editor {
1946        key: Option<KeyRef>,
1947    }
1948
1949    impl StatefulWidget for Editor {
1950        type State = EditorState;
1951
1952        fn key(&self) -> Option<&KeyRef> {
1953            self.key.as_ref()
1954        }
1955
1956        fn create_state(&self) -> EditorState {
1957            EditorState {
1958                state: StateData::new(),
1959                restoration: RestorationMixinData::new(),
1960                controller: None,
1961            }
1962        }
1963    }
1964
1965    struct EditorState {
1966        state: StateData<Editor>,
1967        restoration: RestorationMixinData,
1968        controller: Option<Ref<RestorableTextEditingController>>,
1969    }
1970
1971    impl RestorationMixin for EditorState {
1972        crate::restoration_mixin_accessors!();
1973
1974        fn restoration_id(self: Handle<Self>, _app: &App) -> Option<&str> {
1975            Some("editor")
1976        }
1977
1978        fn restore_state(
1979            self: Handle<Self>,
1980            app: &mut App,
1981            _old_bucket: Option<Handle<RestorationBucket>>,
1982            _initial_restore: bool,
1983        ) {
1984            let controller = match app.get(self).controller.handle() {
1985                Some(controller) => controller,
1986                None => {
1987                    let controller = RestorableTextEditingController::text(app, "hello");
1988                    let handle = controller.handle();
1989                    app.get_mut(self).controller = Some(controller);
1990                    handle
1991                }
1992            };
1993            self.register_for_restoration(app, controller.as_property(), "controller");
1994        }
1995    }
1996
1997    impl State for EditorState {
1998        type Widget = Editor;
1999        crate::state_accessors!();
2000
2001        fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
2002            self.did_change_dependencies_restoration(app);
2003        }
2004
2005        fn dispose(self: Handle<Self>, app: &mut App) {
2006            self.dispose_restoration(app);
2007        }
2008
2009        fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
2010            let _ = app;
2011            SizedBox::shrink().into_widget()
2012        }
2013    }
2014
2015    #[test]
2016    fn restorable_text_editing_to_primitives_is_the_controller_text() {
2017        let cell = AppCell::new();
2018        let mut app = cell.borrow_mut();
2019        let manager = RestorationManager::instance(&mut app);
2020        manager.handle_restoration_update_from_engine(&mut app, true, None);
2021        let key = GlobalKey::new();
2022        let harness = Harness::mount(
2023            &mut app,
2024            RootRestorationScope::new(
2025                Some("app".to_string()),
2026                Editor {
2027                    key: Some(key.clone().into()),
2028                },
2029            )
2030            .into_widget(),
2031        );
2032        harness.pump(&mut app);
2033        let state = harness
2034            .owner
2035            .global_key_element(&app, &key)
2036            .expect("the editor is in the tree")
2037            .state_handle::<EditorState>(&app)
2038            .expect("an EditorState");
2039        let controller = app
2040            .get(state)
2041            .controller
2042            .handle()
2043            .expect("restore_state ran");
2044        assert_eq!(
2045            RestorableListenable::value(controller, &app).text_value(&app),
2046            "hello"
2047        );
2048        assert_eq!(
2049            RestorableProperty::to_primitives(controller, &app),
2050            RestorationData::String("hello".into())
2051        );
2052    }
2053}