use std::fmt::{self, Debug};
use std::rc::Rc;
use indexmap::IndexMap;
use waft_foundation::{
App, ChangeNotifier, ChangeNotifierData, Handle, HandleId, ListenableObject, Listener,
OptionRetained, Ref, Retained,
};
pub use waft_services::RestorationBucket;
use waft_services::{RestorationData, RestorationManager};
use crate::framework::{
BuildContext, InheritedWidget, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
};
use crate::widgets::basic::SizedBox;
fn resolve<T: 'static>(id: HandleId) -> Handle<T> {
Handle::from_id(id)
}
#[derive(Debug)]
pub struct RestorationScope {
pub key: Option<KeyRef>,
pub child: WidgetRef,
pub restoration_id: Option<String>,
}
impl RestorationScope {
pub fn new<K>(restoration_id: Option<String>, child: impl IntoWidget<K>) -> RestorationScope {
RestorationScope {
key: None,
child: child.into_widget(),
restoration_id,
}
}
pub fn key(mut self, key: KeyRef) -> RestorationScope {
self.key = Some(key);
self
}
pub fn maybe_of(app: &mut App, context: BuildContext) -> Option<Handle<RestorationBucket>> {
context
.depend_on_inherited_widget_of_exact_type::<UnmanagedRestorationScope>(app)
.and_then(|scope| scope.bucket.handle())
}
pub fn of(app: &mut App, context: BuildContext) -> Handle<RestorationBucket> {
Self::maybe_of(app, context).expect(
"RestorationScope.of() was called with a context that does not contain a \
RestorationScope widget.\n\
No RestorationScope widget ancestor could be found starting from the context that \
was passed to RestorationScope.of(). This can happen because you are using a \
widget that looks for a RestorationScope ancestor, but no such ancestor exists.\n\
State restoration must be enabled for a RestorationScope to exist. This can be \
done by wrapping the widget tree in a RootRestorationScope.",
)
}
}
impl StatefulWidget for RestorationScope {
type State = RestorationScopeState;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn create_state(&self) -> RestorationScopeState {
RestorationScopeState {
state: StateData::new(),
restoration: RestorationMixinData::new(),
}
}
}
pub struct RestorationScopeState {
state: StateData<RestorationScope>,
restoration: RestorationMixinData,
}
impl RestorationMixin for RestorationScopeState {
crate::restoration_mixin_accessors!();
fn restoration_id(self: Handle<Self>, app: &App) -> Option<&str> {
self.widget(app).restoration_id.as_deref()
}
fn restore_state(
self: Handle<Self>,
app: &mut App,
old_bucket: Option<Handle<RestorationBucket>>,
initial_restore: bool,
) {
let _ = (app, old_bucket, initial_restore);
}
}
impl State for RestorationScopeState {
type Widget = RestorationScope;
crate::state_accessors!();
fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
self.did_change_dependencies_restoration(app);
}
fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &RestorationScope) {
self.did_update_restoration_id(app);
}
fn dispose(self: Handle<Self>, app: &mut App) {
self.dispose_restoration(app);
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let bucket = self.restoration_mixin_data(app).bucket.clone();
let child = self.widget(app).child.clone();
UnmanagedRestorationScope::new(child)
.bucket(bucket)
.into_widget()
}
}
#[derive(Debug)]
pub struct UnmanagedRestorationScope {
pub key: Option<KeyRef>,
pub bucket: Option<Ref<RestorationBucket>>,
pub child: WidgetRef,
}
impl UnmanagedRestorationScope {
pub fn new<K>(child: impl IntoWidget<K>) -> UnmanagedRestorationScope {
UnmanagedRestorationScope {
key: None,
bucket: None,
child: child.into_widget(),
}
}
pub fn key(mut self, key: KeyRef) -> UnmanagedRestorationScope {
self.key = Some(key);
self
}
pub fn bucket(mut self, bucket: Option<Ref<RestorationBucket>>) -> UnmanagedRestorationScope {
self.bucket = bucket;
self
}
}
impl InheritedWidget for UnmanagedRestorationScope {
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn child(&self) -> &WidgetRef {
&self.child
}
fn update_should_notify(&self, old_widget: &UnmanagedRestorationScope) -> bool {
old_widget.bucket != self.bucket
}
}
#[derive(Debug)]
pub struct RootRestorationScope {
pub key: Option<KeyRef>,
pub child: WidgetRef,
pub restoration_id: Option<String>,
}
impl RootRestorationScope {
pub fn new<K>(
restoration_id: Option<String>,
child: impl IntoWidget<K>,
) -> RootRestorationScope {
RootRestorationScope {
key: None,
child: child.into_widget(),
restoration_id,
}
}
pub fn key(mut self, key: KeyRef) -> RootRestorationScope {
self.key = Some(key);
self
}
}
impl StatefulWidget for RootRestorationScope {
type State = RootRestorationScopeState;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn create_state(&self) -> RootRestorationScopeState {
RootRestorationScopeState {
state: StateData::new(),
ok_to_render_blank_container: None,
root_bucket_valid: false,
root_bucket: None,
ancestor_bucket: None,
is_loading_root_bucket: false,
}
}
}
pub struct RootRestorationScopeState {
state: StateData<RootRestorationScope>,
ok_to_render_blank_container: Option<bool>,
root_bucket_valid: bool,
root_bucket: Option<Ref<RestorationBucket>>,
ancestor_bucket: Option<Ref<RestorationBucket>>,
is_loading_root_bucket: bool,
}
impl RootRestorationScopeState {
fn needs_root_bucket_inserted(self: Handle<Self>, app: &App) -> bool {
app.get(self).ancestor_bucket.is_none()
}
fn is_waiting_for_root_bucket(self: Handle<Self>, app: &App) -> bool {
self.widget(app).restoration_id.is_some()
&& self.needs_root_bucket_inserted(app)
&& !app.get(self).root_bucket_valid
}
fn load_root_bucket_if_necessary(self: Handle<Self>, app: &mut App) {
if self.is_waiting_for_root_bucket(app) && !app.get(self).is_loading_root_bucket {
app.get_mut(self).is_loading_root_bucket = true;
let manager = RestorationManager::instance(app);
let bucket = manager.root_bucket(app).map(|bucket| bucket.keep(app));
app.get_mut(self).is_loading_root_bucket = false;
if self.mounted(app) {
manager.add_listener(
app,
Listener::handle_method(self, Self::replace_root_bucket),
);
self.set_state(app, |state| {
state.root_bucket = bucket;
state.root_bucket_valid = true;
state.ok_to_render_blank_container = Some(false);
});
}
}
}
fn replace_root_bucket(self: Handle<Self>, app: &mut App) {
app.get_mut(self).root_bucket_valid = false;
app.get_mut(self).root_bucket = None;
let manager = RestorationManager::instance(app);
manager.remove_listener(
app,
&Listener::handle_method(self, Self::replace_root_bucket),
);
self.load_root_bucket_if_necessary(app);
debug_assert!(!self.is_waiting_for_root_bucket(app));
}
}
impl State for RootRestorationScopeState {
type Widget = RootRestorationScope;
crate::state_accessors!();
fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
let context = self.context(app);
let ancestor_bucket =
RestorationScope::maybe_of(app, context).map(|bucket| bucket.keep(app));
app.get_mut(self).ancestor_bucket = ancestor_bucket;
self.load_root_bucket_if_necessary(app);
if app.get(self).ok_to_render_blank_container.is_none() {
let ok_to_render_blank_container =
self.widget(app).restoration_id.is_some() && self.needs_root_bucket_inserted(app);
app.get_mut(self).ok_to_render_blank_container = Some(ok_to_render_blank_container);
}
}
fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &RootRestorationScope) {
self.load_root_bucket_if_necessary(app);
}
fn dispose(self: Handle<Self>, app: &mut App) {
if app.get(self).root_bucket_valid {
let manager = RestorationManager::instance(app);
manager.remove_listener(
app,
&Listener::handle_method(self, Self::replace_root_bucket),
);
}
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let ok_to_render_blank_container = app
.get(self)
.ok_to_render_blank_container
.expect("didChangeDependencies runs before the first build");
if ok_to_render_blank_container && self.is_waiting_for_root_bucket(app) {
return SizedBox::shrink().into_widget();
}
let this = app.get(self);
let bucket = this
.ancestor_bucket
.clone()
.or_else(|| this.root_bucket.clone());
let restoration_id = self.widget(app).restoration_id.clone();
let child = self.widget(app).child.clone();
UnmanagedRestorationScope::new(RestorationScope::new(restoration_id, child))
.bucket(bucket)
.into_widget()
}
}
pub struct RestorablePropertyData {
restoration_id: Option<String>,
owner: Option<AnyRestorationMixin>,
disposed: bool,
}
impl RestorablePropertyData {
pub fn new() -> RestorablePropertyData {
RestorablePropertyData {
restoration_id: None,
owner: None,
disposed: false,
}
}
}
impl Default for RestorablePropertyData {
fn default() -> RestorablePropertyData {
RestorablePropertyData::new()
}
}
#[macro_export]
macro_rules! restorable_property_accessors {
() => {
fn restorable_property_data(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> &$crate::RestorablePropertyData {
&app.get(self).property
}
fn restorable_property_data_mut(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
) -> &mut $crate::RestorablePropertyData {
&mut app.get_mut(self).property
}
};
}
pub trait RestorableProperty: ChangeNotifier + Sized + 'static {
type Value;
fn restorable_property_data(self: Handle<Self>, app: &App) -> &RestorablePropertyData;
fn restorable_property_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut RestorablePropertyData;
fn create_default_value(self: Handle<Self>, app: &mut App) -> Self::Value;
fn from_primitives(self: Handle<Self>, app: &mut App, data: &RestorationData) -> Self::Value;
fn init_with_value(self: Handle<Self>, app: &mut App, value: Self::Value);
fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData;
fn enabled(self: Handle<Self>, app: &App) -> bool {
let _ = (self, app);
true
}
fn dispose_property(self: Handle<Self>, app: &mut App) {
debug_assert!(ChangeNotifierData::debug_assert_not_disposed(
app.get(self).change_notifier_data()
));
if let Some(owner) = self.restorable_property_data(app).owner {
owner.unregister(app, self.as_property());
}
ChangeNotifierData::dispose(app, self);
self.restorable_property_data_mut(app).disposed = true;
self.did_dispose(app);
}
fn dispose(self: Handle<Self>, app: &mut App) {
self.dispose_property(app);
}
fn did_dispose(self: Handle<Self>, app: &mut App) {
let _ = (self, app);
}
fn state(self: Handle<Self>, app: &App) -> AnyRestorationMixin {
debug_assert!(self.is_registered(app));
self.restorable_property_data(app)
.owner
.expect("a registered property has an owner")
}
fn is_registered(self: Handle<Self>, app: &App) -> bool {
debug_assert!(ChangeNotifierData::debug_assert_not_disposed(
app.get(self).change_notifier_data()
));
self.restorable_property_data(app).restoration_id.is_some()
}
fn as_property(self: Handle<Self>) -> AnyRestorableProperty {
AnyRestorableProperty {
id: self.id(),
vtable: const { &RestorablePropertyVTable::of::<Self>() },
}
}
}
struct RestorablePropertyVTable {
type_name: fn() -> &'static str,
data: fn(&App, HandleId) -> &RestorablePropertyData,
data_mut: fn(&mut App, HandleId) -> &mut RestorablePropertyData,
restore: fn(&mut App, HandleId, Option<&RestorationData>),
to_primitives: fn(&App, HandleId) -> RestorationData,
enabled: fn(&App, HandleId) -> bool,
add_listener: fn(&mut App, HandleId, Listener),
remove_listener: fn(&mut App, HandleId, &Listener),
}
impl RestorablePropertyVTable {
const fn of<P: RestorableProperty>() -> RestorablePropertyVTable {
RestorablePropertyVTable {
type_name: std::any::type_name::<P>,
data: |app, id| P::restorable_property_data(resolve(id), app),
data_mut: |app, id| P::restorable_property_data_mut(resolve(id), app),
restore: |app, id, data| {
let property: Handle<P> = resolve(id);
let value = match data {
Some(data) => P::from_primitives(property, app, data),
None => P::create_default_value(property, app),
};
P::init_with_value(property, app, value);
},
to_primitives: |app, id| P::to_primitives(resolve(id), app),
enabled: |app, id| P::enabled(resolve(id), app),
add_listener: |app, id, listener| {
ListenableObject::add_listener(resolve::<P>(id), app, listener)
},
remove_listener: |app, id, listener| {
ListenableObject::remove_listener(resolve::<P>(id), app, listener)
},
}
}
}
#[derive(Clone, Copy)]
pub struct AnyRestorableProperty {
id: HandleId,
vtable: &'static RestorablePropertyVTable,
}
pub type RestorablePropertyRef = Retained<AnyRestorableProperty>;
waft_foundation::erased_handle!(AnyRestorableProperty: RestorableProperty => RestorableProperty::as_property);
impl Debug for AnyRestorableProperty {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
}
}
impl AnyRestorableProperty {
pub fn id(self) -> HandleId {
self.id
}
pub fn downcast<T: 'static>(self, app: &App) -> Option<Handle<T>> {
app.handle::<T>(self.id)
}
fn data(self, app: &App) -> &RestorablePropertyData {
(self.vtable.data)(app, self.id)
}
fn data_mut(self, app: &mut App) -> &mut RestorablePropertyData {
(self.vtable.data_mut)(app, self.id)
}
pub fn restoration_id(self, app: &App) -> Option<&str> {
self.data(app).restoration_id.as_deref()
}
pub fn owner(self, app: &App) -> Option<AnyRestorationMixin> {
self.data(app).owner
}
pub fn is_registered(self, app: &App) -> bool {
self.data(app).restoration_id.is_some()
}
pub fn disposed(self, app: &App) -> bool {
self.data(app).disposed
}
pub fn enabled(self, app: &App) -> bool {
(self.vtable.enabled)(app, self.id)
}
pub fn to_primitives(self, app: &App) -> RestorationData {
(self.vtable.to_primitives)(app, self.id)
}
pub fn restore(self, app: &mut App, data: Option<&RestorationData>) {
(self.vtable.restore)(app, self.id, data);
}
pub fn add_listener(self, app: &mut App, listener: Listener) {
(self.vtable.add_listener)(app, self.id, listener);
}
pub fn remove_listener(self, app: &mut App, listener: &Listener) {
(self.vtable.remove_listener)(app, self.id, listener);
}
fn register(self, app: &mut App, restoration_id: &str, owner: AnyRestorationMixin) {
let data = self.data_mut(app);
data.restoration_id = Some(restoration_id.to_string());
data.owner = Some(owner);
}
fn unregister(self, app: &mut App) {
let data = self.data_mut(app);
debug_assert!(data.restoration_id.is_some());
debug_assert!(data.owner.is_some());
data.restoration_id = None;
data.owner = None;
}
}
pub struct RestorationMixinData {
bucket: Option<Ref<RestorationBucket>>,
properties: IndexMap<RestorablePropertyRef, Listener>,
debug_properties_waiting_for_reregistration: Option<Vec<RestorablePropertyRef>>,
first_restore_pending: bool,
current_parent: Option<Ref<RestorationBucket>>,
}
impl RestorationMixinData {
pub fn new() -> RestorationMixinData {
RestorationMixinData {
bucket: None,
properties: IndexMap::new(),
debug_properties_waiting_for_reregistration: None,
first_restore_pending: true,
current_parent: None,
}
}
}
impl Default for RestorationMixinData {
fn default() -> RestorationMixinData {
RestorationMixinData::new()
}
}
#[macro_export]
macro_rules! restoration_mixin_accessors {
() => {
fn restoration_mixin_data(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> &$crate::RestorationMixinData {
&app.get(self).restoration
}
fn restoration_mixin_data_mut(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
) -> &mut $crate::RestorationMixinData {
&mut app.get_mut(self).restoration
}
};
}
pub trait RestorationMixin: State + Sized + 'static {
fn restoration_mixin_data(self: Handle<Self>, app: &App) -> &RestorationMixinData;
fn restoration_mixin_data_mut(self: Handle<Self>, app: &mut App) -> &mut RestorationMixinData;
fn restoration_id(self: Handle<Self>, app: &App) -> Option<&str>;
fn bucket(self: Handle<Self>, app: &App) -> Option<Handle<RestorationBucket>> {
self.restoration_mixin_data(app).bucket.handle()
}
fn restore_state(
self: Handle<Self>,
app: &mut App,
old_bucket: Option<Handle<RestorationBucket>>,
initial_restore: bool,
);
fn did_toggle_bucket(
self: Handle<Self>,
app: &mut App,
old_bucket: Option<Handle<RestorationBucket>>,
) {
let _ = old_bucket;
debug_assert!(
self.bucket(app)
.is_none_or(|bucket| !bucket.is_replacing(app))
);
}
fn register_for_restoration(
self: Handle<Self>,
app: &mut App,
property: AnyRestorableProperty,
restoration_id: &str,
) {
if cfg!(debug_assertions) {
let doing_restore = self.debug_doing_restore(app);
let registered_id = property.restoration_id(app).map(str::to_string);
assert!(
registered_id.is_none()
|| (doing_restore && registered_id.as_deref() == Some(restoration_id)),
"Property is already registered under {registered_id:?}."
);
let id_taken = self
.restoration_mixin_data(app)
.properties
.keys()
.any(|other| other.restoration_id(app) == Some(restoration_id));
assert!(
doing_restore || !id_taken,
"\"{restoration_id}\" is already registered to another property."
);
}
let has_serialized_value = self
.bucket(app)
.is_some_and(|bucket| bucket.contains(app, restoration_id));
let serialized_value = has_serialized_value
.then(|| {
self.bucket(app)
.expect("a serialized value implies a bucket")
.read(app, restoration_id)
})
.flatten();
if !property.is_registered(app) {
property.register(app, restoration_id, self.as_restoration_mixin());
let listener = Listener::new(move |app| {
if self.bucket(app).is_none() {
return;
}
self.update_property(app, property);
});
property.add_listener(app, listener.clone());
let kept = property.keep(app);
self.restoration_mixin_data_mut(app)
.properties
.insert(kept, listener);
}
debug_assert!(
property.restoration_id(app) == Some(restoration_id)
&& property.owner(app) == Some(self.as_restoration_mixin())
&& self
.restoration_mixin_data(app)
.properties
.contains_key(&property)
);
property.restore(app, serialized_value.as_ref());
if !has_serialized_value && property.enabled(app) && self.bucket(app).is_some() {
self.update_property(app, property);
}
if cfg!(debug_assertions)
&& let Some(waiting) = self
.restoration_mixin_data_mut(app)
.debug_properties_waiting_for_reregistration
.as_mut()
{
waiting.retain(|other| other != property);
}
}
fn unregister_from_restoration(
self: Handle<Self>,
app: &mut App,
property: AnyRestorableProperty,
) {
debug_assert!(property.owner(app) == Some(self.as_restoration_mixin()));
let restoration_id = property
.restoration_id(app)
.expect("a registered property has an ID")
.to_string();
if let Some(bucket) = self.restoration_mixin_data(app).bucket.handle() {
bucket.remove(app, &restoration_id);
}
self.unregister(app, property);
}
fn did_update_restoration_id(self: Handle<Self>, app: &mut App) {
let bucket_keeps_id =
self.bucket(app).map(|bucket| bucket.restoration_id(app)) == self.restoration_id(app);
if self.restoration_mixin_data(app).current_parent.is_none()
|| bucket_keeps_id
|| self.restore_pending(app)
{
return;
}
let old_bucket = self.bucket(app);
let current_parent = self.restoration_mixin_data(app).current_parent.handle();
let did_replace_bucket = self.update_bucket_if_necessary(app, current_parent, false);
if did_replace_bucket {
debug_assert!(old_bucket != self.bucket(app));
debug_assert!(self.bucket(app).is_none() || old_bucket.is_none());
if let Some(old_bucket) = old_bucket {
old_bucket.dispose(app);
}
}
}
fn restore_pending(self: Handle<Self>, app: &mut App) -> bool {
if self.restoration_mixin_data(app).first_restore_pending {
return true;
}
if self.restoration_id(app).is_none() {
return false;
}
let context = self.context(app);
let potential_new_parent = RestorationScope::maybe_of(app, context);
potential_new_parent != self.restoration_mixin_data(app).current_parent.handle()
&& potential_new_parent.is_some_and(|parent| parent.is_replacing(app))
}
fn did_change_dependencies_restoration(self: Handle<Self>, app: &mut App) {
let old_bucket = self.bucket(app);
let needs_restore = self.restore_pending(app);
let context = self.context(app);
let current_parent = RestorationScope::maybe_of(app, context);
let kept_parent = current_parent.map(|parent| parent.keep(app));
self.restoration_mixin_data_mut(app).current_parent = kept_parent;
let did_replace_bucket =
self.update_bucket_if_necessary(app, current_parent, needs_restore);
if needs_restore {
self.do_restore(app, old_bucket);
}
if did_replace_bucket {
debug_assert!(old_bucket != self.bucket(app));
if let Some(old_bucket) = old_bucket {
old_bucket.dispose(app);
}
}
}
fn dispose_restoration(self: Handle<Self>, app: &mut App) {
let properties: Vec<(AnyRestorableProperty, Listener)> = self
.restoration_mixin_data(app)
.properties
.iter()
.map(|(property, listener)| (property.handle(), listener.clone()))
.collect();
for (property, listener) in properties {
if !property.disposed(app) {
property.remove_listener(app, &listener);
}
}
if let Some(bucket) = self.restoration_mixin_data(app).bucket.handle() {
bucket.dispose(app);
}
self.restoration_mixin_data_mut(app).bucket = None;
}
fn as_restoration_mixin(self: Handle<Self>) -> AnyRestorationMixin {
AnyRestorationMixin {
id: self.id(),
vtable: const { &RestorationMixinVTable::of::<Self>() },
}
}
fn debug_doing_restore(self: Handle<Self>, app: &App) -> bool {
self.restoration_mixin_data(app)
.debug_properties_waiting_for_reregistration
.is_some()
}
fn do_restore(
self: Handle<Self>,
app: &mut App,
old_bucket: Option<Handle<RestorationBucket>>,
) {
if cfg!(debug_assertions) {
let registered: Vec<RestorablePropertyRef> = self
.restoration_mixin_data(app)
.properties
.keys()
.cloned()
.collect();
self.restoration_mixin_data_mut(app)
.debug_properties_waiting_for_reregistration = Some(registered);
}
let initial_restore = self.restoration_mixin_data(app).first_restore_pending;
self.restore_state(app, old_bucket, initial_restore);
self.restoration_mixin_data_mut(app).first_restore_pending = false;
if cfg!(debug_assertions) {
let waiting = self
.restoration_mixin_data_mut(app)
.debug_properties_waiting_for_reregistration
.take()
.expect("set just above");
let missing: Vec<String> = waiting
.iter()
.map(|property| format!(" * {:?}", property.restoration_id(app)))
.collect();
assert!(
missing.is_empty(),
"Previously registered RestorableProperties must be re-registered in \
\"restore_state\". The RestorableProperties with the following IDs were not \
re-registered when \"restore_state\" was called:\n{}",
missing.join("\n")
);
}
}
fn update_bucket_if_necessary(
self: Handle<Self>,
app: &mut App,
parent: Option<Handle<RestorationBucket>>,
restore_pending: bool,
) -> bool {
let restoration_id = self.restoration_id(app).map(str::to_string);
let (Some(restoration_id), Some(parent)) = (restoration_id, parent) else {
let did_replace = self.set_new_bucket_if_necessary(app, None, restore_pending);
debug_assert!(self.bucket(app).is_none());
return did_replace;
};
if restore_pending || self.bucket(app).is_none() {
let debug_owner: Option<Rc<dyn Debug>> = cfg!(debug_assertions)
.then(|| Rc::new(self.as_restoration_mixin()) as Rc<dyn Debug>);
let new_bucket = parent.claim_child(app, &restoration_id, debug_owner);
let new_handle = new_bucket.handle();
let did_replace =
self.set_new_bucket_if_necessary(app, Some(new_bucket), restore_pending);
debug_assert!(self.bucket(app) == Some(new_handle));
return did_replace;
}
debug_assert!(!restore_pending);
let bucket = self
.restoration_mixin_data(app)
.bucket
.clone()
.expect("checked just above");
bucket.rename(app, &restoration_id);
parent.adopt_child(app, &bucket);
false
}
fn set_new_bucket_if_necessary(
self: Handle<Self>,
app: &mut App,
new_bucket: Option<Ref<RestorationBucket>>,
restore_pending: bool,
) -> bool {
if new_bucket.handle() == self.bucket(app) {
return false;
}
let old_bucket = self.bucket(app);
self.restoration_mixin_data_mut(app).bucket = new_bucket;
if !restore_pending {
if self.bucket(app).is_some() {
let properties: Vec<AnyRestorableProperty> = self
.restoration_mixin_data(app)
.properties
.keys()
.map(Retained::handle)
.collect();
for property in properties {
self.update_property(app, property);
}
}
self.did_toggle_bucket(app, old_bucket);
}
true
}
fn update_property(self: Handle<Self>, app: &mut App, property: AnyRestorableProperty) {
let Some(bucket) = self.bucket(app) else {
return;
};
let restoration_id = property
.restoration_id(app)
.expect("a registered property has an ID")
.to_string();
if property.enabled(app) {
let value = property.to_primitives(app);
bucket.write(app, &restoration_id, value);
} else {
bucket.remove(app, &restoration_id);
}
}
fn unregister(self: Handle<Self>, app: &mut App, property: AnyRestorableProperty) {
let listener = self
.restoration_mixin_data_mut(app)
.properties
.shift_remove(&property)
.expect("the property is registered with this mixin");
if cfg!(debug_assertions)
&& let Some(waiting) = self
.restoration_mixin_data_mut(app)
.debug_properties_waiting_for_reregistration
.as_mut()
{
waiting.retain(|other| other != property);
}
property.remove_listener(app, &listener);
property.unregister(app);
}
}
struct RestorationMixinVTable {
type_name: fn() -> &'static str,
unregister: fn(&mut App, HandleId, AnyRestorableProperty),
bucket: fn(&App, HandleId) -> Option<Handle<RestorationBucket>>,
context: fn(&App, HandleId) -> BuildContext,
mounted: fn(&App, HandleId) -> bool,
}
impl RestorationMixinVTable {
const fn of<M: RestorationMixin>() -> RestorationMixinVTable {
RestorationMixinVTable {
type_name: std::any::type_name::<M>,
unregister: |app, id, property| M::unregister(resolve(id), app, property),
bucket: |app, id| M::bucket(resolve(id), app),
context: |app, id| M::context(resolve(id), app),
mounted: |app, id| M::mounted(resolve(id), app),
}
}
}
#[derive(Clone, Copy)]
pub struct AnyRestorationMixin {
id: HandleId,
vtable: &'static RestorationMixinVTable,
}
impl PartialEq for AnyRestorationMixin {
fn eq(&self, other: &AnyRestorationMixin) -> bool {
self.id == other.id
}
}
impl Eq for AnyRestorationMixin {}
impl std::hash::Hash for AnyRestorationMixin {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
impl Debug for AnyRestorationMixin {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
}
}
impl AnyRestorationMixin {
pub fn id(self) -> HandleId {
self.id
}
pub fn downcast<T: 'static>(self, app: &App) -> Option<Handle<T>> {
app.handle::<T>(self.id)
}
pub fn bucket(self, app: &App) -> Option<Handle<RestorationBucket>> {
(self.vtable.bucket)(app, self.id)
}
pub fn context(self, app: &App) -> BuildContext {
(self.vtable.context)(app, self.id)
}
pub fn mounted(self, app: &App) -> bool {
(self.vtable.mounted)(app, self.id)
}
fn unregister(self, app: &mut App, property: AnyRestorableProperty) {
(self.vtable.unregister)(app, self.id, property);
}
}
#[cfg(test)]
mod tests {
use std::cell::RefCell;
use waft_foundation::Ref;
use waft_services::RestorationMap;
use super::*;
use crate::framework::{GlobalKey, StatelessWidget};
use crate::testing::{WidgetTester, test_widgets};
use crate::widgets::restoration_properties::{RestorableInt, RestorableValue};
fn map<const N: usize>(entries: [(&str, RestorationData); N]) -> RestorationMap {
entries
.into_iter()
.map(|(key, value)| (RestorationData::from(key), value))
.collect()
}
fn values<const N: usize>(entries: [(&str, RestorationData); N]) -> RestorationMap {
map([("v", map(entries).into())])
}
fn child(restoration_id: &str, data: RestorationMap) -> RestorationMap {
map([("c", map([(restoration_id, data.into())]).into())])
}
fn at<'a>(data: &'a RestorationMap, path: &[&str]) -> Option<&'a RestorationData> {
let (last, parents) = path.split_last()?;
let mut map = data;
for key in parents {
map = map.get(&RestorationData::from(*key))?.as_map()?;
}
map.get(&RestorationData::from(*last))
}
type SeenBuckets = Rc<RefCell<Vec<Option<Handle<RestorationBucket>>>>>;
#[derive(Debug)]
struct BucketProbe {
seen: SeenBuckets,
}
impl StatelessWidget for BucketProbe {
fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
let bucket = RestorationScope::maybe_of(app, context);
self.seen.borrow_mut().push(bucket);
SizedBox::shrink().into_widget()
}
}
fn probe() -> (WidgetRef, SeenBuckets) {
let seen = Rc::new(RefCell::new(Vec::new()));
let probe = BucketProbe {
seen: Rc::clone(&seen),
}
.into_widget();
(probe, seen)
}
#[derive(Debug)]
struct Counter {
key: Option<KeyRef>,
restoration_id: Option<String>,
}
impl StatefulWidget for Counter {
type State = CounterState;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn create_state(&self) -> CounterState {
CounterState {
state: StateData::new(),
restoration: RestorationMixinData::new(),
count: None,
restores: 0,
}
}
}
struct CounterState {
state: StateData<Counter>,
restoration: RestorationMixinData,
count: Option<Ref<RestorableInt>>,
restores: usize,
}
impl CounterState {
fn count(self: Handle<Self>, app: &App) -> Handle<RestorableInt> {
app.get(self).count.handle().expect("restore_state ran")
}
}
impl RestorationMixin for CounterState {
crate::restoration_mixin_accessors!();
fn restoration_id(self: Handle<Self>, app: &App) -> Option<&str> {
self.widget(app).restoration_id.as_deref()
}
fn restore_state(
self: Handle<Self>,
app: &mut App,
_old_bucket: Option<Handle<RestorationBucket>>,
_initial_restore: bool,
) {
app.get_mut(self).restores += 1;
let count = match app.get(self).count.handle() {
Some(count) => count,
None => {
let count = RestorableInt::new(app, 0);
let handle = count.handle();
app.get_mut(self).count = Some(count);
handle
}
};
self.register_for_restoration(app, count.as_property(), "count");
}
}
impl State for CounterState {
type Widget = Counter;
crate::state_accessors!();
fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
self.did_change_dependencies_restoration(app);
}
fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &Counter) {
self.did_update_restoration_id(app);
}
fn dispose(self: Handle<Self>, app: &mut App) {
self.dispose_restoration(app);
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let _ = app;
SizedBox::shrink().into_widget()
}
}
fn mount<K>(data: Option<RestorationMap>, child: impl IntoWidget<K>) -> WidgetTester {
let mut tester = WidgetTester::restoring(data);
tester.pump_widget(child);
tester
}
fn counter_state(tester: &WidgetTester, key: &GlobalKey) -> Handle<CounterState> {
key.current_state::<CounterState>(&tester.cell.borrow())
.expect("the counter is in the tree")
}
fn sent_at(tester: &WidgetTester, path: &[&str]) -> Option<RestorationData> {
let sent = tester.restoration_data().expect("serialized");
at(&sent, path).cloned()
}
fn counter(key: &GlobalKey, restoration_id: &str) -> Counter {
Counter {
key: Some(key.clone().into()),
restoration_id: Some(restoration_id.to_string()),
}
}
fn app_scope<K>(child: impl IntoWidget<K>) -> RootRestorationScope {
RootRestorationScope::new(Some("app".to_string()), child)
}
#[test]
fn the_root_scope_hands_the_hosts_root_bucket_down() {
let (probe, seen) = probe();
let tester = mount(
Some(child("app", values([("count", 42i64.into())]))),
app_scope(probe),
);
let bucket = seen.borrow()[0].expect("the host enabled restoration");
let mut app = tester.cell.borrow_mut();
assert_eq!(bucket.restoration_id(&app), "app");
assert_eq!(bucket.read(&mut app, "count"), Some(42i64.into()));
}
#[test]
fn the_root_scope_hands_nothing_down_without_a_restoration_id() {
let (probe, seen) = probe();
let _tester = mount(None, RootRestorationScope::new(None, probe));
assert_eq!(seen.borrow().as_slice(), [None]);
}
#[test]
fn a_restoration_scope_claims_the_child_bucket_named_by_its_id() {
let (probe, seen) = probe();
let tester = mount(
Some(child(
"app",
child("greeting", values([("hello", "world".into())])),
)),
app_scope(RestorationScope::new(Some("greeting".to_string()), probe)),
);
let bucket = seen.borrow()[0].expect("the scope claimed a bucket");
let mut app = tester.cell.borrow_mut();
assert_eq!(bucket.restoration_id(&app), "greeting");
assert_eq!(bucket.read(&mut app, "hello"), Some("world".into()));
}
#[test]
fn a_restoration_scope_without_an_id_turns_restoration_off_for_its_subtree() {
let (probe, seen) = probe();
let _tester = mount(None, app_scope(RestorationScope::new(None, probe)));
assert_eq!(seen.borrow().as_slice(), [None]);
}
#[test]
fn a_registered_property_is_restored_from_the_hosts_data() {
let key = GlobalKey::new();
let tester = mount(
Some(child(
"app",
child("counter", values([("count", 7i64.into())])),
)),
app_scope(counter(&key, "counter")),
);
let state = counter_state(&tester, &key);
let app = tester.cell.borrow();
assert_eq!(app.get(state).restores, 1);
let count = state.count(&app);
assert_eq!(*count.value(&app), 7);
}
#[test]
fn a_property_with_no_stored_value_takes_its_default_and_writes_it_out() {
let key = GlobalKey::new();
let mut tester = mount(None, app_scope(counter(&key, "counter")));
let state = counter_state(&tester, &key);
{
let app = tester.cell.borrow();
assert_eq!(*state.count(&app).value(&app), 0);
}
tester.pump();
assert_eq!(
sent_at(&tester, &["c", "app", "c", "counter", "v", "count"]),
Some(0i64.into())
);
}
#[test]
fn a_changed_property_reaches_the_host_at_the_end_of_the_frame() {
let key = GlobalKey::new();
let mut tester = mount(
Some(child(
"app",
child("counter", values([("count", 7i64.into())])),
)),
app_scope(counter(&key, "counter")),
);
tester.pump();
let path = ["c", "app", "c", "counter", "v", "count"];
assert_eq!(sent_at(&tester, &path), Some(7i64.into()));
let state = counter_state(&tester, &key);
tester.update(|app| {
state.count(app).set_value(app, 9);
state.set_state(app, |_| {});
});
assert_eq!(
sent_at(&tester, &path),
Some(7i64.into()),
"the write waits for the end of the frame"
);
tester.pump();
assert_eq!(sent_at(&tester, &path), Some(9i64.into()));
}
#[test]
fn did_update_restoration_id_moves_the_bucket_and_its_data() {
let key = GlobalKey::new();
let mut tester = mount(
Some(child(
"app",
child("counter", values([("count", 7i64.into())])),
)),
app_scope(counter(&key, "counter")),
);
let state = counter_state(&tester, &key);
let bucket = state
.bucket(&tester.cell.borrow())
.expect("the counter claimed a bucket");
tester.pump_widget(app_scope(counter(&key, "renamed")));
{
let app = tester.cell.borrow();
assert_eq!(app.get(state).restores, 1, "a rename does not re-restore");
assert_eq!(
state.bucket(&app),
Some(bucket),
"the same bucket moved to the new ID"
);
assert_eq!(bucket.restoration_id(&app), "renamed");
assert_eq!(*state.count(&app).value(&app), 7);
}
tester.pump();
assert_eq!(
sent_at(&tester, &["c", "app", "c", "renamed", "v", "count"]),
Some(7i64.into())
);
assert_eq!(sent_at(&tester, &["c", "app", "c", "counter"]), None);
}
#[test]
fn new_data_from_the_host_restores_the_registered_properties_again() {
let key = GlobalKey::new();
let mut tester = mount(
Some(child(
"app",
child("counter", values([("count", 7i64.into())])),
)),
app_scope(counter(&key, "counter")),
);
let state = counter_state(&tester, &key);
{
let app = tester.cell.borrow();
assert_eq!(*state.count(&app).value(&app), 7);
}
tester.update(|app| {
let manager = RestorationManager::instance(app);
manager.handle_restoration_update_from_engine(
app,
true,
Some(child(
"app",
child("counter", values([("count", 21i64.into())])),
)),
);
});
tester.pump();
let app = tester.cell.borrow();
assert_eq!(app.get(state).restores, 2);
assert_eq!(*state.count(&app).value(&app), 21);
}
#[test]
fn a_state_without_a_surrounding_scope_gets_no_bucket() {
let key = GlobalKey::new();
let tester = mount(None, counter(&key, "counter"));
let state = counter_state(&tester, &key);
let app = tester.cell.borrow();
assert_eq!(state.bucket(&app), None);
assert_eq!(*state.count(&app).value(&app), 0);
}
#[test]
fn of_panics_outside_any_restoration_scope() {
test_widgets(|tester| {
let key = GlobalKey::new();
tester.pump_widget(SizedBox::shrink().key(key.clone().into()));
let context = key
.current_context(&tester.cell.borrow())
.expect("the box is mounted");
let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
tester.update(|app| RestorationScope::of(app, context))
}));
assert!(panic.is_err());
});
}
}