1use std::any::TypeId;
8use std::collections::HashMap;
9use std::fmt::{self, Debug};
10use std::ptr;
11use std::rc::Rc;
12
13use waft_embedder::{AppLifecycleState, Clip, Color, Locale, TargetPlatform, ViewId, ViewRef};
14use waft_foundation::{App, DebugFlag, Handle, K_IS_WEB, Listenable, OptionRetained, Ref};
15use waft_painting::{AxisDirection, TextStyle};
16use waft_scheduler::SchedulerBinding;
17use waft_services::{KeyEvent, LogicalKeyboardKey};
18
19use crate::binding::{WidgetsBinding, WidgetsBindingObserverObject, WidgetsBindingObserverRef};
20use crate::framework::{
21 BuildContext, GlobalKey, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
22};
23use crate::view::View;
24use crate::widgets::actions::{
25 ActionRef, Actions, ActivateIntent, AnyAction, ButtonActivateIntent, DismissIntent,
26 DoNothingAction, DoNothingAndStopPropagationIntent, DoNothingIntent, PrioritizedAction,
27 PrioritizedIntents, VoidCallbackAction, VoidCallbackIntent,
28};
29use crate::widgets::banner::CheckedModeBanner;
30use crate::widgets::basic::{Builder, WidgetBuilder};
31use crate::widgets::default_text_editing_shortcuts::{DefaultTextEditingShortcuts, shortcut_map};
32use crate::widgets::focus_manager::{KeyEventResult, TraversalEdgeBehavior};
33use crate::widgets::focus_scope::{Focus, FocusScope};
34use crate::widgets::focus_traversal::{
35 DirectionalFocusAction, DirectionalFocusIntent, FocusTraversalGroup, NextFocusAction,
36 NextFocusIntent, PreviousFocusAction, PreviousFocusIntent, ReadingOrderTraversalPolicy,
37 RequestFocusAction, RequestFocusIntent, TraversalDirection,
38};
39use crate::widgets::localizations::{
40 Localizations, LocalizationsDelegateRef, LocalizationsResolver,
41};
42use crate::widgets::navigator::{
43 NavigationNotification, Navigator, NavigatorObserverRef, NavigatorState, RouteFactory,
44 RouteRef, RouteSettings,
45};
46use crate::widgets::notification_listener::{NotificationListener, NotificationListenerCallback};
47use crate::widgets::pages::PageRouteRef;
48use crate::widgets::raw_tooltip::RawTooltip;
49use crate::widgets::restoration::RootRestorationScope;
50use crate::widgets::scrollable_helpers::{ScrollAction, ScrollIncrementType, ScrollIntent};
51use crate::widgets::shared_app_data::SharedAppData;
52use crate::widgets::shortcuts::{ShortcutMap, ShortcutRegistrar, Shortcuts};
53use crate::widgets::tap_region::TapRegionSurface;
54use crate::widgets::text::DefaultTextStyle;
55use crate::widgets::title::Title;
56use crate::widgets::transitions::{ListenableBuilder, TransitionBuilder};
57
58pub type LocaleListResolutionCallback = Rc<dyn Fn(Option<&[Locale]>, &[Locale]) -> Option<Locale>>;
76
77pub type LocaleResolutionCallback = Rc<dyn Fn(Option<&Locale>, &[Locale]) -> Option<Locale>>;
102
103pub fn basic_locale_list_resolution(
146 preferred_locales: Option<&[Locale]>,
147 supported_locales: &[Locale],
148) -> Locale {
149 let first_supported = supported_locales
150 .first()
151 .expect("supportedLocales must not be empty")
152 .clone();
153 let Some(preferred_locales) = preferred_locales.filter(|locales| !locales.is_empty()) else {
154 return first_supported;
155 };
156 let mut all_supported_locales: HashMap<String, &Locale> = HashMap::new();
159 let mut language_and_country_locales: HashMap<String, &Locale> = HashMap::new();
160 let mut language_and_script_locales: HashMap<String, &Locale> = HashMap::new();
161 let mut language_locales: HashMap<&str, &Locale> = HashMap::new();
162 let mut country_locales: HashMap<Option<&str>, &Locale> = HashMap::new();
163 for locale in supported_locales {
164 all_supported_locales
165 .entry(full_key(locale))
166 .or_insert(locale);
167 language_and_script_locales
168 .entry(language_and_script_key(locale))
169 .or_insert(locale);
170 language_and_country_locales
171 .entry(language_and_country_key(locale))
172 .or_insert(locale);
173 language_locales
174 .entry(&locale.language_code)
175 .or_insert(locale);
176 country_locales
177 .entry(locale.country_code.as_deref())
178 .or_insert(locale);
179 }
180
181 let mut matches_language_code: Option<&Locale> = None;
187 let mut matches_country_code: Option<&Locale> = None;
188 for (locale_index, user_locale) in preferred_locales.iter().enumerate() {
190 if all_supported_locales.contains_key(&full_key(user_locale)) {
192 return user_locale.clone();
193 }
194 if user_locale.script_code.is_some()
196 && let Some(matched) =
197 language_and_script_locales.get(&language_and_script_key(user_locale))
198 {
199 return (*matched).clone();
200 }
201 if user_locale.country_code.is_some()
203 && let Some(matched) =
204 language_and_country_locales.get(&language_and_country_key(user_locale))
205 {
206 return (*matched).clone();
207 }
208 if let Some(matched) = matches_language_code {
212 return matched.clone();
213 }
214 if let Some(&matched) = language_locales.get(user_locale.language_code.as_str()) {
216 matches_language_code = Some(matched);
217 let next_prefers_the_same_language = preferred_locales
222 .get(locale_index + 1)
223 .is_some_and(|next| next.language_code == user_locale.language_code);
224 if locale_index == 0 && !next_prefers_the_same_language {
225 return matched.clone();
226 }
227 }
228 if matches_country_code.is_none()
232 && user_locale.country_code.is_some()
233 && let Some(&matched) = country_locales.get(&user_locale.country_code.as_deref())
234 {
235 matches_country_code = Some(matched);
236 }
237 }
238 matches_language_code
242 .or(matches_country_code)
243 .cloned()
244 .unwrap_or(first_supported)
245}
246
247fn full_key(locale: &Locale) -> String {
248 format!(
249 "{}_{:?}_{:?}",
250 locale.language_code, locale.script_code, locale.country_code
251 )
252}
253
254fn language_and_script_key(locale: &Locale) -> String {
255 format!("{}_{:?}", locale.language_code, locale.script_code)
256}
257
258fn language_and_country_key(locale: &Locale) -> String {
259 format!("{}_{:?}", locale.language_code, locale.country_code)
260}
261
262pub type GenerateAppTitle = Rc<dyn Fn(&mut App, BuildContext) -> String>;
269
270pub type PageRouteFactory = Rc<dyn Fn(&mut App, &RouteSettings, WidgetBuilder) -> PageRouteRef>;
274
275pub type InitialRouteListFactory = Rc<dyn Fn(&mut App, &str) -> Vec<RouteRef>>;
279
280pub struct ShowPerformanceOverlayOverride;
282
283impl DebugFlag for ShowPerformanceOverlayOverride {}
284
285pub struct DebugAllowBannerOverride;
287
288impl DebugFlag for DebugAllowBannerOverride {
289 const DEFAULT: bool = true;
290}
291
292pub struct WidgetsApp {
319 pub key: Option<KeyRef>,
321
322 pub navigator_key: Option<GlobalKey>,
337
338 pub on_generate_route: Option<RouteFactory>,
363
364 pub on_generate_initial_routes: Option<InitialRouteListFactory>,
371
372 pub page_route_builder: Option<PageRouteFactory>,
384
385 pub home: Option<WidgetRef>,
416
417 pub routes: HashMap<String, WidgetBuilder>,
447
448 pub on_unknown_route: Option<RouteFactory>,
464
465 pub on_navigation_notification: Option<NotificationListenerCallback<NavigationNotification>>,
474
475 pub initial_route: Option<String>,
506
507 pub navigator_observers: Vec<NavigatorObserverRef>,
519
520 pub builder: Option<TransitionBuilder>,
561
562 pub title: Option<String>,
574
575 pub on_generate_title: Option<GenerateAppTitle>,
585
586 pub text_style: Option<TextStyle>,
588
589 pub color: Color,
595
596 pub locale: Option<Locale>,
612
613 pub localizations_delegates: Option<Vec<LocalizationsDelegateRef>>,
618
619 pub locale_list_resolution_callback: Option<LocaleListResolutionCallback>,
641
642 pub locale_resolution_callback: Option<LocaleResolutionCallback>,
650
651 pub supported_locales: Vec<Locale>,
674
675 pub show_performance_overlay: bool,
681
682 pub show_semantics_debugger: bool,
685
686 pub debug_show_widget_inspector: bool,
692
693 pub debug_show_checked_mode_banner: bool,
706
707 pub shortcuts: Option<ShortcutMap>,
722
723 pub actions: Option<HashMap<TypeId, ActionRef>>,
739
740 pub restoration_scope_id: Option<String>,
755
756 pub use_inherited_media_query: bool,
761}
762
763const PAGE_ROUTE_BUILDER_REQUIRED: &str = "If neither builder nor onGenerateRoute are provided, \
766 the pageRouteBuilder must be specified so that the default handler will know what kind of \
767 PageRoute transition to build.";
768
769impl WidgetsApp {
770 pub fn new(color: Color) -> WidgetsApp {
813 WidgetsApp {
814 key: None,
815 navigator_key: None,
816 on_generate_route: None,
817 on_generate_initial_routes: None,
818 page_route_builder: None,
819 home: None,
820 routes: HashMap::new(),
821 on_unknown_route: None,
822 on_navigation_notification: None,
823 initial_route: None,
824 navigator_observers: Vec::new(),
825 builder: None,
826 title: None,
827 on_generate_title: None,
828 text_style: None,
829 color,
830 locale: None,
831 localizations_delegates: None,
832 locale_list_resolution_callback: None,
833 locale_resolution_callback: None,
834 supported_locales: vec![Locale::new("en").country_code("US")],
835 show_performance_overlay: false,
836 show_semantics_debugger: false,
837 debug_show_widget_inspector: false,
838 debug_show_checked_mode_banner: true,
839 shortcuts: None,
840 actions: None,
841 restoration_scope_id: None,
842 use_inherited_media_query: false,
843 }
844 }
845
846 pub fn key(mut self, key: KeyRef) -> WidgetsApp {
848 self.key = Some(key);
849 self
850 }
851
852 pub fn navigator_key(mut self, navigator_key: GlobalKey) -> WidgetsApp {
854 self.navigator_key = Some(navigator_key);
855 self
856 }
857
858 pub fn on_generate_route(
860 mut self,
861 on_generate_route: impl Fn(&mut App, &RouteSettings) -> Option<RouteRef> + 'static,
862 ) -> WidgetsApp {
863 self.on_generate_route = Some(Rc::new(on_generate_route));
864 self
865 }
866
867 pub fn on_generate_initial_routes(
869 mut self,
870 on_generate_initial_routes: impl Fn(&mut App, &str) -> Vec<RouteRef> + 'static,
871 ) -> WidgetsApp {
872 self.on_generate_initial_routes = Some(Rc::new(on_generate_initial_routes));
873 self
874 }
875
876 pub fn page_route_builder(
880 mut self,
881 page_route_builder: impl Fn(&mut App, &RouteSettings, WidgetBuilder) -> PageRouteRef + 'static,
882 ) -> WidgetsApp {
883 self.page_route_builder = Some(Rc::new(page_route_builder));
884 self
885 }
886
887 #[cfg_attr(debug_assertions, track_caller)]
889 pub fn home<K>(mut self, home: impl IntoWidget<K>) -> WidgetsApp {
890 self.home = Some(home.into_widget());
891 self
892 }
893
894 pub fn routes(
896 mut self,
897 routes: impl IntoIterator<Item = (String, WidgetBuilder)>,
898 ) -> WidgetsApp {
899 self.routes = routes.into_iter().collect();
900 self
901 }
902
903 pub fn on_unknown_route(
905 mut self,
906 on_unknown_route: impl Fn(&mut App, &RouteSettings) -> Option<RouteRef> + 'static,
907 ) -> WidgetsApp {
908 self.on_unknown_route = Some(Rc::new(on_unknown_route));
909 self
910 }
911
912 pub fn on_navigation_notification(
914 mut self,
915 on_navigation_notification: impl Fn(&mut App, &NavigationNotification) -> bool + 'static,
916 ) -> WidgetsApp {
917 self.on_navigation_notification = Some(Rc::new(on_navigation_notification));
918 self
919 }
920
921 pub fn initial_route(mut self, initial_route: impl Into<String>) -> WidgetsApp {
923 self.initial_route = Some(initial_route.into());
924 self
925 }
926
927 pub fn navigator_observers(
929 mut self,
930 navigator_observers: impl IntoIterator<Item = NavigatorObserverRef>,
931 ) -> WidgetsApp {
932 self.navigator_observers = navigator_observers.into_iter().collect();
933 self
934 }
935
936 pub fn builder(
938 mut self,
939 builder: impl Fn(&mut App, BuildContext, Option<&WidgetRef>) -> WidgetRef + 'static,
940 ) -> WidgetsApp {
941 self.builder = Some(Rc::new(builder));
942 self
943 }
944
945 pub fn title(mut self, title: impl Into<String>) -> WidgetsApp {
947 self.title = Some(title.into());
948 self
949 }
950
951 pub fn on_generate_title(
953 mut self,
954 on_generate_title: impl Fn(&mut App, BuildContext) -> String + 'static,
955 ) -> WidgetsApp {
956 self.on_generate_title = Some(Rc::new(on_generate_title));
957 self
958 }
959
960 pub fn text_style(mut self, text_style: TextStyle) -> WidgetsApp {
962 self.text_style = Some(text_style);
963 self
964 }
965
966 pub fn locale(mut self, locale: Locale) -> WidgetsApp {
968 self.locale = Some(locale);
969 self
970 }
971
972 pub fn localizations_delegates(
974 mut self,
975 localizations_delegates: impl IntoIterator<Item = LocalizationsDelegateRef>,
976 ) -> WidgetsApp {
977 self.localizations_delegates = Some(localizations_delegates.into_iter().collect());
978 self
979 }
980
981 pub fn locale_list_resolution_callback(
983 mut self,
984 locale_list_resolution_callback: impl Fn(Option<&[Locale]>, &[Locale]) -> Option<Locale>
985 + 'static,
986 ) -> WidgetsApp {
987 self.locale_list_resolution_callback = Some(Rc::new(locale_list_resolution_callback));
988 self
989 }
990
991 pub fn locale_resolution_callback(
993 mut self,
994 locale_resolution_callback: impl Fn(Option<&Locale>, &[Locale]) -> Option<Locale> + 'static,
995 ) -> WidgetsApp {
996 self.locale_resolution_callback = Some(Rc::new(locale_resolution_callback));
997 self
998 }
999
1000 pub fn supported_locales(
1002 mut self,
1003 supported_locales: impl IntoIterator<Item = Locale>,
1004 ) -> WidgetsApp {
1005 self.supported_locales = supported_locales.into_iter().collect();
1006 debug_assert!(!self.supported_locales.is_empty());
1007 self
1008 }
1009
1010 pub fn show_performance_overlay(mut self, show_performance_overlay: bool) -> WidgetsApp {
1012 self.show_performance_overlay = show_performance_overlay;
1013 self
1014 }
1015
1016 pub fn show_semantics_debugger(mut self, show_semantics_debugger: bool) -> WidgetsApp {
1018 self.show_semantics_debugger = show_semantics_debugger;
1019 self
1020 }
1021
1022 pub fn debug_show_widget_inspector(mut self, debug_show_widget_inspector: bool) -> WidgetsApp {
1024 self.debug_show_widget_inspector = debug_show_widget_inspector;
1025 self
1026 }
1027
1028 pub fn debug_show_checked_mode_banner(
1030 mut self,
1031 debug_show_checked_mode_banner: bool,
1032 ) -> WidgetsApp {
1033 self.debug_show_checked_mode_banner = debug_show_checked_mode_banner;
1034 self
1035 }
1036
1037 pub fn shortcuts(mut self, shortcuts: ShortcutMap) -> WidgetsApp {
1039 self.shortcuts = Some(shortcuts);
1040 self
1041 }
1042
1043 pub fn actions(mut self, actions: HashMap<TypeId, ActionRef>) -> WidgetsApp {
1045 self.actions = Some(actions);
1046 self
1047 }
1048
1049 pub fn restoration_scope_id(mut self, restoration_scope_id: impl Into<String>) -> WidgetsApp {
1051 self.restoration_scope_id = Some(restoration_scope_id.into());
1052 self
1053 }
1054
1055 pub fn use_inherited_media_query(mut self, use_inherited_media_query: bool) -> WidgetsApp {
1057 self.use_inherited_media_query = use_inherited_media_query;
1058 self
1059 }
1060
1061 pub fn show_performance_overlay_override(app: &App) -> bool {
1065 app.debug_flag::<ShowPerformanceOverlayOverride>()
1066 }
1067
1068 pub fn set_show_performance_overlay_override(app: &mut App, value: bool) {
1070 app.set_debug_flag::<ShowPerformanceOverlayOverride>(value);
1071 }
1072
1073 pub fn debug_allow_banner_override(app: &App) -> bool {
1080 app.debug_flag::<DebugAllowBannerOverride>()
1081 }
1082
1083 pub fn set_debug_allow_banner_override(app: &mut App, value: bool) {
1085 app.set_debug_flag::<DebugAllowBannerOverride>(value);
1086 }
1087
1088 pub fn default_shortcuts(app: &App) -> ShortcutMap {
1093 if K_IS_WEB {
1094 return default_web_shortcuts();
1095 }
1096 match app.platform().target_platform() {
1097 TargetPlatform::Android
1098 | TargetPlatform::Fuchsia
1099 | TargetPlatform::Linux
1100 | TargetPlatform::Windows => default_shortcuts_table(),
1101 TargetPlatform::IOS | TargetPlatform::MacOS => default_apple_os_shortcuts(),
1102 }
1103 }
1104
1105 pub fn default_actions(app: &mut App) -> HashMap<TypeId, ActionRef> {
1107 let do_nothing = DoNothingAction::new(app);
1108 let do_nothing_and_stop_propagation = DoNothingAction::new(app);
1109 do_nothing_and_stop_propagation.set_consumes_key(app, false);
1110 let request_focus = RequestFocusAction::new(app);
1111 let next_focus = NextFocusAction::new(app);
1112 let previous_focus = PreviousFocusAction::new(app);
1113 let directional_focus = DirectionalFocusAction::new(app);
1114 let scroll = ScrollAction::new(app);
1115 let prioritized = PrioritizedAction::new(app);
1116 let void_callback = VoidCallbackAction::new(app);
1117 HashMap::from([
1118 (TypeId::of::<DoNothingIntent>(), do_nothing.into_erased()),
1119 (
1120 TypeId::of::<DoNothingAndStopPropagationIntent>(),
1121 do_nothing_and_stop_propagation.into_erased(),
1122 ),
1123 (
1124 TypeId::of::<RequestFocusIntent>(),
1125 request_focus.into_erased(),
1126 ),
1127 (TypeId::of::<NextFocusIntent>(), next_focus.into_erased()),
1128 (
1129 TypeId::of::<PreviousFocusIntent>(),
1130 previous_focus.into_erased(),
1131 ),
1132 (
1133 TypeId::of::<DirectionalFocusIntent>(),
1134 directional_focus.into_erased(),
1135 ),
1136 (TypeId::of::<ScrollIntent>(), scroll.into_erased()),
1137 (
1138 TypeId::of::<PrioritizedIntents>(),
1139 prioritized.into_erased(),
1140 ),
1141 (
1142 TypeId::of::<VoidCallbackIntent>(),
1143 void_callback.into_erased(),
1144 ),
1145 ])
1146 }
1147}
1148
1149impl Debug for WidgetsApp {
1150 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1151 f.debug_struct("WidgetsApp")
1152 .field("title", &self.title)
1153 .field("color", &self.color)
1154 .field("locale", &self.locale)
1155 .field("restorationScopeId", &self.restoration_scope_id)
1156 .finish_non_exhaustive()
1157 }
1158}
1159
1160impl StatefulWidget for WidgetsApp {
1161 type State = WidgetsAppState;
1162
1163 fn key(&self) -> Option<&KeyRef> {
1164 self.key.as_ref()
1165 }
1166
1167 fn debug_check_constructor(&self) {
1168 debug_assert!(
1169 self.home.is_none() || self.on_generate_initial_routes.is_none(),
1170 "If onGenerateInitialRoutes is specified, the home argument will be redundant."
1171 );
1172 debug_assert!(
1173 self.home.is_none() || !self.routes.contains_key(Navigator::DEFAULT_ROUTE_NAME),
1174 "If the home property is specified, the routes table cannot include an entry for \
1175 \"/\", since it would be redundant."
1176 );
1177 debug_assert!(
1178 self.builder.is_some()
1179 || self.home.is_some()
1180 || self.routes.contains_key(Navigator::DEFAULT_ROUTE_NAME)
1181 || self.on_generate_route.is_some()
1182 || self.on_unknown_route.is_some(),
1183 "Either the home property must be specified, or the routes table must include an \
1184 entry for \"/\", or there must be on onGenerateRoute callback specified, or there \
1185 must be an onUnknownRoute callback specified, or the builder property must be \
1186 specified, because otherwise there is nothing to fall back on if the app is \
1187 started with an intent that specifies an unknown route."
1188 );
1189 debug_assert!(
1190 (self.home.is_some()
1191 || !self.routes.is_empty()
1192 || self.on_generate_route.is_some()
1193 || self.on_unknown_route.is_some())
1194 || (self.builder.is_some()
1195 && self.navigator_key.is_none()
1196 && self.initial_route.is_none()
1197 && self.navigator_observers.is_empty()),
1198 "If no route is provided using home, routes, onGenerateRoute, or onUnknownRoute, a \
1199 non-null callback for the builder property must be provided, and the other \
1200 navigator-related properties, navigatorKey, initialRoute, and navigatorObservers, \
1201 must have their initial values (null, null, and the empty list, respectively)."
1202 );
1203 debug_assert!(
1204 self.builder.is_some()
1205 || self.on_generate_route.is_some()
1206 || self.page_route_builder.is_some(),
1207 "{PAGE_ROUTE_BUILDER_REQUIRED}"
1208 );
1209 }
1210
1211 fn create_state(&self) -> WidgetsAppState {
1212 WidgetsAppState {
1213 state: StateData::new(),
1214 navigator: None,
1215 localizations_resolver: None,
1216 observer: None,
1217 app_lifecycle_state: None,
1218 }
1219 }
1220}
1221
1222fn default_shortcuts_table() -> ShortcutMap {
1224 shortcut_map![
1225 ENTER => ActivateIntent::new(),
1227 NUMPAD_ENTER => ActivateIntent::new(),
1228 SPACE => ActivateIntent::new(),
1229 GAME_BUTTON_A => ActivateIntent::new(),
1230 SELECT => ActivateIntent::new(),
1231
1232 ESCAPE => DismissIntent::new(),
1234
1235 TAB => NextFocusIntent::new(),
1237 TAB.shift(true) => PreviousFocusIntent::new(),
1238 ARROW_LEFT => DirectionalFocusIntent::new(TraversalDirection::Left),
1239 ARROW_RIGHT => DirectionalFocusIntent::new(TraversalDirection::Right),
1240 ARROW_DOWN => DirectionalFocusIntent::new(TraversalDirection::Down),
1241 ARROW_UP => DirectionalFocusIntent::new(TraversalDirection::Up),
1242
1243 ARROW_UP.control(true) => ScrollIntent::new(AxisDirection::Up),
1245 ARROW_DOWN.control(true) => ScrollIntent::new(AxisDirection::Down),
1246 ARROW_LEFT.control(true) => ScrollIntent::new(AxisDirection::Left),
1247 ARROW_RIGHT.control(true) => ScrollIntent::new(AxisDirection::Right),
1248 PAGE_UP => ScrollIntent::new(AxisDirection::Up).r#type(ScrollIncrementType::Page),
1249 PAGE_DOWN => ScrollIntent::new(AxisDirection::Down).r#type(ScrollIncrementType::Page),
1250 ]
1251}
1252
1253fn default_web_shortcuts() -> ShortcutMap {
1255 shortcut_map![
1256 SPACE => PrioritizedIntents::new(vec![
1258 Rc::new(ActivateIntent::new()),
1259 Rc::new(ScrollIntent::new(AxisDirection::Down).r#type(ScrollIncrementType::Page)),
1260 ]),
1261 ENTER => ButtonActivateIntent::new(),
1263 NUMPAD_ENTER => ButtonActivateIntent::new(),
1264
1265 ESCAPE => DismissIntent::new(),
1267
1268 TAB => NextFocusIntent::new(),
1270 TAB.shift(true) => PreviousFocusIntent::new(),
1271
1272 ARROW_UP => ScrollIntent::new(AxisDirection::Up),
1274 ARROW_DOWN => ScrollIntent::new(AxisDirection::Down),
1275 ARROW_LEFT => ScrollIntent::new(AxisDirection::Left),
1276 ARROW_RIGHT => ScrollIntent::new(AxisDirection::Right),
1277 PAGE_UP => ScrollIntent::new(AxisDirection::Up).r#type(ScrollIncrementType::Page),
1278 PAGE_DOWN => ScrollIntent::new(AxisDirection::Down).r#type(ScrollIncrementType::Page),
1279 ]
1280}
1281
1282fn default_apple_os_shortcuts() -> ShortcutMap {
1284 shortcut_map![
1285 ENTER => ActivateIntent::new(),
1287 NUMPAD_ENTER => ActivateIntent::new(),
1288 SPACE => ActivateIntent::new(),
1289
1290 ESCAPE => DismissIntent::new(),
1292
1293 TAB => NextFocusIntent::new(),
1295 TAB.shift(true) => PreviousFocusIntent::new(),
1296 ARROW_LEFT => DirectionalFocusIntent::new(TraversalDirection::Left),
1297 ARROW_RIGHT => DirectionalFocusIntent::new(TraversalDirection::Right),
1298 ARROW_DOWN => DirectionalFocusIntent::new(TraversalDirection::Down),
1299 ARROW_UP => DirectionalFocusIntent::new(TraversalDirection::Up),
1300
1301 ARROW_UP.meta(true) => ScrollIntent::new(AxisDirection::Up),
1303 ARROW_DOWN.meta(true) => ScrollIntent::new(AxisDirection::Down),
1304 ARROW_LEFT.meta(true) => ScrollIntent::new(AxisDirection::Left),
1305 ARROW_RIGHT.meta(true) => ScrollIntent::new(AxisDirection::Right),
1306 PAGE_UP => ScrollIntent::new(AxisDirection::Up).r#type(ScrollIncrementType::Page),
1307 PAGE_DOWN => ScrollIntent::new(AxisDirection::Down).r#type(ScrollIncrementType::Page),
1308 ]
1309}
1310
1311pub struct WidgetsAppState {
1313 state: StateData<WidgetsApp>,
1314 navigator: Option<GlobalKey>,
1315 localizations_resolver: Option<Ref<LocalizationsResolver>>,
1316 observer: Option<WidgetsBindingObserverRef>,
1317 app_lifecycle_state: Option<AppLifecycleState>,
1318}
1319
1320impl WidgetsAppState {
1321 fn initial_route_name(self: Handle<Self>, app: &App) -> String {
1326 let default_route_name = app.platform().default_route_name();
1327 if default_route_name != Navigator::DEFAULT_ROUTE_NAME {
1328 return default_route_name;
1329 }
1330 self.widget(app)
1331 .initial_route
1332 .clone()
1333 .unwrap_or(default_route_name)
1334 }
1335
1336 fn default_on_navigation_notification(
1341 self: Handle<Self>,
1342 app: &mut App,
1343 notification: &NavigationNotification,
1344 ) -> bool {
1345 match app.get(self).app_lifecycle_state {
1346 None | Some(AppLifecycleState::Detached) => {
1347 true
1349 }
1350 Some(
1351 AppLifecycleState::Inactive
1352 | AppLifecycleState::Resumed
1353 | AppLifecycleState::Hidden
1354 | AppLifecycleState::Paused,
1355 ) => {
1356 if let Some(view) = self.view(app) {
1357 view.host()
1358 .set_framework_handles_back(notification.can_handle_pop);
1359 }
1360 true
1361 }
1362 }
1363 }
1364
1365 fn view(self: Handle<Self>, app: &App) -> Option<ViewRef> {
1367 let id = View::maybe_id_of(app, self.context(app))?;
1368 app.platform().view(id)
1369 }
1370
1371 fn clear_navigator_resource(self: Handle<Self>, app: &mut App) {
1372 app.get_mut(self).navigator = None;
1373 }
1374
1375 fn update_routing(self: Handle<Self>, app: &mut App, old_widget: Option<&WidgetsApp>) {
1376 if self.uses_navigator(app) {
1377 let navigator_key = self.widget(app).navigator_key.clone();
1378 let key_changed =
1379 old_widget.is_some_and(|old_widget| navigator_key != old_widget.navigator_key);
1380 if app.get(self).navigator.is_none() || key_changed {
1381 app.get_mut(self).navigator =
1382 Some(navigator_key.unwrap_or_else(|| GlobalKey::object(self.id())));
1383 }
1384 debug_assert!(app.get(self).navigator.is_some());
1385 } else {
1386 debug_assert!(self.widget(app).builder.is_some());
1387 self.clear_navigator_resource(app);
1388 }
1389 debug_assert!(self.uses_navigator(app) == app.get(self).navigator.is_some());
1391 }
1392
1393 fn uses_navigator(self: Handle<Self>, app: &App) -> bool {
1394 let widget = self.widget(app);
1395 widget.home.is_some()
1396 || !widget.routes.is_empty()
1397 || widget.on_generate_route.is_some()
1398 || widget.on_unknown_route.is_some()
1399 }
1400
1401 fn on_generate_route(
1402 self: Handle<Self>,
1403 app: &mut App,
1404 settings: &RouteSettings,
1405 ) -> Option<RouteRef> {
1406 let widget = self.widget(app);
1407 let name = settings.name.clone();
1408 let page_content_builder: Option<WidgetBuilder> = match name.as_deref() {
1409 Some(Navigator::DEFAULT_ROUTE_NAME) if widget.home.is_some() => {
1410 Some(Rc::new(move |app: &mut App, _context: BuildContext| {
1411 self.widget(app)
1412 .home
1413 .clone()
1414 .expect("the home route is built while WidgetsApp has a home")
1415 }))
1416 }
1417 _ => name
1418 .as_ref()
1419 .and_then(|name| widget.routes.get(name))
1420 .cloned(),
1421 };
1422
1423 if let Some(page_content_builder) = page_content_builder {
1424 let page_route_builder = self
1425 .widget(app)
1426 .page_route_builder
1427 .clone()
1428 .expect(PAGE_ROUTE_BUILDER_REQUIRED);
1429 let route = page_route_builder(app, settings, page_content_builder);
1430 return Some(route.into_erased());
1431 }
1432 let on_generate_route = self.widget(app).on_generate_route.clone();
1433 if let Some(on_generate_route) = on_generate_route {
1434 return on_generate_route(app, settings);
1435 }
1436 None
1437 }
1438
1439 fn on_unknown_route(
1440 self: Handle<Self>,
1441 app: &mut App,
1442 settings: &RouteSettings,
1443 ) -> Option<RouteRef> {
1444 let on_unknown_route = self
1445 .widget(app)
1446 .on_unknown_route
1447 .clone()
1448 .unwrap_or_else(|| {
1449 panic!(
1450 "Could not find a generator for route {settings:?} in the WidgetsApp.\n\
1451 Make sure your root app widget has provided a way to generate\n\
1452 this route.\n\
1453 Generators for routes are searched for in the following order:\n\
1454 1. For the \"/\" route, the \"home\" property, if non-null, is used.\n\
1455 2. Otherwise, the \"routes\" table is used, if it has an entry for the route.\n\
1456 3. Otherwise, onGenerateRoute is called. It should return a non-null value \
1457 for any valid route not handled by \"home\" and \"routes\".\n\
1458 4. Finally if all else fails onUnknownRoute is called.\n\
1459 Unfortunately, onUnknownRoute was not set."
1460 )
1461 });
1462 let result = on_unknown_route(app, settings);
1463 Some(result.expect(
1464 "The onUnknownRoute callback returned null.\nWhen the WidgetsApp requested a route \
1465 from its onUnknownRoute callback, the callback returned null. Such callbacks must \
1466 never return null.",
1467 ))
1468 }
1469
1470 fn localizations_resolver(self: Handle<Self>, app: &App) -> Handle<LocalizationsResolver> {
1472 app.get(self)
1473 .localizations_resolver
1474 .handle()
1475 .expect("init_state creates the resolver")
1476 }
1477
1478 fn should_update_localizations(self: Handle<Self>, app: &App, old_widget: &WidgetsApp) -> bool {
1479 let widget = self.widget(app);
1480 widget.locale != old_widget.locale
1481 || !same_callback(
1482 &widget.locale_list_resolution_callback,
1483 &old_widget.locale_list_resolution_callback,
1484 )
1485 || !same_callback(
1486 &widget.locale_resolution_callback,
1487 &old_widget.locale_resolution_callback,
1488 )
1489 || widget.supported_locales != old_widget.supported_locales
1490 || !same_delegates(
1491 &widget.localizations_delegates,
1492 &old_widget.localizations_delegates,
1493 )
1494 }
1495
1496 fn update_localizations(self: Handle<Self>, app: &mut App, old_widget: &WidgetsApp) {
1497 if self.should_update_localizations(app, old_widget) {
1498 let widget = self.widget(app);
1499 let locale = widget.locale.clone();
1500 let locale_list_resolution_callback = widget.locale_list_resolution_callback.clone();
1501 let locale_resolution_callback = widget.locale_resolution_callback.clone();
1502 let localizations_delegates = widget.localizations_delegates.clone();
1503 let supported_locales = widget.supported_locales.clone();
1504 self.localizations_resolver(app).update(
1505 app,
1506 locale,
1507 locale_list_resolution_callback,
1508 locale_resolution_callback,
1509 localizations_delegates,
1510 supported_locales,
1511 );
1512 }
1513 }
1514
1515 fn build_navigator(self: Handle<Self>, app: &mut App) -> WidgetRef {
1517 let navigator = app.get(self).navigator.clone().expect("a navigator key");
1518 let widget = self.widget(app);
1519 let observers = widget.navigator_observers.clone();
1520 let on_generate_initial_routes = widget.on_generate_initial_routes.clone();
1521 let initial_route = self.initial_route_name(app);
1522 let mut navigator_widget = Navigator::new()
1523 .clip_behavior(Clip::None)
1524 .restoration_scope_id("nav")
1525 .key(navigator.into())
1526 .initial_route(initial_route)
1527 .on_generate_route(move |app, settings| self.on_generate_route(app, settings))
1528 .on_unknown_route(move |app, settings| self.on_unknown_route(app, settings))
1529 .observers(observers)
1530 .route_traversal_edge_behavior(if K_IS_WEB {
1531 TraversalEdgeBehavior::LeaveFlutterView
1532 } else {
1533 TraversalEdgeBehavior::ParentScope
1534 })
1535 .reports_route_update_to_engine(true);
1536 navigator_widget = match on_generate_initial_routes {
1537 None => navigator_widget
1538 .on_generate_initial_routes(Navigator::default_generate_initial_routes),
1539 Some(on_generate_initial_routes) => navigator_widget.on_generate_initial_routes(
1540 move |app, _navigator, initial_route_name| {
1541 on_generate_initial_routes(app, initial_route_name)
1542 },
1543 ),
1544 };
1545 FocusScope::new(navigator_widget)
1546 .debug_label("Navigator Scope")
1547 .autofocus(true)
1548 .into_widget()
1549 }
1550}
1551
1552fn same_callback<T: ?Sized>(one: &Option<Rc<T>>, other: &Option<Rc<T>>) -> bool {
1554 match (one, other) {
1555 (None, None) => true,
1556 (Some(one), Some(other)) => Rc::ptr_eq(one, other),
1557 _ => false,
1558 }
1559}
1560
1561fn same_delegates(
1563 one: &Option<Vec<LocalizationsDelegateRef>>,
1564 other: &Option<Vec<LocalizationsDelegateRef>>,
1565) -> bool {
1566 match (one, other) {
1567 (None, None) => true,
1568 (Some(one), Some(other)) => {
1569 one.len() == other.len()
1570 && one
1571 .iter()
1572 .zip(other)
1573 .all(|(one, other)| ptr::addr_eq(&raw const **one, &raw const **other))
1574 }
1575 _ => false,
1576 }
1577}
1578
1579impl WidgetsBindingObserverObject for WidgetsAppState {
1580 fn did_pop_route(self: Handle<Self>, app: &mut App, view: ViewId) -> bool {
1583 if View::maybe_id_of(app, self.context(app)) != Some(view) {
1584 return false;
1585 }
1586 let Some(key) = app.get(self).navigator.clone() else {
1587 return false;
1588 };
1589 let Some(navigator) = key.current_state::<NavigatorState>(app) else {
1590 return false;
1591 };
1592 navigator.maybe_pop(app, None)
1593 }
1594
1595 fn did_change_app_lifecycle_state(self: Handle<Self>, app: &mut App, state: AppLifecycleState) {
1596 app.get_mut(self).app_lifecycle_state = Some(state);
1597 }
1598}
1599
1600impl State for WidgetsAppState {
1601 type Widget = WidgetsApp;
1602 crate::state_accessors!();
1603
1604 fn init_state(self: Handle<Self>, app: &mut App) {
1605 let widget = self.widget(app);
1606 let locale = widget.locale.clone();
1607 let locale_list_resolution_callback = widget.locale_list_resolution_callback.clone();
1608 let locale_resolution_callback = widget.locale_resolution_callback.clone();
1609 let localizations_delegates = widget.localizations_delegates.clone();
1610 let supported_locales = widget.supported_locales.clone();
1611 let resolver = LocalizationsResolver::new(
1612 app,
1613 locale,
1614 locale_list_resolution_callback,
1615 locale_resolution_callback,
1616 localizations_delegates,
1617 supported_locales,
1618 );
1619 app.get_mut(self).localizations_resolver = Some(resolver);
1620 self.update_routing(app, None);
1621 let observer: WidgetsBindingObserverRef = Rc::new(self);
1622 WidgetsBinding::instance(app).add_observer(app, Rc::clone(&observer));
1623 app.get_mut(self).observer = Some(observer);
1624 app.get_mut(self).app_lifecycle_state = SchedulerBinding::lifecycle_state(app);
1625 }
1626
1627 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &WidgetsApp) {
1628 self.update_routing(app, Some(old_widget));
1629 self.update_localizations(app, old_widget);
1630 }
1631
1632 fn dispose(self: Handle<Self>, app: &mut App) {
1633 if let Some(observer) = app.get_mut(self).observer.take() {
1634 WidgetsBinding::instance(app).remove_observer(app, &observer);
1635 }
1636 self.localizations_resolver(app).dispose(app);
1637 }
1638
1639 fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1640 let routing: Option<WidgetRef> =
1641 self.uses_navigator(app).then(|| self.build_navigator(app));
1642
1643 let mut result = match self.widget(app).builder.clone() {
1644 Some(builder) => {
1645 Builder::new(move |app, context| builder(app, context, routing.as_ref()))
1646 .into_widget()
1647 }
1648 None => routing.expect("either a builder or a navigator"),
1649 };
1650
1651 if let Some(text_style) = self.widget(app).text_style.clone() {
1652 result = DefaultTextStyle::new(text_style, result).into_widget();
1653 }
1654
1655 if cfg!(debug_assertions)
1659 && self.widget(app).debug_show_checked_mode_banner
1660 && WidgetsApp::debug_allow_banner_override(app)
1661 {
1662 result = CheckedModeBanner::new(result).into_widget();
1663 }
1664
1665 result = Focus::new(result)
1669 .can_request_focus(false)
1670 .on_key_event(Rc::new(|app, _node, event| {
1671 if !matches!(event, KeyEvent::Down(_) | KeyEvent::Repeat(_))
1672 || event.logical_key() != LogicalKeyboardKey::ESCAPE
1673 {
1674 return KeyEventResult::Ignored;
1675 }
1676 if RawTooltip::dismiss_all_tool_tips(app) {
1677 KeyEventResult::Handled
1678 } else {
1679 KeyEventResult::Ignored
1680 }
1681 }))
1682 .into_widget();
1683
1684 let color = self.widget(app).color;
1685 let title: Option<WidgetRef> = match self.widget(app).on_generate_title.clone() {
1686 Some(on_generate_title) => {
1687 let child = result.clone();
1688 Some(
1692 Builder::new(move |app, context| {
1693 let title = on_generate_title(app, context);
1694 Title::new(
1695 color.with_values(Some(1.0), None, None, None, None),
1696 child.clone(),
1697 )
1698 .title(title)
1699 .into_widget()
1700 })
1701 .into_widget(),
1702 )
1703 }
1704 None if self.widget(app).title.is_none() && K_IS_WEB => None,
1707 None => {
1708 let title = self.widget(app).title.clone().unwrap_or_default();
1709 Some(
1710 Title::new(
1711 color.with_values(Some(1.0), None, None, None, None),
1712 result.clone(),
1713 )
1714 .title(title)
1715 .into_widget(),
1716 )
1717 }
1718 };
1719
1720 let resolver = app
1721 .get(self)
1722 .localizations_resolver
1723 .clone()
1724 .expect("init_state creates the resolver");
1725 let localized = title.unwrap_or(result);
1726 let localizations = ListenableBuilder::new(
1727 Rc::new(resolver.clone()) as Rc<dyn Listenable>,
1728 move |app, _context, _child| {
1729 let locale = resolver.locale(app);
1730 let delegates = resolver.localizations_delegates(app);
1731 Localizations::new(locale, delegates)
1732 .is_application_level(true)
1733 .child(localized.clone())
1734 .into_widget()
1735 },
1736 );
1737
1738 let actions = match self.widget(app).actions.clone() {
1739 Some(actions) => actions,
1740 None => {
1741 let mut actions = WidgetsApp::default_actions(app);
1742 let scroll = ScrollAction::new(app);
1743 actions.insert(
1744 TypeId::of::<ScrollIntent>(),
1745 AnyAction::overridable(app, scroll.into_erased(), context),
1746 );
1747 actions
1748 }
1749 };
1750 let policy = ReadingOrderTraversalPolicy::new(app).into_erased();
1751 let shortcuts = match self.widget(app).shortcuts.clone() {
1752 Some(shortcuts) => shortcuts,
1753 None => WidgetsApp::default_shortcuts(app),
1754 };
1755 let on_navigation_notification = self.widget(app).on_navigation_notification.clone();
1756 let restoration_scope_id = self.widget(app).restoration_scope_id.clone();
1757
1758 RootRestorationScope::new(
1759 restoration_scope_id,
1760 SharedAppData::new(
1761 NotificationListener::<NavigationNotification>::new(
1762 Shortcuts::new(
1763 shortcuts,
1764 DefaultTextEditingShortcuts::new(Actions::new(
1765 actions,
1766 FocusTraversalGroup::new(TapRegionSurface::new(
1767 ShortcutRegistrar::new(localizations),
1768 ))
1769 .policy(policy),
1770 )),
1771 )
1772 .debug_label("<Default WidgetsApp Shortcuts>"),
1773 )
1774 .on_notification(move |app, notification| match &on_navigation_notification {
1775 Some(on_navigation_notification) => {
1776 on_navigation_notification(app, notification)
1777 }
1778 None => self.default_on_navigation_notification(app, notification),
1779 })
1780 .into_widget(),
1781 ),
1782 )
1783 .into_widget()
1784 }
1785}
1786
1787#[cfg(test)]
1788mod tests {
1789 use super::*;
1790 use waft_foundation::AppCell;
1791
1792 fn locale(language: &str, country: Option<&str>) -> Locale {
1793 let locale = Locale::new(language);
1794 match country {
1795 Some(country) => locale.country_code(country),
1796 None => locale,
1797 }
1798 }
1799
1800 #[test]
1801 fn a_perfect_match_wins_over_everything_later_in_the_list() {
1802 let supported = [
1803 locale("en", Some("US")),
1804 locale("fr", Some("FR")),
1805 locale("zh", Some("CN")),
1806 ];
1807 let preferred = [locale("fr", Some("FR")), locale("en", Some("US"))];
1808 assert_eq!(
1809 basic_locale_list_resolution(Some(&preferred), &supported),
1810 locale("fr", Some("FR"))
1811 );
1812 }
1813
1814 #[test]
1815 fn a_language_and_script_match_beats_a_language_and_country_match() {
1816 let supported = [
1817 locale("zh", Some("CN")),
1818 Locale::new("zh").script_code("Hant"),
1819 Locale::new("zh").script_code("Hans"),
1820 ];
1821 let preferred = [Locale::new("zh").script_code("Hant").country_code("CN")];
1822 assert_eq!(
1823 basic_locale_list_resolution(Some(&preferred), &supported),
1824 Locale::new("zh").script_code("Hant")
1825 );
1826 }
1827
1828 #[test]
1829 fn a_language_only_match_defers_to_a_better_match_for_the_same_language() {
1830 let supported = [locale("en", Some("US")), locale("en", Some("GB"))];
1831 let preferred = [locale("en", Some("AU")), locale("en", Some("GB"))];
1834 assert_eq!(
1835 basic_locale_list_resolution(Some(&preferred), &supported),
1836 locale("en", Some("GB"))
1837 );
1838 let preferred = [locale("en", Some("AU")), locale("fr", Some("FR"))];
1840 assert_eq!(
1841 basic_locale_list_resolution(Some(&preferred), &supported),
1842 locale("en", Some("US"))
1843 );
1844 }
1845
1846 #[test]
1847 fn a_country_only_match_is_the_last_resort_before_the_first_supported_locale() {
1848 let supported = [locale("en", Some("US")), locale("fr", Some("CA"))];
1849 let preferred = [locale("de", Some("CA"))];
1850 assert_eq!(
1851 basic_locale_list_resolution(Some(&preferred), &supported),
1852 locale("fr", Some("CA"))
1853 );
1854 let preferred = [locale("de", Some("DE"))];
1855 assert_eq!(
1856 basic_locale_list_resolution(Some(&preferred), &supported),
1857 locale("en", Some("US"))
1858 );
1859 assert_eq!(
1860 basic_locale_list_resolution(None, &supported),
1861 locale("en", Some("US"))
1862 );
1863 assert_eq!(
1864 basic_locale_list_resolution(Some(&[]), &supported),
1865 locale("en", Some("US"))
1866 );
1867 }
1868
1869 use std::cell::{Cell, RefCell};
1872 use std::time::Duration;
1873
1874 use waft_embedder::TextDirection;
1875 use waft_painting::PaintingBinding;
1876 use waft_services::LogicalKeyboardKey;
1877 use waft_test::{IMPLICIT_VIEW_ID, TestPlatform, TestView};
1878
1879 use crate::framework::{Notification, StatelessWidget};
1880 use crate::testing::{
1881 Finder, TestWidgetsApp, WidgetTester, expect, find, finds_nothing, finds_widgets,
1882 test_widgets,
1883 };
1884 use crate::widgets::actions::IntentRef;
1885 use crate::widgets::basic::SizedBox;
1886 use crate::widgets::focus_manager::{AnyFocusNode, FocusManager, FocusNodeLeaf, primary_focus};
1887 use crate::widgets::focus_scope::Focus;
1888 use crate::widgets::localizations::WidgetsLocalizations;
1889
1890 const COLOR: Color = Color::new(0xFF2196F3);
1892
1893 #[derive(Debug)]
1895 struct Marker;
1896
1897 impl StatelessWidget for Marker {
1898 fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
1899 SizedBox::new().width(10.0).height(10.0).into_widget()
1900 }
1901 }
1902
1903 fn app_of(platform: TargetPlatform) -> Rc<AppCell> {
1905 AppCell::with_platform(Rc::new(TestPlatform::new().on(platform)))
1906 }
1907
1908 fn install_fonts(app: &mut App) {
1911 let binding = PaintingBinding::instance(app);
1912 if !binding.has_fonts(app) {
1913 binding.install_fonts(app, |fonts| {
1914 fonts.add_source(valo_system_fonts::SystemFonts::load());
1915 });
1916 }
1917 }
1918
1919 fn mount_in_every_view(cell: &AppCell, widget: WidgetRef) {
1922 crate::binding::run_app(&mut cell.borrow_mut(), widget);
1923 cell.elapse(Duration::ZERO);
1924 crate::test_harness::pump_every_view(&mut cell.borrow_mut(), Duration::ZERO);
1925 }
1926
1927 fn settle_every_view(app: &mut App) {
1929 let mut at = Duration::ZERO;
1930 for _ in 0..20 {
1931 at += Duration::from_millis(20);
1932 crate::test_harness::pump_every_view(app, at);
1933 }
1934 }
1935
1936 fn built<W: 'static>() -> Finder {
1938 find::by_type::<W>().skip_offstage(false)
1939 }
1940
1941 fn intents_for(shortcuts: &ShortcutMap, key: LogicalKeyboardKey) -> Vec<IntentRef> {
1943 shortcuts
1944 .iter()
1945 .filter(|(activator, _)| {
1946 activator
1947 .triggers()
1948 .is_some_and(|triggers| triggers.contains(&key))
1949 })
1950 .map(|(_, intent)| Rc::clone(intent))
1951 .collect()
1952 }
1953
1954 #[test]
1955 fn home_is_shown_by_the_first_route_of_the_navigator_the_app_builds() {
1956 test_widgets(|tester| {
1957 tester.pump_widget(
1958 TestWidgetsApp::new()
1959 .color(COLOR)
1960 .home(Marker)
1961 .into_widget(),
1962 );
1963 tester.pump_and_settle();
1964 expect(tester, &built::<Navigator>(), finds_widgets());
1966 expect(tester, &built::<Marker>(), finds_widgets());
1968 });
1969 }
1970
1971 #[derive(Debug)]
1973 struct OtherMarker;
1974
1975 impl StatelessWidget for OtherMarker {
1976 fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
1977 SizedBox::new().width(20.0).height(20.0).into_widget()
1978 }
1979 }
1980
1981 #[test]
1984 fn pumping_the_app_with_a_new_home_shows_the_new_page() {
1985 test_widgets(|tester| {
1986 tester.pump_widget(
1987 TestWidgetsApp::new()
1988 .color(COLOR)
1989 .home(Marker)
1990 .into_widget(),
1991 );
1992 tester.pump_and_settle();
1993
1994 tester.pump_widget(
1995 TestWidgetsApp::new()
1996 .color(COLOR)
1997 .home(OtherMarker)
1998 .into_widget(),
1999 );
2000 tester.pump_and_settle();
2001 expect(tester, &built::<OtherMarker>(), finds_widgets());
2003 expect(tester, &built::<Marker>(), finds_nothing());
2005 });
2006 }
2007
2008 #[test]
2009 fn a_routes_table_entry_for_the_default_route_is_the_first_route() {
2010 test_widgets(|tester| {
2011 let builder: WidgetBuilder = Rc::new(|_app, _context| Marker.into_widget());
2012 tester.pump_widget(
2013 TestWidgetsApp::new()
2014 .color(COLOR)
2015 .routes([(String::from("/"), builder)])
2016 .into_widget(),
2017 );
2018 tester.pump_and_settle();
2019 expect(tester, &built::<Marker>(), finds_widgets());
2020 });
2021 }
2022
2023 #[test]
2026 fn a_home_without_a_page_route_builder_panics_at_construction() {
2027 let panic = std::panic::catch_unwind(|| WidgetsApp::new(COLOR).home(Marker).into_widget())
2028 .expect_err("a home app needs a page route builder");
2029 let message = panic
2030 .downcast_ref::<String>()
2031 .map(String::as_str)
2032 .or_else(|| panic.downcast_ref::<&str>().copied())
2033 .unwrap_or_default();
2034 assert!(
2035 message.contains("pageRouteBuilder must be specified"),
2036 "Flutter's message: {message}"
2037 );
2038 let panic = std::panic::catch_unwind(|| {
2039 WidgetsApp::new(COLOR)
2040 .routes([(
2041 String::from("/"),
2042 Rc::new(|_app: &mut App, _context: BuildContext| Marker.into_widget())
2043 as WidgetBuilder,
2044 )])
2045 .into_widget()
2046 })
2047 .expect_err("a routes app needs a page route builder");
2048 let message = panic
2049 .downcast_ref::<String>()
2050 .map(String::as_str)
2051 .or_else(|| panic.downcast_ref::<&str>().copied())
2052 .unwrap_or_default();
2053 assert!(message.contains("pageRouteBuilder must be specified"));
2054 }
2055
2056 #[test]
2057 fn only_a_builder_needs_no_page_route_builder() {
2058 test_widgets(|tester| {
2059 tester.pump_widget(
2060 WidgetsApp::new(COLOR)
2061 .builder(|_app, _context, _child| Marker.into_widget())
2062 .into_widget(),
2063 );
2064 tester.pump_and_settle();
2065 expect(tester, &built::<Marker>(), finds_widgets());
2066 });
2067 }
2068
2069 #[test]
2070 fn a_builder_replaces_the_navigator_and_is_handed_no_child() {
2071 test_widgets(|tester| {
2072 let had_child = Rc::new(Cell::new(true));
2073 let sink = Rc::clone(&had_child);
2074 tester.pump_widget(
2075 WidgetsApp::new(COLOR)
2076 .builder(move |_app, _context, child| {
2077 sink.set(child.is_some());
2078 Marker.into_widget()
2079 })
2080 .into_widget(),
2081 );
2082 assert!(!had_child.get(), "no routes, so the builder gets no child");
2083 expect(tester, &built::<Marker>(), finds_widgets());
2084 expect(tester, &built::<Navigator>(), finds_nothing());
2085 });
2086 }
2087
2088 #[test]
2089 fn a_builder_wraps_the_navigator_when_the_app_has_routes() {
2090 test_widgets(|tester| {
2091 let had_child = Rc::new(Cell::new(false));
2092 let sink = Rc::clone(&had_child);
2093 tester.pump_widget(
2094 TestWidgetsApp::new()
2095 .color(COLOR)
2096 .home(SizedBox::shrink())
2097 .builder(move |_app, _context, child| {
2098 sink.set(child.is_some());
2099 child.expect("the navigator").clone()
2100 })
2101 .into_widget(),
2102 );
2103 tester.pump_and_settle();
2104 assert!(had_child.get());
2105 expect(tester, &built::<Navigator>(), finds_widgets());
2106 });
2107 }
2108
2109 #[test]
2113 fn a_back_press_pops_the_app_navigator_until_it_is_at_the_first_route() {
2114 test_widgets(|tester| {
2115 let captured: Rc<Cell<Option<BuildContext>>> = Rc::default();
2116 let sink = Rc::clone(&captured);
2117 tester.pump_widget(
2118 TestWidgetsApp::new()
2119 .color(COLOR)
2120 .home(Builder::new(move |_app, context| {
2121 sink.set(Some(context));
2122 Marker.into_widget()
2123 }))
2124 .into_widget(),
2125 );
2126 tester.pump_and_settle();
2127 let mut app = tester.cell.borrow_mut();
2128 let binding = WidgetsBinding::instance(&mut app);
2129 assert!(
2130 !binding.handle_pop_route(&mut app, IMPLICIT_VIEW_ID),
2131 "at the first route there is nowhere to go back to"
2132 );
2133
2134 let context = captured.get().expect("the home built");
2135 let settings = RouteSettings::new().name("second");
2136 let route = TestWidgetsApp::default_page_route_builder(
2137 &mut app,
2138 &settings,
2139 Rc::new(|_app, _context| SizedBox::shrink().into_widget()),
2140 );
2141 Navigator::of(&mut app, context, false).push(&mut app, route.into_erased());
2142 drop(app);
2143 tester.pump_and_settle();
2144 let mut app = tester.cell.borrow_mut();
2145
2146 assert!(
2147 binding.handle_pop_route(&mut app, IMPLICIT_VIEW_ID),
2148 "the pushed route is popped"
2149 );
2150 drop(app);
2151 tester.pump_and_settle();
2152 let mut app = tester.cell.borrow_mut();
2153 assert!(
2154 !binding.handle_pop_route(&mut app, IMPLICIT_VIEW_ID),
2155 "back at the first route it answers that it did not go back"
2156 );
2157 });
2158 }
2159
2160 fn framework_handles_backs(view: &TestView) -> Vec<bool> {
2162 view.test_host().framework_handles_back()
2163 }
2164
2165 #[test]
2168 fn widgets_app_calls_set_framework_handles_back_only_when_app_is_ready() {
2169 test_widgets(|tester| {
2170 tester.update(|app| {
2173 SchedulerBinding::handle_app_lifecycle_state_changed(
2174 app,
2175 AppLifecycleState::Resumed,
2176 )
2177 });
2178 let captured: Rc<Cell<Option<BuildContext>>> = Rc::default();
2179 let sink = Rc::clone(&captured);
2180 tester.pump_widget(
2181 WidgetsApp::new(COLOR)
2182 .builder(move |_app, context, _child| {
2183 sink.set(Some(context));
2184 Marker.into_widget()
2185 })
2186 .into_widget(),
2187 );
2188 let mut app = tester.cell.borrow_mut();
2189 let context = captured.get().expect("the builder ran");
2190
2191 assert!(framework_handles_backs(tester.view()).is_empty());
2192
2193 NavigationNotification::new(true).dispatch(&mut app, Some(context));
2194 drop(app);
2195 tester.pump_and_settle();
2196 let mut app = tester.cell.borrow_mut();
2197 assert_eq!(framework_handles_backs(tester.view()).last(), Some(&true));
2198
2199 NavigationNotification::new(false).dispatch(&mut app, Some(context));
2200 drop(app);
2201 tester.pump_and_settle();
2202 let mut app = tester.cell.borrow_mut();
2203 assert_eq!(framework_handles_backs(tester.view()).last(), Some(&false));
2204
2205 SchedulerBinding::handle_app_lifecycle_state_changed(
2209 &mut app,
2210 AppLifecycleState::Inactive,
2211 );
2212
2213 let inactive_start_calls_length = framework_handles_backs(tester.view()).len();
2214 NavigationNotification::new(true).dispatch(&mut app, Some(context));
2215 drop(app);
2216 tester.pump_and_settle();
2217 let mut app = tester.cell.borrow_mut();
2218 assert_eq!(
2219 framework_handles_backs(tester.view()).len(),
2220 inactive_start_calls_length + 1
2221 );
2222
2223 NavigationNotification::new(false).dispatch(&mut app, Some(context));
2224 drop(app);
2225 tester.pump_and_settle();
2226 let mut app = tester.cell.borrow_mut();
2227 assert_eq!(
2228 framework_handles_backs(tester.view()).len(),
2229 inactive_start_calls_length + 2
2230 );
2231
2232 SchedulerBinding::handle_app_lifecycle_state_changed(
2234 &mut app,
2235 AppLifecycleState::Detached,
2236 );
2237
2238 let final_calls_length = framework_handles_backs(tester.view()).len();
2239 NavigationNotification::new(true).dispatch(&mut app, Some(context));
2240 drop(app);
2241 tester.pump_and_settle();
2242 let mut app = tester.cell.borrow_mut();
2243 assert_eq!(
2244 framework_handles_backs(tester.view()).len(),
2245 final_calls_length
2246 );
2247
2248 NavigationNotification::new(false).dispatch(&mut app, Some(context));
2249 drop(app);
2250 tester.pump_and_settle();
2251 assert_eq!(
2252 framework_handles_backs(tester.view()).len(),
2253 final_calls_length
2254 );
2255 });
2256 }
2257
2258 #[test]
2261 fn the_host_hears_whether_the_app_navigator_can_go_back_as_routes_come_and_go() {
2262 test_widgets(|tester| {
2263 tester.update(|app| {
2264 SchedulerBinding::handle_app_lifecycle_state_changed(
2265 app,
2266 AppLifecycleState::Resumed,
2267 )
2268 });
2269 let captured: Rc<Cell<Option<BuildContext>>> = Rc::default();
2270 let sink = Rc::clone(&captured);
2271 tester.pump_widget(
2272 TestWidgetsApp::new()
2273 .color(COLOR)
2274 .home(Builder::new(move |_app, context| {
2275 sink.set(Some(context));
2276 Marker.into_widget()
2277 }))
2278 .into_widget(),
2279 );
2280 tester.pump_and_settle();
2281 let mut app = tester.cell.borrow_mut();
2282 assert_eq!(
2283 framework_handles_backs(tester.view()).last(),
2284 Some(&false),
2285 "a single route is already defaulted to false"
2286 );
2287
2288 let context = captured.get().expect("the home built");
2289 let settings = RouteSettings::new().name("/one");
2290 let route = TestWidgetsApp::default_page_route_builder(
2291 &mut app,
2292 &settings,
2293 Rc::new(|_app, _context| SizedBox::shrink().into_widget()),
2294 );
2295 Navigator::of(&mut app, context, false).push(&mut app, route.into_erased());
2296 drop(app);
2297 tester.pump_and_settle();
2298 let mut app = tester.cell.borrow_mut();
2299 assert_eq!(framework_handles_backs(tester.view()).last(), Some(&true));
2300
2301 let binding = WidgetsBinding::instance(&mut app);
2302 assert!(binding.handle_pop_route(&mut app, IMPLICIT_VIEW_ID));
2303 drop(app);
2304 tester.pump_and_settle();
2305 assert_eq!(framework_handles_backs(tester.view()).last(), Some(&false));
2306 });
2307 }
2308
2309 #[test]
2312 fn back_in_one_view_pops_that_views_navigator_and_its_host_hears_of_it() {
2313 let views = [ViewId(0), ViewId(1)]
2314 .map(|id| Rc::new(TestView::with_pixel_ratio(800.0, 600.0, 2.0).with_id(id)));
2315 let mut platform = TestPlatform::new().on(TargetPlatform::Android);
2316 for view in &views {
2317 platform = platform.with_view(Rc::clone(view) as ViewRef);
2318 }
2319 let cell = AppCell::with_platform(Rc::new(platform));
2320 let mut app = cell.borrow_mut();
2321 install_fonts(&mut app);
2322 SchedulerBinding::handle_app_lifecycle_state_changed(&mut app, AppLifecycleState::Resumed);
2323 let homes: Rc<RefCell<Vec<BuildContext>>> = Rc::default();
2324 let sink = Rc::clone(&homes);
2325 drop(app);
2326 mount_in_every_view(
2327 &cell,
2328 TestWidgetsApp::new()
2329 .color(COLOR)
2330 .home(Builder::new(move |_app, context| {
2331 sink.borrow_mut().push(context);
2332 Marker.into_widget()
2333 }))
2334 .into_widget(),
2335 );
2336 let mut app = cell.borrow_mut();
2337 settle_every_view(&mut app);
2338 let home_in = |app: &App, view: ViewId| {
2339 let homes = homes.borrow();
2340 *homes
2341 .iter()
2342 .find(|home| View::maybe_id_of(app, **home) == Some(view))
2343 .expect("a home in each view")
2344 };
2345 let second = home_in(&app, ViewId(1));
2346 let settings = RouteSettings::new().name("/one");
2347 let route = TestWidgetsApp::default_page_route_builder(
2348 &mut app,
2349 &settings,
2350 Rc::new(|_app, _context| SizedBox::shrink().into_widget()),
2351 );
2352 Navigator::of(&mut app, second, false).push(&mut app, route.into_erased());
2353 settle_every_view(&mut app);
2354 assert_eq!(framework_handles_backs(&views[0]).last(), Some(&false));
2355 assert_eq!(framework_handles_backs(&views[1]).last(), Some(&true));
2356
2357 let binding = WidgetsBinding::instance(&mut app);
2358 assert!(
2359 !binding.handle_pop_route(&mut app, ViewId(0)),
2360 "the first view's navigator has nowhere to go back to"
2361 );
2362 assert!(binding.handle_pop_route(&mut app, ViewId(1)));
2363 settle_every_view(&mut app);
2364 assert_eq!(framework_handles_backs(&views[1]).last(), Some(&false));
2365 }
2366
2367 #[test]
2368 fn the_locale_argument_overrides_the_resolver_and_the_widgets_delegate_is_supplied() {
2369 test_widgets(|tester| {
2370 let captured: Rc<Cell<Option<BuildContext>>> = Rc::default();
2371 let sink = Rc::clone(&captured);
2372 tester.pump_widget(
2373 WidgetsApp::new(COLOR)
2374 .locale(Locale::new("fr"))
2375 .supported_locales([Locale::new("en").country_code("US"), Locale::new("fr")])
2376 .builder(move |_app, context, _child| {
2377 sink.set(Some(context));
2378 Marker.into_widget()
2379 })
2380 .into_widget(),
2381 );
2382 let mut app = tester.cell.borrow_mut();
2383 let context = captured.get().expect("the builder ran");
2384 assert_eq!(
2385 Localizations::locale_of(&mut app, context),
2386 Locale::new("fr"),
2387 "the locale argument wins over the platform's locales"
2388 );
2389 let localizations = Localizations::of::<dyn WidgetsLocalizations>(&mut app, context)
2390 .expect("DefaultWidgetsLocalizations");
2391 assert_eq!(localizations.text_direction(), TextDirection::Ltr);
2392 });
2393 }
2394
2395 #[test]
2396 fn the_default_shortcuts_bind_tab_to_focus_traversal_on_every_platform() {
2397 for platform in [
2398 TargetPlatform::Android,
2399 TargetPlatform::Fuchsia,
2400 TargetPlatform::Linux,
2401 TargetPlatform::Windows,
2402 TargetPlatform::IOS,
2403 TargetPlatform::MacOS,
2404 ] {
2405 let cell = app_of(platform);
2406 let app = cell.borrow();
2407 let shortcuts = WidgetsApp::default_shortcuts(&app);
2408 let tab = intents_for(&shortcuts, LogicalKeyboardKey::TAB);
2409 assert_eq!(tab.len(), 2, "{platform:?} binds tab and shift-tab");
2410 assert!(
2411 tab[0].as_any().is::<NextFocusIntent>(),
2412 "{platform:?} binds tab to NextFocusIntent"
2413 );
2414 assert!(
2415 tab[1].as_any().is::<PreviousFocusIntent>(),
2416 "{platform:?} binds shift-tab to PreviousFocusIntent"
2417 );
2418 }
2419 }
2420
2421 #[test]
2422 fn the_apple_default_shortcuts_scroll_with_the_meta_key() {
2423 let cell = app_of(TargetPlatform::MacOS);
2424 let app = cell.borrow();
2425 let shortcuts = WidgetsApp::default_shortcuts(&app);
2426 let arrow_up = intents_for(&shortcuts, LogicalKeyboardKey::ARROW_UP);
2427 assert!(arrow_up[0].as_any().is::<DirectionalFocusIntent>());
2428 assert!(arrow_up[1].as_any().is::<ScrollIntent>());
2429 let (activator, _) = shortcuts
2430 .iter()
2431 .find(|(_, intent)| intent.as_any().is::<ScrollIntent>())
2432 .expect("a scroll shortcut");
2433 assert!(
2434 activator.debug_describe_keys().contains("Meta"),
2435 "the apple table scrolls with meta, not control"
2436 );
2437 }
2438
2439 #[test]
2440 fn the_default_actions_request_focus_for_a_request_focus_intent() {
2441 test_widgets(|tester| {
2442 tester.pump_widget(
2443 Focus::new(SizedBox::shrink())
2444 .debug_label("target")
2445 .into_widget(),
2446 );
2447 let mut app = tester.cell.borrow_mut();
2448 let root_scope = FocusManager::instance(&mut app).root_scope(&app).handle();
2449 let node: AnyFocusNode = FocusNodeLeaf::as_node(root_scope)
2450 .descendants(&mut app)
2451 .into_iter()
2452 .find(|node| node.debug_label(&app).as_deref() == Some("target"))
2453 .expect("the focus node");
2454 let actions = WidgetsApp::default_actions(&mut app);
2455 let action = actions[&TypeId::of::<RequestFocusIntent>()].handle();
2456 let kept_node = node.keep(&app);
2457 action.invoke(&mut app, &RequestFocusIntent::new(kept_node), None);
2458 app.drain_microtasks();
2459 assert_eq!(primary_focus(&mut app), Some(node));
2460 });
2461 }
2462
2463 #[test]
2464 fn the_debug_banner_is_built_unless_it_is_turned_off() {
2465 test_widgets(|tester| {
2466 tester.pump_widget(
2467 TestWidgetsApp::new()
2468 .color(COLOR)
2469 .home(Marker)
2470 .into_widget(),
2471 );
2472 tester.pump_and_settle();
2473 let banner = if cfg!(debug_assertions) {
2475 finds_widgets()
2476 } else {
2477 finds_nothing()
2478 };
2479 expect(tester, &built::<CheckedModeBanner>(), banner);
2480 });
2481 test_widgets(|tester| {
2482 tester.pump_widget(
2483 WidgetsApp::new(COLOR)
2484 .page_route_builder(TestWidgetsApp::default_page_route_builder)
2485 .home(Marker)
2486 .debug_show_checked_mode_banner(false)
2487 .into_widget(),
2488 );
2489 tester.pump_and_settle();
2490 expect(tester, &built::<CheckedModeBanner>(), finds_nothing());
2491 });
2492 }
2493
2494 #[test]
2495 fn a_restoration_scope_id_names_the_root_restoration_scope() {
2496 test_widgets(|tester| {
2497 tester.pump_widget(
2498 TestWidgetsApp::new()
2499 .color(COLOR)
2500 .home(Marker)
2501 .restoration_scope_id("app")
2502 .into_widget(),
2503 );
2504 tester.pump_and_settle();
2505 let restoration_id = tester.widget(
2506 built::<RootRestorationScope>().first(),
2507 |scope: &RootRestorationScope| scope.restoration_id.clone(),
2508 );
2509 assert_eq!(restoration_id.as_deref(), Some("app"));
2510 });
2511 test_widgets(|tester| {
2512 tester.pump_widget(
2513 TestWidgetsApp::new()
2514 .color(COLOR)
2515 .home(Marker)
2516 .into_widget(),
2517 );
2518 tester.pump_and_settle();
2519 let restoration_id = tester.widget(
2520 built::<RootRestorationScope>().first(),
2521 |scope: &RootRestorationScope| scope.restoration_id.clone(),
2522 );
2523 assert_eq!(restoration_id, None, "restoration stays off");
2524 });
2525 }
2526
2527 #[test]
2528 fn the_platforms_default_route_name_overrides_the_initial_route() {
2529 let tester =
2530 &mut WidgetTester::with_platform(TestPlatform::new().with_default_route("/deep"));
2531 let deep: WidgetBuilder = Rc::new(|_app, _context| Marker.into_widget());
2532 tester.pump_widget(
2533 TestWidgetsApp::new()
2534 .color(COLOR)
2535 .initial_route("/ignored")
2536 .routes([
2537 (
2538 String::from("/"),
2539 Rc::new(|_app: &mut App, _context: BuildContext| {
2540 SizedBox::shrink().into_widget()
2541 }) as WidgetBuilder,
2542 ),
2543 (String::from("/deep"), deep),
2544 ])
2545 .into_widget(),
2546 );
2547 tester.pump_and_settle();
2548 expect(tester, &built::<Marker>(), finds_widgets());
2549 }
2550}