use std::any::Any;
use std::collections::HashMap;
use std::fmt::{self, Debug};
use waft_foundation::{App, ChangeNotifier, ChangeNotifierData, Handle, Listenable, Listener};
use waft_scheduler::{FrameCallback, SchedulerBinding, SchedulerPhase};
use crate::framework::{
BuildContext, IntoWidget, KeyRef, Notification, ParentDataElement, State, StateData,
StatefulWidget, StatelessWidget, WidgetRef, downcast_widget,
};
use crate::view::View;
use crate::widgets::notification_listener::NotificationListener;
use crate::widgets::sliver::KeepAlive;
#[derive(Debug)]
pub struct AutomaticKeepAlive {
pub key: Option<KeyRef>,
pub child: WidgetRef,
}
impl AutomaticKeepAlive {
pub fn new<K>(child: impl IntoWidget<K>) -> AutomaticKeepAlive {
AutomaticKeepAlive {
key: None,
child: child.into_widget(),
}
}
pub fn key(mut self, key: KeyRef) -> AutomaticKeepAlive {
self.key = Some(key);
self
}
}
impl StatefulWidget for AutomaticKeepAlive {
type State = AutomaticKeepAliveState;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn create_state(&self) -> AutomaticKeepAliveState {
AutomaticKeepAliveState {
state: StateData::new(),
handles: None,
child: None,
keeping_alive: false,
}
}
}
pub struct AutomaticKeepAliveState {
state: StateData<AutomaticKeepAlive>,
handles: Option<HashMap<Handle<KeepAliveHandle>, Listener>>,
child: Option<WidgetRef>,
keeping_alive: bool,
}
impl AutomaticKeepAliveState {
fn update_child(self: Handle<Self>, app: &mut App) {
let child = self.widget(app).child.clone();
let this = self;
app.get_mut(self).child = Some(
NotificationListener::<KeepAliveNotification>::new(child)
.on_notification(move |app, notification| this.add_client(app, notification))
.into_widget(),
);
}
fn add_client(self: Handle<Self>, app: &mut App, notification: &KeepAliveNotification) -> bool {
let handle = notification.handle;
let callback = self.create_callback(handle);
{
let handles = app.get_mut(self).handles.get_or_insert_with(HashMap::new);
debug_assert!(
!handles.contains_key(&handle),
"the same handle cannot be used in two KeepAliveNotifications without triggering it first"
);
handles.insert(handle, callback.clone());
}
Listenable::add_listener(&handle, app, callback);
if !app.get(self).keeping_alive {
app.get_mut(self).keeping_alive = true;
if let Some(child_element) = self.get_child_element(app) {
self.update_parent_data_of_child(app, child_element);
} else {
SchedulerBinding::add_post_frame_callback(
app,
FrameCallback::new(move |app, _time_stamp| {
if !self.mounted(app) {
return;
}
let child_element = self.get_child_element(app);
debug_assert!(child_element.is_some());
self.update_parent_data_of_child(
app,
child_element
.expect("the KeepAlive child exists after the first build"),
);
}),
View::maybe_id_of(app, self.context(app)),
);
}
}
false
}
fn get_child_element(
self: Handle<Self>,
app: &App,
) -> Option<Handle<ParentDataElement<KeepAlive>>> {
debug_assert!(self.mounted(app));
let element = self.context(app);
let mut child_element = None;
element.visit_children(app, &mut |child| {
child_element = Some(child);
});
let child_element = child_element?;
debug_assert!(child_element.is_parent_data_element());
Some(
child_element
.downcast::<ParentDataElement<KeepAlive>>(app)
.expect("the only child is the KeepAlive ParentDataElement"),
)
}
fn update_parent_data_of_child(
self: Handle<Self>,
app: &mut App,
child_element: Handle<ParentDataElement<KeepAlive>>,
) {
let context = self.context(app);
let widget = self.build(app, context);
let keep_alive =
downcast_widget::<KeepAlive>(&*widget).expect("AutomaticKeepAlive builds a KeepAlive");
child_element.apply_widget_out_of_turn(app, keep_alive);
}
fn create_callback(self: Handle<Self>, handle: Handle<KeepAliveHandle>) -> Listener {
Listener::new(move |app| {
if cfg!(debug_assertions) && !self.mounted(app) {
panic!(
"AutomaticKeepAlive handle triggered after AutomaticKeepAlive was disposed.\n\
Widgets should always trigger their KeepAliveNotification handle when they are \
deactivated, so that they (or their handle) do not send spurious events later \
when they are no longer in the tree."
);
}
let callback = app
.get_mut(self)
.handles
.as_mut()
.expect("a client was registered")
.remove(&handle)
.expect("the firing handle is still registered");
Listenable::remove_listener(&handle, app, &callback);
if app
.get(self)
.handles
.as_ref()
.expect("a client was registered")
.is_empty()
{
if SchedulerBinding::scheduler_phase(app) < SchedulerPhase::PersistentCallbacks {
self.set_state(app, |state| {
state.keeping_alive = false;
});
} else {
app.get_mut(self).keeping_alive = false;
app.schedule_microtask(Listener::new(move |app| {
if self.mounted(app)
&& app
.get(self)
.handles
.as_ref()
.expect("a client was registered")
.is_empty()
{
self.set_state(app, |state| {
debug_assert!(!state.keeping_alive);
});
}
}));
}
}
})
}
}
impl State for AutomaticKeepAliveState {
type Widget = AutomaticKeepAlive;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
self.update_child(app);
}
fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &AutomaticKeepAlive) {
self.update_child(app);
}
fn dispose(self: Handle<Self>, app: &mut App) {
if let Some(handles) = app.get_mut(self).handles.take() {
for (handle, callback) in handles {
Listenable::remove_listener(&handle, app, &callback);
}
}
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let keeping_alive = app.get(self).keeping_alive;
let child = app
.get(self)
.child
.clone()
.expect("the child is created in init_state");
KeepAlive::new(keeping_alive, child).into_widget()
}
}
#[derive(Debug)]
pub struct KeepAliveNotification {
pub handle: Handle<KeepAliveHandle>,
}
impl KeepAliveNotification {
pub fn new(handle: Handle<KeepAliveHandle>) -> KeepAliveNotification {
KeepAliveNotification { handle }
}
}
impl Notification for KeepAliveNotification {
fn as_any(&self) -> &dyn Any {
self
}
}
pub struct KeepAliveHandle {
change_notifier: ChangeNotifierData,
}
impl KeepAliveHandle {
pub fn new(app: &mut App) -> Handle<KeepAliveHandle> {
app.create(KeepAliveHandle {
change_notifier: ChangeNotifierData::new(),
})
}
pub fn dispose(self: Handle<Self>, app: &mut App) {
self.notify_listeners(app);
app.get_mut(self).change_notifier.dispose();
app.destroy(self);
}
}
impl ChangeNotifier for KeepAliveHandle {
fn change_notifier_data(&self) -> &ChangeNotifierData {
&self.change_notifier
}
fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
&mut self.change_notifier
}
}
impl Debug for KeepAliveHandle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("KeepAliveHandle").finish_non_exhaustive()
}
}
#[derive(Default)]
pub struct AutomaticKeepAliveClientMixinData {
pub keep_alive_handle: Option<Handle<KeepAliveHandle>>,
}
impl AutomaticKeepAliveClientMixinData {
pub fn new() -> AutomaticKeepAliveClientMixinData {
AutomaticKeepAliveClientMixinData::default()
}
}
pub trait AutomaticKeepAliveClientMixin: State {
fn automatic_keep_alive_client_data(
self: Handle<Self>,
app: &App,
) -> &AutomaticKeepAliveClientMixinData;
fn automatic_keep_alive_client_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut AutomaticKeepAliveClientMixinData;
fn want_keep_alive(self: Handle<Self>, app: &App) -> bool;
fn update_keep_alive(self: Handle<Self>, app: &mut App) {
if self.want_keep_alive(app) {
if self
.automatic_keep_alive_client_data(app)
.keep_alive_handle
.is_none()
{
self.ensure_keep_alive(app);
}
} else if self
.automatic_keep_alive_client_data(app)
.keep_alive_handle
.is_some()
{
self.release_keep_alive(app);
}
}
fn init_state(self: Handle<Self>, app: &mut App) {
if self.want_keep_alive(app) {
self.ensure_keep_alive(app);
}
}
fn deactivate(self: Handle<Self>, app: &mut App) {
if self
.automatic_keep_alive_client_data(app)
.keep_alive_handle
.is_some()
{
self.release_keep_alive(app);
}
}
fn build(self: Handle<Self>, app: &mut App) -> WidgetRef {
if self.want_keep_alive(app)
&& self
.automatic_keep_alive_client_data(app)
.keep_alive_handle
.is_none()
{
self.ensure_keep_alive(app);
}
NullWidget.into_widget()
}
}
trait AutomaticKeepAliveClientMixinPrivate: AutomaticKeepAliveClientMixin {
fn ensure_keep_alive(self: Handle<Self>, app: &mut App) {
debug_assert!(
self.automatic_keep_alive_client_data(app)
.keep_alive_handle
.is_none()
);
let handle = KeepAliveHandle::new(app);
self.automatic_keep_alive_client_data_mut(app)
.keep_alive_handle = Some(handle);
KeepAliveNotification::new(handle).dispatch(app, Some(self.context(app)));
}
fn release_keep_alive(self: Handle<Self>, app: &mut App) {
let handle = self
.automatic_keep_alive_client_data_mut(app)
.keep_alive_handle
.take()
.expect("a keep-alive handle is registered");
handle.dispose(app);
}
}
impl<S: AutomaticKeepAliveClientMixin> AutomaticKeepAliveClientMixinPrivate for S {}
#[derive(Debug)]
struct NullWidget;
impl StatelessWidget for NullWidget {
fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
panic!(
"Widgets that mix AutomaticKeepAliveClientMixin into their State must \
call super.build() but must ignore the return value of the superclass."
);
}
}
#[cfg(test)]
mod tests {
use std::cell::Cell;
use std::rc::Rc;
use waft_foundation::{AppCell, ValueKey};
use super::*;
use crate::framework::{Element, KeyRef};
use crate::test_harness::Harness;
use crate::widgets::basic::SizedBox;
#[derive(Debug)]
struct KeepClient {
want: bool,
}
impl StatefulWidget for KeepClient {
type State = KeepClientState;
fn create_state(&self) -> KeepClientState {
KeepClientState {
state: StateData::new(),
automatic_keep_alive_client: AutomaticKeepAliveClientMixinData::new(),
}
}
}
struct KeepClientState {
state: StateData<KeepClient>,
automatic_keep_alive_client: AutomaticKeepAliveClientMixinData,
}
impl AutomaticKeepAliveClientMixin for KeepClientState {
fn automatic_keep_alive_client_data(
self: Handle<Self>,
app: &App,
) -> &AutomaticKeepAliveClientMixinData {
&app.get(self).automatic_keep_alive_client
}
fn automatic_keep_alive_client_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut AutomaticKeepAliveClientMixinData {
&mut app.get_mut(self).automatic_keep_alive_client
}
fn want_keep_alive(self: Handle<Self>, app: &App) -> bool {
self.widget(app).want
}
}
impl State for KeepClientState {
type Widget = KeepClient;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
AutomaticKeepAliveClientMixin::init_state(self, app);
}
fn deactivate(self: Handle<Self>, app: &mut App) {
AutomaticKeepAliveClientMixin::deactivate(self, app);
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let _ = AutomaticKeepAliveClientMixin::build(self, app);
SizedBox::shrink().into_widget()
}
}
fn host_state(harness: &Harness, app: &App) -> Handle<KeepClientState> {
let mut element = harness.root.as_element();
loop {
if let Some(state) = element.state_handle::<KeepClientState>(app) {
return state;
}
element = element.children(app)[0];
}
}
#[test]
fn mixin_want_keep_alive_true_dispatches() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let harness = Harness::mount(&mut app, KeepClient { want: true }.into_widget());
harness.pump(&mut app);
let state = host_state(&harness, &app);
assert!(
app.get(state)
.automatic_keep_alive_client
.keep_alive_handle
.is_some()
);
AutomaticKeepAliveClientMixin::update_keep_alive(state, &mut app);
assert!(
app.get(state)
.automatic_keep_alive_client
.keep_alive_handle
.is_some()
);
let _ =
AutomaticKeepAlive::new(SizedBox::shrink()).key(Rc::new(ValueKey::new(1)) as KeyRef);
}
#[test]
fn keep_alive_handle_dispose_notifies() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let handle = KeepAliveHandle::new(&mut app);
let notified = Rc::new(Cell::new(false));
Listenable::add_listener(
&handle,
&mut app,
Listener::new({
let notified = Rc::clone(¬ified);
move |_app| notified.set(true)
}),
);
handle.dispose(&mut app);
assert!(notified.get());
}
}