Skip to main content

waft_widgets/widgets/
app.rs

1//! Flutter counterpart: `widgets/app.dart`.
2//!
3//! [`WidgetsApp`], the widget an application is built from: the navigator, the localizations,
4//! the default shortcuts and actions, and the debug banner. `WidgetsApp.router` waits with
5//! `router.dart`.
6
7use 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
58/// The signature of `WidgetsApp.localeListResolutionCallback`.
59///
60/// A [`LocaleListResolutionCallback`] is responsible for computing the locale of the app's
61/// `Localizations` object when the app starts and when user changes the list of
62/// locales for the device.
63///
64/// The `locales` list is the device's preferred locales when the app started, or the
65/// device's preferred locales the user selected after the app was started. This list
66/// is in order of preference. If this list is null or empty, then Flutter has not yet
67/// received the locale information from the platform. The `supported_locales` parameter
68/// is just the value of `WidgetsApp.supportedLocales`.
69///
70/// See also:
71///
72///  * [`LocaleResolutionCallback`], which takes only one default locale (instead of a list)
73///    and is attempted only after this callback fails or is null. [`LocaleListResolutionCallback`]
74///    is recommended over [`LocaleResolutionCallback`].
75pub type LocaleListResolutionCallback = Rc<dyn Fn(Option<&[Locale]>, &[Locale]) -> Option<Locale>>;
76
77/// The signature of `WidgetsApp.localeResolutionCallback`.
78///
79/// It is recommended to provide a [`LocaleListResolutionCallback`] instead of a
80/// [`LocaleResolutionCallback`] when possible, as [`LocaleResolutionCallback`] only
81/// receives a subset of the information provided in [`LocaleListResolutionCallback`].
82///
83/// A [`LocaleResolutionCallback`] is responsible for computing the locale of the app's
84/// `Localizations` object when the app starts and when user changes the default
85/// locale for the device after [`LocaleListResolutionCallback`] fails or is not provided.
86///
87/// This callback is also used if the app is created with a specific locale using
88/// the `WidgetsApp.new` `locale` parameter.
89///
90/// The `locale` is either the value of `WidgetsApp.locale`, or the device's default
91/// locale when the app started, or the device locale the user selected after the app
92/// was started. The default locale is the first locale in the list of preferred
93/// locales. If `locale` is null, then Flutter has not yet received the locale
94/// information from the platform. The `supported_locales` parameter is just the value of
95/// `WidgetsApp.supportedLocales`.
96///
97/// See also:
98///
99///  * [`LocaleListResolutionCallback`], which takes a list of preferred locales (instead of one locale).
100///    Resolutions by [`LocaleListResolutionCallback`] take precedence over [`LocaleResolutionCallback`].
101pub type LocaleResolutionCallback = Rc<dyn Fn(Option<&Locale>, &[Locale]) -> Option<Locale>>;
102
103/// The default locale resolution algorithm.
104///
105/// Custom resolution algorithms can be provided through
106/// `WidgetsApp.localeListResolutionCallback` or
107/// `WidgetsApp.localeResolutionCallback`.
108///
109/// When no custom locale resolution algorithms are provided or if both fail
110/// to resolve, Flutter will default to calling this algorithm.
111///
112/// This algorithm prioritizes speed at the cost of slightly less appropriate
113/// resolutions for edge cases.
114///
115/// This algorithm will resolve to the earliest preferred locale that
116/// matches the most fields, prioritizing in the order of perfect match,
117/// languageCode+countryCode, languageCode+scriptCode, languageCode-only.
118///
119/// In the case where a locale is matched by languageCode-only and is not the
120/// default (first) locale, the next preferred locale with a
121/// perfect match can supersede the languageCode-only match if it exists.
122///
123/// When a preferredLocale matches more than one supported locale, it will
124/// resolve to the first matching locale listed in the supportedLocales.
125///
126/// When all preferred locales have been exhausted without a match, the first
127/// countryCode only match will be returned.
128///
129/// When no match at all is found, the first (default) locale in
130/// `supported_locales` will be returned.
131///
132/// To summarize, the main matching priority is:
133///
134///  1. `Locale.languageCode`, `Locale.scriptCode`, and `Locale.countryCode`
135///  2. `Locale.languageCode` and `Locale.scriptCode` only
136///  3. `Locale.languageCode` and `Locale.countryCode` only
137///  4. `Locale.languageCode` only (with caveats, see above)
138///  5. `Locale.countryCode` only when all `preferred_locales` fail to match
139///  6. Returns the first element of `supported_locales` as a fallback
140///
141/// This algorithm does not take language distance (how similar languages are to each other)
142/// into account, and will not handle edge cases such as resolving `de` to `fr` rather than `zh`
143/// when `de` is not supported and `zh` is listed before `fr` (German is closer to French
144/// than Chinese).
145pub 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    // The hashmaps below are the 'flattened' representation of the supported locales;
157    // only the first supported locale with the same key is kept.
158    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    // Since languageCode-only matches are possibly low quality, we don't return
182    // it instantly when we find such a match. We check to see if the next
183    // preferred locale in the list has a high accuracy match, and only return
184    // the languageCode-only match when a higher accuracy match in the next
185    // preferred locale cannot be found.
186    let mut matches_language_code: Option<&Locale> = None;
187    let mut matches_country_code: Option<&Locale> = None;
188    // Loop over user's preferred locales
189    for (locale_index, user_locale) in preferred_locales.iter().enumerate() {
190        // Look for perfect match.
191        if all_supported_locales.contains_key(&full_key(user_locale)) {
192            return user_locale.clone();
193        }
194        // Look for language+script match.
195        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        // Look for language+country match.
202        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 there was a languageCode-only match in the previous iteration's higher
209        // ranked preferred locale, we return it if the current userLocale does not
210        // have a better match.
211        if let Some(matched) = matches_language_code {
212            return matched.clone();
213        }
214        // Look and store language-only match.
215        if let Some(&matched) = language_locales.get(user_locale.language_code.as_str()) {
216            matches_language_code = Some(matched);
217            // Since first (default) locale is usually highly preferred, we will allow
218            // a languageCode-only match to be instantly matched. If the next preferred
219            // languageCode is the same, we defer hastily returning until the next iteration
220            // since at worst it is the same and at best it has a strong match.
221            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        // countryCode-only match. When all else except default supported locale fails,
229        // attempt to match by country only, as a user is likely to be familiar with a
230        // language from their listed country.
231        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    // When there is no languageCode-only match. Fallback to matching countryCode only. Country
239    // fallback only applies on iOS. When there is no countryCode-only match, we return first
240    // supported locale.
241    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
262/// The signature of [`WidgetsApp::on_generate_title`].
263///
264/// Used to generate a value for the app's [`Title::title`], which the device uses
265/// to identify the app for the user. The `context` includes the [`WidgetsApp`]'s
266/// `Localizations` widget so that this method can be used to produce a
267/// localized title.
268pub type GenerateAppTitle = Rc<dyn Fn(&mut App, BuildContext) -> String>;
269
270/// The signature of [`WidgetsApp::page_route_builder`].
271///
272/// Creates a `PageRoute` using the given [`RouteSettings`] and [`WidgetBuilder`].
273pub type PageRouteFactory = Rc<dyn Fn(&mut App, &RouteSettings, WidgetBuilder) -> PageRouteRef>;
274
275/// The signature of [`WidgetsApp::on_generate_initial_routes`].
276///
277/// Creates a series of one or more initial routes.
278pub type InitialRouteListFactory = Rc<dyn Fn(&mut App, &str) -> Vec<RouteRef>>;
279
280/// The [`App`] debug flag of [`WidgetsApp::show_performance_overlay_override`].
281pub struct ShowPerformanceOverlayOverride;
282
283impl DebugFlag for ShowPerformanceOverlayOverride {}
284
285/// The [`App`] debug flag of [`WidgetsApp::debug_allow_banner_override`].
286pub struct DebugAllowBannerOverride;
287
288impl DebugFlag for DebugAllowBannerOverride {
289    const DEFAULT: bool = true;
290}
291
292/// A convenience widget that wraps a number of widgets that are commonly
293/// required for an application.
294///
295/// One of the primary roles that [`WidgetsApp`] provides is binding the system
296/// back button to popping the [`Navigator`] or quitting the application.
297///
298/// It is used by both `MaterialApp` and `CupertinoApp` to implement base
299/// functionality for an app.
300///
301/// Find references to many of the widgets that [`WidgetsApp`] wraps in the "See
302/// also" section.
303///
304/// See also:
305///
306///  * [`CheckedModeBanner`], which displays a `Banner` saying "DEBUG" when
307///    running in debug mode.
308///  * [`DefaultTextStyle`], the text style to apply to descendant `Text` widgets
309///    without an explicit style.
310///  * `MediaQuery`, which establishes a subtree in which media queries resolve
311///    to a `MediaQueryData`.
312///  * [`Localizations`], which defines the [`Locale`] for its `child`.
313///  * [`Title`], a widget that describes this app in the operating system.
314///  * [`Navigator`], a widget that manages a set of child widgets with a stack
315///    discipline.
316///  * `Overlay`, a widget that manages a `Stack` of entries that can be managed
317///    independently.
318pub struct WidgetsApp {
319    /// See [`Widget::key`](crate::Widget::key).
320    pub key: Option<KeyRef>,
321
322    /// A key to use when building the [`Navigator`].
323    ///
324    /// If a [`navigator_key`](Self::navigator_key) is specified, the [`Navigator`] can be
325    /// directly manipulated without first obtaining it from a [`BuildContext`] via
326    /// [`Navigator::of`]: from the [`navigator_key`](Self::navigator_key), use the
327    /// [`GlobalKey::current_state`] getter.
328    ///
329    /// If this is changed, a new [`Navigator`] will be created, losing all the
330    /// application state in the process; in that case, the
331    /// [`navigator_observers`](Self::navigator_observers) must also be changed, since the
332    /// previous observers will be attached to the previous navigator.
333    ///
334    /// The [`Navigator`] is only built if [`on_generate_route`](Self::on_generate_route) is not
335    /// `None`; if it is `None`, [`navigator_key`](Self::navigator_key) must also be `None`.
336    pub navigator_key: Option<GlobalKey>,
337
338    /// The route generator callback used when the app is navigated to a
339    /// named route.
340    ///
341    /// If this returns `None` when building the routes to handle the specified
342    /// [`initial_route`](Self::initial_route), then all the routes are discarded and
343    /// [`Navigator::DEFAULT_ROUTE_NAME`] is used instead (`/`). See
344    /// [`initial_route`](Self::initial_route).
345    ///
346    /// During normal app operation, the [`on_generate_route`](Self::on_generate_route) callback
347    /// will only be applied to route names pushed by the application, and so should never
348    /// return `None`.
349    ///
350    /// This is used if [`routes`](Self::routes) does not contain the requested route.
351    ///
352    /// The [`Navigator`] is only built if routes are provided (either via
353    /// [`home`](Self::home), [`routes`](Self::routes),
354    /// [`on_generate_route`](Self::on_generate_route), or
355    /// [`on_unknown_route`](Self::on_unknown_route)); if they are not,
356    /// [`builder`](Self::builder) must not be `None`.
357    ///
358    /// If this property is not set, either the [`routes`](Self::routes) or
359    /// [`home`](Self::home) properties must be set, so that the default handler knows what
360    /// routes to build, and [`page_route_builder`](Self::page_route_builder) must be set too, so
361    /// that handler knows what transition to build them with.
362    pub on_generate_route: Option<RouteFactory>,
363
364    /// The routes generator callback used for generating initial routes if
365    /// [`initial_route`](Self::initial_route) is provided.
366    ///
367    /// If this property is not set, the underlying
368    /// [`Navigator::on_generate_initial_routes`] will default to
369    /// [`Navigator::default_generate_initial_routes`].
370    pub on_generate_initial_routes: Option<InitialRouteListFactory>,
371
372    /// The `PageRoute` generator callback used when the app is navigated to a
373    /// named route.
374    ///
375    /// A `PageRoute` represents the page in a [`Navigator`], so that it can
376    /// correctly animate between pages, and to represent the "return value" of
377    /// a route (e.g. which button a user selected in a modal dialog).
378    ///
379    /// This callback can be used, for example, to specify that a `MaterialPageRoute`
380    /// or a `CupertinoPageRoute` should be used for building page transitions. It is required
381    /// when `home` or `routes` are used and neither `builder` nor `onGenerateRoute` is given,
382    /// as Flutter's assert checks; a kit app sets this to its kit's route.
383    pub page_route_builder: Option<PageRouteFactory>,
384
385    /// The widget for the default route of the app ([`Navigator::DEFAULT_ROUTE_NAME`],
386    /// which is `/`).
387    ///
388    /// This is the route that is displayed first when the application is started
389    /// normally, unless [`initial_route`](Self::initial_route) is specified. It's also the
390    /// route that's displayed if the [`initial_route`](Self::initial_route) can't be
391    /// displayed.
392    ///
393    /// If [`home`](Self::home) is specified, then [`routes`](Self::routes) must not include
394    /// an entry for `/`, as [`home`](Self::home) takes its place.
395    ///
396    /// The [`Navigator`] is only built if routes are provided (either via
397    /// [`home`](Self::home), [`routes`](Self::routes),
398    /// [`on_generate_route`](Self::on_generate_route), or
399    /// [`on_unknown_route`](Self::on_unknown_route)); if they are not,
400    /// [`builder`](Self::builder) must not be `None`.
401    ///
402    /// The difference between using [`home`](Self::home) and using
403    /// [`builder`](Self::builder) is that the [`home`](Self::home) subtree is inserted into
404    /// the application below a [`Navigator`] (and thus below an `Overlay`, which
405    /// [`Navigator`] uses). With [`home`](Self::home), therefore, dialog boxes will work
406    /// automatically, the [`routes`](Self::routes) table will be used, and APIs such as
407    /// [`Navigator::push`] and [`Navigator::pop`] will work as expected. In contrast, the
408    /// widget returned from [`builder`](Self::builder) is inserted _above_ the app's
409    /// [`Navigator`] (if any).
410    ///
411    /// If this property is set, the [`page_route_builder`](Self::page_route_builder) property
412    /// must also be set, unless a [`builder`](Self::builder) or
413    /// [`on_generate_route`](Self::on_generate_route) is, so that the default route handler
414    /// will know what kind of `PageRoute`s to build.
415    pub home: Option<WidgetRef>,
416
417    /// The application's top-level routing table.
418    ///
419    /// When a named route is pushed with [`Navigator::push_named`], the route name is
420    /// looked up in this map. If the name is present, the associated
421    /// [`WidgetBuilder`] is used to construct a `PageRoute` specified by
422    /// [`page_route_builder`](Self::page_route_builder) to perform an appropriate transition,
423    /// including `Hero` animations, to the new route.
424    ///
425    /// If the app only has one page, then you can specify it using [`home`](Self::home)
426    /// instead.
427    ///
428    /// If [`home`](Self::home) is specified, then it implies an entry in this table for the
429    /// [`Navigator::DEFAULT_ROUTE_NAME`] route (`/`), and it is an error to
430    /// redundantly provide such a route in the [`routes`](Self::routes) table.
431    ///
432    /// If a route is requested that is not specified in this table (or by
433    /// [`home`](Self::home)), then the [`on_generate_route`](Self::on_generate_route) callback
434    /// is called to build the page instead.
435    ///
436    /// The [`Navigator`] is only built if routes are provided (either via
437    /// [`home`](Self::home), [`routes`](Self::routes),
438    /// [`on_generate_route`](Self::on_generate_route), or
439    /// [`on_unknown_route`](Self::on_unknown_route)); if they are not,
440    /// [`builder`](Self::builder) must not be `None`.
441    ///
442    /// If the routes map is not empty, the [`page_route_builder`](Self::page_route_builder)
443    /// property must be set, unless a [`builder`](Self::builder) or
444    /// [`on_generate_route`](Self::on_generate_route) is, so that the default route handler
445    /// will know what kind of `PageRoute`s to build.
446    pub routes: HashMap<String, WidgetBuilder>,
447
448    /// Called when [`on_generate_route`](Self::on_generate_route) fails to generate a route,
449    /// except for the [`initial_route`](Self::initial_route).
450    ///
451    /// This callback is typically used for error handling. For example, this
452    /// callback might always generate a "not found" page that describes the route
453    /// that wasn't found.
454    ///
455    /// Unknown routes can arise either from errors in the app or from external
456    /// requests to push routes, such as from Android intents.
457    ///
458    /// The [`Navigator`] is only built if routes are provided (either via
459    /// [`home`](Self::home), [`routes`](Self::routes),
460    /// [`on_generate_route`](Self::on_generate_route), or
461    /// [`on_unknown_route`](Self::on_unknown_route)); if they are not,
462    /// [`builder`](Self::builder) must not be `None`.
463    pub on_unknown_route: Option<RouteFactory>,
464
465    /// The callback to use when receiving a [`NavigationNotification`].
466    ///
467    /// By default this updates the engine with the navigation status and stops
468    /// bubbling the notification.
469    ///
470    /// See also:
471    ///
472    ///  * [`NotificationListener::on_notification`], which uses this callback.
473    pub on_navigation_notification: Option<NotificationListenerCallback<NavigationNotification>>,
474
475    /// The name of the first route to show, if a [`Navigator`] is built.
476    ///
477    /// Defaults to [`Platform::default_route_name`](waft_embedder::Platform::default_route_name),
478    /// which may be overridden by the code that launched the application.
479    ///
480    /// If the route name starts with a slash, then it is treated as a "deep link",
481    /// and before this route is pushed, the routes leading to this one are pushed
482    /// also. For example, if the route was `/a/b/c`, then the app would start
483    /// with the four routes `/`, `/a`, `/a/b`, and `/a/b/c` loaded, in that order.
484    /// Even if the route was just `/a`, the app would start with `/` and `/a`
485    /// loaded. You can use the
486    /// [`on_generate_initial_routes`](Self::on_generate_initial_routes) property to override
487    /// this behavior.
488    ///
489    /// Intermediate routes aren't required to exist. In the example above, `/a`
490    /// and `/a/b` could be skipped if they have no matching route. But `/a/b/c` is
491    /// required to have a route, else [`initial_route`](Self::initial_route) is ignored and
492    /// [`Navigator::DEFAULT_ROUTE_NAME`] is used instead (`/`). This can happen if the
493    /// app is started with an intent that specifies a non-existent route.
494    ///
495    /// The [`Navigator`] is only built if routes are provided (either via
496    /// [`home`](Self::home), [`routes`](Self::routes),
497    /// [`on_generate_route`](Self::on_generate_route), or
498    /// [`on_unknown_route`](Self::on_unknown_route)); if they are not,
499    /// [`initial_route`](Self::initial_route) must be `None` and
500    /// [`builder`](Self::builder) must not be `None`.
501    ///
502    /// Changing the [`initial_route`](Self::initial_route) will have no effect, as it only
503    /// controls the _initial_ route. To change the route while the application is running,
504    /// use the [`Navigator`] APIs.
505    pub initial_route: Option<String>,
506
507    /// The list of observers for the [`Navigator`] created for this app.
508    ///
509    /// This list must be replaced by a list of newly-created observers if the
510    /// [`navigator_key`](Self::navigator_key) is changed.
511    ///
512    /// The [`Navigator`] is only built if routes are provided (either via
513    /// [`home`](Self::home), [`routes`](Self::routes),
514    /// [`on_generate_route`](Self::on_generate_route), or
515    /// [`on_unknown_route`](Self::on_unknown_route)); if they are not,
516    /// [`navigator_observers`](Self::navigator_observers) must be the empty list and
517    /// [`builder`](Self::builder) must not be `None`.
518    pub navigator_observers: Vec<NavigatorObserverRef>,
519
520    /// A builder for inserting widgets above the [`Navigator`] but below the
521    /// other widgets created by the [`WidgetsApp`] widget, or for replacing the
522    /// [`Navigator`] entirely.
523    ///
524    /// For example, from the [`BuildContext`] passed to this method, the
525    /// `Directionality`, [`Localizations`], [`DefaultTextStyle`], `MediaQuery`, etc,
526    /// are all available. They can also be overridden in a way that impacts all
527    /// the routes in the [`Navigator`].
528    ///
529    /// This is rarely useful, but can be used in applications that wish to
530    /// override those defaults, e.g. to force the application into right-to-left
531    /// mode despite being in English, or to override the `MediaQuery` metrics
532    /// (e.g. to leave a gap for advertisements shown by a plugin from OEM code).
533    ///
534    /// For specifically overriding the [`title`](Self::title) with a value based on the
535    /// [`Localizations`], consider [`on_generate_title`](Self::on_generate_title) instead.
536    ///
537    /// The [`builder`](Self::builder) callback is passed two arguments, the [`BuildContext`]
538    /// and a [`Navigator`] widget (as `child`).
539    ///
540    /// If no routes are provided using [`home`](Self::home), [`routes`](Self::routes),
541    /// [`on_generate_route`](Self::on_generate_route), or
542    /// [`on_unknown_route`](Self::on_unknown_route), the `child` will be `None`, and it is
543    /// the responsibility of the [`builder`](Self::builder) to provide the application's
544    /// routing machinery.
545    ///
546    /// If routes _are_ provided using one or more of those properties, then `child` is not
547    /// `None`, and the returned value should include the `child` in the widget subtree; if it
548    /// does not, then the application will have no [`Navigator`] and the routing related
549    /// properties are ignored.
550    ///
551    /// If [`builder`](Self::builder) is `None`, it is as if a builder was specified that
552    /// returned the `child` directly. If it is `None`, routes must be provided using one of
553    /// the other properties listed above.
554    ///
555    /// Unless a [`Navigator`] is provided, either implicitly from
556    /// [`builder`](Self::builder) being `None`, or by a [`builder`](Self::builder) including
557    /// its `child` argument, or by a [`builder`](Self::builder) explicitly providing a
558    /// [`Navigator`] of its own, widgets and APIs such as `Hero`, [`Navigator::push`] and
559    /// [`Navigator::pop`], will not function.
560    pub builder: Option<TransitionBuilder>,
561
562    /// A one-line description used by the device to identify the app for the user.
563    ///
564    /// On Android the titles appear above the task manager's app snapshots which are
565    /// displayed when the user presses the "recent apps" button. On iOS this
566    /// value cannot be used. `CFBundleDisplayName` from the app's `Info.plist` is
567    /// referred to instead whenever present, `CFBundleName` otherwise.
568    /// On the web it is used as the page title, which shows up in the browser's list of open
569    /// tabs.
570    ///
571    /// To provide a localized title instead, use
572    /// [`on_generate_title`](Self::on_generate_title).
573    pub title: Option<String>,
574
575    /// If non-`None` this callback function is called to produce the app's
576    /// title string, otherwise [`title`](Self::title) is used.
577    ///
578    /// The [`on_generate_title`](Self::on_generate_title) `context` parameter includes the
579    /// [`WidgetsApp`]'s [`Localizations`] widget so that this callback can be used to produce
580    /// a localized title.
581    ///
582    /// The [`on_generate_title`](Self::on_generate_title) callback is called each time the
583    /// [`WidgetsApp`] rebuilds.
584    pub on_generate_title: Option<GenerateAppTitle>,
585
586    /// The default text style for `Text` in the application.
587    pub text_style: Option<TextStyle>,
588
589    /// The primary color to use for the application in the operating system
590    /// interface.
591    ///
592    /// For example, on Android this is the color used for the application in the
593    /// application switcher.
594    pub color: Color,
595
596    /// The initial locale for this app's [`Localizations`] widget is based
597    /// on this value.
598    ///
599    /// If the `locale` is `None` then the system's locale value is used.
600    ///
601    /// The value of [`Localizations::locale_of`] will equal this locale if
602    /// it matches one of the [`supported_locales`](Self::supported_locales). Otherwise it
603    /// will be the first element of [`supported_locales`](Self::supported_locales).
604    ///
605    /// See also:
606    ///
607    ///  * [`locale_resolution_callback`](Self::locale_resolution_callback), which can override
608    ///    the default [`supported_locales`](Self::supported_locales) matching algorithm.
609    ///  * [`localizations_delegates`](Self::localizations_delegates), which collectively define
610    ///    all of the localized resources used by this app.
611    pub locale: Option<Locale>,
612
613    /// The delegates for this app's [`Localizations`] widget.
614    ///
615    /// The delegates collectively define all of the localized resources
616    /// for this application's [`Localizations`] widget.
617    pub localizations_delegates: Option<Vec<LocalizationsDelegateRef>>,
618
619    /// This callback is responsible for choosing the app's locale
620    /// when the app is started, and when the user changes the
621    /// device's locale.
622    ///
623    /// When a [`locale_list_resolution_callback`](Self::locale_list_resolution_callback) is
624    /// provided, the resolver will first attempt to resolve the locale with it. If the
625    /// callback or result is `None`, it will fall back to trying the
626    /// [`locale_resolution_callback`](Self::locale_resolution_callback). If both are left
627    /// `None` or fail to resolve, the basic fallback algorithm will be used.
628    ///
629    /// The priority of each available fallback is:
630    ///
631    ///  1. [`locale_list_resolution_callback`](Self::locale_list_resolution_callback) is
632    ///     attempted.
633    ///  2. [`locale_resolution_callback`](Self::locale_resolution_callback) is attempted.
634    ///  3. [`basic_locale_list_resolution`], the basic resolution algorithm, is attempted last.
635    ///
636    /// This callback considers the entire list of preferred locales.
637    ///
638    /// This algorithm should be able to handle a `None` or empty list of preferred locales,
639    /// which indicates the platform has not reported locale information yet.
640    pub locale_list_resolution_callback: Option<LocaleListResolutionCallback>,
641
642    /// See [`locale_list_resolution_callback`](Self::locale_list_resolution_callback).
643    ///
644    /// This callback considers only the default locale, which is the first locale
645    /// in the preferred locales list. It is preferred to set
646    /// [`locale_list_resolution_callback`](Self::locale_list_resolution_callback) over
647    /// [`locale_resolution_callback`](Self::locale_resolution_callback) as it provides the
648    /// full preferred locales list.
649    pub locale_resolution_callback: Option<LocaleResolutionCallback>,
650
651    /// The list of locales that this app has been localized for.
652    ///
653    /// By default only the American English locale is supported. Apps should
654    /// configure this list to match the locales they support.
655    ///
656    /// The order of the list matters. The default locale resolution algorithm,
657    /// [`basic_locale_list_resolution`], attempts to match by the following priority:
658    ///
659    ///  1. `Locale::language_code`, `Locale::script_code`, and `Locale::country_code`
660    ///  2. `Locale::language_code` and `Locale::script_code` only
661    ///  3. `Locale::language_code` and `Locale::country_code` only
662    ///  4. `Locale::language_code` only
663    ///  5. `Locale::country_code` only when all preferred locales fail to match
664    ///  6. Returns the first element of [`supported_locales`](Self::supported_locales) as a
665    ///     fallback
666    ///
667    /// When more than one supported locale matches one of these criteria, only
668    /// the first matching locale is returned.
669    ///
670    /// When supporting languages with more than one script, it is recommended
671    /// to specify the `Locale::script_code` explicitly. Locales may also be defined without
672    /// `Locale::country_code` to specify a generic fallback for a particular script.
673    pub supported_locales: Vec<Locale>,
674
675    /// Turns on a performance overlay.
676    ///
677    /// See also:
678    ///
679    ///  * <https://flutter.dev/to/performance-overlay>
680    pub show_performance_overlay: bool,
681
682    /// Turns on an overlay that shows the accessibility information
683    /// reported by the framework.
684    pub show_semantics_debugger: bool,
685
686    /// Turns on an overlay that enables inspecting the widget tree.
687    ///
688    /// The inspector is only available in debug mode as it depends on
689    /// `RenderObject.debugDescribeChildren` which should not be called outside of
690    /// debug mode.
691    pub debug_show_widget_inspector: bool,
692
693    /// Turns on a little "DEBUG" banner in debug mode to indicate
694    /// that the app is in debug mode. This is on by default (in
695    /// debug mode), to turn it off, set the setter argument to
696    /// false. In release mode this has no effect.
697    ///
698    /// To get this banner in your application if you're not using
699    /// [`WidgetsApp`], include a [`CheckedModeBanner`] widget in your app.
700    ///
701    /// This banner is intended to deter people from complaining that your
702    /// app is slow when it's in debug mode. In debug mode, a large number of
703    /// expensive diagnostics are enabled to aid in development, and so performance in debug
704    /// mode is not representative of what will happen in release mode.
705    pub debug_show_checked_mode_banner: bool,
706
707    /// The default map of keyboard shortcuts to intents for the application.
708    ///
709    /// By default, this is set to [`WidgetsApp::default_shortcuts`].
710    ///
711    /// Passing this will not replace [`DefaultTextEditingShortcuts`]. These can be
712    /// overridden by using a [`Shortcuts`] widget lower in the widget tree.
713    ///
714    /// See also:
715    ///
716    ///  * `SingleActivator`, which defines shortcut key combination of a single
717    ///    key and modifiers, such as "Delete" or "Control+C".
718    ///  * The [`Shortcuts`] widget, which defines a keyboard mapping.
719    ///  * The [`Actions`] widget, which defines the mapping from intent to action.
720    ///  * The `Intent` and `Action` traits, which allow definition of new actions.
721    pub shortcuts: Option<ShortcutMap>,
722
723    /// The default map of intent keys to actions for the application.
724    ///
725    /// By default, this is the output of [`WidgetsApp::default_actions`]. Specifying
726    /// [`actions`](Self::actions) for an app overrides the default, so if you wish to modify
727    /// the default [`actions`](Self::actions), you can call [`WidgetsApp::default_actions`]
728    /// and modify the resulting map, passing it as the [`actions`](Self::actions) for this
729    /// app. You may also add to the bindings, or override specific bindings for a widget
730    /// subtree, by adding your own [`Actions`] widget.
731    ///
732    /// See also:
733    ///
734    ///  * The [`shortcuts`](Self::shortcuts) parameter, which defines the default set of
735    ///    shortcuts for the application.
736    ///  * The [`Shortcuts`] widget, which defines a keyboard mapping.
737    ///  * The [`Actions`] widget, which defines the mapping from intent to action.
738    pub actions: Option<HashMap<TypeId, ActionRef>>,
739
740    /// The identifier to use for state restoration of this app.
741    ///
742    /// Providing a restoration ID inserts a [`RootRestorationScope`] into the
743    /// widget hierarchy, which enables state restoration for descendant widgets.
744    ///
745    /// Providing a restoration ID also enables the [`Navigator`] built
746    /// by the [`WidgetsApp`] to restore its state (i.e. to restore the history
747    /// stack of active `Route`s). See the documentation on [`Navigator`] for more
748    /// details around state restoration of `Route`s.
749    ///
750    /// See also:
751    ///
752    ///  * `RestorationManager`, which explains how state restoration works in
753    ///    Flutter.
754    pub restoration_scope_id: Option<String>,
755
756    /// Dart's deprecated `useInheritedMediaQuery`. This setting is ignored.
757    ///
758    /// The widget never introduces its own `MediaQuery`; the `View` widget takes
759    /// care of that.
760    pub use_inherited_media_query: bool,
761}
762
763/// Flutter's message for an app that routes with `home` or `routes` but names no page route:
764/// the constructor's assert in a debug build, the first route's panic in a release one.
765const 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    /// Creates a widget that wraps a number of widgets that are commonly
771    /// required for an application.
772    ///
773    /// Most callers will want to use the [`home`](Self::home) or [`routes`](Self::routes)
774    /// setters, or both. The [`home`](Self::home) setter is a convenience for the following
775    /// [`routes`](Self::routes) map:
776    ///
777    /// ```text
778    /// {"/": |app, context| my_widget}
779    /// ```
780    ///
781    /// It is possible to specify both [`home`](Self::home) and [`routes`](Self::routes), but
782    /// only if [`routes`](Self::routes) does _not_ contain an entry for `"/"`. Conversely, if
783    /// [`home`](Self::home) is omitted, [`routes`](Self::routes) _must_ contain an entry for
784    /// `"/"`.
785    ///
786    /// If [`home`](Self::home) or [`routes`](Self::routes) are set, the routing implementation
787    /// needs to know how to build `PageRoute`s, so the
788    /// [`page_route_builder`](Self::page_route_builder) setter must be given one too, unless a
789    /// [`builder`](Self::builder) or [`on_generate_route`](Self::on_generate_route) is; Flutter's
790    /// assert checks it when the widget is turned into a [`WidgetRef`] in a debug build.
791    ///
792    /// The [`builder`](Self::builder) setter is designed to provide the ability to wrap the
793    /// visible content of the app in some other widget. It is recommended that you use
794    /// [`home`](Self::home) rather than [`builder`](Self::builder) if you intend to only
795    /// display a single route in your app.
796    ///
797    /// [`WidgetsApp`] is also able to provide a custom implementation of routing via the
798    /// [`on_generate_route`](Self::on_generate_route) and
799    /// [`on_unknown_route`](Self::on_unknown_route) setters. These correspond to
800    /// [`Navigator::on_generate_route`] and [`Navigator::on_unknown_route`]. If
801    /// [`home`](Self::home), [`routes`](Self::routes), and [`builder`](Self::builder) are
802    /// unset, or if they fail to create a requested route,
803    /// [`on_generate_route`](Self::on_generate_route) will be invoked. If that fails,
804    /// [`on_unknown_route`](Self::on_unknown_route) will be invoked.
805    ///
806    /// The [`supported_locales`](Self::supported_locales) list must have one or more elements.
807    /// By default it is `[Locale::new("en").country_code("US")]`.
808    ///
809    /// The configuration is checked when the widget is turned into a `WidgetRef`: Dart's
810    /// constructor asserts run there, because a fluent setter cannot see the fields that are
811    /// still to come.
812    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    /// Dart `WidgetsApp(key:)`.
847    pub fn key(mut self, key: KeyRef) -> WidgetsApp {
848        self.key = Some(key);
849        self
850    }
851
852    /// Dart `WidgetsApp(navigatorKey:)`.
853    pub fn navigator_key(mut self, navigator_key: GlobalKey) -> WidgetsApp {
854        self.navigator_key = Some(navigator_key);
855        self
856    }
857
858    /// Dart `WidgetsApp(onGenerateRoute:)`.
859    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    /// Dart `WidgetsApp(onGenerateInitialRoutes:)`.
868    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    /// Dart `WidgetsApp(pageRouteBuilder:)`, which a [`home`](Self::home) or
877    /// [`routes`](Self::routes) app must give unless it also gives a [`builder`](Self::builder)
878    /// or [`on_generate_route`](Self::on_generate_route).
879    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    /// Dart `WidgetsApp(home:)`.
888    #[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    /// Dart `WidgetsApp(routes:)`.
895    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    /// Dart `WidgetsApp(onUnknownRoute:)`.
904    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    /// Dart `WidgetsApp(onNavigationNotification:)`.
913    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    /// Dart `WidgetsApp(initialRoute:)`.
922    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    /// Dart `WidgetsApp(navigatorObservers:)`.
928    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    /// Dart `WidgetsApp(builder:)`.
937    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    /// Dart `WidgetsApp(title:)`.
946    pub fn title(mut self, title: impl Into<String>) -> WidgetsApp {
947        self.title = Some(title.into());
948        self
949    }
950
951    /// Dart `WidgetsApp(onGenerateTitle:)`.
952    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    /// Dart `WidgetsApp(textStyle:)`.
961    pub fn text_style(mut self, text_style: TextStyle) -> WidgetsApp {
962        self.text_style = Some(text_style);
963        self
964    }
965
966    /// Dart `WidgetsApp(locale:)`.
967    pub fn locale(mut self, locale: Locale) -> WidgetsApp {
968        self.locale = Some(locale);
969        self
970    }
971
972    /// Dart `WidgetsApp(localizationsDelegates:)`.
973    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    /// Dart `WidgetsApp(localeListResolutionCallback:)`.
982    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    /// Dart `WidgetsApp(localeResolutionCallback:)`.
992    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    /// Dart `WidgetsApp(supportedLocales:)`.
1001    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    /// Dart `WidgetsApp(showPerformanceOverlay:)`.
1011    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    /// Dart `WidgetsApp(showSemanticsDebugger:)`.
1017    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    /// Dart `WidgetsApp(debugShowWidgetInspector:)`.
1023    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    /// Dart `WidgetsApp(debugShowCheckedModeBanner:)`.
1029    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    /// Dart `WidgetsApp(shortcuts:)`.
1038    pub fn shortcuts(mut self, shortcuts: ShortcutMap) -> WidgetsApp {
1039        self.shortcuts = Some(shortcuts);
1040        self
1041    }
1042
1043    /// Dart `WidgetsApp(actions:)`.
1044    pub fn actions(mut self, actions: HashMap<TypeId, ActionRef>) -> WidgetsApp {
1045        self.actions = Some(actions);
1046        self
1047    }
1048
1049    /// Dart `WidgetsApp(restorationScopeId:)`.
1050    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    /// Dart `WidgetsApp(useInheritedMediaQuery:)`, which is ignored.
1056    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    /// If true, forces the performance overlay to be visible in all instances.
1062    ///
1063    /// Used by the `showPerformanceOverlay` VM service extension.
1064    pub fn show_performance_overlay_override(app: &App) -> bool {
1065        app.debug_flag::<ShowPerformanceOverlayOverride>()
1066    }
1067
1068    /// Sets [`show_performance_overlay_override`](Self::show_performance_overlay_override).
1069    pub fn set_show_performance_overlay_override(app: &mut App, value: bool) {
1070        app.set_debug_flag::<ShowPerformanceOverlayOverride>(value);
1071    }
1072
1073    /// If false, prevents the debug banner from being visible.
1074    ///
1075    /// Used by the `debugAllowBanner` VM service extension.
1076    ///
1077    /// This is how `flutter run` turns off the banner when you take a screen shot
1078    /// with "s".
1079    pub fn debug_allow_banner_override(app: &App) -> bool {
1080        app.debug_flag::<DebugAllowBannerOverride>()
1081    }
1082
1083    /// Sets [`debug_allow_banner_override`](Self::debug_allow_banner_override).
1084    pub fn set_debug_allow_banner_override(app: &mut App, value: bool) {
1085        app.set_debug_flag::<DebugAllowBannerOverride>(value);
1086    }
1087
1088    /// Generates the default shortcut key bindings based on the platform.
1089    ///
1090    /// Used by [`WidgetsApp`] to assign a default value to
1091    /// [`shortcuts`](Self::shortcuts).
1092    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    /// The default value of [`actions`](Self::actions).
1106    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
1222/// Dart's `_defaultShortcuts`, whose name the public getter takes.
1223fn default_shortcuts_table() -> ShortcutMap {
1224    shortcut_map![
1225        // Activation
1226        ENTER => ActivateIntent::new(),
1227        NUMPAD_ENTER => ActivateIntent::new(),
1228        SPACE => ActivateIntent::new(),
1229        GAME_BUTTON_A => ActivateIntent::new(),
1230        SELECT => ActivateIntent::new(),
1231
1232        // Dismissal
1233        ESCAPE => DismissIntent::new(),
1234
1235        // Keyboard traversal.
1236        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        // Scrolling
1244        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
1253/// Default shortcuts for the web platform.
1254fn default_web_shortcuts() -> ShortcutMap {
1255    shortcut_map![
1256        // Activation
1257        SPACE => PrioritizedIntents::new(vec![
1258            Rc::new(ActivateIntent::new()),
1259            Rc::new(ScrollIntent::new(AxisDirection::Down).r#type(ScrollIncrementType::Page)),
1260        ]),
1261        // On the web, enter activates buttons, but not other controls.
1262        ENTER => ButtonActivateIntent::new(),
1263        NUMPAD_ENTER => ButtonActivateIntent::new(),
1264
1265        // Dismissal
1266        ESCAPE => DismissIntent::new(),
1267
1268        // Keyboard traversal.
1269        TAB => NextFocusIntent::new(),
1270        TAB.shift(true) => PreviousFocusIntent::new(),
1271
1272        // Scrolling
1273        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
1282/// Default shortcuts for the macOS and iOS platforms.
1283fn default_apple_os_shortcuts() -> ShortcutMap {
1284    shortcut_map![
1285        // Activation
1286        ENTER => ActivateIntent::new(),
1287        NUMPAD_ENTER => ActivateIntent::new(),
1288        SPACE => ActivateIntent::new(),
1289
1290        // Dismissal
1291        ESCAPE => DismissIntent::new(),
1292
1293        // Keyboard traversal
1294        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        // Scrolling
1302        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
1311/// Dart's `_WidgetsAppState`.
1312pub 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    /// The route the navigator starts with.
1322    ///
1323    /// If the platform's default route name isn't `/`, it was set intentionally by the host,
1324    /// and it overrides whatever is in [`WidgetsApp::initial_route`].
1325    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    /// The default value for [`WidgetsApp::on_navigation_notification`].
1337    ///
1338    /// Does nothing and stops bubbling if the app is detached. Otherwise, updates the host of the
1339    /// view the app is in with [`NavigationNotification::can_handle_pop`] and stops bubbling.
1340    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                // Avoid updating the engine when the app isn't ready.
1348                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    /// The view the app is built in, which its navigator's Back and its word on Back are about.
1366    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        // If we use a navigator, we have a navigator key.
1390        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    /// The resolver that keeps the app's locale and delegates up to date.
1471    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    /// Dart's `_usesNavigator` branch of `build`: the navigator and the focus scope over it.
1516    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
1552/// Dart's `==` on two optional callbacks: the same `Rc` allocation, or both absent.
1553fn 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
1561/// Dart's `==` on two optional delegate lists: pairwise identity, as Dart compares the lists.
1562fn 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    /// Dart's `WidgetsApp.didPopRoute`: the app's own navigator goes back, if it has one
1581    /// and it has something to go back to, for a Back in the view the app is built in.
1582    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        // The performance overlay, the semantics debugger, and the widget inspector wait; see
1656        // PORTING.md.
1657
1658        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        // TODO(victorsanni): https://github.com/flutter/flutter/issues/180319
1666        // Use actions and shortcuts to dismiss tooltips when esc is pressed instead
1667        // of using a Focus widget.
1668        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                // This Builder exists to provide a context below the Localizations widget.
1689                // The on_generate_title callback can refer to Localizations via its context
1690                // parameter.
1691                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            // Updating the title element in the DOM is problematic in embedded and multiview
1705            // modes as the title should be managed by host apps.
1706            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        // The first preferred locale only matches by language, but the second is a perfect
1832        // match for the same language, so it supersedes.
1833        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        // A different language next: the language-only match stands.
1839        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    // ---- WidgetsApp ----
1870
1871    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    /// The `color` every test app is given.
1891    const COLOR: Color = Color::new(0xFF2196F3);
1892
1893    /// A leaf that is easy to find in the element tree.
1894    #[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    /// An [`App`] on a host with no views, for the tables that only read the target platform.
1904    fn app_of(platform: TargetPlatform) -> Rc<AppCell> {
1905        AppCell::with_platform(Rc::new(TestPlatform::new().on(platform)))
1906    }
1907
1908    /// What the shell does at start-up: the app-wide fonts, here the OS fonts, which the
1909    /// debug banner needs to paint its text.
1910    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    /// Runs `widget` as the content of every view, and the first frame of each: the
1920    /// multi-view case's start, which the one-view tester has no counterpart of.
1921    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    /// Runs frames of every view until the route transitions have settled.
1928    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    /// Dart's `find.byType(W, skipOffstage: false)`.
1937    fn built<W: 'static>() -> Finder {
1938        find::by_type::<W>().skip_offstage(false)
1939    }
1940
1941    /// The intents the shortcuts bind to `key`, in the table's order.
1942    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            // The app builds one.
1965            expect(tester, &built::<Navigator>(), finds_widgets());
1966            // The home route shows home.
1967            expect(tester, &built::<Marker>(), finds_widgets());
1968        });
1969    }
1970
1971    /// A second leaf, told apart from [`Marker`].
1972    #[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    // The home route reads `widget.home` when it builds, as Dart's `_onGenerateRoute` does, so
1982    // a new home shows on the next frame.
1983    #[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            // The new home shows.
2002            expect(tester, &built::<OtherMarker>(), finds_widgets());
2003            // The old home is gone.
2004            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    /// Flutter's assert that a `home` or `routes` app names the page transition it builds with:
2024    /// checked when the widget is turned into a `WidgetRef`, as Dart's constructor checks it.
2025    #[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    /// Android's back button and back gesture both arrive here. The app goes back while it
2110    /// has somewhere to go, and says it did not once it is at the first route, which is how
2111    /// the host knows to close the activity instead.
2112    #[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    /// Every value the app told `view`'s host of whether it handles back, in order.
2161    fn framework_handles_backs(view: &TestView) -> Vec<bool> {
2162        view.test_host().framework_handles_back()
2163    }
2164
2165    /// Flutter's app_test.dart, "WidgetsApp calls setFrameworkHandlesBack only when app is
2166    /// ready".
2167    #[test]
2168    fn widgets_app_calls_set_framework_handles_back_only_when_app_is_ready() {
2169        test_widgets(|tester| {
2170            // Start in the `resumed` state, where set_framework_handles_back should be called like
2171            // normal.
2172            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            // Set the app state to inactive, where set_framework_handles_back is still called. This
2206            // could happen when responding to a tap on a notification when the app is not active and
2207            // immediately navigating, for example.
2208            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            // Set the app state to detached, where set_framework_handles_back shouldn't be called.
2233            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    /// Flutter's navigator_test.dart, "a single route is already defaulted to false" and
2259    /// "navigating around a single Navigator with system back", on a `WidgetsApp`.
2260    #[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    /// Back in one of two views, each with its app, pops that view's navigator alone, and each
2310    /// view's host hears of its own navigator.
2311    #[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            // The banner is a debug-mode widget.
2474            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}