use crate::widgets::actions::ActionRef;
use crate::widgets::navigator::RouteRef;
use crate::widgets::scroll_controller::ScrollControllerRef;
use std::any::Any;
use std::collections::HashMap;
use std::fmt::{self, Debug};
use std::rc::Rc;
use std::time::Duration;
use waft_animation::{
Animatable, Animation, AnimationBehavior, AnimationController, AnimationRef, AnimationStatus,
AnimationStatusListener, AnyAnimation, ColorTween, Curve, CurveTween, Curves, Drive,
ProxyAnimation, TrainHoppingAnimation, k_always_complete_animation,
k_always_dismissed_animation,
};
use waft_foundation::{
App, Completer, CompleterFuture, Handle, HandleId, Listener, MergingListenable, Retained,
ValueListenable,
};
use waft_painting::Color;
use waft_physics::Simulation;
use waft_rendering::OrdinalSortKey;
use waft_scheduler::{FrameCallback, SchedulerBinding, SchedulerPhase, TickerFuture};
use crate::framework::{
BuildContext, GlobalKey, InheritedModel, InheritedWidget, IntoWidget, KeyRef, Notification,
State, StateData, StatefulWidget, WidgetRef,
};
use crate::view::View;
use crate::widgets::actions::{Action, ActionData, Actions, DismissAction, DismissIntent};
use crate::widgets::basic::{Builder, IgnorePointer, Offstage, RepaintBoundary, Semantics};
use crate::widgets::focus_manager::{FocusNodeLeaf, FocusScopeNode, TraversalEdgeBehavior};
use crate::widgets::focus_scope::FocusScope;
use crate::widgets::modal_barrier::{AnimatedModalBarrier, ModalBarrier};
use crate::widgets::navigator::{
AnyRoute, NavigationNotification, Navigator, NavigatorObserver, NavigatorObserverData, Route,
RouteBase, RoutePopDisposition, RoutePredicate, RouteResult, RouteSettingsRef,
};
use crate::widgets::overlay::OverlayEntry;
use crate::widgets::page_storage::{PageStorage, PageStorageBucket};
use crate::widgets::primary_scroll_controller::PrimaryScrollController;
use crate::widgets::restoration::RestorationScope;
use crate::widgets::scroll_controller::ScrollController;
use crate::widgets::scroll_controller::ScrollControllerLeaf;
use crate::widgets::transitions::{AnimatedBuilder, DelegatedTransitionBuilder, ListenableBuilder};
use waft_foundation::OptionRetained;
use waft_foundation::Ref;
pub struct OverlayRouteData {
overlay_entries: Vec<Ref<OverlayEntry>>,
}
impl OverlayRouteData {
pub fn new() -> OverlayRouteData {
OverlayRouteData {
overlay_entries: Vec::new(),
}
}
}
impl Default for OverlayRouteData {
fn default() -> OverlayRouteData {
OverlayRouteData::new()
}
}
#[macro_export]
macro_rules! overlay_route_accessors {
() => {
fn overlay_route_data(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> &$crate::OverlayRouteData {
&app.get(self).overlay_route
}
fn overlay_route_data_mut(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
) -> &mut $crate::OverlayRouteData {
&mut app.get_mut(self).overlay_route
}
};
}
pub trait OverlayRoute: Route {
fn overlay_route_data(self: Handle<Self>, app: &App) -> &OverlayRouteData;
fn overlay_route_data_mut(self: Handle<Self>, app: &mut App) -> &mut OverlayRouteData;
fn create_overlay_entries(self: Handle<Self>, app: &mut App) -> Vec<Ref<OverlayEntry>>;
fn overlay_entries(self: Handle<Self>, app: &App) -> Vec<Handle<OverlayEntry>> {
self.overlay_route_data(app)
.overlay_entries
.iter()
.map(Retained::handle)
.collect()
}
fn install(self: Handle<Self>, app: &mut App) {
debug_assert!(self.overlay_route_data(app).overlay_entries.is_empty());
let entries = OverlayRoute::create_overlay_entries(self, app);
self.overlay_route_data_mut(app)
.overlay_entries
.extend(entries);
RouteBase::install(self, app);
}
fn finished_when_popped(self: Handle<Self>, app: &App) -> bool {
let _ = app;
true
}
fn did_pop(self: Handle<Self>, app: &mut App, result: RouteResult) -> bool {
let return_value = RouteBase::did_pop(self, app, result);
debug_assert!(return_value);
if OverlayRoute::finished_when_popped(self, app) {
let navigator = self
.as_route()
.navigator(app)
.expect("a popped route is installed");
navigator.finalize_route(app, self.as_route());
}
return_value
}
fn dispose(self: Handle<Self>, app: &mut App) {
for entry in OverlayRoute::overlay_entries(self, app) {
entry.dispose(app);
}
self.overlay_route_data_mut(app).overlay_entries.clear();
RouteBase::dispose(self, app);
}
}
pub struct TransitionRouteData {
transition_completer: Completer<RouteResult>,
pop_finalized: bool,
animation: Option<AnimationRef<f64>>,
controller: Option<Ref<AnimationController>>,
secondary_animation: Ref<ProxyAnimation>,
pub will_dispose_animation_controller: bool,
result: RouteResult,
train_hopping_listener_remover: Option<TrainHoppingListenerRemover>,
}
type TrainHoppingListenerRemover = Rc<dyn Fn(&mut App)>;
impl TransitionRouteData {
pub fn new(app: &mut App) -> TransitionRouteData {
let dismissed = k_always_dismissed_animation(app);
TransitionRouteData {
transition_completer: Completer::new(),
pop_finalized: false,
animation: None,
controller: None,
secondary_animation: ProxyAnimation::new(app, Some(dismissed)),
will_dispose_animation_controller: true,
result: None,
train_hopping_listener_remover: None,
}
}
}
#[macro_export]
macro_rules! transition_route_accessors {
() => {
fn transition_route_data(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> &$crate::TransitionRouteData {
&app.get(self).transition_route
}
fn transition_route_data_mut(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
) -> &mut $crate::TransitionRouteData {
&mut app.get_mut(self).transition_route
}
};
}
pub trait PredictiveBackRoute: Route {
fn pop_gesture_enabled(self: Handle<Self>, app: &mut App) -> bool;
fn handle_start_back_gesture(self: Handle<Self>, app: &mut App, progress: f64);
fn handle_update_back_gesture_progress(self: Handle<Self>, app: &mut App, progress: f64);
fn handle_commit_back_gesture(self: Handle<Self>, app: &mut App);
fn handle_cancel_back_gesture(self: Handle<Self>, app: &mut App);
}
pub trait TransitionRoute: OverlayRoute + PredictiveBackRoute {
fn transition_route_data(self: Handle<Self>, app: &App) -> &TransitionRouteData;
fn transition_route_data_mut(self: Handle<Self>, app: &mut App) -> &mut TransitionRouteData;
fn as_transition_route(self: Handle<Self>) -> AnyTransitionRoute {
AnyTransitionRoute {
id: self.id(),
vtable: const { &TransitionRouteVTable::of::<Self>() },
}
}
fn completed(self: Handle<Self>, app: &App) -> CompleterFuture<RouteResult> {
self.transition_route_data(app)
.transition_completer
.future()
}
fn transition_duration(self: Handle<Self>, app: &mut App) -> Duration;
fn reverse_transition_duration(self: Handle<Self>, app: &mut App) -> Duration {
TransitionRoute::transition_duration(self, app)
}
fn opaque(self: Handle<Self>, app: &App) -> bool;
fn allow_snapshotting(self: Handle<Self>, app: &App) -> bool {
let _ = app;
true
}
fn finished_when_popped(self: Handle<Self>, app: &App) -> bool {
let controller = self
.transition_route_data(app)
.controller
.handle()
.expect("an installed route");
controller.status(app).is_dismissed() && !self.transition_route_data(app).pop_finalized
}
fn animation(self: Handle<Self>, app: &App) -> Option<AnyAnimation<f64>> {
self.transition_route_data(app).animation.handle()
}
fn controller(self: Handle<Self>, app: &App) -> Option<Handle<AnimationController>> {
self.transition_route_data(app).controller.handle()
}
fn secondary_animation(self: Handle<Self>, app: &App) -> Option<AnyAnimation<f64>> {
Some(
self.transition_route_data(app)
.secondary_animation
.as_animation(),
)
}
fn debug_transition_completed(self: Handle<Self>, app: &App) -> bool {
let mut disposed = false;
if cfg!(debug_assertions) {
disposed = self
.transition_route_data(app)
.transition_completer
.is_completed();
}
disposed
}
fn create_animation_controller(self: Handle<Self>, app: &mut App) -> Ref<AnimationController> {
debug_assert!(
!TransitionRoute::debug_transition_completed(self, app),
"cannot reuse a route after disposing it"
);
let duration = TransitionRoute::transition_duration(self, app);
let reverse_duration = TransitionRoute::reverse_transition_duration(self, app);
let navigator = self
.as_route()
.navigator(app)
.expect("an installed route has a navigator");
AnimationController::new(
app,
None,
Some(duration),
Some(reverse_duration),
0.0,
1.0,
AnimationBehavior::Normal,
navigator,
)
}
fn create_animation(self: Handle<Self>, app: &mut App) -> AnimationRef<f64> {
TransitionRouteBase::create_animation(self, app)
}
fn create_simulation(
self: Handle<Self>,
app: &mut App,
forward: bool,
) -> Option<Box<dyn Simulation>> {
let _ = forward;
debug_assert!(
TransitionRoute::transition_duration(self, app) >= Duration::ZERO,
"the duration must be positive for a non-simulation animation"
);
None
}
fn create_simulation_and_verify(
self: Handle<Self>,
app: &mut App,
forward: bool,
) -> Option<Box<dyn Simulation>> {
let simulation = TransitionRoute::create_simulation(self, app, forward);
debug_assert!(
TransitionRoute::transition_duration(self, app) >= Duration::ZERO,
"the duration must be positive for an animation that doesn't use a simulation; \
either set transition_duration or set create_simulation"
);
simulation
}
fn handle_status_changed(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
match status {
AnimationStatus::Completed => {
let entries = Route::overlay_entries(self, app);
if let Some(first) = entries.first().copied() {
let opaque = TransitionRoute::opaque(self, app);
first.set_opaque(app, opaque);
}
}
AnimationStatus::Forward | AnimationStatus::Reverse => {
let entries = Route::overlay_entries(self, app);
if let Some(first) = entries.first().copied() {
first.set_opaque(app, false);
}
}
AnimationStatus::Dismissed => {
if !self.as_route().is_active(app) {
let navigator = self
.as_route()
.navigator(app)
.expect("an active route has a navigator");
navigator.finalize_route(app, self.as_route());
self.transition_route_data_mut(app).pop_finalized = true;
}
}
}
}
fn install(self: Handle<Self>, app: &mut App) {
debug_assert!(
!TransitionRoute::debug_transition_completed(self, app),
"cannot install a route after disposing it"
);
let controller = TransitionRoute::create_animation_controller(self, app);
self.transition_route_data_mut(app).controller = Some(controller);
let animation = TransitionRoute::create_animation(self, app);
animation.add_status_listener(
app,
AnimationStatusListener::handle_method(self, Self::handle_status_changed),
);
let animation_handle = animation.handle();
self.transition_route_data_mut(app).animation = Some(animation);
OverlayRoute::install(self, app);
let entries = Route::overlay_entries(self, app);
if animation_handle.is_completed(app)
&& let Some(first) = entries.first().copied()
{
let opaque = TransitionRoute::opaque(self, app);
first.set_opaque(app, opaque);
}
}
fn did_push(self: Handle<Self>, app: &mut App) -> TickerFuture {
debug_assert!(
self.transition_route_data(app).controller.is_some(),
"didPush called before install or after dispose"
);
debug_assert!(
!TransitionRoute::debug_transition_completed(self, app),
"cannot reuse a route after disposing it"
);
RouteBase::did_push(self, app);
let simulation = TransitionRoute::create_simulation_and_verify(self, app, true);
let controller = self
.transition_route_data(app)
.controller
.handle()
.expect("installed");
match simulation {
None => controller.forward(app, None),
Some(simulation) => controller.animate_with(app, simulation),
}
}
fn did_add(self: Handle<Self>, app: &mut App) {
debug_assert!(
self.transition_route_data(app).controller.is_some(),
"didAdd called before install or after dispose"
);
debug_assert!(
!TransitionRoute::debug_transition_completed(self, app),
"cannot reuse a route after disposing it"
);
RouteBase::did_add(self, app);
let controller = self
.transition_route_data(app)
.controller
.handle()
.expect("installed");
let upper_bound = app.get(controller).upper_bound;
controller.set_value(app, upper_bound);
}
fn did_replace(self: Handle<Self>, app: &mut App, old_route: Option<AnyRoute>) {
debug_assert!(
self.transition_route_data(app).controller.is_some(),
"didReplace called before install or after dispose"
);
debug_assert!(
!TransitionRoute::debug_transition_completed(self, app),
"cannot reuse a route after disposing it"
);
if let Some(old) = old_route.and_then(|route| route.as_transition_route(app)) {
let value = old.controller_value(app);
let controller = self
.transition_route_data(app)
.controller
.handle()
.expect("installed");
controller.set_value(app, value);
}
RouteBase::did_replace(self, app, old_route);
}
fn did_pop(self: Handle<Self>, app: &mut App, result: RouteResult) -> bool {
debug_assert!(
self.transition_route_data(app).controller.is_some(),
"didPop called before install or after dispose"
);
debug_assert!(
!self
.transition_route_data(app)
.transition_completer
.is_completed(),
"cannot reuse a route after disposing it"
);
self.transition_route_data_mut(app).result = result.clone();
let simulation = TransitionRoute::create_simulation_and_verify(self, app, false);
let controller = self
.transition_route_data(app)
.controller
.handle()
.expect("installed");
match simulation {
None => {
controller.reverse(app, None);
}
Some(simulation) => {
controller.animate_back_with(app, simulation);
}
}
OverlayRoute::did_pop(self, app, result)
}
fn did_pop_next(self: Handle<Self>, app: &mut App, next_route: AnyRoute) {
debug_assert!(
self.transition_route_data(app).controller.is_some(),
"didPopNext called before install or after dispose"
);
debug_assert!(
!TransitionRoute::debug_transition_completed(self, app),
"cannot reuse a route after disposing it"
);
TransitionRoute::update_secondary_animation(self, app, Some(next_route));
RouteBase::did_pop_next(self, app, next_route);
}
fn did_change_next(self: Handle<Self>, app: &mut App, next_route: Option<AnyRoute>) {
debug_assert!(
self.transition_route_data(app).controller.is_some(),
"didChangeNext called before install or after dispose"
);
debug_assert!(
!TransitionRoute::debug_transition_completed(self, app),
"cannot reuse a route after disposing it"
);
TransitionRoute::update_secondary_animation(self, app, next_route);
RouteBase::did_change_next(self, app, next_route);
}
fn update_secondary_animation(self: Handle<Self>, app: &mut App, next_route: Option<AnyRoute>) {
let previous_train_hopping_listener_remover = self
.transition_route_data_mut(app)
.train_hopping_listener_remover
.take();
let next = next_route.and_then(|route| route.as_transition_route(app));
let coordinates = match next {
Some(next) => {
TransitionRoute::can_transition_to(self, app, next)
&& next.can_transition_from(app, TransitionRoute::as_transition_route(self))
}
None => false,
};
if let (Some(next), true) = (next, coordinates) {
let secondary = self.transition_route_data(app).secondary_animation.handle();
match secondary.parent(app) {
Some(current) => {
let current_train = match current.downcast::<TrainHoppingAnimation>(app) {
Some(hopping) => app.get(hopping).current_train().expect("a running train"),
None => current,
};
let next_train = next.underlying_animation(app).expect("an installed route");
if current_train.value(app) == next_train.value(app)
|| !next_train.is_animating(app)
{
let next_train = next_train.keep(app);
TransitionRoute::set_secondary_animation(
self,
app,
Some(next_train),
Some(next.completed(app)),
);
} else {
let slot: Rc<std::cell::RefCell<Option<Ref<TrainHoppingAnimation>>>> =
Rc::new(std::cell::RefCell::new(None));
let jump_on_animation_end =
AnimationStatusListener::new(move |status: AnimationStatus, app| {
if status.is_animating() || self.upgrade(app).is_none() {
return;
}
let kept_train = next_train.upgrade(app);
TransitionRoute::set_secondary_animation(
self,
app,
kept_train,
Some(next.completed(app)),
);
if let Some(remover) = self
.transition_route_data_mut(app)
.train_hopping_listener_remover
.take()
{
remover(app);
}
});
let remover = {
let listener = jump_on_animation_end.clone();
let slot = Rc::clone(&slot);
Rc::new(move |app: &mut App| {
next_train.remove_status_listener(app, &listener);
let hopping = slot.borrow_mut().take();
if let Some(animation) = hopping {
animation.dispose(app);
}
})
};
self.transition_route_data_mut(app)
.train_hopping_listener_remover = Some(remover);
next_train.add_status_listener(app, jump_on_animation_end);
let on_switched_train = {
let slot = Rc::downgrade(&slot);
Listener::new(move |app| {
let new_animation = slot
.upgrade()
.and_then(|slot| slot.borrow().as_ref().map(Retained::handle))
.expect("the hopping animation, kept until the remover runs");
debug_assert!(
self.transition_route_data(app)
.secondary_animation
.parent(app)
== Some(new_animation.as_animation())
);
let current = app.get(new_animation).current_train();
debug_assert!(current == next.underlying_animation(app));
let current = current.and_then(|current| current.upgrade(app));
TransitionRoute::set_secondary_animation(
self,
app,
current,
Some(next.completed(app)),
);
if let Some(remover) = self
.transition_route_data_mut(app)
.train_hopping_listener_remover
.take()
{
remover(app);
}
})
};
let current_train = current_train.keep(app);
let kept_next_train = next_train.keep(app);
let new_animation = TrainHoppingAnimation::new(
app,
current_train,
Some(kept_next_train),
Some(on_switched_train),
);
let erased: AnimationRef<f64> = new_animation.erase();
*slot.borrow_mut() = Some(new_animation);
self.set_secondary_animation(app, Some(erased), Some(next.completed(app)));
}
}
None => {
let animation = next
.underlying_animation(app)
.and_then(|animation| animation.upgrade(app));
TransitionRoute::set_secondary_animation(
self,
app,
animation,
Some(next.completed(app)),
);
}
}
} else {
let dismissed = k_always_dismissed_animation(app);
TransitionRoute::set_secondary_animation(self, app, Some(dismissed), None);
}
if let Some(remover) = previous_train_hopping_listener_remover {
remover(app);
}
}
fn set_secondary_animation(
self: Handle<Self>,
app: &mut App,
animation: Option<AnimationRef<f64>>,
disposed: Option<CompleterFuture<RouteResult>>,
) {
let secondary = self.transition_route_data(app).secondary_animation.clone();
let animation_handle = animation.handle();
secondary.set_parent(app, animation);
if let Some(disposed) = disposed {
disposed.then(app, move |app, _| {
if secondary.parent(app) == animation_handle {
let dismissed = k_always_dismissed_animation(app);
secondary.set_parent(app, Some(dismissed));
if let Some(animation) = animation_handle
&& let Some(hopping) = animation.downcast::<TrainHoppingAnimation>(app)
{
hopping.dispose(app);
}
}
});
}
}
fn can_transition_to(self: Handle<Self>, app: &App, next_route: AnyTransitionRoute) -> bool {
let _ = (app, next_route);
true
}
fn can_transition_from(
self: Handle<Self>,
app: &App,
previous_route: AnyTransitionRoute,
) -> bool {
let _ = (app, previous_route);
true
}
fn handle_start_back_gesture(self: Handle<Self>, app: &mut App, progress: f64) {
debug_assert!(self.as_route().is_current(app));
if let Some(controller) = self.transition_route_data(app).controller.handle() {
controller.set_value(app, progress);
}
if let Some(navigator) = self.as_route().navigator(app) {
navigator.did_start_user_gesture(app);
}
}
fn handle_update_back_gesture_progress(self: Handle<Self>, app: &mut App, progress: f64) {
if !self.as_route().is_current(app) {
return;
}
if let Some(controller) = self.transition_route_data(app).controller.handle() {
controller.set_value(app, progress);
}
}
fn handle_cancel_back_gesture(self: Handle<Self>, app: &mut App) {
TransitionRoute::handle_drag_end(self, app, true);
}
fn handle_commit_back_gesture(self: Handle<Self>, app: &mut App) {
TransitionRoute::handle_drag_end(self, app, false);
}
fn handle_drag_end(self: Handle<Self>, app: &mut App, animate_forward: bool) {
if self.as_route().is_current(app) {
let controller = self
.transition_route_data(app)
.controller
.handle()
.expect("installed");
if animate_forward {
if !controller.status(app).is_completed() {
controller.forward(app, None);
}
} else {
if let Some(navigator) = self.as_route().navigator(app) {
navigator.pop(app, None);
}
if let Some(controller) = self.transition_route_data(app).controller.handle()
&& controller.is_animating(app)
{
let upper_bound = app.get(controller).upper_bound;
controller.reverse(app, Some(upper_bound));
}
}
}
let controller = self.transition_route_data(app).controller.handle();
let animating = match controller {
Some(controller) => controller.is_animating(app),
None => false,
};
if animating {
let controller = controller.expect("an animating controller");
let me: Rc<std::cell::OnceCell<waft_animation::WeakAnimationStatusListener>> =
Rc::default();
let listener = {
let me = Rc::clone(&me);
AnimationStatusListener::new(move |_status, app| {
if let Some(navigator) = self.as_route().navigator(app) {
navigator.did_stop_user_gesture(app);
}
if let Some(registered) = me
.get()
.and_then(waft_animation::WeakAnimationStatusListener::upgrade)
{
controller.remove_status_listener(app, ®istered);
}
})
};
let _ = me.set(listener.downgrade());
controller.add_status_listener(app, listener);
} else if let Some(navigator) = self.as_route().navigator(app) {
navigator.did_stop_user_gesture(app);
}
}
fn dispose(self: Handle<Self>, app: &mut App) {
debug_assert!(
!self
.transition_route_data(app)
.transition_completer
.is_completed(),
"cannot dispose a route twice"
);
if let Some(animation) = self.transition_route_data(app).animation.handle() {
animation.remove_status_listener(
app,
&AnimationStatusListener::handle_method(self, Self::handle_status_changed),
);
}
if self
.transition_route_data(app)
.will_dispose_animation_controller
&& let Some(controller) = self.transition_route_data(app).controller.handle()
{
controller.dispose(app);
}
let result = self.transition_route_data(app).result.clone();
let transition_completer = self.transition_route_data(app).transition_completer.clone();
transition_completer.complete(app, result);
OverlayRoute::dispose(self, app);
}
fn debug_label(self: Handle<Self>) -> String {
std::any::type_name::<Self>().to_string()
}
}
pub trait TransitionRouteBase: TransitionRoute {
fn create_animation(self: Handle<Self>, app: &mut App) -> AnimationRef<f64> {
debug_assert!(
!TransitionRoute::debug_transition_completed(self, app),
"cannot reuse a route after disposing it"
);
self.transition_route_data(app)
.controller
.as_ref()
.expect("createAnimationController ran first")
.erase()
}
}
impl<T: TransitionRoute> TransitionRouteBase for T {}
struct TransitionRouteVTable {
type_name: fn() -> &'static str,
route: fn(HandleId) -> AnyRoute,
animation: fn(&App, HandleId) -> Option<AnyAnimation<f64>>,
underlying_animation: fn(&App, HandleId) -> Option<AnyAnimation<f64>>,
controller: fn(&App, HandleId) -> Option<Handle<AnimationController>>,
controller_value: fn(&App, HandleId) -> f64,
opaque: fn(&App, HandleId) -> bool,
allow_snapshotting: fn(&App, HandleId) -> bool,
transition_duration: fn(&mut App, HandleId) -> Duration,
reverse_transition_duration: fn(&mut App, HandleId) -> Duration,
can_transition_to: fn(&App, HandleId, AnyTransitionRoute) -> bool,
can_transition_from: fn(&App, HandleId, AnyTransitionRoute) -> bool,
completed: fn(&App, HandleId) -> CompleterFuture<RouteResult>,
pop_gesture_enabled: fn(&mut App, HandleId) -> bool,
handle_start_back_gesture: fn(&mut App, HandleId, f64),
handle_update_back_gesture_progress: fn(&mut App, HandleId, f64),
handle_commit_back_gesture: fn(&mut App, HandleId),
handle_cancel_back_gesture: fn(&mut App, HandleId),
}
impl TransitionRouteVTable {
const fn of<R: TransitionRoute>() -> TransitionRouteVTable {
TransitionRouteVTable {
type_name: std::any::type_name::<R>,
route: |id| Route::as_route(resolve::<R>(id)),
animation: |app, id| R::animation(resolve(id), app),
underlying_animation: |app, id| {
R::transition_route_data(resolve::<R>(id), app)
.animation
.handle()
},
controller: |app, id| R::controller(resolve(id), app),
controller_value: |app, id| {
let controller = R::transition_route_data(resolve::<R>(id), app)
.controller
.handle()
.expect("an installed route");
controller.value(app)
},
opaque: |app, id| R::opaque(resolve(id), app),
allow_snapshotting: |app, id| R::allow_snapshotting(resolve(id), app),
transition_duration: |app, id| R::transition_duration(resolve(id), app),
reverse_transition_duration: |app, id| R::reverse_transition_duration(resolve(id), app),
can_transition_to: |app, id, next| R::can_transition_to(resolve(id), app, next),
can_transition_from: |app, id, prev| R::can_transition_from(resolve(id), app, prev),
completed: |app, id| R::completed(resolve(id), app),
pop_gesture_enabled: |app, id| {
PredictiveBackRoute::pop_gesture_enabled(resolve::<R>(id), app)
},
handle_start_back_gesture: |app, id, progress| {
PredictiveBackRoute::handle_start_back_gesture(resolve::<R>(id), app, progress)
},
handle_update_back_gesture_progress: |app, id, progress| {
PredictiveBackRoute::handle_update_back_gesture_progress(
resolve::<R>(id),
app,
progress,
)
},
handle_commit_back_gesture: |app, id| {
PredictiveBackRoute::handle_commit_back_gesture(resolve::<R>(id), app)
},
handle_cancel_back_gesture: |app, id| {
PredictiveBackRoute::handle_cancel_back_gesture(resolve::<R>(id), app)
},
}
}
}
#[derive(Clone, Copy)]
pub struct AnyTransitionRoute {
id: HandleId,
vtable: &'static TransitionRouteVTable,
}
impl From<AnyTransitionRoute> for AnyRoute {
fn from(route: AnyTransitionRoute) -> AnyRoute {
route.as_route()
}
}
pub type TransitionRouteRef = Retained<AnyTransitionRoute>;
waft_foundation::erased_handle!(AnyTransitionRoute: TransitionRoute => TransitionRoute::as_transition_route);
impl Debug for AnyTransitionRoute {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
}
}
impl AnyTransitionRoute {
pub fn as_route(self) -> AnyRoute {
(self.vtable.route)(self.id)
}
pub fn animation(self, app: &App) -> Option<AnyAnimation<f64>> {
(self.vtable.animation)(app, self.id)
}
pub fn underlying_animation(self, app: &App) -> Option<AnyAnimation<f64>> {
(self.vtable.underlying_animation)(app, self.id)
}
pub fn controller(self, app: &App) -> Option<Handle<AnimationController>> {
(self.vtable.controller)(app, self.id)
}
pub fn controller_value(self, app: &App) -> f64 {
(self.vtable.controller_value)(app, self.id)
}
pub fn opaque(self, app: &App) -> bool {
(self.vtable.opaque)(app, self.id)
}
pub fn allow_snapshotting(self, app: &App) -> bool {
(self.vtable.allow_snapshotting)(app, self.id)
}
pub fn transition_duration(self, app: &mut App) -> Duration {
(self.vtable.transition_duration)(app, self.id)
}
pub fn reverse_transition_duration(self, app: &mut App) -> Duration {
(self.vtable.reverse_transition_duration)(app, self.id)
}
pub fn can_transition_to(self, app: &App, next_route: AnyTransitionRoute) -> bool {
(self.vtable.can_transition_to)(app, self.id, next_route)
}
pub fn can_transition_from(self, app: &App, previous_route: AnyTransitionRoute) -> bool {
(self.vtable.can_transition_from)(app, self.id, previous_route)
}
pub fn completed(self, app: &App) -> CompleterFuture<RouteResult> {
(self.vtable.completed)(app, self.id)
}
pub fn pop_gesture_enabled(self, app: &mut App) -> bool {
(self.vtable.pop_gesture_enabled)(app, self.id)
}
pub fn handle_start_back_gesture(self, app: &mut App, progress: f64) {
(self.vtable.handle_start_back_gesture)(app, self.id, progress)
}
pub fn handle_update_back_gesture_progress(self, app: &mut App, progress: f64) {
(self.vtable.handle_update_back_gesture_progress)(app, self.id, progress)
}
pub fn handle_commit_back_gesture(self, app: &mut App) {
(self.vtable.handle_commit_back_gesture)(app, self.id)
}
pub fn handle_cancel_back_gesture(self, app: &mut App) {
(self.vtable.handle_cancel_back_gesture)(app, self.id)
}
}
fn resolve<L: 'static>(id: HandleId) -> Handle<L> {
Handle::from_id(id)
}
pub struct LocalHistoryEntry {
pub on_remove: Option<Listener>,
owner: Option<AnyRoute>,
pub implies_app_bar_dismissal: bool,
}
impl LocalHistoryEntry {
pub fn new(app: &mut App) -> Ref<LocalHistoryEntry> {
app.create(LocalHistoryEntry {
on_remove: None,
owner: None,
implies_app_bar_dismissal: true,
})
}
pub fn on_remove(self: Ref<Self>, app: &mut App, on_remove: Listener) -> Ref<Self> {
app.get_mut(&self).on_remove = Some(on_remove);
self
}
pub fn implies_app_bar_dismissal(
self: Ref<Self>,
app: &mut App,
implies_app_bar_dismissal: bool,
) -> Ref<Self> {
app.get_mut(&self).implies_app_bar_dismissal = implies_app_bar_dismissal;
self
}
pub fn remove(self: Handle<Self>, app: &mut App) {
if let Some(owner) = app.get(self).owner {
let modal = owner
.as_modal_route(app)
.expect("a local history entry belongs to a modal route");
modal.remove_local_history_entry(app, self);
}
debug_assert!(app.get(self).owner.is_none());
}
fn notify_removed(self: Handle<Self>, app: &mut App) {
if let Some(on_remove) = app.get(self).on_remove.clone() {
on_remove.call(app);
}
}
}
impl Debug for LocalHistoryEntry {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("LocalHistoryEntry")
}
}
pub struct LocalHistoryRouteData {
local_history: Option<Vec<Ref<LocalHistoryEntry>>>,
entries_implies_app_bar_dismissal: i64,
}
impl LocalHistoryRouteData {
pub fn new() -> LocalHistoryRouteData {
LocalHistoryRouteData {
local_history: None,
entries_implies_app_bar_dismissal: 0,
}
}
}
impl Default for LocalHistoryRouteData {
fn default() -> LocalHistoryRouteData {
LocalHistoryRouteData::new()
}
}
#[macro_export]
macro_rules! local_history_route_accessors {
() => {
fn local_history_route_data(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> &$crate::LocalHistoryRouteData {
&app.get(self).local_history
}
fn local_history_route_data_mut(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
) -> &mut $crate::LocalHistoryRouteData {
&mut app.get_mut(self).local_history
}
};
}
pub trait LocalHistoryRoute: TransitionRoute {
fn local_history_route_data(self: Handle<Self>, app: &App) -> &LocalHistoryRouteData;
fn local_history_route_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut LocalHistoryRouteData;
fn add_local_history_entry(self: Handle<Self>, app: &mut App, entry: Ref<LocalHistoryEntry>) {
debug_assert!(app.get(&entry).owner.is_none());
app.get_mut(&entry).owner = Some(self.as_route());
let implies_app_bar_dismissal = app.get(&entry).implies_app_bar_dismissal;
let data = self.local_history_route_data_mut(app);
let history = data.local_history.get_or_insert_with(Vec::new);
let was_empty = history.is_empty();
history.push(entry);
let mut internal_state_changed = false;
if implies_app_bar_dismissal {
let data = self.local_history_route_data_mut(app);
internal_state_changed = data.entries_implies_app_bar_dismissal == 0;
data.entries_implies_app_bar_dismissal += 1;
}
if was_empty || internal_state_changed {
Route::changed_internal_state(self, app);
}
}
fn remove_local_history_entry(
self: Handle<Self>,
app: &mut App,
entry: Handle<LocalHistoryEntry>,
) {
debug_assert!(app.get(entry).owner == Some(self.as_route()));
let data = self.local_history_route_data_mut(app);
let history = data.local_history.as_mut().expect("a local history");
debug_assert!(history.iter().any(|held| held == entry));
let position = history.iter().position(|held| held == entry);
let mut internal_state_changed = false;
if let Some(position) = position {
history.remove(position);
if app.get(entry).implies_app_bar_dismissal {
let data = self.local_history_route_data_mut(app);
data.entries_implies_app_bar_dismissal -= 1;
internal_state_changed = data.entries_implies_app_bar_dismissal == 0;
}
}
app.get_mut(entry).owner = None;
entry.notify_removed(app);
let data = self.local_history_route_data(app);
if data.local_history.as_ref().is_some_and(Vec::is_empty) || internal_state_changed {
debug_assert_eq!(
self.local_history_route_data(app)
.entries_implies_app_bar_dismissal,
0
);
if SchedulerBinding::scheduler_phase(app) == SchedulerPhase::PersistentCallbacks {
SchedulerBinding::add_post_frame_callback(
app,
FrameCallback::new(move |app, _duration| {
if self.upgrade(app).is_some() && self.as_route().is_active(app) {
Route::changed_internal_state(self, app);
}
}),
self.as_route()
.navigator(app)
.and_then(|navigator| View::maybe_id_of(app, navigator.context(app))),
);
} else {
Route::changed_internal_state(self, app);
}
}
}
fn will_pop(self: Handle<Self>, app: &mut App) -> RoutePopDisposition {
if Route::will_handle_pop_internally(self, app) {
return RoutePopDisposition::Pop;
}
RouteBase::will_pop(self, app)
}
fn pop_disposition(self: Handle<Self>, app: &mut App) -> RoutePopDisposition {
if Route::will_handle_pop_internally(self, app) {
return RoutePopDisposition::Pop;
}
RouteBase::pop_disposition(self, app)
}
fn did_pop(self: Handle<Self>, app: &mut App, result: RouteResult) -> bool {
let last = self
.local_history_route_data_mut(app)
.local_history
.as_mut()
.and_then(Vec::pop);
if let Some(entry) = last {
debug_assert!(app.get(&entry).owner == Some(self.as_route()));
app.get_mut(&entry).owner = None;
entry.notify_removed(app);
let mut internal_state_changed = false;
if app.get(&entry).implies_app_bar_dismissal {
let data = self.local_history_route_data_mut(app);
data.entries_implies_app_bar_dismissal -= 1;
internal_state_changed = data.entries_implies_app_bar_dismissal == 0;
}
let empty = self
.local_history_route_data(app)
.local_history
.as_ref()
.is_some_and(Vec::is_empty);
if empty || internal_state_changed {
Route::changed_internal_state(self, app);
}
return false;
}
TransitionRoute::did_pop(self, app, result)
}
fn will_handle_pop_internally(self: Handle<Self>, app: &App) -> bool {
self.local_history_route_data(app)
.local_history
.as_ref()
.is_some_and(|history| !history.is_empty())
}
}
struct DismissModalAction {
action: ActionData,
context: BuildContext,
}
impl DismissModalAction {
fn new(app: &mut App, context: BuildContext) -> Ref<DismissModalAction> {
app.create(DismissModalAction {
action: ActionData::new(),
context,
})
}
}
impl Action for DismissModalAction {
type Intent = DismissIntent;
crate::action_accessors!();
fn is_enabled(self: Handle<Self>, app: &mut App, _intent: &DismissIntent) -> bool {
let context = app.get(self).context;
let route = AnyModalRoute::of(app, context).expect("a dismiss action inside a modal route");
route.barrier_dismissible(app)
}
fn invoke(self: Handle<Self>, app: &mut App, _intent: &DismissIntent) -> Option<Rc<dyn Any>> {
let context = app.get(self).context;
let popped = Navigator::of(app, context, false).maybe_pop(app, None);
Some(Rc::new(popped))
}
}
impl DismissAction for DismissModalAction {}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
enum ModalRouteAspect {
IsCurrent,
CanPop,
Settings,
IsActive,
IsFirst,
Opaque,
PopDisposition,
}
#[derive(Debug)]
struct ModalScopeStatus {
is_current: bool,
can_pop: bool,
implies_app_bar_dismissal: bool,
opaque: bool,
route: ModalRouteRef,
child: WidgetRef,
}
impl InheritedWidget for ModalScopeStatus {
fn child(&self) -> &WidgetRef {
&self.child
}
fn update_should_notify(&self, old: &ModalScopeStatus) -> bool {
self.is_current != old.is_current
|| self.can_pop != old.can_pop
|| self.implies_app_bar_dismissal != old.implies_app_bar_dismissal
|| self.route != old.route
|| self.opaque != old.opaque
}
}
impl ModalScopeStatus {
fn into_widget(self) -> WidgetRef {
IntoWidget::<crate::framework::InheritedModelKind>::into_widget(self)
}
}
impl InheritedModel for ModalScopeStatus {
type Aspect = ModalRouteAspect;
fn update_should_notify_dependent(
&self,
old_widget: &ModalScopeStatus,
dependencies: &std::collections::HashSet<ModalRouteAspect>,
) -> bool {
dependencies.iter().any(|dependency| match dependency {
ModalRouteAspect::IsCurrent => self.is_current != old_widget.is_current,
ModalRouteAspect::CanPop => self.can_pop != old_widget.can_pop,
ModalRouteAspect::Settings
| ModalRouteAspect::IsActive
| ModalRouteAspect::IsFirst
| ModalRouteAspect::PopDisposition => self.route != old_widget.route,
ModalRouteAspect::Opaque => self.opaque != old_widget.opaque,
})
}
}
#[derive(Debug)]
struct ModalScope {
key: Option<KeyRef>,
route: AnyModalRoute,
}
impl StatefulWidget for ModalScope {
type State = ModalScopeState;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn create_state(&self) -> ModalScopeState {
ModalScopeState {
state: StateData::new(),
page: None,
listenable: None,
focus_scope_node: None,
primary_scroll_controller: None,
no_gesture_in_progress: None,
}
}
}
struct ModalScopeState {
state: StateData<ModalScope>,
page: Option<WidgetRef>,
listenable: Option<Rc<MergingListenable>>,
focus_scope_node: Option<Ref<FocusScopeNode>>,
primary_scroll_controller: Option<Ref<ScrollController>>,
no_gesture_in_progress: Option<Ref<waft_foundation::ValueNotifier<bool>>>,
}
impl ModalScopeState {
fn focus_scope_node(self: Handle<Self>, app: &App) -> Handle<FocusScopeNode> {
app.get(self)
.focus_scope_node
.handle()
.expect("init_state has run")
}
fn route(self: Handle<Self>, app: &App) -> AnyModalRoute {
self.widget(app).route
}
fn update_focus_scope_node(self: Handle<Self>, app: &mut App) {
let route = self.route(app);
let navigator = route
.as_route()
.navigator(app)
.expect("a mounted scope has a navigator");
let traversal_edge_behavior = match route.traversal_edge_behavior(app) {
Some(behavior) => behavior,
None => navigator.widget(app).route_traversal_edge_behavior,
};
let directional_traversal_edge_behavior =
match route.directional_traversal_edge_behavior(app) {
Some(behavior) => behavior,
None => {
navigator
.widget(app)
.route_directional_traversal_edge_behavior
}
};
let node = self.focus_scope_node(app);
node.set_traversal_edge_behavior(app, traversal_edge_behavior);
node.set_directional_traversal_edge_behavior(app, directional_traversal_edge_behavior);
if route.as_route().is_current(app) && self.should_request_focus(app) {
let focus_node = navigator.focus_node(app);
if let Some(scope) = focus_node.as_node().enclosing_scope(app) {
scope.set_first_focus(app, node);
}
}
}
fn force_rebuild_page(self: Handle<Self>, app: &mut App) {
self.set_state(app, |state| {
state.page = None;
});
}
fn should_ignore_focus_request(self: Handle<Self>, app: &mut App) -> bool {
let route = self.route(app);
let reversing = route
.animation(app)
.is_some_and(|animation| animation.status(app) == AnimationStatus::Reverse);
reversing
|| route
.as_route()
.navigator(app)
.is_some_and(|navigator| navigator.user_gesture_in_progress(app))
}
fn should_request_focus(self: Handle<Self>, app: &App) -> bool {
self.route(app).as_route().request_focus(app)
}
fn route_set_state(self: Handle<Self>, app: &mut App, change: impl FnOnce(&mut App)) {
let route = self.route(app);
if route.as_route().is_current(app)
&& !self.should_ignore_focus_request(app)
&& self.should_request_focus(app)
{
let navigator = route.as_route().navigator(app).expect("a current route");
let focus_node = navigator.focus_node(app);
let node = self.focus_scope_node(app);
if let Some(scope) = focus_node.as_node().enclosing_scope(app) {
scope.set_first_focus(app, node);
}
}
change(app);
self.set_state(app, |_state| {});
}
}
impl State for ModalScopeState {
type Widget = ModalScope;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
let node = FocusScopeNode::new(app);
node.as_node()
.set_debug_label(app, Some("ModalScopeState Focus Scope".to_string()));
app.get_mut(self).focus_scope_node = Some(node);
app.get_mut(self).primary_scroll_controller =
Some(ScrollController::new(app, 0.0, true, None, None, None));
app.get_mut(self).no_gesture_in_progress =
Some(app.create(waft_foundation::ValueNotifier::new(false)));
let route = self.route(app);
let as_listenable = |animation: AnyAnimation<f64>| {
Rc::new(animation.keep(app)) as Rc<dyn waft_foundation::Listenable>
};
let animations: Vec<Option<Rc<dyn waft_foundation::Listenable>>> = vec![
route.animation(app).map(as_listenable),
route.secondary_animation(app).map(as_listenable),
];
app.get_mut(self).listenable = Some(Rc::new(MergingListenable::new(animations)));
}
fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &ModalScope) {
debug_assert!(self.widget(app).route == old_widget.route);
self.update_focus_scope_node(app);
}
fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
app.get_mut(self).page = None;
self.update_focus_scope_node(app);
}
fn dispose(self: Handle<Self>, app: &mut App) {
let node = self.focus_scope_node(app);
node.dispose(app);
let controller = app
.get(self)
.primary_scroll_controller
.handle()
.expect("init_state");
ScrollController::dispose(controller.as_controller(), app);
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let route = self.route(app);
let route_kept = route.keep(app);
let node = app
.get(self)
.focus_scope_node
.clone()
.expect("init_state has run");
let is_current = route.as_route().is_current(app);
node.set_skip_traversal(app, !is_current);
let page = match app.get(self).page.clone() {
Some(page) => page,
None => {
let page_route = route_kept.clone();
let page = RepaintBoundary::new()
.key(route.subtree_key(app).into())
.child(Builder::new(move |app, context| {
let (animation, secondary) = page_route.animations(app);
page_route.build_page(app, context, animation, secondary)
}))
.into_widget();
app.get_mut(self).page = Some(page.clone());
page
}
};
let gesture_notifier: Rc<dyn waft_foundation::Listenable> = match route
.as_route()
.navigator(app)
{
Some(navigator) => Rc::new(navigator.user_gesture_in_progress_notifier(app).keep(app)),
None => Rc::new(
app.get(self)
.no_gesture_in_progress
.clone()
.expect("init_state"),
),
};
let listenable = app.get(self).listenable.clone().expect("init_state");
let transitions_route = route_kept.clone();
let transitions_node = node.clone();
let transitions = ListenableBuilder::new(listenable, move |app, context, child| {
let route = &transitions_route;
let node = transitions_node.clone();
let child = child.cloned().expect("the cached page");
let (animation, secondary) = route.animations(app);
let ignoring = ListenableBuilder::new(Rc::clone(&gesture_notifier), {
move |app: &mut App, _context: BuildContext, child: Option<&WidgetRef>| {
let ignore_events = self.should_ignore_focus_request(app);
node.set_can_request_focus(app, !ignore_events);
let mut widget = IgnorePointer::new().ignoring(ignore_events);
if let Some(child) = child {
widget = widget.child(child.clone());
}
widget.into_widget()
}
})
.child(child)
.into_widget();
route.build_flexible_transitions(app, context, animation, secondary, ignoring)
})
.child(page)
.into_widget();
let scope_child = Builder::new(move |app, context| {
let dismiss_action: ActionRef = DismissModalAction::new(app, context).into_erased();
let mut actions = HashMap::new();
actions.insert(
<DismissModalAction as Action>::intent_type(),
dismiss_action,
);
let controller: ScrollControllerRef = app
.get(self)
.primary_scroll_controller
.as_ref()
.expect("init_state")
.erase();
Actions::new(
actions,
PrimaryScrollController::new(
controller,
FocusScope::with_external_focus_node(
RepaintBoundary::new().child(transitions.clone()),
node.clone(),
),
),
)
.into_widget()
});
let storage_bucket = route.storage_bucket(app).keep(app);
let status = ModalScopeStatus {
route: route_kept,
is_current,
can_pop: route.can_pop(app),
opaque: route.opaque(app),
implies_app_bar_dismissal: route.implies_app_bar_dismissal(app),
child: Offstage::new()
.offstage(route.offstage(app))
.child(PageStorage::new(storage_bucket, scope_child))
.into_widget(),
};
let restoration_scope_id = route.as_route().restoration_scope_id(app).keep(app);
AnimatedBuilder::new(
Rc::new(restoration_scope_id.clone()),
move |app, _context, child| {
let child = child.cloned().expect("the modal scope status");
let id = app.get(&restoration_scope_id).value().clone();
RestorationScope::new(id, child).into_widget()
},
)
.child(status.into_widget())
.into_widget()
}
}
pub struct ModalRouteData {
pub filter: Option<waft_rendering::ImageFilterConfig>,
pub traversal_edge_behavior: Option<TraversalEdgeBehavior>,
pub directional_traversal_edge_behavior: Option<TraversalEdgeBehavior>,
pub received_transition: Option<DelegatedTransitionBuilder>,
offstage: bool,
animation_proxy: Option<Ref<ProxyAnimation>>,
secondary_animation_proxy: Option<Ref<ProxyAnimation>>,
pop_entries: Vec<Rc<dyn PopEntry>>,
scope_key: GlobalKey,
subtree_key: GlobalKey,
storage_bucket: Ref<PageStorageBucket>,
modal_barrier: Option<Ref<OverlayEntry>>,
modal_scope: Option<Ref<OverlayEntry>>,
modal_scope_cache: Option<WidgetRef>,
}
impl ModalRouteData {
pub fn new(app: &mut App) -> ModalRouteData {
ModalRouteData {
filter: None,
traversal_edge_behavior: None,
directional_traversal_edge_behavior: None,
received_transition: None,
offstage: false,
animation_proxy: None,
secondary_animation_proxy: None,
pop_entries: Vec::new(),
scope_key: GlobalKey::new(),
subtree_key: GlobalKey::new(),
storage_bucket: PageStorageBucket::new(app),
modal_barrier: None,
modal_scope: None,
modal_scope_cache: None,
}
}
}
#[macro_export]
macro_rules! modal_route_accessors {
() => {
fn modal_route_data(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> &$crate::ModalRouteData {
&app.get(self).modal_route
}
fn modal_route_data_mut(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
) -> &mut $crate::ModalRouteData {
&mut app.get_mut(self).modal_route
}
};
}
pub trait ModalRoute: LocalHistoryRoute {
fn modal_route_data(self: Handle<Self>, app: &App) -> &ModalRouteData;
fn modal_route_data_mut(self: Handle<Self>, app: &mut App) -> &mut ModalRouteData;
fn as_modal_route(self: Handle<Self>) -> AnyModalRoute {
AnyModalRoute {
id: self.id(),
vtable: const { &ModalRouteVTable::of::<Self>() },
}
}
fn set_state(self: Handle<Self>, app: &mut App, change: impl FnOnce(&mut App)) {
let key = self.modal_route_data(app).scope_key.clone();
match key.current_state::<ModalScopeState>(app) {
Some(state) => state.route_set_state(app, change),
None => {
change(app);
}
}
}
fn build_page(
self: Handle<Self>,
app: &mut App,
context: BuildContext,
animation: AnimationRef<f64>,
secondary_animation: AnimationRef<f64>,
) -> WidgetRef;
fn build_transitions(
self: Handle<Self>,
app: &mut App,
context: BuildContext,
animation: AnimationRef<f64>,
secondary_animation: AnimationRef<f64>,
child: WidgetRef,
) -> WidgetRef {
let _ = (app, context, animation, secondary_animation);
child
}
fn delegated_transition(self: Handle<Self>, app: &App) -> Option<DelegatedTransitionBuilder> {
let _ = app;
None
}
fn build_flexible_transitions(
self: Handle<Self>,
app: &mut App,
context: BuildContext,
animation: AnimationRef<f64>,
secondary_animation: AnimationRef<f64>,
child: WidgetRef,
) -> WidgetRef {
let received = self.modal_route_data(app).received_transition.clone();
let Some(received) = received else {
return ModalRoute::build_transitions(
self,
app,
context,
animation,
secondary_animation,
child,
);
};
if secondary_animation.is_dismissed(app) {
return ModalRoute::build_transitions(
self,
app,
context,
animation,
secondary_animation,
child,
);
}
let proxy_animation: AnimationRef<f64> = ProxyAnimation::new(app, None).into_erased();
let proxied_original_transitions = ModalRoute::build_transitions(
self,
app,
context,
animation.clone(),
proxy_animation,
child,
);
let allow_snapshotting = TransitionRoute::allow_snapshotting(self, app);
received
.call(
app,
context,
animation,
secondary_animation,
allow_snapshotting,
Some(&proxied_original_transitions),
)
.unwrap_or(proxied_original_transitions)
}
fn install(self: Handle<Self>, app: &mut App) {
TransitionRoute::install(self, app);
let animation = self.transition_route_data(app).animation.clone();
let secondary: AnimationRef<f64> =
self.transition_route_data(app).secondary_animation.erase();
self.modal_route_data_mut(app).animation_proxy = Some(ProxyAnimation::new(app, animation));
self.modal_route_data_mut(app).secondary_animation_proxy =
Some(ProxyAnimation::new(app, Some(secondary)));
}
fn did_push(self: Handle<Self>, app: &mut App) -> TickerFuture {
let key = self.modal_route_data(app).scope_key.clone();
if let Some(state) = key.current_state::<ModalScopeState>(app) {
let navigator = self.as_route().navigator(app).expect("an installed route");
if navigator.widget(app).request_focus {
let focus_node = navigator.focus_node(app);
let scope_node = state.focus_scope_node(app);
if let Some(scope) = focus_node.as_node().enclosing_scope(app) {
scope.set_first_focus(app, scope_node);
}
}
}
TransitionRoute::did_push(self, app)
}
fn did_add(self: Handle<Self>, app: &mut App) {
let key = self.modal_route_data(app).scope_key.clone();
if let Some(state) = key.current_state::<ModalScopeState>(app) {
let navigator = self.as_route().navigator(app).expect("an installed route");
if navigator.widget(app).request_focus {
let focus_node = navigator.focus_node(app);
let scope_node = state.focus_scope_node(app);
if let Some(scope) = focus_node.as_node().enclosing_scope(app) {
scope.set_first_focus(app, scope_node);
}
}
}
TransitionRoute::did_add(self, app);
}
fn barrier_dismissible(self: Handle<Self>, app: &App) -> bool;
fn semantics_dismissible(self: Handle<Self>, app: &App) -> bool {
let _ = app;
true
}
fn barrier_color(self: Handle<Self>, app: &App) -> Option<Color>;
fn barrier_label(self: Handle<Self>, app: &App) -> Option<String>;
fn barrier_curve(self: Handle<Self>, app: &App) -> Rc<dyn Curve> {
let _ = app;
Curves::ease()
}
fn maintain_state(self: Handle<Self>, app: &App) -> bool;
fn pop_gesture_in_progress(self: Handle<Self>, app: &App) -> bool {
self.as_route()
.navigator(app)
.expect("an installed route")
.user_gesture_in_progress(app)
}
fn pop_gesture_enabled(self: Handle<Self>, app: &mut App) -> bool {
if self.as_route().is_first(app) {
return false;
}
if Route::will_handle_pop_internally(self, app) {
return false;
}
if Route::pop_disposition(self, app) == RoutePopDisposition::DoNotPop {
return false;
}
let animation = TransitionRoute::animation(self, app).expect("an installed route");
if !animation.is_completed(app) {
return false;
}
true
}
fn offstage(self: Handle<Self>, app: &App) -> bool {
self.modal_route_data(app).offstage
}
fn set_offstage(self: Handle<Self>, app: &mut App, value: bool) {
if self.modal_route_data(app).offstage == value {
return;
}
ModalRoute::set_state(self, app, |app| {
self.modal_route_data_mut(app).offstage = value;
});
let offstage = self.modal_route_data(app).offstage;
let animation_proxy = self
.modal_route_data(app)
.animation_proxy
.handle()
.expect("installed");
let parent = if offstage {
Some(k_always_complete_animation(app))
} else {
self.transition_route_data(app).animation.clone()
};
animation_proxy.set_parent(app, parent);
let secondary_proxy = self
.modal_route_data(app)
.secondary_animation_proxy
.handle()
.expect("installed");
let parent = if offstage {
k_always_dismissed_animation(app)
} else {
self.transition_route_data(app).secondary_animation.erase()
};
secondary_proxy.set_parent(app, Some(parent));
Route::changed_internal_state(self, app);
}
fn subtree_context(self: Handle<Self>, app: &mut App) -> Option<BuildContext> {
let key = self.modal_route_data(app).subtree_key.clone();
key.current_context(app)
}
fn animation(self: Handle<Self>, app: &App) -> Option<AnyAnimation<f64>> {
self.modal_route_data(app)
.animation_proxy
.handle()
.map(Animation::as_animation)
}
fn secondary_animation(self: Handle<Self>, app: &App) -> Option<AnyAnimation<f64>> {
self.modal_route_data(app)
.secondary_animation_proxy
.handle()
.map(Animation::as_animation)
}
fn pop_disposition(self: Handle<Self>, app: &mut App) -> RoutePopDisposition {
for pop_entry in self.modal_route_data(app).pop_entries.clone() {
if !*pop_entry.can_pop_notifier(app).value(app) {
return RoutePopDisposition::DoNotPop;
}
}
LocalHistoryRoute::pop_disposition(self, app)
}
fn on_pop_invoked_with_result(
self: Handle<Self>,
app: &mut App,
did_pop: bool,
result: RouteResult,
) {
for pop_entry in self.modal_route_data(app).pop_entries.clone() {
pop_entry.on_pop_invoked_with_result(app, did_pop, result.clone());
}
RouteBase::on_pop_invoked_with_result(self, app, did_pop, result);
}
fn register_pop_entry(self: Handle<Self>, app: &mut App, pop_entry: Rc<dyn PopEntry>) {
if !self
.modal_route_data(app)
.pop_entries
.iter()
.any(|held| Rc::ptr_eq(held, &pop_entry))
{
self.modal_route_data_mut(app)
.pop_entries
.push(Rc::clone(&pop_entry));
}
let notifier = pop_entry.can_pop_notifier(app);
notifier.add_listener(
app,
Listener::handle_method(self, Self::maybe_dispatch_navigation_notification),
);
ModalRoute::maybe_dispatch_navigation_notification(self, app);
}
fn unregister_pop_entry(self: Handle<Self>, app: &mut App, pop_entry: Rc<dyn PopEntry>) {
self.modal_route_data_mut(app)
.pop_entries
.retain(|held| !Rc::ptr_eq(held, &pop_entry));
let notifier = pop_entry.can_pop_notifier(app);
notifier.remove_listener(
app,
&Listener::handle_method(self, Self::maybe_dispatch_navigation_notification),
);
ModalRoute::maybe_dispatch_navigation_notification(self, app);
}
fn maybe_dispatch_navigation_notification(self: Handle<Self>, app: &mut App) {
if !self.as_route().is_current(app) {
return;
}
let notification = NavigationNotification::new(
Route::pop_disposition(self, app) == RoutePopDisposition::DoNotPop,
);
match SchedulerBinding::scheduler_phase(app) {
SchedulerPhase::PostFrameCallbacks => {
let context = ModalRoute::subtree_context(self, app);
notification.dispatch(app, context);
}
SchedulerPhase::Idle
| SchedulerPhase::MidFrameMicrotasks
| SchedulerPhase::PersistentCallbacks
| SchedulerPhase::TransientCallbacks => {
let context = ModalRoute::subtree_context(self, app);
SchedulerBinding::add_post_frame_callback(
app,
FrameCallback::new(move |app, _time_stamp| {
if self.upgrade(app).is_none() {
return;
}
let context = ModalRoute::subtree_context(self, app);
if !context.is_some_and(|context| context.mounted(app)) {
return;
}
notification.dispatch(app, context);
}),
context.and_then(|context| View::maybe_id_of(app, context)),
);
}
}
}
fn did_change_previous(self: Handle<Self>, app: &mut App, previous_route: Option<AnyRoute>) {
RouteBase::did_change_previous(self, app, previous_route);
Route::changed_internal_state(self, app);
}
fn did_change_next(self: Handle<Self>, app: &mut App, next_route: Option<AnyRoute>) {
self.update_received_transition(app, next_route);
TransitionRoute::did_change_next(self, app, next_route);
Route::changed_internal_state(self, app);
}
fn did_pop_next(self: Handle<Self>, app: &mut App, next_route: AnyRoute) {
self.update_received_transition(app, Some(next_route));
TransitionRoute::did_pop_next(self, app, next_route);
Route::changed_internal_state(self, app);
ModalRoute::maybe_dispatch_navigation_notification(self, app);
}
fn update_received_transition(self: Handle<Self>, app: &mut App, next_route: Option<AnyRoute>) {
let next_modal = next_route.and_then(|route| route.as_modal_route(app));
let received = match next_modal {
Some(next) => {
let next_transition = next
.as_route()
.as_transition_route(app)
.expect("a modal route is a transition route");
let mine = ModalRoute::delegated_transition(self, app);
let theirs = next.delegated_transition(app);
let differs = mine != theirs;
if TransitionRoute::can_transition_to(self, app, next_transition) && differs {
theirs
} else {
None
}
}
None => None,
};
self.modal_route_data_mut(app).received_transition = received;
}
fn changed_internal_state(self: Handle<Self>, app: &mut App) {
RouteBase::changed_internal_state(self, app);
if SchedulerBinding::scheduler_phase(app) != SchedulerPhase::PersistentCallbacks {
ModalRoute::set_state(self, app, |_app| {
});
let barrier = self
.modal_route_data(app)
.modal_barrier
.handle()
.expect("installed");
barrier.mark_needs_build(app);
}
let maintain_state = ModalRoute::maintain_state(self, app);
let scope = self
.modal_route_data(app)
.modal_scope
.handle()
.expect("installed");
scope.set_maintain_state(app, maintain_state);
}
fn changed_external_state(self: Handle<Self>, app: &mut App) {
RouteBase::changed_external_state(self, app);
let barrier = self
.modal_route_data(app)
.modal_barrier
.handle()
.expect("installed");
barrier.mark_needs_build(app);
let key = self.modal_route_data(app).scope_key.clone();
if let Some(state) = key.current_state::<ModalScopeState>(app) {
state.force_rebuild_page(app);
}
}
fn can_pop(self: Handle<Self>, app: &mut App) -> bool {
self.as_route().has_active_route_below(app) || Route::will_handle_pop_internally(self, app)
}
fn implies_app_bar_dismissal(self: Handle<Self>, app: &App) -> bool {
self.as_route().has_active_route_below(app)
|| self
.local_history_route_data(app)
.entries_implies_app_bar_dismissal
> 0
}
fn fullscreen_dialog(self: Handle<Self>, app: &App) -> bool {
let _ = app;
false
}
fn build_modal_barrier_entry(
self: Handle<Self>,
app: &mut App,
context: BuildContext,
) -> WidgetRef {
let mut barrier = ModalRoute::build_modal_barrier(self, app, context);
if let Some(filter) = self.modal_route_data(app).filter.clone() {
barrier = crate::widgets::basic::BackdropFilter::new(filter)
.child(barrier)
.into_widget();
}
let animation = TransitionRoute::animation(self, app).expect("an installed route");
barrier = IgnorePointer::new()
.ignoring(!animation.is_forward_or_completed(app))
.child(barrier)
.into_widget();
if ModalRoute::semantics_dismissible(self, app)
&& ModalRoute::barrier_dismissible(self, app)
{
barrier = Semantics::new()
.sort_key(Rc::new(OrdinalSortKey::new(1.0)))
.child(barrier)
.into_widget();
}
barrier
}
fn build_modal_barrier(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
ModalRouteBase::build_modal_barrier(self, app, context)
}
fn build_modal_scope(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
let _ = context;
match self.modal_route_data(app).modal_scope_cache.clone() {
Some(cache) => cache,
None => {
let key = self.modal_route_data(app).scope_key.clone();
let scope = Semantics::new()
.sort_key(Rc::new(OrdinalSortKey::new(0.0)))
.child(ModalScope {
key: Some(key.into()),
route: ModalRoute::as_modal_route(self),
})
.into_widget();
self.modal_route_data_mut(app).modal_scope_cache = Some(scope.clone());
scope
}
}
}
fn create_overlay_entries(self: Handle<Self>, app: &mut App) -> Vec<Ref<OverlayEntry>> {
let barrier = OverlayEntry::new(
app,
Rc::new(move |app, context| ModalRoute::build_modal_barrier_entry(self, app, context)),
false,
false,
false,
);
self.modal_route_data_mut(app).modal_barrier = Some(barrier.clone());
let maintain_state = ModalRoute::maintain_state(self, app);
let opaque = TransitionRoute::opaque(self, app);
let scope = OverlayEntry::new(
app,
Rc::new(move |app, context| ModalRoute::build_modal_scope(self, app, context)),
false,
maintain_state,
opaque,
);
self.modal_route_data_mut(app).modal_scope = Some(scope.clone());
vec![barrier, scope]
}
}
pub trait ModalRouteBase: ModalRoute {
fn build_modal_barrier(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
let _ = context;
let barrier_color = ModalRoute::barrier_color(self, app);
let dismissible = ModalRoute::barrier_dismissible(self, app);
let semantics_label = ModalRoute::barrier_label(self, app);
let semantics_dismissible = ModalRoute::semantics_dismissible(self, app);
match barrier_color {
Some(barrier_color) if barrier_color.a != 0.0 && !ModalRoute::offstage(self, app) => {
let transparent = barrier_color.with_values(Some(0.0), None, None, None, None);
debug_assert!(barrier_color != transparent);
let animation = TransitionRoute::animation(self, app)
.expect("an installed route keeps its animation")
.keep(app);
let curve = ModalRoute::barrier_curve(self, app);
let color_tween = ColorTween::new(app, Some(transparent), Some(barrier_color));
let curve_tween = CurveTween::new(app, curve);
let color = animation.drive(app, color_tween.chain(curve_tween));
AnimatedModalBarrier::new(color)
.dismissible(dismissible)
.barrier_semantics_dismissible(semantics_dismissible)
.maybe_semantics_label(semantics_label)
.into_widget()
}
_ => ModalBarrier::new()
.dismissible(dismissible)
.barrier_semantics_dismissible(semantics_dismissible)
.maybe_semantics_label(semantics_label)
.into_widget(),
}
}
}
impl<R: ModalRoute> ModalRouteBase for R {}
type BuildFlexibleTransitionsSlot = fn(
&mut App,
HandleId,
BuildContext,
AnimationRef<f64>,
AnimationRef<f64>,
WidgetRef,
) -> WidgetRef;
struct ModalRouteVTable {
type_name: fn() -> &'static str,
route: fn(HandleId) -> AnyRoute,
transition_route: fn(HandleId) -> AnyTransitionRoute,
barrier_dismissible: fn(&App, HandleId) -> bool,
barrier_color: fn(&App, HandleId) -> Option<Color>,
barrier_label: fn(&App, HandleId) -> Option<String>,
maintain_state: fn(&App, HandleId) -> bool,
opaque: fn(&App, HandleId) -> bool,
offstage: fn(&App, HandleId) -> bool,
set_offstage: fn(&mut App, HandleId, bool),
animation: fn(&App, HandleId) -> Option<AnyAnimation<f64>>,
secondary_animation: fn(&App, HandleId) -> Option<AnyAnimation<f64>>,
delegated_transition: fn(&App, HandleId) -> Option<DelegatedTransitionBuilder>,
can_pop: fn(&mut App, HandleId) -> bool,
implies_app_bar_dismissal: fn(&App, HandleId) -> bool,
fullscreen_dialog: fn(&App, HandleId) -> bool,
pop_gesture_in_progress: fn(&App, HandleId) -> bool,
traversal_edge_behavior: fn(&App, HandleId) -> Option<TraversalEdgeBehavior>,
directional_traversal_edge_behavior: fn(&App, HandleId) -> Option<TraversalEdgeBehavior>,
storage_bucket: fn(&App, HandleId) -> Handle<PageStorageBucket>,
subtree_key: fn(&App, HandleId) -> GlobalKey,
subtree_context: fn(&mut App, HandleId) -> Option<BuildContext>,
build_page:
fn(&mut App, HandleId, BuildContext, AnimationRef<f64>, AnimationRef<f64>) -> WidgetRef,
build_flexible_transitions: BuildFlexibleTransitionsSlot,
add_local_history_entry: fn(&mut App, HandleId, Ref<LocalHistoryEntry>),
remove_local_history_entry: fn(&mut App, HandleId, Handle<LocalHistoryEntry>),
register_pop_entry: fn(&mut App, HandleId, Rc<dyn PopEntry>),
unregister_pop_entry: fn(&mut App, HandleId, Rc<dyn PopEntry>),
}
impl ModalRouteVTable {
const fn of<R: ModalRoute>() -> ModalRouteVTable {
ModalRouteVTable {
type_name: std::any::type_name::<R>,
route: |id| Route::as_route(resolve::<R>(id)),
transition_route: |id| TransitionRoute::as_transition_route(resolve::<R>(id)),
barrier_dismissible: |app, id| R::barrier_dismissible(resolve(id), app),
barrier_color: |app, id| R::barrier_color(resolve(id), app),
barrier_label: |app, id| R::barrier_label(resolve(id), app),
maintain_state: |app, id| R::maintain_state(resolve(id), app),
opaque: |app, id| TransitionRoute::opaque(resolve::<R>(id), app),
offstage: |app, id| R::offstage(resolve(id), app),
set_offstage: |app, id, value| R::set_offstage(resolve(id), app, value),
animation: |app, id| ModalRoute::animation(resolve::<R>(id), app),
secondary_animation: |app, id| ModalRoute::secondary_animation(resolve::<R>(id), app),
delegated_transition: |app, id| R::delegated_transition(resolve(id), app),
can_pop: |app, id| R::can_pop(resolve(id), app),
implies_app_bar_dismissal: |app, id| R::implies_app_bar_dismissal(resolve(id), app),
fullscreen_dialog: |app, id| R::fullscreen_dialog(resolve(id), app),
pop_gesture_in_progress: |app, id| R::pop_gesture_in_progress(resolve(id), app),
traversal_edge_behavior: |app, id| {
R::modal_route_data(resolve::<R>(id), app).traversal_edge_behavior
},
directional_traversal_edge_behavior: |app, id| {
R::modal_route_data(resolve::<R>(id), app).directional_traversal_edge_behavior
},
storage_bucket: |app, id| {
R::modal_route_data(resolve::<R>(id), app)
.storage_bucket
.handle()
},
subtree_key: |app, id| {
R::modal_route_data(resolve::<R>(id), app)
.subtree_key
.clone()
},
subtree_context: |app, id| R::subtree_context(resolve::<R>(id), app),
build_page: |app, id, context, animation, secondary| {
R::build_page(resolve(id), app, context, animation, secondary)
},
build_flexible_transitions: |app, id, context, animation, secondary, child| {
R::build_flexible_transitions(
resolve(id),
app,
context,
animation,
secondary,
child,
)
},
add_local_history_entry: |app, id, entry| {
LocalHistoryRoute::add_local_history_entry(resolve::<R>(id), app, entry)
},
remove_local_history_entry: |app, id, entry| {
LocalHistoryRoute::remove_local_history_entry(resolve::<R>(id), app, entry)
},
register_pop_entry: |app, id, entry| R::register_pop_entry(resolve(id), app, entry),
unregister_pop_entry: |app, id, entry| R::unregister_pop_entry(resolve(id), app, entry),
}
}
}
#[derive(Clone, Copy)]
pub struct AnyModalRoute {
id: HandleId,
vtable: &'static ModalRouteVTable,
}
impl From<AnyModalRoute> for AnyRoute {
fn from(route: AnyModalRoute) -> AnyRoute {
route.as_route()
}
}
impl From<AnyModalRoute> for AnyTransitionRoute {
fn from(route: AnyModalRoute) -> AnyTransitionRoute {
route.as_transition_route()
}
}
pub type ModalRouteRef = Retained<AnyModalRoute>;
waft_foundation::erased_handle!(AnyModalRoute: ModalRoute => ModalRoute::as_modal_route);
impl Debug for AnyModalRoute {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
}
}
impl AnyModalRoute {
pub fn animations(self, app: &App) -> (AnimationRef<f64>, AnimationRef<f64>) {
let kept = |animation: Option<AnyAnimation<f64>>| {
animation
.expect("an installed route keeps its animations")
.keep(app)
};
(
kept(self.animation(app)),
kept(self.secondary_animation(app)),
)
}
pub fn of(app: &mut App, context: BuildContext) -> Option<AnyModalRoute> {
AnyModalRoute::of_aspect(app, context, None)
}
fn of_aspect(
app: &mut App,
context: BuildContext,
aspect: Option<ModalRouteAspect>,
) -> Option<AnyModalRoute> {
ModalScopeStatus::inherit_from(app, context, aspect).map(|status| status.route.handle())
}
pub fn is_current_of(app: &mut App, context: BuildContext) -> Option<bool> {
let route = AnyModalRoute::of_aspect(app, context, Some(ModalRouteAspect::IsCurrent))?;
Some(route.as_route().is_current(app))
}
pub fn can_pop_of(app: &mut App, context: BuildContext) -> Option<bool> {
let route = AnyModalRoute::of_aspect(app, context, Some(ModalRouteAspect::CanPop))?;
Some(route.can_pop(app))
}
pub fn settings_of(app: &mut App, context: BuildContext) -> Option<RouteSettingsRef> {
let route = AnyModalRoute::of_aspect(app, context, Some(ModalRouteAspect::Settings))?;
Some(route.as_route().settings(app))
}
pub fn is_active_of(app: &mut App, context: BuildContext) -> Option<bool> {
let route = AnyModalRoute::of_aspect(app, context, Some(ModalRouteAspect::IsActive))?;
Some(route.as_route().is_active(app))
}
pub fn is_first_of(app: &mut App, context: BuildContext) -> Option<bool> {
let route = AnyModalRoute::of_aspect(app, context, Some(ModalRouteAspect::IsFirst))?;
Some(route.as_route().is_first(app))
}
pub fn opaque_of(app: &mut App, context: BuildContext) -> Option<bool> {
let route = AnyModalRoute::of_aspect(app, context, Some(ModalRouteAspect::Opaque))?;
Some(route.opaque(app))
}
pub fn pop_disposition_of(app: &mut App, context: BuildContext) -> Option<RoutePopDisposition> {
let route = AnyModalRoute::of_aspect(app, context, Some(ModalRouteAspect::PopDisposition))?;
Some(route.as_route().pop_disposition(app))
}
pub fn with_name(name: &str) -> RoutePredicate {
let name = name.to_string();
Rc::new(move |app, route: AnyRoute| {
!route.will_handle_pop_internally(app)
&& route.as_modal_route(app).is_some()
&& route.settings(app).name() == Some(name.as_str())
})
}
pub fn as_route(self) -> AnyRoute {
(self.vtable.route)(self.id)
}
pub fn as_transition_route(self) -> AnyTransitionRoute {
(self.vtable.transition_route)(self.id)
}
pub fn barrier_dismissible(self, app: &App) -> bool {
(self.vtable.barrier_dismissible)(app, self.id)
}
pub fn barrier_color(self, app: &App) -> Option<Color> {
(self.vtable.barrier_color)(app, self.id)
}
pub fn barrier_label(self, app: &App) -> Option<String> {
(self.vtable.barrier_label)(app, self.id)
}
pub fn maintain_state(self, app: &App) -> bool {
(self.vtable.maintain_state)(app, self.id)
}
pub fn opaque(self, app: &App) -> bool {
(self.vtable.opaque)(app, self.id)
}
pub fn offstage(self, app: &App) -> bool {
(self.vtable.offstage)(app, self.id)
}
pub fn set_offstage(self, app: &mut App, value: bool) {
(self.vtable.set_offstage)(app, self.id, value)
}
pub fn animation(self, app: &App) -> Option<AnyAnimation<f64>> {
(self.vtable.animation)(app, self.id)
}
pub fn secondary_animation(self, app: &App) -> Option<AnyAnimation<f64>> {
(self.vtable.secondary_animation)(app, self.id)
}
pub fn delegated_transition(self, app: &App) -> Option<DelegatedTransitionBuilder> {
(self.vtable.delegated_transition)(app, self.id)
}
pub fn can_pop(self, app: &mut App) -> bool {
(self.vtable.can_pop)(app, self.id)
}
pub fn implies_app_bar_dismissal(self, app: &App) -> bool {
(self.vtable.implies_app_bar_dismissal)(app, self.id)
}
pub fn fullscreen_dialog(self, app: &App) -> bool {
(self.vtable.fullscreen_dialog)(app, self.id)
}
pub fn pop_gesture_in_progress(self, app: &App) -> bool {
(self.vtable.pop_gesture_in_progress)(app, self.id)
}
pub fn traversal_edge_behavior(self, app: &App) -> Option<TraversalEdgeBehavior> {
(self.vtable.traversal_edge_behavior)(app, self.id)
}
pub fn directional_traversal_edge_behavior(self, app: &App) -> Option<TraversalEdgeBehavior> {
(self.vtable.directional_traversal_edge_behavior)(app, self.id)
}
pub fn storage_bucket(self, app: &App) -> Handle<PageStorageBucket> {
(self.vtable.storage_bucket)(app, self.id)
}
pub fn subtree_key(self, app: &App) -> GlobalKey {
(self.vtable.subtree_key)(app, self.id)
}
pub fn subtree_context(self, app: &mut App) -> Option<BuildContext> {
(self.vtable.subtree_context)(app, self.id)
}
pub fn build_page(
self,
app: &mut App,
context: BuildContext,
animation: AnimationRef<f64>,
secondary_animation: AnimationRef<f64>,
) -> WidgetRef {
(self.vtable.build_page)(app, self.id, context, animation, secondary_animation)
}
pub fn build_flexible_transitions(
self,
app: &mut App,
context: BuildContext,
animation: AnimationRef<f64>,
secondary_animation: AnimationRef<f64>,
child: WidgetRef,
) -> WidgetRef {
(self.vtable.build_flexible_transitions)(
app,
self.id,
context,
animation,
secondary_animation,
child,
)
}
pub fn add_local_history_entry(self, app: &mut App, entry: Ref<LocalHistoryEntry>) {
(self.vtable.add_local_history_entry)(app, self.id, entry)
}
pub fn remove_local_history_entry(self, app: &mut App, entry: Handle<LocalHistoryEntry>) {
(self.vtable.remove_local_history_entry)(app, self.id, entry)
}
pub fn register_pop_entry(self, app: &mut App, pop_entry: Rc<dyn PopEntry>) {
(self.vtable.register_pop_entry)(app, self.id, pop_entry)
}
pub fn unregister_pop_entry(self, app: &mut App, pop_entry: Rc<dyn PopEntry>) {
(self.vtable.unregister_pop_entry)(app, self.id, pop_entry)
}
}
pub trait PopupRoute: ModalRoute {
fn opaque(self: Handle<Self>, app: &App) -> bool {
let _ = app;
false
}
fn maintain_state(self: Handle<Self>, app: &App) -> bool {
let _ = app;
true
}
fn allow_snapshotting(self: Handle<Self>, app: &App) -> bool {
let _ = app;
false
}
}
#[macro_export]
macro_rules! modal_route_overrides {
() => {
$crate::route_accessors!();
fn as_transition_route(
self: ::waft_foundation::Handle<Self>,
) -> ::std::option::Option<$crate::AnyTransitionRoute> {
::std::option::Option::Some($crate::TransitionRoute::as_transition_route(self))
}
fn as_modal_route(
self: ::waft_foundation::Handle<Self>,
) -> ::std::option::Option<$crate::AnyModalRoute> {
::std::option::Option::Some($crate::ModalRoute::as_modal_route(self))
}
fn overlay_entries(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> ::std::vec::Vec<::waft_foundation::Handle<$crate::OverlayEntry>> {
$crate::OverlayRoute::overlay_entries(self, app)
}
fn install(self: ::waft_foundation::Handle<Self>, app: &mut ::waft_foundation::App) {
$crate::ModalRoute::install(self, app)
}
fn did_push(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
) -> ::waft_scheduler::TickerFuture {
$crate::ModalRoute::did_push(self, app)
}
fn did_add(self: ::waft_foundation::Handle<Self>, app: &mut ::waft_foundation::App) {
$crate::ModalRoute::did_add(self, app)
}
fn did_replace(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
old_route: ::std::option::Option<$crate::AnyRoute>,
) {
$crate::TransitionRoute::did_replace(self, app, old_route)
}
fn will_pop(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
) -> $crate::RoutePopDisposition {
$crate::LocalHistoryRoute::will_pop(self, app)
}
fn pop_disposition(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
) -> $crate::RoutePopDisposition {
$crate::ModalRoute::pop_disposition(self, app)
}
fn on_pop_invoked_with_result(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
did_pop: bool,
result: $crate::RouteResult,
) {
$crate::ModalRoute::on_pop_invoked_with_result(self, app, did_pop, result)
}
fn will_handle_pop_internally(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> bool {
$crate::LocalHistoryRoute::will_handle_pop_internally(self, app)
}
fn did_pop(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
result: $crate::RouteResult,
) -> bool {
$crate::LocalHistoryRoute::did_pop(self, app, result)
}
fn did_pop_next(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
next_route: $crate::AnyRoute,
) {
$crate::ModalRoute::did_pop_next(self, app, next_route)
}
fn did_change_next(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
next_route: ::std::option::Option<$crate::AnyRoute>,
) {
$crate::ModalRoute::did_change_next(self, app, next_route)
}
fn did_change_previous(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
previous_route: ::std::option::Option<$crate::AnyRoute>,
) {
$crate::ModalRoute::did_change_previous(self, app, previous_route)
}
fn changed_internal_state(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
) {
$crate::ModalRoute::changed_internal_state(self, app)
}
fn changed_external_state(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
) {
$crate::ModalRoute::changed_external_state(self, app)
}
fn dispose(self: ::waft_foundation::Handle<Self>, app: &mut ::waft_foundation::App) {
$crate::TransitionRoute::dispose(self, app)
}
};
}
#[macro_export]
macro_rules! modal_overlay_route_overrides {
() => {
$crate::overlay_route_accessors!();
fn create_overlay_entries(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
) -> ::std::vec::Vec<::waft_foundation::Ref<$crate::OverlayEntry>> {
$crate::ModalRoute::create_overlay_entries(self, app)
}
fn finished_when_popped(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> bool {
$crate::TransitionRoute::finished_when_popped(self, app)
}
};
}
#[macro_export]
macro_rules! modal_predictive_back_route_overrides {
($pop_gesture_enabled:path) => {
fn pop_gesture_enabled(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
) -> bool {
$pop_gesture_enabled(self, app)
}
fn handle_start_back_gesture(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
progress: f64,
) {
$crate::TransitionRoute::handle_start_back_gesture(self, app, progress)
}
fn handle_update_back_gesture_progress(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
progress: f64,
) {
$crate::TransitionRoute::handle_update_back_gesture_progress(self, app, progress)
}
fn handle_commit_back_gesture(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
) {
$crate::TransitionRoute::handle_commit_back_gesture(self, app)
}
fn handle_cancel_back_gesture(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
) {
$crate::TransitionRoute::handle_cancel_back_gesture(self, app)
}
};
}
#[macro_export]
macro_rules! modal_transition_route_overrides {
() => {
$crate::transition_route_accessors!();
fn animation(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> ::std::option::Option<::waft_animation::AnyAnimation<f64>> {
$crate::ModalRoute::animation(self, app)
}
fn secondary_animation(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> ::std::option::Option<::waft_animation::AnyAnimation<f64>> {
$crate::ModalRoute::secondary_animation(self, app)
}
};
}
pub struct RouteObserver {
navigator_observer: NavigatorObserverData,
matches: RoutePredicate,
listeners: Vec<(RouteRef, Vec<Rc<dyn RouteAware>>)>,
}
impl RouteObserver {
pub fn new(app: &mut App, matches: RoutePredicate) -> Ref<RouteObserver> {
app.create(RouteObserver {
navigator_observer: NavigatorObserverData::new(),
matches,
listeners: Vec::new(),
})
}
pub fn debug_observing_route(self: Handle<Self>, app: &App, route: AnyRoute) -> bool {
let mut contained = false;
if cfg!(debug_assertions) {
contained = app
.get(self)
.listeners
.iter()
.any(|(held, _)| held == route);
}
contained
}
pub fn subscribe(
self: Handle<Self>,
app: &mut App,
route_aware: Rc<dyn RouteAware>,
route: AnyRoute,
) {
let kept = route.keep(app);
let listeners = &mut app.get_mut(self).listeners;
let subscribers = match listeners.iter_mut().find(|(held, _)| held == route) {
Some((_, subscribers)) => subscribers,
None => {
listeners.push((kept, Vec::new()));
&mut listeners.last_mut().expect("just pushed").1
}
};
if subscribers
.iter()
.any(|held| Rc::ptr_eq(held, &route_aware))
{
return;
}
subscribers.push(Rc::clone(&route_aware));
route_aware.did_push(app);
}
pub fn unsubscribe(self: Handle<Self>, app: &mut App, route_aware: Rc<dyn RouteAware>) {
let listeners = &mut app.get_mut(self).listeners;
for (_, subscribers) in listeners.iter_mut() {
subscribers.retain(|held| !Rc::ptr_eq(held, &route_aware));
}
listeners.retain(|(_, subscribers)| !subscribers.is_empty());
}
fn subscribers_of(
self: Handle<Self>,
app: &App,
route: AnyRoute,
) -> Option<Vec<Rc<dyn RouteAware>>> {
app.get(self)
.listeners
.iter()
.find(|(held, _)| held == route)
.map(|(_, subscribers)| subscribers.clone())
}
fn matches(self: Handle<Self>, app: &mut App, route: Option<AnyRoute>) -> bool {
let Some(route) = route else {
return false;
};
let matches = Rc::clone(&app.get(self).matches);
matches(app, route)
}
}
impl NavigatorObserver for RouteObserver {
crate::navigator_observer_accessors!();
fn did_pop(
self: Handle<Self>,
app: &mut App,
route: AnyRoute,
previous_route: Option<AnyRoute>,
) {
if !self.matches(app, Some(route)) || !self.matches(app, previous_route) {
return;
}
let previous_route = previous_route.expect("matched above");
if let Some(previous_subscribers) = self.subscribers_of(app, previous_route) {
for route_aware in previous_subscribers {
route_aware.did_pop_next(app);
}
}
if let Some(subscribers) = self.subscribers_of(app, route) {
for route_aware in subscribers {
route_aware.did_pop(app);
}
}
}
fn did_push(
self: Handle<Self>,
app: &mut App,
route: AnyRoute,
previous_route: Option<AnyRoute>,
) {
if !self.matches(app, Some(route)) || !self.matches(app, previous_route) {
return;
}
let previous_route = previous_route.expect("matched above");
if let Some(previous_subscribers) = self.subscribers_of(app, previous_route) {
for route_aware in previous_subscribers {
route_aware.did_push_next(app);
}
}
}
}
pub trait RouteAware {
fn did_pop_next(&self, app: &mut App);
fn did_push(&self, app: &mut App);
fn did_pop(&self, app: &mut App);
fn did_push_next(&self, app: &mut App);
}
pub trait RouteAwareObject: Sized + 'static {
fn did_pop_next(self: Handle<Self>, app: &mut App) {
let _ = app;
}
fn did_push(self: Handle<Self>, app: &mut App) {
let _ = app;
}
fn did_pop(self: Handle<Self>, app: &mut App) {
let _ = app;
}
fn did_push_next(self: Handle<Self>, app: &mut App) {
let _ = app;
}
}
impl<T: RouteAwareObject> RouteAware for Handle<T> {
fn did_pop_next(&self, app: &mut App) {
T::did_pop_next(*self, app);
}
fn did_push(&self, app: &mut App) {
T::did_push(*self, app);
}
fn did_pop(&self, app: &mut App) {
T::did_pop(*self, app);
}
fn did_push_next(&self, app: &mut App) {
T::did_push_next(*self, app);
}
}
pub type RoutePageBuilder =
Rc<dyn Fn(&mut App, BuildContext, AnimationRef<f64>, AnimationRef<f64>) -> WidgetRef>;
pub type RouteTransitionsBuilder = Rc<
dyn Fn(&mut App, BuildContext, AnimationRef<f64>, AnimationRef<f64>, WidgetRef) -> WidgetRef,
>;
#[derive(Clone, Debug)]
pub struct RouteBarrierDetails {
pub animation: AnimationRef<f64>,
pub barrier_color: Option<Color>,
pub barrier_label: Option<String>,
pub barrier_dismissible: bool,
}
impl RouteBarrierDetails {
pub fn new(animation: AnimationRef<f64>, barrier_dismissible: bool) -> RouteBarrierDetails {
RouteBarrierDetails {
animation,
barrier_color: None,
barrier_label: None,
barrier_dismissible,
}
}
pub fn barrier_color(mut self, barrier_color: Color) -> RouteBarrierDetails {
self.barrier_color = Some(barrier_color);
self
}
pub fn barrier_label(mut self, barrier_label: String) -> RouteBarrierDetails {
self.barrier_label = Some(barrier_label);
self
}
}
pub type RouteBarrierBuilder =
Rc<dyn Fn(&mut App, BuildContext, &RouteBarrierDetails, WidgetRef) -> WidgetRef>;
pub type PopInvokedWithResultCallback = Rc<dyn Fn(&mut App, bool, RouteResult)>;
pub trait PopEntry {
fn on_pop_invoked_with_result(&self, app: &mut App, did_pop: bool, result: RouteResult);
fn can_pop_notifier(&self, app: &App) -> Rc<dyn ValueListenable<bool>>;
}
pub trait PopEntryObject: Sized + 'static {
fn on_pop_invoked_with_result(
self: Handle<Self>,
app: &mut App,
did_pop: bool,
result: RouteResult,
);
fn can_pop_notifier(self: Handle<Self>, app: &App) -> Rc<dyn ValueListenable<bool>>;
}
impl<T: PopEntryObject> PopEntry for Handle<T> {
fn on_pop_invoked_with_result(&self, app: &mut App, did_pop: bool, result: RouteResult) {
T::on_pop_invoked_with_result(*self, app, did_pop, result);
}
fn can_pop_notifier(&self, app: &App) -> Rc<dyn ValueListenable<bool>> {
T::can_pop_notifier(*self, app)
}
}
pub struct RawDialogRouteData {
pub page_builder: RoutePageBuilder,
pub barrier_dismissible: bool,
pub barrier_label: Option<String>,
pub barrier_color: Option<Color>,
pub transition_duration: Duration,
pub transition_builder: Option<RouteTransitionsBuilder>,
pub barrier_builder: Option<RouteBarrierBuilder>,
pub fullscreen_dialog: bool,
}
impl RawDialogRouteData {
pub fn new(page_builder: RoutePageBuilder) -> RawDialogRouteData {
RawDialogRouteData {
page_builder,
barrier_dismissible: true,
barrier_label: None,
barrier_color: Some(Color::new(0x8000_0000)),
transition_duration: Duration::from_millis(200),
transition_builder: None,
barrier_builder: None,
fullscreen_dialog: false,
}
}
}
#[macro_export]
macro_rules! raw_dialog_route_accessors {
() => {
fn raw_dialog_route_data(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> &$crate::RawDialogRouteData {
&app.get(self).raw_dialog_route
}
fn raw_dialog_route_data_mut(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
) -> &mut $crate::RawDialogRouteData {
&mut app.get_mut(self).raw_dialog_route
}
};
}
pub trait RawDialogRouteLeaf: PopupRoute {
fn raw_dialog_route_data(self: Handle<Self>, app: &App) -> &RawDialogRouteData;
fn raw_dialog_route_data_mut(self: Handle<Self>, app: &mut App) -> &mut RawDialogRouteData;
fn barrier_dismissible(self: Handle<Self>, app: &App) -> bool {
self.raw_dialog_route_data(app).barrier_dismissible
}
fn barrier_label(self: Handle<Self>, app: &App) -> Option<String> {
self.raw_dialog_route_data(app).barrier_label.clone()
}
fn barrier_color(self: Handle<Self>, app: &App) -> Option<Color> {
self.raw_dialog_route_data(app).barrier_color
}
fn transition_duration(self: Handle<Self>, app: &App) -> Duration {
self.raw_dialog_route_data(app).transition_duration
}
fn fullscreen_dialog(self: Handle<Self>, app: &App) -> bool {
self.raw_dialog_route_data(app).fullscreen_dialog
}
fn build_page(
self: Handle<Self>,
app: &mut App,
context: BuildContext,
animation: AnimationRef<f64>,
secondary_animation: AnimationRef<f64>,
) -> WidgetRef {
RawDialogRoute::build_page(self, app, context, animation, secondary_animation)
}
fn build_transitions(
self: Handle<Self>,
app: &mut App,
context: BuildContext,
animation: AnimationRef<f64>,
secondary_animation: AnimationRef<f64>,
child: WidgetRef,
) -> WidgetRef {
RawDialogRoute::build_transitions(self, app, context, animation, secondary_animation, child)
}
fn build_modal_barrier(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
RawDialogRoute::build_modal_barrier(self, app, context)
}
}
#[macro_export]
macro_rules! raw_dialog_route_modal_route_overrides {
() => {
$crate::modal_route_accessors!();
fn barrier_dismissible(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> bool {
$crate::RawDialogRouteLeaf::barrier_dismissible(self, app)
}
fn barrier_label(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> ::std::option::Option<::std::string::String> {
$crate::RawDialogRouteLeaf::barrier_label(self, app)
}
fn barrier_color(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> ::std::option::Option<::waft_painting::Color> {
$crate::RawDialogRouteLeaf::barrier_color(self, app)
}
fn maintain_state(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> bool {
$crate::PopupRoute::maintain_state(self, app)
}
fn fullscreen_dialog(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> bool {
$crate::RawDialogRouteLeaf::fullscreen_dialog(self, app)
}
fn build_page(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
context: $crate::BuildContext,
animation: ::waft_animation::AnimationRef<f64>,
secondary_animation: ::waft_animation::AnimationRef<f64>,
) -> $crate::WidgetRef {
$crate::RawDialogRouteLeaf::build_page(
self,
app,
context,
animation,
secondary_animation,
)
}
fn build_transitions(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
context: $crate::BuildContext,
animation: ::waft_animation::AnimationRef<f64>,
secondary_animation: ::waft_animation::AnimationRef<f64>,
child: $crate::WidgetRef,
) -> $crate::WidgetRef {
$crate::RawDialogRouteLeaf::build_transitions(
self,
app,
context,
animation,
secondary_animation,
child,
)
}
fn build_modal_barrier(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
context: $crate::BuildContext,
) -> $crate::WidgetRef {
$crate::RawDialogRouteLeaf::build_modal_barrier(self, app, context)
}
};
}
#[macro_export]
macro_rules! raw_dialog_route_transition_route_overrides {
() => {
$crate::modal_transition_route_overrides!();
fn transition_duration(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
) -> ::std::time::Duration {
$crate::RawDialogRouteLeaf::transition_duration(self, app)
}
fn opaque(self: ::waft_foundation::Handle<Self>, app: &::waft_foundation::App) -> bool {
$crate::PopupRoute::opaque(self, app)
}
fn allow_snapshotting(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> bool {
$crate::PopupRoute::allow_snapshotting(self, app)
}
};
}
pub struct RawDialogRoute {
route: crate::widgets::navigator::RouteData,
overlay_route: OverlayRouteData,
transition_route: TransitionRouteData,
local_history: LocalHistoryRouteData,
modal_route: ModalRouteData,
raw_dialog_route: RawDialogRouteData,
}
impl RawDialogRoute {
pub fn new(app: &mut App, page_builder: RoutePageBuilder) -> Ref<RawDialogRoute> {
let route = crate::widgets::navigator::RouteData::new(app, None, None);
let transition_route = TransitionRouteData::new(app);
let modal_route = ModalRouteData::new(app);
app.create(RawDialogRoute {
route,
overlay_route: OverlayRouteData::new(),
transition_route,
local_history: LocalHistoryRouteData::new(),
modal_route,
raw_dialog_route: RawDialogRouteData::new(page_builder),
})
}
pub fn settings(self: Ref<Self>, app: &mut App, settings: RouteSettingsRef) -> Ref<Self> {
self.route_data_mut(app).set_settings(settings);
self
}
pub fn request_focus(self: Ref<Self>, app: &mut App, request_focus: bool) -> Ref<Self> {
self.route_data_mut(app)
.set_request_focus(Some(request_focus));
self
}
pub fn barrier_dismissible(
self: Ref<Self>,
app: &mut App,
barrier_dismissible: bool,
) -> Ref<Self> {
self.raw_dialog_route_data_mut(app).barrier_dismissible = barrier_dismissible;
self
}
pub fn barrier_color(
self: Ref<Self>,
app: &mut App,
barrier_color: Option<Color>,
) -> Ref<Self> {
self.raw_dialog_route_data_mut(app).barrier_color = barrier_color;
self
}
pub fn barrier_label(self: Ref<Self>, app: &mut App, barrier_label: String) -> Ref<Self> {
self.raw_dialog_route_data_mut(app).barrier_label = Some(barrier_label);
self
}
pub fn transition_duration(
self: Ref<Self>,
app: &mut App,
transition_duration: Duration,
) -> Ref<Self> {
self.raw_dialog_route_data_mut(app).transition_duration = transition_duration;
self
}
pub fn transition_builder(
self: Ref<Self>,
app: &mut App,
transition_builder: RouteTransitionsBuilder,
) -> Ref<Self> {
self.raw_dialog_route_data_mut(app).transition_builder = Some(transition_builder);
self
}
pub fn barrier_builder(
self: Ref<Self>,
app: &mut App,
barrier_builder: RouteBarrierBuilder,
) -> Ref<Self> {
self.raw_dialog_route_data_mut(app).barrier_builder = Some(barrier_builder);
self
}
pub fn traversal_edge_behavior(
self: Ref<Self>,
app: &mut App,
behavior: TraversalEdgeBehavior,
) -> Ref<Self> {
self.modal_route_data_mut(app).traversal_edge_behavior = Some(behavior);
self
}
pub fn directional_traversal_edge_behavior(
self: Ref<Self>,
app: &mut App,
behavior: TraversalEdgeBehavior,
) -> Ref<Self> {
self.modal_route_data_mut(app)
.directional_traversal_edge_behavior = Some(behavior);
self
}
pub fn fullscreen_dialog(self: Ref<Self>, app: &mut App, fullscreen_dialog: bool) -> Ref<Self> {
self.raw_dialog_route_data_mut(app).fullscreen_dialog = fullscreen_dialog;
self
}
pub fn build_page<R: RawDialogRouteLeaf>(
this: Handle<R>,
app: &mut App,
context: BuildContext,
animation: AnimationRef<f64>,
secondary_animation: AnimationRef<f64>,
) -> WidgetRef {
let page_builder = Rc::clone(&this.raw_dialog_route_data(app).page_builder);
Semantics::new()
.scopes_route(true)
.explicit_child_nodes(true)
.child(page_builder(app, context, animation, secondary_animation))
.into_widget()
}
pub fn build_transitions<R: RawDialogRouteLeaf>(
this: Handle<R>,
app: &mut App,
context: BuildContext,
animation: AnimationRef<f64>,
secondary_animation: AnimationRef<f64>,
child: WidgetRef,
) -> WidgetRef {
match this.raw_dialog_route_data(app).transition_builder.clone() {
None => crate::widgets::transitions::FadeTransition::new(animation)
.child(child)
.into_widget(),
Some(transition_builder) => {
transition_builder(app, context, animation, secondary_animation, child)
}
}
}
pub fn build_modal_barrier<R: RawDialogRouteLeaf>(
this: Handle<R>,
app: &mut App,
context: BuildContext,
) -> WidgetRef {
let barrier = ModalRouteBase::build_modal_barrier(this, app, context);
let Some(barrier_builder) = this.raw_dialog_route_data(app).barrier_builder.clone() else {
return barrier;
};
Builder::new(move |app, context| {
let animation = TransitionRoute::animation(this, app)
.expect("an installed route keeps its animation")
.keep(app);
let mut details =
RouteBarrierDetails::new(animation, ModalRoute::barrier_dismissible(this, app));
if let Some(color) = ModalRoute::barrier_color(this, app) {
details = details.barrier_color(color);
}
if let Some(label) = ModalRoute::barrier_label(this, app) {
details = details.barrier_label(label);
}
barrier_builder(app, context, &details, barrier.clone())
})
.into_widget()
}
}
impl Route for RawDialogRoute {
crate::modal_route_overrides!();
}
impl OverlayRoute for RawDialogRoute {
crate::modal_overlay_route_overrides!();
}
impl PredictiveBackRoute for RawDialogRoute {
crate::modal_predictive_back_route_overrides!(ModalRoute::pop_gesture_enabled);
}
impl TransitionRoute for RawDialogRoute {
crate::raw_dialog_route_transition_route_overrides!();
}
impl LocalHistoryRoute for RawDialogRoute {
crate::local_history_route_accessors!();
}
impl ModalRoute for RawDialogRoute {
crate::raw_dialog_route_modal_route_overrides!();
}
impl PopupRoute for RawDialogRoute {}
impl RawDialogRouteLeaf for RawDialogRoute {
crate::raw_dialog_route_accessors!();
}
pub struct ShowGeneralDialog {
page_builder: RoutePageBuilder,
barrier_dismissible: bool,
barrier_label: Option<String>,
barrier_color: Color,
transition_duration: Duration,
transition_builder: Option<RouteTransitionsBuilder>,
barrier_builder: Option<RouteBarrierBuilder>,
use_root_navigator: bool,
fullscreen_dialog: bool,
route_settings: Option<RouteSettingsRef>,
request_focus: Option<bool>,
}
impl ShowGeneralDialog {
pub fn new(page_builder: RoutePageBuilder) -> ShowGeneralDialog {
ShowGeneralDialog {
page_builder,
barrier_dismissible: false,
barrier_label: None,
barrier_color: Color::new(0x8000_0000),
transition_duration: Duration::from_millis(200),
transition_builder: None,
barrier_builder: None,
use_root_navigator: true,
fullscreen_dialog: false,
route_settings: None,
request_focus: None,
}
}
pub fn barrier_dismissible(mut self, barrier_dismissible: bool) -> ShowGeneralDialog {
self.barrier_dismissible = barrier_dismissible;
self
}
pub fn barrier_label(mut self, barrier_label: impl Into<String>) -> ShowGeneralDialog {
self.barrier_label = Some(barrier_label.into());
self
}
pub fn barrier_color(mut self, barrier_color: Color) -> ShowGeneralDialog {
self.barrier_color = barrier_color;
self
}
pub fn transition_duration(mut self, transition_duration: Duration) -> ShowGeneralDialog {
self.transition_duration = transition_duration;
self
}
pub fn transition_builder(
mut self,
transition_builder: RouteTransitionsBuilder,
) -> ShowGeneralDialog {
self.transition_builder = Some(transition_builder);
self
}
pub fn barrier_builder(mut self, barrier_builder: RouteBarrierBuilder) -> ShowGeneralDialog {
self.barrier_builder = Some(barrier_builder);
self
}
pub fn use_root_navigator(mut self, use_root_navigator: bool) -> ShowGeneralDialog {
self.use_root_navigator = use_root_navigator;
self
}
pub fn fullscreen_dialog(mut self, fullscreen_dialog: bool) -> ShowGeneralDialog {
self.fullscreen_dialog = fullscreen_dialog;
self
}
pub fn route_settings(mut self, route_settings: RouteSettingsRef) -> ShowGeneralDialog {
self.route_settings = Some(route_settings);
self
}
pub fn request_focus(mut self, request_focus: bool) -> ShowGeneralDialog {
self.request_focus = Some(request_focus);
self
}
pub fn show(self, app: &mut App, context: BuildContext) -> CompleterFuture<RouteResult> {
let ShowGeneralDialog {
page_builder,
barrier_dismissible,
barrier_label,
barrier_color,
transition_duration,
transition_builder,
barrier_builder,
use_root_navigator,
fullscreen_dialog,
route_settings,
request_focus,
} = self;
debug_assert!(!barrier_dismissible || barrier_label.is_some());
let mut route = RawDialogRoute::new(app, page_builder)
.barrier_dismissible(app, barrier_dismissible)
.barrier_color(app, Some(barrier_color))
.transition_duration(app, transition_duration)
.fullscreen_dialog(app, fullscreen_dialog);
if let Some(barrier_label) = barrier_label {
route = route.barrier_label(app, barrier_label);
}
if let Some(transition_builder) = transition_builder {
route = route.transition_builder(app, transition_builder);
}
if let Some(barrier_builder) = barrier_builder {
route = route.barrier_builder(app, barrier_builder);
}
if let Some(route_settings) = route_settings {
route = route.settings(app, route_settings);
}
if let Some(request_focus) = request_focus {
route = route.request_focus(app, request_focus);
}
let navigator = Navigator::of(app, context, use_root_navigator);
navigator.push(app, route.into_erased())
}
}
#[cfg(test)]
mod tests {
use std::cell::{Cell, RefCell};
use waft_embedder::{Offset, TextDirection};
use waft_painting::AlignmentGeometry;
use super::*;
use crate::framework::{IntoWidget, StatelessWidget};
use crate::testing::{WidgetTester, test_widgets};
use crate::widgets::basic::{Align, Directionality, SizedBox};
use crate::widgets::navigator::{NavigatorState, RouteSettings};
use crate::widgets::pages::PageRouteBuilder;
use crate::widgets::pop_scope::PopScope;
fn corner_page(child: Option<WidgetRef>) -> RoutePageBuilder {
Rc::new(move |_app, _context, _animation, _secondary| {
let box_widget = match child.clone() {
Some(child) => SizedBox::new().width(10.0).height(10.0).child(child),
None => SizedBox::new().width(10.0).height(10.0),
};
Align::new()
.alignment(AlignmentGeometry::TOP_LEFT)
.child(box_widget)
.into_widget()
})
}
fn page_route(app: &mut App, child: Option<WidgetRef>, name: &str) -> Ref<PageRouteBuilder> {
PageRouteBuilder::new(app, corner_page(child))
.settings(app, RouteSettings::new().name(name.to_string()).into())
}
fn navigator(
key: &GlobalKey,
on_generate_route: impl Fn(&mut App, &RouteSettings) -> Option<RouteRef> + 'static,
) -> WidgetRef {
Directionality::new(
TextDirection::Ltr,
Navigator::new()
.key(key.clone().into())
.on_generate_route(on_generate_route),
)
.into_widget()
}
fn state(key: &GlobalKey, tester: &WidgetTester) -> Handle<NavigatorState> {
key.current_state::<NavigatorState>(&tester.cell.borrow())
.expect("a mounted navigator")
}
fn mount_navigator(tester: &mut WidgetTester, key: &GlobalKey) -> Handle<NavigatorState> {
tester.pump_widget(navigator(key, |app, _settings| {
Some(page_route(app, None, "/").into_erased())
}));
let navigator_state = state(key, tester);
tester.pump_and_settle();
navigator_state
}
type ProbeRead = Rc<dyn Fn(&mut App, BuildContext)>;
struct Probe {
read: ProbeRead,
}
impl Debug for Probe {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Probe")
}
}
impl StatelessWidget for Probe {
fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
(self.read)(app, context);
SizedBox::new().into_widget()
}
}
fn probe(read: impl Fn(&mut App, BuildContext) + 'static) -> WidgetRef {
Probe {
read: Rc::new(read),
}
.into_widget()
}
#[test]
fn pushing_a_page_route_runs_its_transition_to_completion_and_popping_runs_it_back() {
test_widgets(|tester| {
let key = GlobalKey::new();
let navigator_state = mount_navigator(tester, &key);
let pushed: RouteRef =
tester.update(|app| page_route(app, None, "second").into_erased());
tester.update(|app| navigator_state.push(app, pushed.clone()));
tester.pump();
let animation = {
let app = tester.cell.borrow();
let animation = pushed
.as_transition_route(&app)
.expect("a page route is a transition route")
.animation(&app)
.expect("an installed route");
assert!(animation.value(&app) < 1.0, "the transition starts at 0");
animation
};
tester.pump_and_settle();
{
let app = tester.cell.borrow();
assert_eq!(animation.value(&app), 1.0);
assert!(pushed.is_current(&app));
assert!(!pushed.is_first(&app));
}
let popped = Rc::new(Cell::new(false));
tester.update(|app| {
pushed.popped(app).then(app, {
let popped = Rc::clone(&popped);
move |_app, _result| popped.set(true)
});
navigator_state.pop(app, None);
app.drain_microtasks();
});
assert!(popped.get(), "the popped future resolves at once");
tester.pump_and_settle();
assert_eq!(animation.value(&tester.cell.borrow()), 0.0);
});
}
#[test]
fn modal_route_of_reports_is_current_and_is_first() {
test_widgets(|tester| {
let key = GlobalKey::new();
let seen: Rc<RefCell<Vec<(bool, bool)>>> = Rc::new(RefCell::new(Vec::new()));
let watcher = probe({
let seen = Rc::clone(&seen);
move |app, context| {
let route = AnyModalRoute::of(app, context).expect("a modal route");
let is_current = route.as_route().is_current(app);
let is_first = route.as_route().is_first(app);
seen.borrow_mut().push((is_current, is_first));
}
});
tester.pump_widget(navigator(&key, move |app, _settings| {
Some(page_route(app, Some(watcher.clone()), "/").into_erased())
}));
let navigator_state = state(&key, tester);
tester.pump_and_settle();
assert_eq!(seen.borrow().last().copied(), Some((true, true)));
tester.update(|app| {
let second: RouteRef = page_route(app, None, "second").into_erased();
navigator_state.push(app, second);
});
tester.pump_and_settle();
assert_eq!(
seen.borrow().last().copied(),
Some((false, true)),
"the first route is no longer current once another is pushed"
);
});
}
#[test]
fn a_pop_scope_with_can_pop_false_blocks_maybe_pop() {
test_widgets(|tester| {
let key = GlobalKey::new();
let blocked = Rc::new(Cell::new(false));
let scope = PopScope::new(SizedBox::new())
.can_pop(false)
.on_pop_invoked_with_result({
let blocked = Rc::clone(&blocked);
Rc::new(move |_app, did_pop, _result| blocked.set(!did_pop))
})
.into_widget();
let navigator_state = mount_navigator(tester, &key);
let second: RouteRef =
tester.update(|app| page_route(app, Some(scope), "second").into_erased());
tester.update(|app| navigator_state.push(app, second.clone()));
tester.pump_and_settle();
assert!(second.is_current(&tester.cell.borrow()));
assert!(
tester.update(|app| navigator_state.maybe_pop(app, None)),
"the pop is handled — by being refused — rather than bubbling"
);
tester.pump_and_settle();
assert!(
second.is_current(&tester.cell.borrow()),
"the route is still on top"
);
assert!(blocked.get(), "the pop was reported as not having happened");
});
}
#[test]
fn tapping_the_barrier_dismisses_a_dismissible_popup_route() {
test_widgets(|tester| {
let key = GlobalKey::new();
let navigator_state = mount_navigator(tester, &key);
let dialog: RouteRef = tester.update(|app| {
RawDialogRoute::new(app, corner_page(None))
.barrier_dismissible(app, true)
.barrier_label(app, "dismiss".to_string())
.into_erased()
});
tester.update(|app| navigator_state.push(app, dialog.clone()));
tester.pump_and_settle();
assert!(dialog.is_current(&tester.cell.borrow()));
tester.tap_at(Offset::new(150.0, 100.0), 1);
tester.pump();
tester.pump_and_settle();
assert!(
!dialog.is_active(&tester.cell.borrow()),
"the barrier popped the dialog"
);
});
}
#[test]
fn rebuilding_a_coloured_barrier_leaves_no_new_arena_objects() {
test_widgets(|tester| {
let key = GlobalKey::new();
let navigator_state = mount_navigator(tester, &key);
let dialog = tester.update(|app| {
RawDialogRoute::new(app, corner_page(None))
.barrier_color(app, Some(Color::new(0x80000000)))
});
tester.update(|app| navigator_state.push(app, dialog.clone().into_erased()));
tester.pump_and_settle();
tester.assert_leaves_nothing_behind(|tester| {
tester.update(|app| ModalRoute::changed_internal_state(dialog.handle(), app));
tester.pump_by(Duration::from_millis(20));
});
});
}
#[test]
fn a_popped_route_is_freed_once_its_entry_goes() {
test_widgets(|tester| {
let key = GlobalKey::new();
let navigator_state = mount_navigator(tester, &key);
let dialog = {
let dialog = tester.update(|app| {
RawDialogRoute::new(app, corner_page(None))
.barrier_color(app, Some(Color::new(0x80000000)))
});
let named = dialog.handle();
tester.update(|app| navigator_state.push(app, dialog.clone().into_erased()));
tester.pump_and_settle();
tester.update(|app| navigator_state.pop(app, None));
tester.pump_and_settle();
assert!(
named
.transition_route_data(&tester.cell.borrow())
.transition_completer
.is_completed(),
"the route is disposed"
);
named
};
tester.cell.checkpoint();
assert!(
!tester.cell.borrow().contains(dialog),
"the popped route is freed"
);
});
}
#[test]
fn a_finished_train_hop_leaves_the_secondary_animation_on_the_new_route_and_frees_it() {
test_widgets(|tester| {
let key = GlobalKey::new();
let navigator_state = mount_navigator(tester, &key);
let one = tester.update(|app| page_route(app, None, "one"));
let one_route = one.handle();
tester.update(|app| navigator_state.push(app, one.into_erased()));
tester.pump_and_settle();
let secondary_parent = |tester: &WidgetTester| {
let app = tester.cell.borrow();
one_route
.transition_route_data(&app)
.secondary_animation
.parent(&app)
};
let dismissed = tester.update(|app| k_always_dismissed_animation(app).handle());
assert_eq!(secondary_parent(tester), Some(dismissed));
let two: RouteRef = tester.update(|app| page_route(app, None, "two").into_erased());
tester.update(|app| navigator_state.push(app, two.clone()));
tester.pump();
tester.pump_by(Duration::from_millis(100));
let two_animation = {
let app = tester.cell.borrow();
two.as_transition_route(&app)
.and_then(|route| route.underlying_animation(&app))
};
assert_eq!(secondary_parent(tester), two_animation);
let three: RouteRef = tester.update(|app| page_route(app, None, "three").into_erased());
tester.update(|app| navigator_state.push_replacement(app, three.clone(), None));
tester.pump();
tester.pump_by(Duration::from_millis(1));
let hopper = {
let app = tester.cell.borrow();
let hopper = one_route
.transition_route_data(&app)
.secondary_animation
.parent(&app)
.and_then(|parent| parent.downcast::<TrainHoppingAnimation>(&app))
.expect("the secondary animation hops trains");
assert_eq!(app.get(hopper).current_train(), two_animation);
hopper
};
tester.pump_and_settle();
let three_animation = {
let app = tester.cell.borrow();
three
.as_transition_route(&app)
.and_then(|route| route.underlying_animation(&app))
};
assert_eq!(secondary_parent(tester), three_animation);
tester.cell.checkpoint();
assert!(
!tester.cell.borrow().contains(hopper),
"the finished hop's animation is freed"
);
tester.update(|app| navigator_state.pop(app, None));
tester.pump_and_settle();
assert_eq!(secondary_parent(tester), Some(dismissed));
});
}
#[test]
fn a_non_dismissible_barrier_keeps_the_route() {
test_widgets(|tester| {
let key = GlobalKey::new();
let navigator_state = mount_navigator(tester, &key);
let dialog: RouteRef = tester.update(|app| {
RawDialogRoute::new(app, corner_page(None))
.barrier_dismissible(app, false)
.into_erased()
});
tester.update(|app| navigator_state.push(app, dialog.clone()));
tester.pump_and_settle();
tester.tap_at(Offset::new(150.0, 100.0), 1);
tester.pump();
tester.pump_and_settle();
assert!(
dialog.is_current(&tester.cell.borrow()),
"the tap did nothing"
);
});
}
#[test]
fn local_history_entries_are_popped_before_the_route() {
test_widgets(|tester| {
let key = GlobalKey::new();
let navigator_state = mount_navigator(tester, &key);
let second = tester.update(|app| page_route(app, None, "second"));
tester.update(|app| navigator_state.push(app, second.clone().into_erased()));
tester.pump_and_settle();
let removed = Rc::new(Cell::new(false));
tester.update(|app| {
let entry = LocalHistoryEntry::new(app).on_remove(app, {
let removed = Rc::clone(&removed);
Listener::new(move |_app| removed.set(true))
});
LocalHistoryRoute::add_local_history_entry(second.handle(), app, entry);
assert!(Route::will_handle_pop_internally(second.handle(), app));
navigator_state.pop(app, None);
});
tester.pump();
assert!(removed.get(), "the local history entry was removed");
assert!(
second.as_route().is_current(&tester.cell.borrow()),
"the route itself is still on top"
);
tester.update(|app| navigator_state.pop(app, None));
tester.pump_and_settle();
assert!(
!second.as_route().is_active(&tester.cell.borrow()),
"the route popped next"
);
});
}
struct Watcher {
pushed: Cell<usize>,
pushed_next: Cell<usize>,
popped: Cell<usize>,
popped_next: Cell<usize>,
}
impl RouteAwareObject for Watcher {
fn did_push(self: Handle<Self>, app: &mut App) {
let count = app.get(self).pushed.get();
app.get(self).pushed.set(count + 1);
}
fn did_push_next(self: Handle<Self>, app: &mut App) {
let count = app.get(self).pushed_next.get();
app.get(self).pushed_next.set(count + 1);
}
fn did_pop(self: Handle<Self>, app: &mut App) {
let count = app.get(self).popped.get();
app.get(self).popped.set(count + 1);
}
fn did_pop_next(self: Handle<Self>, app: &mut App) {
let count = app.get(self).popped_next.get();
app.get(self).popped_next.set(count + 1);
}
}
#[test]
fn a_route_observer_notifies_its_route_aware() {
test_widgets(|tester| {
let key = GlobalKey::new();
let observer = tester.update(|app| {
RouteObserver::new(
app,
Rc::new(|app, route: AnyRoute| route.as_page_route(app).is_some()),
)
});
let initial: Rc<Cell<Option<AnyRoute>>> = Rc::new(Cell::new(None));
tester.pump_widget(Directionality::new(
TextDirection::Ltr,
Navigator::new()
.key(key.clone().into())
.on_generate_route({
let initial = Rc::clone(&initial);
move |app, _settings| {
let route: RouteRef = page_route(app, None, "/").into_erased();
initial.set(Some(route.handle()));
Some(route)
}
})
.observers(vec![observer.erase()]),
));
let navigator_state = state(&key, tester);
tester.pump_and_settle();
let first = initial.get().expect("the initial route");
let watcher = tester.update(|app| {
app.create(Watcher {
pushed: Cell::new(0),
pushed_next: Cell::new(0),
popped: Cell::new(0),
popped_next: Cell::new(0),
})
});
tester.update(|app| observer.subscribe(app, Rc::new(watcher.handle()), first));
assert_eq!(tester.cell.borrow().get(&watcher).pushed.get(), 1);
tester.update(|app| {
let second: RouteRef = page_route(app, None, "second").into_erased();
navigator_state.push(app, second);
});
tester.pump_and_settle();
assert_eq!(tester.cell.borrow().get(&watcher).pushed_next.get(), 1);
tester.update(|app| navigator_state.pop(app, None));
tester.pump_and_settle();
let app = tester.cell.borrow();
assert_eq!(app.get(&watcher).popped_next.get(), 1);
assert_eq!(app.get(&watcher).popped.get(), 0);
});
}
}