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, AnimationStatus,
AnimationStatusListener, AnyAnimation, ColorTween, Curve, CurveTween, Curves, ProxyAnimation,
TrainHoppingAnimation, k_always_complete_animation, k_always_dismissed_animation,
};
use waft_foundation::{
App, Completer, CompleterFuture, Handle, HandleId, Listener, MergingListenable, ValueListenable,
};
use waft_painting::Color;
use waft_physics::Simulation;
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};
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};
pub struct OverlayRouteData {
overlay_entries: Vec<Handle<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<Handle<OverlayEntry>>;
fn overlay_entries(self: Handle<Self>, app: &App) -> Vec<Handle<OverlayEntry>> {
self.overlay_route_data(app).overlay_entries.clone()
}
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 self.overlay_route_data(app).overlay_entries.clone() {
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<AnyAnimation<f64>>,
controller: Option<Handle<AnimationController>>,
secondary_animation: Handle<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: &App) -> Duration;
fn reverse_transition_duration(self: Handle<Self>, app: &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
.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
}
fn controller(self: Handle<Self>, app: &App) -> Option<Handle<AnimationController>> {
self.transition_route_data(app).controller
}
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,
) -> Handle<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::create(
app,
None,
Some(duration),
Some(reverse_duration),
0.0,
1.0,
AnimationBehavior::Normal,
navigator,
)
}
fn create_animation(self: Handle<Self>, app: &mut App) -> AnyAnimation<f64> {
debug_assert!(
!TransitionRoute::debug_transition_completed(self, app),
"cannot reuse a route after disposing it"
);
let controller = self
.transition_route_data(app)
.controller
.expect("createAnimationController ran first");
controller.view()
}
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),
);
self.transition_route_data_mut(app).animation = Some(animation);
OverlayRoute::install(self, app);
let entries = Route::overlay_entries(self, app);
if animation.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
.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
.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
.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
.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;
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)
{
TransitionRoute::set_secondary_animation(
self,
app,
Some(next_train),
Some(next.completed(app)),
);
} else {
let slot: Rc<std::cell::Cell<Option<Handle<TrainHoppingAnimation>>>> =
Rc::new(std::cell::Cell::new(None));
let jump_on_animation_end =
AnimationStatusListener::new(move |status: AnimationStatus, app| {
if !status.is_animating() {
TransitionRoute::set_secondary_animation(
self,
app,
Some(next_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);
if let Some(animation) = slot.get() {
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::clone(&slot);
Listener::new(move |app| {
let new_animation = slot.get().expect("the hopping animation");
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));
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 new_animation = TrainHoppingAnimation::create(
app,
current_train,
Some(next_train),
Some(on_switched_train),
);
slot.set(Some(new_animation));
self.set_secondary_animation(
app,
Some(new_animation.as_animation()),
Some(next.completed(app)),
);
}
}
None => {
let animation = next.underlying_animation(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<AnyAnimation<f64>>,
disposed: Option<CompleterFuture<RouteResult>>,
) {
let secondary = self.transition_route_data(app).secondary_animation;
secondary.set_parent(app, animation);
if let Some(disposed) = disposed {
disposed.then(app, move |app, _| {
if secondary.parent(app) == animation {
let dismissed = k_always_dismissed_animation(app);
secondary.set_parent(app, Some(dismissed));
if let Some(animation) = animation
&& 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 {
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 {
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
.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
&& 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;
let animating = match controller {
Some(controller) => controller.is_animating(app),
None => false,
};
if animating {
let controller = controller.expect("an animating controller");
let slot: Rc<std::cell::RefCell<Option<AnimationStatusListener>>> =
Rc::new(std::cell::RefCell::new(None));
let listener = {
let slot = Rc::clone(&slot);
AnimationStatusListener::new(move |_status, app| {
if let Some(navigator) = self.as_route().navigator(app) {
navigator.did_stop_user_gesture(app);
}
let registered = slot.borrow().clone();
if let Some(registered) = registered {
controller.remove_status_listener(app, ®istered);
}
})
};
*slot.borrow_mut() = Some(listener.clone());
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 {
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
{
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()
}
}
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_value: fn(&App, HandleId) -> f64,
opaque: fn(&App, HandleId) -> bool,
allow_snapshotting: fn(&App, HandleId) -> bool,
transition_duration: fn(&App, HandleId) -> Duration,
reverse_transition_duration: fn(&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
},
controller_value: |app, id| {
let controller = R::transition_route_data(resolve::<R>(id), app)
.controller
.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 PartialEq for AnyTransitionRoute {
fn eq(&self, other: &AnyTransitionRoute) -> bool {
self.id == other.id
}
}
impl Eq for AnyTransitionRoute {}
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_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: &App) -> Duration {
(self.vtable.transition_duration)(app, self.id)
}
pub fn reverse_transition_duration(self, app: &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) -> Handle<LocalHistoryEntry> {
app.create(LocalHistoryEntry {
on_remove: None,
owner: None,
implies_app_bar_dismissal: true,
})
}
pub fn on_remove(self: Handle<Self>, app: &mut App, on_remove: Listener) -> Handle<Self> {
app.get_mut(self).on_remove = Some(on_remove);
self
}
pub fn implies_app_bar_dismissal(
self: Handle<Self>,
app: &mut App,
implies_app_bar_dismissal: bool,
) -> Handle<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<Handle<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: Handle<LocalHistoryEntry>,
) {
debug_assert!(app.get(entry).owner.is_none());
app.get_mut(entry).owner = Some(self.as_route());
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 app.get(entry).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.contains(&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.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) -> Handle<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: AnyModalRoute,
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<Handle<FocusScopeNode>>,
primary_scroll_controller: Option<Handle<ScrollController>>,
no_gesture_in_progress: Option<Handle<waft_foundation::ValueNotifier<bool>>>,
}
impl ModalScopeState {
fn focus_scope_node(self: Handle<Self>, app: &App) -> Handle<FocusScopeNode> {
app.get(self).focus_scope_node.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 animations: Vec<Option<Rc<dyn waft_foundation::Listenable>>> = vec![
route
.animation(app)
.map(|animation| Rc::new(animation) as Rc<dyn waft_foundation::Listenable>),
route
.secondary_animation(app)
.map(|animation| Rc::new(animation) as Rc<dyn waft_foundation::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.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 node = self.focus_scope_node(app);
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 = RepaintBoundary::new()
.key(Rc::new(route.subtree_key(app)))
.child(Builder::new(move |app, context| {
let animation = route.animation(app).expect("an installed route");
let secondary = route.secondary_animation(app).expect("an installed route");
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)),
None => Rc::new(app.get(self).no_gesture_in_progress.expect("init_state")),
};
let listenable = app.get(self).listenable.clone().expect("init_state");
let transitions = ListenableBuilder::new(listenable, move |app, context, child| {
let child = child.cloned().expect("the cached page");
let animation = route.animation(app).expect("an installed route");
let secondary = route.secondary_animation(app).expect("an installed route");
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 mut actions = HashMap::new();
actions.insert(
<DismissModalAction as Action>::intent_type(),
Action::as_action(DismissModalAction::new(app, context)),
);
let controller = app.get(self).primary_scroll_controller.expect("init_state");
Actions::new(
actions,
PrimaryScrollController::new(
controller.as_controller(),
FocusScope::with_external_focus_node(
RepaintBoundary::new().child(transitions.clone()),
node,
),
),
)
.into_widget()
});
let status = ModalScopeStatus {
route,
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(route.storage_bucket(app), scope_child))
.into_widget(),
};
let restoration_scope_id = route.as_route().restoration_scope_id(app);
AnimatedBuilder::new(
Rc::new(restoration_scope_id),
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<Handle<ProxyAnimation>>,
secondary_animation_proxy: Option<Handle<ProxyAnimation>>,
pop_entries: Vec<Rc<dyn PopEntry>>,
scope_key: GlobalKey,
subtree_key: GlobalKey,
storage_bucket: Handle<PageStorageBucket>,
modal_barrier: Option<Handle<OverlayEntry>>,
modal_scope: Option<Handle<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: AnyAnimation<f64>,
secondary_animation: AnyAnimation<f64>,
) -> WidgetRef;
fn build_transitions(
self: Handle<Self>,
app: &mut App,
context: BuildContext,
animation: AnyAnimation<f64>,
secondary_animation: AnyAnimation<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: AnyAnimation<f64>,
secondary_animation: AnyAnimation<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 = ProxyAnimation::new(app, None);
let proxied_original_transitions = ModalRoute::build_transitions(
self,
app,
context,
animation,
proxy_animation.as_animation(),
child,
);
let allow_snapshotting = TransitionRoute::allow_snapshotting(self, app);
received(
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;
let secondary = self
.transition_route_data(app)
.secondary_animation
.as_animation();
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
.expect("installed");
let parent = if offstage {
Some(k_always_complete_animation(app))
} else {
self.transition_route_data(app).animation
};
animation_proxy.set_parent(app, parent);
let secondary_proxy = self
.modal_route_data(app)
.secondary_animation_proxy
.expect("installed");
let parent = if offstage {
k_always_dismissed_animation(app)
} else {
self.transition_route_data(app)
.secondary_animation
.as_animation()
};
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
.map(Animation::as_animation)
}
fn secondary_animation(self: Handle<Self>, app: &App) -> Option<AnyAnimation<f64>> {
self.modal_route_data(app)
.secondary_animation_proxy
.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| {
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 = match (&mine, &theirs) {
(None, None) => false,
(Some(mine), Some(theirs)) => !Rc::ptr_eq(mine, theirs),
_ => true,
};
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.expect("installed");
barrier.mark_needs_build(app);
}
let maintain_state = ModalRoute::maintain_state(self, app);
let scope = self.modal_route_data(app).modal_scope.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.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");
IgnorePointer::new()
.ignoring(!animation.is_forward_or_completed(app))
.child(barrier)
.into_widget()
}
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 = ModalScope {
key: Some(Rc::new(key)),
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<Handle<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);
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);
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");
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,
AnyAnimation<f64>,
AnyAnimation<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, AnyAnimation<f64>, AnyAnimation<f64>) -> WidgetRef,
build_flexible_transitions: BuildFlexibleTransitionsSlot,
add_local_history_entry: fn(&mut App, HandleId, Handle<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,
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 PartialEq for AnyModalRoute {
fn eq(&self, other: &AnyModalRoute) -> bool {
self.id == other.id
}
}
impl Eq for AnyModalRoute {}
impl std::hash::Hash for AnyModalRoute {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.id.hash(state);
}
}
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 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)
}
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: AnyAnimation<f64>,
secondary_animation: AnyAnimation<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: AnyAnimation<f64>,
secondary_animation: AnyAnimation<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: Handle<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::Handle<$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<(AnyRoute, Vec<Rc<dyn RouteAware>>)>,
}
impl RouteObserver {
pub fn new(app: &mut App, matches: RoutePredicate) -> Handle<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 listeners = &mut app.get_mut(self).listeners;
let subscribers = match listeners.iter_mut().find(|(held, _)| *held == route) {
Some((_, subscribers)) => subscribers,
None => {
listeners.push((route, 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, AnyAnimation<f64>, AnyAnimation<f64>) -> WidgetRef>;
pub type RouteTransitionsBuilder = Rc<
dyn Fn(&mut App, BuildContext, AnyAnimation<f64>, AnyAnimation<f64>, WidgetRef) -> WidgetRef,
>;
#[derive(Clone, Debug)]
pub struct RouteBarrierDetails {
pub animation: AnyAnimation<f64>,
pub barrier_color: Option<Color>,
pub barrier_label: Option<String>,
pub barrier_dismissible: bool,
}
impl RouteBarrierDetails {
pub fn new(animation: AnyAnimation<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: AnyAnimation<f64>,
secondary_animation: AnyAnimation<f64>,
) -> WidgetRef {
RawDialogRoute::build_page(self, app, context, animation, secondary_animation)
}
fn build_transitions(
self: Handle<Self>,
app: &mut App,
context: BuildContext,
animation: AnyAnimation<f64>,
secondary_animation: AnyAnimation<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::AnyAnimation<f64>,
secondary_animation: ::waft_animation::AnyAnimation<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::AnyAnimation<f64>,
secondary_animation: ::waft_animation::AnyAnimation<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: &::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) -> Handle<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: Handle<Self>, app: &mut App, settings: RouteSettingsRef) -> Handle<Self> {
self.route_data_mut(app).set_settings(settings);
self
}
pub fn request_focus(self: Handle<Self>, app: &mut App, request_focus: bool) -> Handle<Self> {
self.route_data_mut(app)
.set_request_focus(Some(request_focus));
self
}
pub fn barrier_dismissible(
self: Handle<Self>,
app: &mut App,
barrier_dismissible: bool,
) -> Handle<Self> {
self.raw_dialog_route_data_mut(app).barrier_dismissible = barrier_dismissible;
self
}
pub fn barrier_color(
self: Handle<Self>,
app: &mut App,
barrier_color: Option<Color>,
) -> Handle<Self> {
self.raw_dialog_route_data_mut(app).barrier_color = barrier_color;
self
}
pub fn barrier_label(self: Handle<Self>, app: &mut App, barrier_label: String) -> Handle<Self> {
self.raw_dialog_route_data_mut(app).barrier_label = Some(barrier_label);
self
}
pub fn transition_duration(
self: Handle<Self>,
app: &mut App,
transition_duration: Duration,
) -> Handle<Self> {
self.raw_dialog_route_data_mut(app).transition_duration = transition_duration;
self
}
pub fn transition_builder(
self: Handle<Self>,
app: &mut App,
transition_builder: RouteTransitionsBuilder,
) -> Handle<Self> {
self.raw_dialog_route_data_mut(app).transition_builder = Some(transition_builder);
self
}
pub fn barrier_builder(
self: Handle<Self>,
app: &mut App,
barrier_builder: RouteBarrierBuilder,
) -> Handle<Self> {
self.raw_dialog_route_data_mut(app).barrier_builder = Some(barrier_builder);
self
}
pub fn traversal_edge_behavior(
self: Handle<Self>,
app: &mut App,
behavior: TraversalEdgeBehavior,
) -> Handle<Self> {
self.modal_route_data_mut(app).traversal_edge_behavior = Some(behavior);
self
}
pub fn directional_traversal_edge_behavior(
self: Handle<Self>,
app: &mut App,
behavior: TraversalEdgeBehavior,
) -> Handle<Self> {
self.modal_route_data_mut(app)
.directional_traversal_edge_behavior = Some(behavior);
self
}
pub fn fullscreen_dialog(
self: Handle<Self>,
app: &mut App,
fullscreen_dialog: bool,
) -> Handle<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: AnyAnimation<f64>,
secondary_animation: AnyAnimation<f64>,
) -> WidgetRef {
let page_builder = Rc::clone(&this.raw_dialog_route_data(app).page_builder);
page_builder(app, context, animation, secondary_animation)
}
pub fn build_transitions<R: RawDialogRouteLeaf>(
this: Handle<R>,
app: &mut App,
context: BuildContext,
animation: AnyAnimation<f64>,
secondary_animation: AnyAnimation<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");
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!();
}
#[expect(
clippy::too_many_arguments,
reason = "Dart's named arguments; a free function has no receiver for the fluent setters"
)]
pub fn show_general_dialog(
app: &mut App,
context: BuildContext,
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>,
) -> CompleterFuture<RouteResult> {
debug_assert!(!barrier_dismissible || barrier_label.is_some());
let 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.barrier_label(app, barrier_label);
}
if let Some(transition_builder) = transition_builder {
route.transition_builder(app, transition_builder);
}
if let Some(barrier_builder) = barrier_builder {
route.barrier_builder(app, barrier_builder);
}
if let Some(route_settings) = route_settings {
route.settings(app, route_settings);
}
if let Some(request_focus) = request_focus {
route.request_focus(app, request_focus);
}
let navigator = Navigator::of(app, context, use_root_navigator);
navigator.push(app, route.as_route())
}
#[cfg(test)]
mod tests {
use std::cell::{Cell, RefCell};
use waft_foundation::AppCell;
use waft_embedder::{Offset, PointerDeviceKind, TargetPlatform, TextDirection};
use waft_gestures::{GestureBinding, PointerDownEvent, PointerEvent, PointerUpEvent};
use waft_painting::AlignmentGeometry;
use waft_test::{TestPlatform, TestView};
use super::*;
use crate::binding::run_app;
use crate::framework::{IntoWidget, StatelessWidget};
use crate::test_harness::pump_every_view;
use crate::widgets::basic::{Align, Directionality, SizedBox};
use crate::widgets::navigator::{NavigatorState, RouteSettings};
use crate::widgets::pages::PageRouteBuilder;
use crate::widgets::pop_scope::PopScope;
const VIEW_WIDTH: f64 = 300.0;
const VIEW_HEIGHT: f64 = 200.0;
fn app_with_view() -> Rc<AppCell> {
let platform = TestPlatform::new()
.on(TargetPlatform::MacOS)
.with_view(Rc::new(TestView::new(VIEW_WIDTH, VIEW_HEIGHT)));
AppCell::with_platform(Rc::new(platform))
}
fn mount(cell: &AppCell, child: WidgetRef) {
run_app(&mut cell.borrow_mut(), child);
cell.elapse(Duration::ZERO);
pump_every_view(&mut cell.borrow_mut(), Duration::ZERO);
}
fn settle(app: &mut App, from: Duration) -> Duration {
let mut at = from;
for _ in 0..40 {
at += Duration::from_millis(20);
pump_every_view(app, at);
}
at
}
fn tap_at(app: &mut App, position: Offset) {
GestureBinding::instance(app).handle_pointer_event(
app,
PointerEvent::Down(PointerDownEvent {
pointer: 1,
position,
kind: PointerDeviceKind::Touch,
..PointerDownEvent::default()
}),
);
app.drain_microtasks();
GestureBinding::instance(app).handle_pointer_event(
app,
PointerEvent::Up(PointerUpEvent {
pointer: 1,
position,
kind: PointerDeviceKind::Touch,
..PointerUpEvent::default()
}),
);
app.drain_microtasks();
}
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) -> Handle<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<AnyRoute> + 'static,
) -> WidgetRef {
Directionality::new(
TextDirection::Ltr,
Navigator::new()
.key(Rc::new(key.clone()))
.on_generate_route(on_generate_route),
)
.into_widget()
}
fn state(key: &GlobalKey, app: &mut App) -> Handle<NavigatorState> {
key.current_state::<NavigatorState>(app)
.expect("a mounted navigator")
}
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() {
let cell = app_with_view();
let key = GlobalKey::new();
mount(
&cell,
navigator(&key, |app, _settings| {
Some(page_route(app, None, "/").as_route())
}),
);
let mut app = cell.borrow_mut();
let navigator_state = state(&key, &mut app);
let at = settle(&mut app, Duration::ZERO);
let pushed = page_route(&mut app, None, "second").as_route();
navigator_state.push(&mut app, pushed);
pump_every_view(&mut app, at);
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");
let at = settle(&mut app, at);
assert_eq!(animation.value(&app), 1.0);
assert!(pushed.is_current(&app));
assert!(!pushed.is_first(&app));
let popped = Rc::new(Cell::new(false));
pushed.popped(&app).then(&mut app, {
let popped = Rc::clone(&popped);
move |_app, _result| popped.set(true)
});
navigator_state.pop(&mut app, None);
app.drain_microtasks();
assert!(popped.get(), "the popped future resolves at once");
settle(&mut app, at);
assert_eq!(animation.value(&app), 0.0);
}
#[test]
fn modal_route_of_reports_is_current_and_is_first() {
let cell = app_with_view();
let app = cell.borrow();
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));
}
});
drop(app);
mount(
&cell,
navigator(&key, move |app, _settings| {
Some(page_route(app, Some(watcher.clone()), "/").as_route())
}),
);
let mut app = cell.borrow_mut();
let navigator_state = state(&key, &mut app);
let at = settle(&mut app, Duration::ZERO);
assert_eq!(seen.borrow().last().copied(), Some((true, true)));
let second = page_route(&mut app, None, "second").as_route();
navigator_state.push(&mut app, second);
settle(&mut app, at);
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() {
let cell = app_with_view();
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();
mount(
&cell,
navigator(&key, |app, _settings| {
Some(page_route(app, None, "/").as_route())
}),
);
let mut app = cell.borrow_mut();
let navigator_state = state(&key, &mut app);
let at = settle(&mut app, Duration::ZERO);
let second = page_route(&mut app, Some(scope), "second").as_route();
navigator_state.push(&mut app, second);
let at = settle(&mut app, at);
assert!(second.is_current(&app));
assert!(
navigator_state.maybe_pop(&mut app, None),
"the pop is handled — by being refused — rather than bubbling"
);
settle(&mut app, at);
assert!(second.is_current(&app), "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() {
let cell = app_with_view();
let key = GlobalKey::new();
mount(
&cell,
navigator(&key, |app, _settings| {
Some(page_route(app, None, "/").as_route())
}),
);
let mut app = cell.borrow_mut();
let navigator_state = state(&key, &mut app);
let at = settle(&mut app, Duration::ZERO);
let dialog = RawDialogRoute::new(&mut app, corner_page(None))
.barrier_dismissible(&mut app, true)
.barrier_label(&mut app, "dismiss".to_string())
.as_route();
navigator_state.push(&mut app, dialog);
let at = settle(&mut app, at);
assert!(dialog.is_current(&app));
tap_at(&mut app, Offset::new(150.0, 100.0));
pump_every_view(&mut app, at);
settle(&mut app, at);
assert!(!dialog.is_active(&app), "the barrier popped the dialog");
}
#[test]
fn a_non_dismissible_barrier_keeps_the_route() {
let cell = app_with_view();
let key = GlobalKey::new();
mount(
&cell,
navigator(&key, |app, _settings| {
Some(page_route(app, None, "/").as_route())
}),
);
let mut app = cell.borrow_mut();
let navigator_state = state(&key, &mut app);
let at = settle(&mut app, Duration::ZERO);
let dialog = RawDialogRoute::new(&mut app, corner_page(None))
.barrier_dismissible(&mut app, false)
.as_route();
navigator_state.push(&mut app, dialog);
let at = settle(&mut app, at);
tap_at(&mut app, Offset::new(150.0, 100.0));
pump_every_view(&mut app, at);
settle(&mut app, at);
assert!(dialog.is_current(&app), "the tap did nothing");
}
#[test]
fn local_history_entries_are_popped_before_the_route() {
let cell = app_with_view();
let key = GlobalKey::new();
mount(
&cell,
navigator(&key, |app, _settings| {
Some(page_route(app, None, "/").as_route())
}),
);
let mut app = cell.borrow_mut();
let navigator_state = state(&key, &mut app);
let at = settle(&mut app, Duration::ZERO);
let second = page_route(&mut app, None, "second");
navigator_state.push(&mut app, second.as_route());
let at = settle(&mut app, at);
let removed = Rc::new(Cell::new(false));
let entry = LocalHistoryEntry::new(&mut app).on_remove(&mut app, {
let removed = Rc::clone(&removed);
Listener::new(move |_app| removed.set(true))
});
LocalHistoryRoute::add_local_history_entry(second, &mut app, entry);
assert!(Route::will_handle_pop_internally(second, &app));
navigator_state.pop(&mut app, None);
pump_every_view(&mut app, at);
assert!(removed.get(), "the local history entry was removed");
assert!(
second.as_route().is_current(&app),
"the route itself is still on top"
);
navigator_state.pop(&mut app, None);
settle(&mut app, at);
assert!(!second.as_route().is_active(&app), "the route popped next");
}
#[test]
fn a_route_observer_notifies_its_route_aware() {
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);
}
}
let cell = app_with_view();
let mut app = cell.borrow_mut();
let key = GlobalKey::new();
let observer = RouteObserver::new(
&mut app,
Rc::new(|app, route: AnyRoute| route.as_page_route(app).is_some()),
);
let initial: Rc<Cell<Option<AnyRoute>>> = Rc::new(Cell::new(None));
drop(app);
mount(
&cell,
Directionality::new(
TextDirection::Ltr,
Navigator::new()
.key(Rc::new(key.clone()))
.on_generate_route({
let initial = Rc::clone(&initial);
move |app, _settings| {
let route = page_route(app, None, "/").as_route();
initial.set(Some(route));
Some(route)
}
})
.observers(vec![observer.as_observer()]),
)
.into_widget(),
);
let mut app = cell.borrow_mut();
let navigator_state = state(&key, &mut app);
let at = settle(&mut app, Duration::ZERO);
let first = initial.get().expect("the initial route");
let watcher = app.create(Watcher {
pushed: Cell::new(0),
pushed_next: Cell::new(0),
popped: Cell::new(0),
popped_next: Cell::new(0),
});
observer.subscribe(&mut app, Rc::new(watcher), first);
assert_eq!(app.get(watcher).pushed.get(), 1);
let second = page_route(&mut app, None, "second").as_route();
navigator_state.push(&mut app, second);
let at = settle(&mut app, at);
assert_eq!(app.get(watcher).pushed_next.get(), 1);
navigator_state.pop(&mut app, None);
settle(&mut app, at);
assert_eq!(app.get(watcher).popped_next.get(), 1);
assert_eq!(app.get(watcher).popped.get(), 0);
}
}