Skip to main content

waft_material/
app.rs

1//! Port of material_ui's `app.dart`.
2//!
3//! [`MaterialApp`], the widget a Material Design application is built from, the
4//! [`ThemeMode`] it chooses its theme by, and the [`MaterialScrollBehavior`] it installs.
5//! `MaterialApp.router` waits with `router.dart`.
6
7use std::any::{Any, TypeId};
8use std::collections::HashMap;
9use std::fmt::{self, Debug};
10use std::rc::Rc;
11use std::time::Duration;
12
13use waft_animation::{AnimationStyle, Curve, Curves};
14use waft_embedder::{
15    Brightness, Clip, Color, FontWeight, Locale, SystemUiOverlayStyle, TargetPlatform,
16    TextDecoration, TextDecorationStyle,
17};
18use waft_foundation::{App, Handle, Ref};
19use waft_painting::{Axis, TextStyle, axis_direction_to_axis};
20use waft_services::SystemChrome;
21use waft_widgets::{
22    ActionRef, AndroidOverscrollIndicator, BuildContext, Builder, DefaultSelectionStyle,
23    GenerateAppTitle, GlobalKey, GlowingOverscrollIndicator, HeroController, HeroControllerScope,
24    InitialRouteListFactory, IntoWidget, KeyRef, LocaleListResolutionCallback,
25    LocaleResolutionCallback, LocalizationsDelegateRef, MediaQuery, NavigationNotification,
26    NavigatorObserverRef, NotificationListenerCallback, RouteFactory, RouteRef, RouteSettings,
27    RouteSettingsRef, ScrollBehavior, ScrollBehaviorRef, ScrollConfiguration, ScrollableDetails,
28    ShortcutMap, SizedBox, State, StateData, StatefulWidget, StretchingOverscrollIndicator,
29    TransitionBuilder, View, WidgetBuilder, WidgetRef, WidgetsApp,
30};
31
32use waft_cupertino::DefaultCupertinoLocalizations;
33
34use crate::arc::MaterialRectArcTween;
35use crate::colors::Colors;
36use crate::material_localizations::DefaultMaterialLocalizations;
37use crate::page::MaterialPageRoute;
38use crate::scaffold::ScaffoldMessenger;
39use crate::scrollbar::Scrollbar;
40use crate::theme::{AnimatedTheme, K_THEME_ANIMATION_DURATION, Theme};
41use crate::theme_data::ThemeData;
42
43/// [`MaterialApp`] uses this [`TextStyle`] as its `DefaultTextStyle` to encourage
44/// developers to be intentional about their `DefaultTextStyle`.
45///
46/// In Material Design, most `Text` widgets are contained in `Material` widgets,
47/// which sets a specific `DefaultTextStyle`. If you're seeing text that uses
48/// this text style, consider putting your text in a `Material` widget (or
49/// another widget that sets a `DefaultTextStyle`).
50///
51/// Dart's `const _errorTextStyle`, a function because a `TextStyle` holds a `String`.
52fn error_text_style() -> TextStyle {
53    TextStyle::new()
54        .color(Color::new(0xD0FF0000))
55        .font_family("monospace")
56        .font_size(48.0)
57        .font_weight(FontWeight::W900)
58        .decoration(TextDecoration::UNDERLINE)
59        .decoration_color(Color::new(0xFFFFFF00))
60        .decoration_style(TextDecorationStyle::Double)
61        .debug_label("fallback style; consider putting your text in a Material")
62}
63
64/// Describes which theme will be used by [`MaterialApp`].
65#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
66pub enum ThemeMode {
67    /// Use either the light or dark theme based on what the user has selected in
68    /// the system settings.
69    System,
70
71    /// Always use the light mode regardless of system preference.
72    Light,
73
74    /// Always use the dark mode (if available) regardless of system preference.
75    Dark,
76}
77
78impl ThemeMode {
79    /// Whether this theme mode follows the system setting.
80    pub fn is_system(self) -> bool {
81        self == ThemeMode::System
82    }
83
84    /// Whether this theme mode forces light mode.
85    pub fn is_light(self) -> bool {
86        self == ThemeMode::Light
87    }
88
89    /// Whether this theme mode forces dark mode.
90    pub fn is_dark(self) -> bool {
91        self == ThemeMode::Dark
92    }
93}
94
95/// An application that uses Material Design.
96///
97/// A convenience widget that wraps a number of widgets that are commonly
98/// required for Material Design applications. It builds upon a [`WidgetsApp`] by
99/// adding material-design specific functionality, such as [`AnimatedTheme`] and
100/// `GridPaper`.
101///
102/// [`MaterialApp`] configures its [`WidgetsApp::text_style`] with an ugly red/yellow
103/// text style that's intended to warn the developer that their app hasn't defined
104/// a default text style. Typically the app's `Scaffold` builds a `Material` widget
105/// whose default `Material::text_style` defines the text style for the entire scaffold.
106///
107/// The [`MaterialApp`] configures the top-level `Navigator` to search for routes
108/// in the following order:
109///
110///  1. For the `/` route, the [`home`](Self::home) property, if non-null, is used.
111///
112///  2. Otherwise, the [`routes`](Self::routes) table is used, if it has an entry for the route.
113///
114///  3. Otherwise, [`on_generate_route`](Self::on_generate_route) is called, if provided. It
115///     should return a non-null value for any _valid_ route not handled by
116///     [`home`](Self::home) and [`routes`](Self::routes).
117///
118///  4. Finally if all else fails [`on_unknown_route`](Self::on_unknown_route) is called.
119///
120/// If a `Navigator` is created, at least one of these options must handle the
121/// `/` route, since it is used when an invalid [`initial_route`](Self::initial_route) is
122/// specified on startup (e.g. by another application launching this one with an intent on
123/// Android; see `Platform::default_route_name`).
124///
125/// This widget also configures the observer of the top-level `Navigator` (if
126/// any) to perform `Hero` animations.
127///
128/// The [`MaterialApp`] automatically creates a [`DefaultSelectionStyle`]. It uses
129/// the colors in the [`ThemeData::text_selection_theme`] if they are not null;
130/// otherwise, the [`MaterialApp`] sets [`DefaultSelectionStyle::selection_color`] to
131/// `ColorScheme::primary` with 0.4 opacity and
132/// [`DefaultSelectionStyle::cursor_color`] to `ColorScheme::primary`.
133///
134/// If [`home`](Self::home), [`routes`](Self::routes),
135/// [`on_generate_route`](Self::on_generate_route), and
136/// [`on_unknown_route`](Self::on_unknown_route) are all null, and
137/// [`builder`](Self::builder) is not null, then no `Navigator` is created.
138///
139/// ```text
140/// MaterialApp::new()
141///     .debug_show_checked_mode_banner(false)
142///     .home(Scaffold::new().body(Center::new().child(Text::new("Hello World"))))
143/// ```
144///
145/// ## Troubleshooting
146///
147/// ### Why is my app's text red with yellow underlines?
148///
149/// `Text` widgets that lack a `Material` ancestor will be rendered with an ugly
150/// red/yellow text style.
151///
152/// The typical fix is to give the widget a `Scaffold` ancestor. The `Scaffold` creates
153/// a `Material` widget that defines its default text style.
154///
155/// See also:
156///
157///  * `Scaffold`, which provides standard app elements like an `AppBar` and a `Drawer`.
158///  * `Navigator`, which is used to manage the app's stack of pages.
159///  * [`MaterialPageRoute`], which defines an app page that transitions in a material-specific way.
160///  * [`WidgetsApp`], which defines the basic app elements but does not depend on the material library.
161///
162/// The four themes are shared, as Dart shares the one [`ThemeData`] object: the theme a build
163/// selects is the one given, so `ThemeData::localize`'s identity cache hits across rebuilds.
164pub struct MaterialApp {
165    /// See [`Widget::key`](waft_widgets::Widget::key).
166    pub key: Option<KeyRef>,
167
168    /// See [`WidgetsApp::navigator_key`].
169    pub navigator_key: Option<GlobalKey>,
170
171    /// A key to use when building the [`ScaffoldMessenger`].
172    ///
173    /// If a [`scaffold_messenger_key`](Self::scaffold_messenger_key) is specified, the
174    /// [`ScaffoldMessenger`] can be directly manipulated without first obtaining it from a
175    /// [`BuildContext`] via [`ScaffoldMessenger::of`]: from the
176    /// [`scaffold_messenger_key`](Self::scaffold_messenger_key), use
177    /// `GlobalKey::current_state`.
178    pub scaffold_messenger_key: Option<GlobalKey>,
179
180    /// See [`WidgetsApp::home`].
181    pub home: Option<WidgetRef>,
182
183    /// The application's top-level routing table.
184    ///
185    /// When a named route is pushed with `Navigator::push_named`, the route name is
186    /// looked up in this map. If the name is present, the associated
187    /// [`WidgetBuilder`] is used to construct a [`MaterialPageRoute`] that
188    /// performs an appropriate transition, including `Hero` animations, to the
189    /// new route.
190    ///
191    /// See [`WidgetsApp::routes`].
192    pub routes: HashMap<String, WidgetBuilder>,
193
194    /// See [`WidgetsApp::initial_route`].
195    pub initial_route: Option<String>,
196
197    /// See [`WidgetsApp::on_generate_route`].
198    pub on_generate_route: Option<RouteFactory>,
199
200    /// See [`WidgetsApp::on_generate_initial_routes`].
201    pub on_generate_initial_routes: Option<InitialRouteListFactory>,
202
203    /// See [`WidgetsApp::on_unknown_route`].
204    pub on_unknown_route: Option<RouteFactory>,
205
206    /// See [`WidgetsApp::on_navigation_notification`].
207    pub on_navigation_notification: Option<NotificationListenerCallback<NavigationNotification>>,
208
209    /// See [`WidgetsApp::navigator_observers`].
210    pub navigator_observers: Vec<NavigatorObserverRef>,
211
212    /// See [`WidgetsApp::builder`].
213    ///
214    /// Material specific features such as `showDialog` and `showMenu`, and widgets
215    /// such as `Tooltip`, `PopupMenuButton`, also require a `Navigator` to properly
216    /// function.
217    pub builder: Option<TransitionBuilder>,
218
219    /// See [`WidgetsApp::title`].
220    ///
221    /// This value is passed unmodified to [`WidgetsApp::title`].
222    pub title: Option<String>,
223
224    /// See [`WidgetsApp::on_generate_title`].
225    ///
226    /// This value is passed unmodified to [`WidgetsApp::on_generate_title`].
227    pub on_generate_title: Option<GenerateAppTitle>,
228
229    /// Default visual properties, like colors fonts and shapes, for this app's
230    /// material widgets.
231    ///
232    /// A second [`dark_theme`](Self::dark_theme) [`ThemeData`] value, which is used to provide
233    /// a dark version of the user interface can also be specified.
234    /// [`theme_mode`](Self::theme_mode) will control which theme will be used if a
235    /// [`dark_theme`](Self::dark_theme) is provided.
236    ///
237    /// The default value of this property is the value of [`ThemeData::light`].
238    ///
239    /// See also:
240    ///
241    ///  * [`theme_mode`](Self::theme_mode), which controls which theme to use.
242    ///  * `MediaQueryData::platform_brightness`, which indicates the platform's
243    ///    desired brightness and is used to automatically toggle between
244    ///    [`theme`](Self::theme) and [`dark_theme`](Self::dark_theme) in [`MaterialApp`].
245    ///  * [`ThemeData::brightness`], which indicates the [`Brightness`] of a theme's
246    ///    colors.
247    pub theme: Option<Rc<ThemeData>>,
248
249    /// The [`ThemeData`] to use when a 'dark mode' is requested by the system.
250    ///
251    /// Some host platforms allow the users to select a system-wide 'dark mode',
252    /// or the application may want to offer the user the ability to choose a
253    /// dark theme just for this application. This is theme that will be used for
254    /// such cases. [`theme_mode`](Self::theme_mode) will control which theme will be used.
255    ///
256    /// This theme should have a [`ThemeData::brightness`] set to [`Brightness::Dark`].
257    ///
258    /// Uses [`theme`](Self::theme) instead when null. Defaults to the value of
259    /// [`ThemeData::light`] when both [`dark_theme`](Self::dark_theme) and
260    /// [`theme`](Self::theme) are null.
261    ///
262    /// See also:
263    ///
264    ///  * [`theme_mode`](Self::theme_mode), which controls which theme to use.
265    ///  * `MediaQueryData::platform_brightness`, which indicates the platform's
266    ///    desired brightness and is used to automatically toggle between
267    ///    [`theme`](Self::theme) and [`dark_theme`](Self::dark_theme) in [`MaterialApp`].
268    ///  * [`ThemeData::brightness`], which is typically set to the value of
269    ///    `MediaQueryData::platform_brightness`.
270    pub dark_theme: Option<Rc<ThemeData>>,
271
272    /// The [`ThemeData`] to use when 'high contrast' is requested by the system.
273    ///
274    /// Some host platforms (for example, iOS) allow the users to increase
275    /// contrast through an accessibility setting.
276    ///
277    /// Uses [`theme`](Self::theme) instead when null.
278    ///
279    /// See also:
280    ///
281    ///  * `MediaQueryData::high_contrast`, which indicates the platform's
282    ///    desire to increase contrast.
283    pub high_contrast_theme: Option<Rc<ThemeData>>,
284
285    /// The [`ThemeData`] to use when a 'dark mode' and 'high contrast' is requested
286    /// by the system.
287    ///
288    /// Some host platforms (for example, iOS) allow the users to increase
289    /// contrast through an accessibility setting.
290    ///
291    /// This theme should have a [`ThemeData::brightness`] set to [`Brightness::Dark`].
292    ///
293    /// Uses [`dark_theme`](Self::dark_theme) instead when null.
294    ///
295    /// See also:
296    ///
297    ///  * `MediaQueryData::high_contrast`, which indicates the platform's
298    ///    desire to increase contrast.
299    pub high_contrast_dark_theme: Option<Rc<ThemeData>>,
300
301    /// Determines which theme will be used by the application if both [`theme`](Self::theme)
302    /// and [`dark_theme`](Self::dark_theme) are provided.
303    ///
304    /// If set to [`ThemeMode::System`], the choice of which theme to use will
305    /// be based on the user's system preferences. If the [`MediaQuery::platform_brightness_of`]
306    /// is [`Brightness::Light`], [`theme`](Self::theme) will be used. If it is
307    /// [`Brightness::Dark`], [`dark_theme`](Self::dark_theme) will be used (unless it is null,
308    /// in which case [`theme`](Self::theme) will be used.
309    ///
310    /// If set to [`ThemeMode::Light`] the [`theme`](Self::theme) will always be used,
311    /// regardless of the user's system preference.
312    ///
313    /// If set to [`ThemeMode::Dark`] the [`dark_theme`](Self::dark_theme) will be used
314    /// regardless of the user's system preference. If [`dark_theme`](Self::dark_theme) is null
315    /// then it will fallback to using [`theme`](Self::theme).
316    ///
317    /// The default value is [`ThemeMode::System`].
318    ///
319    /// See also:
320    ///
321    ///  * [`theme`](Self::theme), which is used when a light mode is selected.
322    ///  * [`dark_theme`](Self::dark_theme), which is used when a dark mode is selected.
323    ///  * [`ThemeData::brightness`], which indicates to various parts of the
324    ///    system what kind of theme is being used.
325    pub theme_mode: Option<ThemeMode>,
326
327    /// The duration of animated theme changes.
328    ///
329    /// When the theme changes (either by the [`theme`](Self::theme),
330    /// [`dark_theme`](Self::dark_theme) or [`theme_mode`](Self::theme_mode) parameters
331    /// changing) it is animated to the new theme over time.
332    /// The [`theme_animation_duration`](Self::theme_animation_duration) determines how long
333    /// this animation takes.
334    ///
335    /// To have the theme change immediately, you can set this to [`Duration::ZERO`].
336    ///
337    /// The default is [`K_THEME_ANIMATION_DURATION`].
338    ///
339    /// See also:
340    ///   [`theme_animation_curve`](Self::theme_animation_curve), which defines the curve used
341    ///   for the animation.
342    pub theme_animation_duration: Duration,
343
344    /// The curve to apply when animating theme changes.
345    ///
346    /// The default is [`Curves::linear`].
347    ///
348    /// This is ignored if [`theme_animation_duration`](Self::theme_animation_duration) is
349    /// [`Duration::ZERO`].
350    ///
351    /// See also:
352    ///   [`theme_animation_duration`](Self::theme_animation_duration), which defines how long
353    ///   the animation is.
354    pub theme_animation_curve: Rc<dyn Curve>,
355
356    /// See [`WidgetsApp::color`].
357    pub color: Option<Color>,
358
359    /// See [`WidgetsApp::locale`].
360    pub locale: Option<Locale>,
361
362    /// See [`WidgetsApp::localizations_delegates`].
363    ///
364    /// Delegates that produce `WidgetsLocalizations` and `MaterialLocalizations`
365    /// are included automatically. Apps can provide their own versions of these
366    /// localizations by creating implementations of `LocalizationsDelegate` whose load
367    /// methods return custom versions of `WidgetsLocalizations` or `MaterialLocalizations`.
368    ///
369    /// Only the first delegate of each `LocalizationsDelegate` type is used and the
370    /// automatically included delegates are added to the end of the app's
371    /// [`localizations_delegates`](Self::localizations_delegates) list, so a delegate given
372    /// here overrides the included one of its type.
373    ///
374    /// See also:
375    ///
376    ///  * [`supported_locales`](Self::supported_locales), which must be specified along with
377    ///    [`localizations_delegates`](Self::localizations_delegates).
378    pub localizations_delegates: Option<Vec<LocalizationsDelegateRef>>,
379
380    /// See [`WidgetsApp::locale_list_resolution_callback`].
381    ///
382    /// This callback is passed along to the [`WidgetsApp`] built by this widget.
383    pub locale_list_resolution_callback: Option<LocaleListResolutionCallback>,
384
385    /// See [`WidgetsApp::locale_resolution_callback`].
386    ///
387    /// This callback is passed along to the [`WidgetsApp`] built by this widget.
388    pub locale_resolution_callback: Option<LocaleResolutionCallback>,
389
390    /// See [`WidgetsApp::supported_locales`].
391    ///
392    /// It is passed along unmodified to the [`WidgetsApp`] built by this widget.
393    ///
394    /// See also:
395    ///
396    ///  * [`localizations_delegates`](Self::localizations_delegates), which must be specified
397    ///    for localized applications.
398    pub supported_locales: Vec<Locale>,
399
400    /// Turns on a performance overlay.
401    ///
402    /// See also:
403    ///
404    ///  * <https://flutter.dev/to/performance-overlay>
405    pub show_performance_overlay: bool,
406
407    /// Turns on checkerboarding of raster cache images.
408    pub checkerboard_raster_cache_images: bool,
409
410    /// Turns on checkerboarding of layers rendered to offscreen bitmaps.
411    pub checkerboard_offscreen_layers: bool,
412
413    /// Turns on an overlay that shows the accessibility information
414    /// reported by the framework.
415    pub show_semantics_debugger: bool,
416
417    /// See [`WidgetsApp::debug_show_checked_mode_banner`].
418    pub debug_show_checked_mode_banner: bool,
419
420    /// See [`WidgetsApp::shortcuts`].
421    pub shortcuts: Option<ShortcutMap>,
422
423    /// See [`WidgetsApp::actions`].
424    pub actions: Option<HashMap<TypeId, ActionRef>>,
425
426    /// See [`WidgetsApp::restoration_scope_id`].
427    pub restoration_scope_id: Option<String>,
428
429    /// The default [`ScrollBehavior`] for the application.
430    ///
431    /// When null, defaults to [`MaterialScrollBehavior`].
432    ///
433    /// See also:
434    ///
435    ///  * [`ScrollConfiguration`], which controls how `Scrollable` widgets behave
436    ///    in a subtree.
437    pub scroll_behavior: Option<ScrollBehaviorRef>,
438
439    /// Turns on a `GridPaper` overlay that paints a baseline grid
440    /// Material apps.
441    ///
442    /// Only available in debug mode.
443    ///
444    /// See also:
445    ///
446    ///  * <https://material.io/design/layout/spacing-methods.html>
447    pub debug_show_material_grid: bool,
448
449    /// Dart's deprecated `useInheritedMediaQuery`. This setting is ignored.
450    ///
451    /// The widget never introduces its own `MediaQuery`; the `View` widget takes
452    /// care of that.
453    pub use_inherited_media_query: bool,
454
455    /// Used to override the theme animation curve and duration.
456    ///
457    /// If [`AnimationStyle::duration`] is provided, it will be used to override
458    /// the theme animation duration in the underlying [`AnimatedTheme`] widget.
459    /// If it is null, then [`theme_animation_duration`](Self::theme_animation_duration) will
460    /// be used. Otherwise, defaults to 200ms.
461    ///
462    /// If [`AnimationStyle::curve`] is provided, it will be used to override
463    /// the theme animation curve in the underlying [`AnimatedTheme`] widget.
464    /// If it is null, then [`theme_animation_curve`](Self::theme_animation_curve) will be
465    /// used. Otherwise, defaults to [`Curves::linear`].
466    ///
467    /// To disable the theme animation, use [`AnimationStyle::NO_ANIMATION`].
468    pub theme_animation_style: Option<AnimationStyle>,
469}
470
471impl Default for MaterialApp {
472    fn default() -> MaterialApp {
473        MaterialApp {
474            key: None,
475            navigator_key: None,
476            scaffold_messenger_key: None,
477            home: None,
478            routes: HashMap::new(),
479            initial_route: None,
480            on_generate_route: None,
481            on_generate_initial_routes: None,
482            on_unknown_route: None,
483            on_navigation_notification: None,
484            navigator_observers: Vec::new(),
485            builder: None,
486            title: Some(String::new()),
487            on_generate_title: None,
488            theme: None,
489            dark_theme: None,
490            high_contrast_theme: None,
491            high_contrast_dark_theme: None,
492            theme_mode: Some(ThemeMode::System),
493            theme_animation_duration: K_THEME_ANIMATION_DURATION,
494            theme_animation_curve: Curves::linear(),
495            color: None,
496            locale: None,
497            localizations_delegates: None,
498            locale_list_resolution_callback: None,
499            locale_resolution_callback: None,
500            supported_locales: vec![Locale::new("en").country_code("US")],
501            show_performance_overlay: false,
502            checkerboard_raster_cache_images: false,
503            checkerboard_offscreen_layers: false,
504            show_semantics_debugger: false,
505            debug_show_checked_mode_banner: true,
506            shortcuts: None,
507            actions: None,
508            restoration_scope_id: None,
509            scroll_behavior: None,
510            debug_show_material_grid: false,
511            use_inherited_media_query: false,
512            theme_animation_style: None,
513        }
514    }
515}
516
517impl MaterialApp {
518    /// Creates a MaterialApp; Dart's named arguments are the setters.
519    ///
520    /// At least one of [`home`](Self::home), [`routes`](Self::routes),
521    /// [`on_generate_route`](Self::on_generate_route), or [`builder`](Self::builder) must be
522    /// set. If only [`routes`](Self::routes) is given, it must include an entry for
523    /// `Navigator::DEFAULT_ROUTE_NAME` (`/`), since that is the route used when the
524    /// application is launched with an intent that specifies an otherwise unsupported route.
525    ///
526    /// This class creates an instance of [`WidgetsApp`].
527    pub fn new() -> MaterialApp {
528        MaterialApp::default()
529    }
530
531    /// Dart `MaterialApp(key:)`.
532    pub fn key(mut self, key: KeyRef) -> MaterialApp {
533        self.key = Some(key);
534        self
535    }
536
537    /// Dart `MaterialApp(navigatorKey:)`.
538    pub fn navigator_key(mut self, navigator_key: GlobalKey) -> MaterialApp {
539        self.navigator_key = Some(navigator_key);
540        self
541    }
542
543    /// Dart `MaterialApp(scaffoldMessengerKey:)`.
544    pub fn scaffold_messenger_key(mut self, scaffold_messenger_key: GlobalKey) -> MaterialApp {
545        self.scaffold_messenger_key = Some(scaffold_messenger_key);
546        self
547    }
548
549    /// Dart `MaterialApp(home:)`.
550    #[cfg_attr(debug_assertions, track_caller)]
551    pub fn home<K>(mut self, home: impl IntoWidget<K>) -> MaterialApp {
552        self.home = Some(home.into_widget());
553        self
554    }
555
556    /// Dart `MaterialApp(routes:)`.
557    pub fn routes(
558        mut self,
559        routes: impl IntoIterator<Item = (String, WidgetBuilder)>,
560    ) -> MaterialApp {
561        self.routes = routes.into_iter().collect();
562        self
563    }
564
565    /// Dart `MaterialApp(initialRoute:)`.
566    pub fn initial_route(mut self, initial_route: impl Into<String>) -> MaterialApp {
567        self.initial_route = Some(initial_route.into());
568        self
569    }
570
571    /// Dart `MaterialApp(onGenerateRoute:)`.
572    pub fn on_generate_route(
573        mut self,
574        on_generate_route: impl Fn(&mut App, &RouteSettings) -> Option<RouteRef> + 'static,
575    ) -> MaterialApp {
576        self.on_generate_route = Some(Rc::new(on_generate_route));
577        self
578    }
579
580    /// Dart `MaterialApp(onGenerateInitialRoutes:)`.
581    pub fn on_generate_initial_routes(
582        mut self,
583        on_generate_initial_routes: impl Fn(&mut App, &str) -> Vec<RouteRef> + 'static,
584    ) -> MaterialApp {
585        self.on_generate_initial_routes = Some(Rc::new(on_generate_initial_routes));
586        self
587    }
588
589    /// Dart `MaterialApp(onUnknownRoute:)`.
590    pub fn on_unknown_route(
591        mut self,
592        on_unknown_route: impl Fn(&mut App, &RouteSettings) -> Option<RouteRef> + 'static,
593    ) -> MaterialApp {
594        self.on_unknown_route = Some(Rc::new(on_unknown_route));
595        self
596    }
597
598    /// Dart `MaterialApp(onNavigationNotification:)`.
599    pub fn on_navigation_notification(
600        mut self,
601        on_navigation_notification: impl Fn(&mut App, &NavigationNotification) -> bool + 'static,
602    ) -> MaterialApp {
603        self.on_navigation_notification = Some(Rc::new(on_navigation_notification));
604        self
605    }
606
607    /// Dart `MaterialApp(navigatorObservers:)`.
608    pub fn navigator_observers(
609        mut self,
610        navigator_observers: impl IntoIterator<Item = NavigatorObserverRef>,
611    ) -> MaterialApp {
612        self.navigator_observers = navigator_observers.into_iter().collect();
613        self
614    }
615
616    /// Dart `MaterialApp(builder:)`.
617    pub fn builder(
618        mut self,
619        builder: impl Fn(&mut App, BuildContext, Option<&WidgetRef>) -> WidgetRef + 'static,
620    ) -> MaterialApp {
621        self.builder = Some(Rc::new(builder));
622        self
623    }
624
625    /// Dart `MaterialApp(title:)`.
626    pub fn title(mut self, title: impl Into<String>) -> MaterialApp {
627        self.title = Some(title.into());
628        self
629    }
630
631    /// Dart `MaterialApp(onGenerateTitle:)`.
632    pub fn on_generate_title(
633        mut self,
634        on_generate_title: impl Fn(&mut App, BuildContext) -> String + 'static,
635    ) -> MaterialApp {
636        self.on_generate_title = Some(Rc::new(on_generate_title));
637        self
638    }
639
640    /// Dart `MaterialApp(theme:)`.
641    pub fn theme(mut self, theme: impl Into<Rc<ThemeData>>) -> MaterialApp {
642        self.theme = Some(theme.into());
643        self
644    }
645
646    /// Dart `MaterialApp(darkTheme:)`.
647    pub fn dark_theme(mut self, dark_theme: impl Into<Rc<ThemeData>>) -> MaterialApp {
648        self.dark_theme = Some(dark_theme.into());
649        self
650    }
651
652    /// Dart `MaterialApp(highContrastTheme:)`.
653    pub fn high_contrast_theme(
654        mut self,
655        high_contrast_theme: impl Into<Rc<ThemeData>>,
656    ) -> MaterialApp {
657        self.high_contrast_theme = Some(high_contrast_theme.into());
658        self
659    }
660
661    /// Dart `MaterialApp(highContrastDarkTheme:)`.
662    pub fn high_contrast_dark_theme(
663        mut self,
664        high_contrast_dark_theme: impl Into<Rc<ThemeData>>,
665    ) -> MaterialApp {
666        self.high_contrast_dark_theme = Some(high_contrast_dark_theme.into());
667        self
668    }
669
670    /// Dart `MaterialApp(themeMode:)`.
671    pub fn theme_mode(mut self, theme_mode: ThemeMode) -> MaterialApp {
672        self.theme_mode = Some(theme_mode);
673        self
674    }
675
676    /// Dart `MaterialApp(themeAnimationDuration:)`.
677    pub fn theme_animation_duration(mut self, theme_animation_duration: Duration) -> MaterialApp {
678        self.theme_animation_duration = theme_animation_duration;
679        self
680    }
681
682    /// Dart `MaterialApp(themeAnimationCurve:)`.
683    pub fn theme_animation_curve(mut self, theme_animation_curve: Rc<dyn Curve>) -> MaterialApp {
684        self.theme_animation_curve = theme_animation_curve;
685        self
686    }
687
688    /// Dart `MaterialApp(color:)`.
689    pub fn color(mut self, color: Color) -> MaterialApp {
690        self.color = Some(color);
691        self
692    }
693
694    /// Dart `MaterialApp(locale:)`.
695    pub fn locale(mut self, locale: Locale) -> MaterialApp {
696        self.locale = Some(locale);
697        self
698    }
699
700    /// Dart `MaterialApp(localizationsDelegates:)`.
701    pub fn localizations_delegates(
702        mut self,
703        localizations_delegates: impl IntoIterator<Item = LocalizationsDelegateRef>,
704    ) -> MaterialApp {
705        self.localizations_delegates = Some(localizations_delegates.into_iter().collect());
706        self
707    }
708
709    /// Dart `MaterialApp(localeListResolutionCallback:)`.
710    pub fn locale_list_resolution_callback(
711        mut self,
712        locale_list_resolution_callback: impl Fn(Option<&[Locale]>, &[Locale]) -> Option<Locale>
713        + 'static,
714    ) -> MaterialApp {
715        self.locale_list_resolution_callback = Some(Rc::new(locale_list_resolution_callback));
716        self
717    }
718
719    /// Dart `MaterialApp(localeResolutionCallback:)`.
720    pub fn locale_resolution_callback(
721        mut self,
722        locale_resolution_callback: impl Fn(Option<&Locale>, &[Locale]) -> Option<Locale> + 'static,
723    ) -> MaterialApp {
724        self.locale_resolution_callback = Some(Rc::new(locale_resolution_callback));
725        self
726    }
727
728    /// Dart `MaterialApp(supportedLocales:)`.
729    pub fn supported_locales(
730        mut self,
731        supported_locales: impl IntoIterator<Item = Locale>,
732    ) -> MaterialApp {
733        self.supported_locales = supported_locales.into_iter().collect();
734        self
735    }
736
737    /// Dart `MaterialApp(debugShowMaterialGrid:)`.
738    pub fn debug_show_material_grid(mut self, debug_show_material_grid: bool) -> MaterialApp {
739        self.debug_show_material_grid = debug_show_material_grid;
740        self
741    }
742
743    /// Dart `MaterialApp(showPerformanceOverlay:)`.
744    pub fn show_performance_overlay(mut self, show_performance_overlay: bool) -> MaterialApp {
745        self.show_performance_overlay = show_performance_overlay;
746        self
747    }
748
749    /// Dart `MaterialApp(checkerboardRasterCacheImages:)`.
750    pub fn checkerboard_raster_cache_images(
751        mut self,
752        checkerboard_raster_cache_images: bool,
753    ) -> MaterialApp {
754        self.checkerboard_raster_cache_images = checkerboard_raster_cache_images;
755        self
756    }
757
758    /// Dart `MaterialApp(checkerboardOffscreenLayers:)`.
759    pub fn checkerboard_offscreen_layers(
760        mut self,
761        checkerboard_offscreen_layers: bool,
762    ) -> MaterialApp {
763        self.checkerboard_offscreen_layers = checkerboard_offscreen_layers;
764        self
765    }
766
767    /// Dart `MaterialApp(showSemanticsDebugger:)`.
768    pub fn show_semantics_debugger(mut self, show_semantics_debugger: bool) -> MaterialApp {
769        self.show_semantics_debugger = show_semantics_debugger;
770        self
771    }
772
773    /// Dart `MaterialApp(debugShowCheckedModeBanner:)`.
774    pub fn debug_show_checked_mode_banner(
775        mut self,
776        debug_show_checked_mode_banner: bool,
777    ) -> MaterialApp {
778        self.debug_show_checked_mode_banner = debug_show_checked_mode_banner;
779        self
780    }
781
782    /// Dart `MaterialApp(shortcuts:)`.
783    pub fn shortcuts(mut self, shortcuts: ShortcutMap) -> MaterialApp {
784        self.shortcuts = Some(shortcuts);
785        self
786    }
787
788    /// Dart `MaterialApp(actions:)`.
789    pub fn actions(mut self, actions: HashMap<TypeId, ActionRef>) -> MaterialApp {
790        self.actions = Some(actions);
791        self
792    }
793
794    /// Dart `MaterialApp(restorationScopeId:)`.
795    pub fn restoration_scope_id(mut self, restoration_scope_id: impl Into<String>) -> MaterialApp {
796        self.restoration_scope_id = Some(restoration_scope_id.into());
797        self
798    }
799
800    /// Dart `MaterialApp(scrollBehavior:)`.
801    pub fn scroll_behavior(mut self, scroll_behavior: ScrollBehaviorRef) -> MaterialApp {
802        self.scroll_behavior = Some(scroll_behavior);
803        self
804    }
805
806    /// Dart `MaterialApp(useInheritedMediaQuery:)`, which is ignored.
807    pub fn use_inherited_media_query(mut self, use_inherited_media_query: bool) -> MaterialApp {
808        self.use_inherited_media_query = use_inherited_media_query;
809        self
810    }
811
812    /// Dart `MaterialApp(themeAnimationStyle:)`.
813    pub fn theme_animation_style(mut self, theme_animation_style: AnimationStyle) -> MaterialApp {
814        self.theme_animation_style = Some(theme_animation_style);
815        self
816    }
817
818    /// The [`HeroController`] used for Material page transitions.
819    ///
820    /// Used by the [`MaterialApp`].
821    pub fn create_material_hero_controller(app: &mut App) -> Ref<HeroController> {
822        HeroController::new(app).create_rect_tween(
823            app,
824            Rc::new(|_app, begin, end| Rc::new(MaterialRectArcTween::new(begin, end))),
825        )
826    }
827}
828
829impl Debug for MaterialApp {
830    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
831        f.debug_struct("MaterialApp")
832            .field("title", &self.title)
833            .field("themeMode", &self.theme_mode)
834            .field("locale", &self.locale)
835            .field("restorationScopeId", &self.restoration_scope_id)
836            .finish_non_exhaustive()
837    }
838}
839
840impl StatefulWidget for MaterialApp {
841    type State = MaterialAppState;
842
843    fn key(&self) -> Option<&KeyRef> {
844        self.key.as_ref()
845    }
846
847    fn create_state(&self) -> MaterialAppState {
848        MaterialAppState {
849            state: StateData::new(),
850            hero_controller: None,
851        }
852    }
853}
854
855/// Describes how `Scrollable` widgets behave for [`MaterialApp`]s.
856///
857/// Setting a [`MaterialScrollBehavior`] will apply a
858/// [`GlowingOverscrollIndicator`] to `Scrollable` descendants when executing on
859/// [`TargetPlatform::Android`] and [`TargetPlatform::Fuchsia`].
860///
861/// When using the desktop platform, if the `Scrollable` widget scrolls in the
862/// [`Axis::Vertical`], a [`Scrollbar`] is applied.
863///
864/// If the scroll direction is [`Axis::Horizontal`] scroll views are less
865/// discoverable, so consider adding a Scrollbar in these cases, either directly
866/// or through the [`build_scrollbar`](ScrollBehavior::build_scrollbar) method.
867///
868/// [`ThemeData::use_material3`] specifies the
869/// overscroll indicator that is used on [`TargetPlatform::Android`], which
870/// defaults to true, resulting in a [`StretchingOverscrollIndicator`]. Setting
871/// [`ThemeData::use_material3`] to false will instead use a
872/// [`GlowingOverscrollIndicator`].
873///
874/// See also:
875///
876///  * [`ScrollBehavior`], the default scrolling behavior extended by this class.
877#[derive(Clone, Copy, Debug, Default)]
878pub struct MaterialScrollBehavior;
879
880impl MaterialScrollBehavior {
881    /// Creates a MaterialScrollBehavior that decorates `Scrollable`s with
882    /// [`StretchingOverscrollIndicator`]s and [`Scrollbar`]s based on the current
883    /// platform and provided [`ScrollableDetails`].
884    ///
885    /// [`ThemeData::use_material3`] specifies the
886    /// overscroll indicator that is used on [`TargetPlatform::Android`], which
887    /// defaults to true, resulting in a [`StretchingOverscrollIndicator`]. Setting
888    /// [`ThemeData::use_material3`] to false will instead use a
889    /// [`GlowingOverscrollIndicator`].
890    pub const fn new() -> MaterialScrollBehavior {
891        MaterialScrollBehavior
892    }
893}
894
895impl ScrollBehavior for MaterialScrollBehavior {
896    fn as_any(&self) -> &dyn Any {
897        self
898    }
899
900    fn get_platform(&self, app: &mut App, context: BuildContext) -> TargetPlatform {
901        Theme::of(app, context).platform
902    }
903
904    fn build_scrollbar(
905        &self,
906        app: &mut App,
907        context: BuildContext,
908        child: WidgetRef,
909        details: &ScrollableDetails,
910    ) -> WidgetRef {
911        // When modifying this function, consider modifying the implementation in
912        // the base class ScrollBehavior as well.
913        match axis_direction_to_axis(details.direction) {
914            Axis::Horizontal => child,
915            Axis::Vertical => match self.get_platform(app, context) {
916                TargetPlatform::Linux | TargetPlatform::MacOS | TargetPlatform::Windows => {
917                    debug_assert!(details.controller.is_some());
918                    let mut scrollbar = Scrollbar::new(child);
919                    if let Some(controller) = details.controller.clone() {
920                        scrollbar = scrollbar.controller(controller);
921                    }
922                    scrollbar.into_widget()
923                }
924                TargetPlatform::Android | TargetPlatform::Fuchsia | TargetPlatform::IOS => child,
925            },
926        }
927    }
928
929    fn build_overscroll_indicator(
930        &self,
931        app: &mut App,
932        context: BuildContext,
933        child: WidgetRef,
934        details: &ScrollableDetails,
935    ) -> WidgetRef {
936        // When modifying this function, consider modifying the implementation in
937        // the base class ScrollBehavior as well.
938        let indicator = if Theme::of(app, context).use_material3 {
939            AndroidOverscrollIndicator::Stretch
940        } else {
941            AndroidOverscrollIndicator::Glow
942        };
943        match self.get_platform(app, context) {
944            TargetPlatform::IOS
945            | TargetPlatform::Linux
946            | TargetPlatform::MacOS
947            | TargetPlatform::Windows => return child,
948            TargetPlatform::Android => match indicator {
949                AndroidOverscrollIndicator::Stretch => {
950                    return StretchingOverscrollIndicator::new(details.direction)
951                        .clip_behavior(details.decoration_clip_behavior.unwrap_or(Clip::HardEdge))
952                        .child(child)
953                        .into_widget();
954                }
955                AndroidOverscrollIndicator::Glow => {}
956            },
957            TargetPlatform::Fuchsia => {}
958        }
959        GlowingOverscrollIndicator::new(
960            details.direction,
961            Theme::of(app, context).color_scheme.secondary(),
962        )
963        .child(child)
964        .into_widget()
965    }
966}
967
968/// Dart's `_MaterialAppState`.
969pub struct MaterialAppState {
970    state: StateData<MaterialApp>,
971    hero_controller: Option<Ref<HeroController>>,
972}
973
974impl MaterialAppState {
975    fn hero_controller(self: Handle<Self>, app: &App) -> Ref<HeroController> {
976        app.get(self)
977            .hero_controller
978            .clone()
979            .expect("init_state creates the controller")
980    }
981
982    /// Combine the Localizations for Material with the ones contributed
983    /// by the [`MaterialApp::localizations_delegates`] parameter, if any. Only the first
984    /// delegate of a particular `LocalizationsDelegate` type is loaded so the
985    /// [`MaterialApp::localizations_delegates`] parameter can be used to override
986    /// `_MaterialLocalizationsDelegate`.
987    fn localizations_delegates(self: Handle<Self>, app: &App) -> Vec<LocalizationsDelegateRef> {
988        let mut delegates = self
989            .widget(app)
990            .localizations_delegates
991            .clone()
992            .unwrap_or_default();
993        delegates.push(DefaultMaterialLocalizations::delegate());
994        delegates.push(DefaultCupertinoLocalizations::delegate());
995        delegates
996    }
997
998    fn theme_builder(self: Handle<Self>, app: &mut App, context: BuildContext) -> Rc<ThemeData> {
999        // Resolve which theme to use based on brightness and high contrast.
1000        let mode = self.widget(app).theme_mode.unwrap_or(ThemeMode::System);
1001        let platform_brightness = MediaQuery::platform_brightness_of(app, context);
1002        let use_dark_theme = mode == ThemeMode::Dark
1003            || (mode == ThemeMode::System && platform_brightness == Brightness::Dark);
1004        let high_contrast = MediaQuery::high_contrast_of(app, context);
1005        let widget = self.widget(app);
1006        let mut theme: Option<&Rc<ThemeData>> = None;
1007        if use_dark_theme && high_contrast && widget.high_contrast_dark_theme.is_some() {
1008            theme = widget.high_contrast_dark_theme.as_ref();
1009        } else if use_dark_theme && widget.dark_theme.is_some() {
1010            theme = widget.dark_theme.as_ref();
1011        } else if high_contrast && widget.high_contrast_theme.is_some() {
1012            theme = widget.high_contrast_theme.as_ref();
1013        }
1014        let theme = match theme.or(widget.theme.as_ref()) {
1015            Some(theme) => Rc::clone(theme),
1016            None => Rc::new(ThemeData::new(app)),
1017        };
1018        if let Some(view) = View::maybe_of(app, context) {
1019            SystemChrome::set_system_ui_overlay_style(
1020                app,
1021                view.id(),
1022                match theme.brightness() {
1023                    Brightness::Dark => &SystemUiOverlayStyle::LIGHT,
1024                    Brightness::Light => &SystemUiOverlayStyle::DARK,
1025                },
1026            );
1027        }
1028
1029        theme
1030    }
1031
1032    fn material_builder(
1033        self: Handle<Self>,
1034        app: &mut App,
1035        context: BuildContext,
1036        child: Option<&WidgetRef>,
1037    ) -> WidgetRef {
1038        let theme = self.theme_builder(app, context);
1039        // Dart's deprecated `withOpacity`: its rounding to an 8-bit alpha is part of the
1040        // behaviour being ported.
1041        #[allow(deprecated)]
1042        let effective_selection_color = theme
1043            .text_selection_theme
1044            .selection_color
1045            .unwrap_or_else(|| theme.color_scheme.primary().with_opacity(0.40));
1046        let effective_cursor_color = theme
1047            .text_selection_theme
1048            .cursor_color
1049            .unwrap_or(theme.color_scheme.primary());
1050
1051        let mut child_widget = child
1052            .cloned()
1053            .unwrap_or_else(|| SizedBox::shrink().into_widget());
1054
1055        if let Some(builder) = self.widget(app).builder.clone() {
1056            let child = child.cloned();
1057            child_widget = Builder::new(move |app, context| {
1058                // Why are we surrounding a builder with a builder?
1059                //
1060                // The widget.builder may contain code that invokes
1061                // Theme.of(), which should return the theme we selected
1062                // above in AnimatedTheme. However, if we invoke
1063                // widget.builder() directly as the child of AnimatedTheme
1064                // then there is no BuildContext separating them, the
1065                // widget.builder() will not find the theme. Therefore, we
1066                // surround widget.builder with yet another builder so that
1067                // a context separates them and Theme.of() correctly
1068                // resolves to the theme we passed to AnimatedTheme.
1069                builder(app, context, child.as_ref())
1070            })
1071            .into_widget();
1072        }
1073
1074        let mut scaffold_messenger = ScaffoldMessenger::new(
1075            DefaultSelectionStyle::new(child_widget)
1076                .selection_color(effective_selection_color)
1077                .cursor_color(effective_cursor_color),
1078        );
1079        if let Some(scaffold_messenger_key) = self.widget(app).scaffold_messenger_key.clone() {
1080            scaffold_messenger = scaffold_messenger.key(scaffold_messenger_key.into());
1081        }
1082        child_widget = scaffold_messenger.into_widget();
1083
1084        let widget = self.widget(app);
1085        if widget.theme_animation_style.as_ref() != Some(&AnimationStyle::NO_ANIMATION) {
1086            let duration = widget
1087                .theme_animation_style
1088                .as_ref()
1089                .and_then(|style| style.duration)
1090                .unwrap_or(widget.theme_animation_duration);
1091            let curve = widget
1092                .theme_animation_style
1093                .as_ref()
1094                .and_then(|style| style.curve.clone())
1095                .unwrap_or_else(|| Rc::clone(&widget.theme_animation_curve));
1096            child_widget = AnimatedTheme::new(theme, child_widget)
1097                .duration(duration)
1098                .curve(curve)
1099                .into_widget();
1100        } else {
1101            child_widget = Theme::new(theme, child_widget).into_widget();
1102        }
1103
1104        child_widget
1105    }
1106
1107    fn build_widget_app(self: Handle<Self>, app: &App) -> WidgetsApp {
1108        // The color property is always pulled from the light theme, even if dark
1109        // mode is activated. This was done to simplify the technical details
1110        // of switching themes and it was deemed acceptable because this color
1111        // property is only used on old Android OSes to color the app bar in
1112        // Android's switcher UI.
1113        //
1114        // blue is the primary color of the default theme.
1115        let widget = self.widget(app);
1116        let material_color = widget
1117            .color
1118            .or_else(|| widget.theme.as_ref().map(|theme| theme.primary_color))
1119            .unwrap_or_else(|| Colors::BLUE.primary());
1120
1121        // The `WidgetsApp.router` branch waits with `router.dart`; see PORTING.md.
1122
1123        let localizations_delegates = self.localizations_delegates(app);
1124        let mut widgets_app = WidgetsApp::new(material_color)
1125            .key(GlobalKey::object(self.id()).into())
1126            .navigator_observers(widget.navigator_observers.clone())
1127            .page_route_builder(|app, settings, builder| {
1128                let route = MaterialPageRoute::new(app, builder)
1129                    .settings(app, RouteSettingsRef::Settings(settings.clone()));
1130                route.into_erased()
1131            })
1132            .routes(widget.routes.clone())
1133            .builder(move |app, context, child| self.material_builder(app, context, child))
1134            .text_style(error_text_style())
1135            .localizations_delegates(localizations_delegates)
1136            .supported_locales(widget.supported_locales.clone())
1137            .show_performance_overlay(widget.show_performance_overlay)
1138            .show_semantics_debugger(widget.show_semantics_debugger)
1139            .debug_show_checked_mode_banner(widget.debug_show_checked_mode_banner);
1140        // The inspector's three button builders wait with `widget_inspector.dart`; see
1141        // PORTING.md.
1142
1143        if let Some(navigator_key) = widget.navigator_key.clone() {
1144            widgets_app = widgets_app.navigator_key(navigator_key);
1145        }
1146        if let Some(home) = widget.home.clone() {
1147            widgets_app = widgets_app.home(home);
1148        }
1149        if let Some(initial_route) = widget.initial_route.clone() {
1150            widgets_app = widgets_app.initial_route(initial_route);
1151        }
1152        if let Some(on_generate_route) = widget.on_generate_route.clone() {
1153            widgets_app = widgets_app
1154                .on_generate_route(move |app, settings| on_generate_route(app, settings));
1155        }
1156        if let Some(on_generate_initial_routes) = widget.on_generate_initial_routes.clone() {
1157            widgets_app = widgets_app
1158                .on_generate_initial_routes(move |app, name| on_generate_initial_routes(app, name));
1159        }
1160        if let Some(on_unknown_route) = widget.on_unknown_route.clone() {
1161            widgets_app =
1162                widgets_app.on_unknown_route(move |app, settings| on_unknown_route(app, settings));
1163        }
1164        if let Some(on_navigation_notification) = widget.on_navigation_notification.clone() {
1165            widgets_app = widgets_app.on_navigation_notification(move |app, notification| {
1166                on_navigation_notification(app, notification)
1167            });
1168        }
1169        if let Some(title) = widget.title.clone() {
1170            widgets_app = widgets_app.title(title);
1171        }
1172        if let Some(on_generate_title) = widget.on_generate_title.clone() {
1173            widgets_app =
1174                widgets_app.on_generate_title(move |app, context| on_generate_title(app, context));
1175        }
1176        if let Some(locale) = widget.locale.clone() {
1177            widgets_app = widgets_app.locale(locale);
1178        }
1179        if let Some(callback) = widget.locale_resolution_callback.clone() {
1180            widgets_app = widgets_app
1181                .locale_resolution_callback(move |locale, supported| callback(locale, supported));
1182        }
1183        if let Some(callback) = widget.locale_list_resolution_callback.clone() {
1184            widgets_app = widgets_app.locale_list_resolution_callback(move |locales, supported| {
1185                callback(locales, supported)
1186            });
1187        }
1188        if let Some(shortcuts) = widget.shortcuts.clone() {
1189            widgets_app = widgets_app.shortcuts(shortcuts);
1190        }
1191        if let Some(actions) = widget.actions.clone() {
1192            widgets_app = widgets_app.actions(actions);
1193        }
1194        if let Some(restoration_scope_id) = widget.restoration_scope_id.clone() {
1195            widgets_app = widgets_app.restoration_scope_id(restoration_scope_id);
1196        }
1197        widgets_app
1198    }
1199}
1200
1201impl State for MaterialAppState {
1202    type Widget = MaterialApp;
1203    waft_widgets::state_accessors!();
1204
1205    fn init_state(self: Handle<Self>, app: &mut App) {
1206        let hero_controller = MaterialApp::create_material_hero_controller(app);
1207        app.get_mut(self).hero_controller = Some(hero_controller);
1208    }
1209
1210    fn dispose(self: Handle<Self>, app: &mut App) {
1211        self.hero_controller(app).dispose(app);
1212    }
1213
1214    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
1215        let result = self.build_widget_app(app).into_widget();
1216        // The `GridPaper` that `debug_show_material_grid` puts over `result` waits with
1217        // `grid_paper.dart`; see PORTING.md.
1218
1219        let behavior = self
1220            .widget(app)
1221            .scroll_behavior
1222            .clone()
1223            .unwrap_or_else(|| ScrollBehaviorRef::new(MaterialScrollBehavior::new()));
1224        let hero_controller = self.hero_controller(app);
1225        ScrollConfiguration::new(behavior, HeroControllerScope::new(hero_controller, result))
1226            .into_widget()
1227    }
1228}
1229
1230#[cfg(test)]
1231mod tests {
1232    use std::cell::{Cell, RefCell};
1233    use std::panic::{AssertUnwindSafe, catch_unwind};
1234
1235    use waft_embedder::{Offset, Rect, Size};
1236    use waft_foundation::{CompleterFuture, Listener};
1237    use waft_test::TestPlatform;
1238    use waft_widgets::{
1239        AnyElement, Center, CheckedModeBanner, FocusNodeLeaf, FocusScope, FocusScopeNode, ListView,
1240        Localizations, MediaQuery, MediaQueryData, Navigator, NavigatorState,
1241        NeverScrollableScrollPhysics, PageRouteBuilder, RouteResult, ScrollController,
1242        ScrollPhysicsRef, ScrollViewKeyboardDismissBehavior, Text, UnconstrainedBox,
1243        WidgetsBinding, WidgetsLocalizations, downcast_widget,
1244    };
1245
1246    use waft_rendering::testing::{PaintCall, paints};
1247    use waft_widgets::testing::{
1248        TargetPlatformVariant, TestPointer, WidgetTester, expect, find, finds_one_widget,
1249        test_widgets, test_widgets_variant,
1250    };
1251
1252    use super::*;
1253    use crate::elevated_button::ElevatedButton;
1254    use crate::material::Material;
1255    use crate::material_localizations::MaterialLocalizations;
1256    use crate::scaffold::{Scaffold, ScaffoldMessengerState};
1257    use crate::test_support::{PaintInspection, is_same_color_as};
1258    use waft_cupertino::CupertinoLocalizations;
1259
1260    const ALL_PLATFORMS: [TargetPlatform; 6] = [
1261        TargetPlatform::Android,
1262        TargetPlatform::Fuchsia,
1263        TargetPlatform::IOS,
1264        TargetPlatform::Linux,
1265        TargetPlatform::MacOS,
1266        TargetPlatform::Windows,
1267    ];
1268
1269    /// An Android tester whose host reports `brightness`.
1270    fn tester_with_brightness(brightness: Brightness) -> WidgetTester {
1271        WidgetTester::with_platform(
1272            TestPlatform::new()
1273                .on(TargetPlatform::Android)
1274                .with_brightness(brightness),
1275        )
1276    }
1277
1278    /// Dart's `tester.pumpWidget(app)`, with the theme data `app` needs made on the tester's app.
1279    fn pump(tester: &mut WidgetTester, app: impl FnOnce(&App) -> MaterialApp) {
1280        let root = app(&tester.cell.borrow()).into_widget();
1281        tester.pump_widget(root);
1282    }
1283
1284    /// A `Builder` that keeps the theme it sees in `seen`, each time it builds.
1285    fn theme_probe(seen: &Rc<RefCell<Option<Rc<ThemeData>>>>) -> Builder {
1286        let seen = Rc::clone(seen);
1287        Builder::new(move |app, context| {
1288            *seen.borrow_mut() = Some(Theme::of(app, context));
1289            SizedBox::new().into_widget()
1290        })
1291    }
1292
1293    /// A `Builder` that keeps its build context in `seen`.
1294    fn context_probe(seen: &Rc<Cell<Option<BuildContext>>>) -> Builder {
1295        let seen = Rc::clone(seen);
1296        Builder::new(move |_app, context| {
1297            seen.set(Some(context));
1298            SizedBox::new().into_widget()
1299        })
1300    }
1301
1302    fn applied(seen: &Rc<RefCell<Option<Rc<ThemeData>>>>) -> Rc<ThemeData> {
1303        seen.borrow().clone().expect("the probe built")
1304    }
1305
1306    fn brightness_theme(app: &App, brightness: Brightness) -> ThemeData {
1307        ThemeData::builder().brightness(brightness).build(app)
1308    }
1309
1310    fn primary_theme(app: &App, primary_color: Color) -> ThemeData {
1311        ThemeData::builder().primary_color(primary_color).build(app)
1312    }
1313
1314    fn text_page(text: &'static str) -> WidgetBuilder {
1315        Rc::new(move |_app, _context| Text::new(text).into_widget())
1316    }
1317
1318    fn count_page(text: &'static str, count: &Rc<Cell<u32>>) -> WidgetBuilder {
1319        let count = Rc::clone(count);
1320        Rc::new(move |_app, _context| {
1321            count.set(count.get() + 1);
1322            Text::new(text).into_widget()
1323        })
1324    }
1325
1326    fn route_table(names: &[&'static str]) -> Vec<(String, WidgetBuilder)> {
1327        names
1328            .iter()
1329            .map(|name| {
1330                let text: &'static str = match *name {
1331                    "/" => "route \"/\"",
1332                    "/a" => "route \"/a\"",
1333                    "/a/b" => "route \"/a/b\"",
1334                    _ => "route \"/b\"",
1335                };
1336                (name.to_string(), text_page(text))
1337            })
1338            .collect()
1339    }
1340
1341    fn found(tester: &WidgetTester, text: &str) -> usize {
1342        find::text(text).skip_offstage(false).evaluate(tester).len()
1343    }
1344
1345    fn onstage(tester: &WidgetTester, text: &str) -> usize {
1346        find::text(text).evaluate(tester).len()
1347    }
1348
1349    fn navigator(tester: &WidgetTester) -> Handle<NavigatorState> {
1350        let element = *find::by_type::<Navigator>()
1351            .evaluate(tester)
1352            .first()
1353            .expect("a navigator");
1354        element
1355            .state_handle::<NavigatorState>(&tester.cell.borrow())
1356            .expect("a navigator's state")
1357    }
1358
1359    fn center_of_text(tester: &WidgetTester, text: &str) -> Offset {
1360        let element = *find::text(text)
1361            .evaluate(tester)
1362            .first()
1363            .expect("the text is mounted");
1364        tester.get_rect(element).center()
1365    }
1366
1367    /// The colour of the first `Material`: Dart's `tester.widget<Material>(find.byType(Material)).color`.
1368    fn material_color(tester: &WidgetTester) -> Option<Color> {
1369        let element = *find::by_type::<Material>()
1370            .evaluate(tester)
1371            .first()
1372            .expect("a Material");
1373        tester.widget(element, |material: &Material| material.color)
1374    }
1375
1376    fn count_of<W: 'static>(tester: &WidgetTester) -> usize {
1377        find::by_type::<W>().evaluate(tester).len()
1378    }
1379
1380    #[test]
1381    fn the_theme_mode_getters_say_which_mode_it_is() {
1382        assert!(ThemeMode::System.is_system());
1383        assert!(!ThemeMode::System.is_light());
1384        assert!(!ThemeMode::System.is_dark());
1385
1386        assert!(!ThemeMode::Light.is_system());
1387        assert!(ThemeMode::Light.is_light());
1388        assert!(!ThemeMode::Light.is_dark());
1389
1390        assert!(!ThemeMode::Dark.is_system());
1391        assert!(!ThemeMode::Dark.is_light());
1392        assert!(ThemeMode::Dark.is_dark());
1393    }
1394
1395    // 'Can nest apps'.
1396    #[test]
1397    fn apps_can_nest() {
1398        test_widgets(|tester| {
1399            pump(tester, |_| {
1400                MaterialApp::new().home(MaterialApp::new().home(Text::new("Home sweet home")))
1401            });
1402            assert_eq!(onstage(tester, "Home sweet home"), 1);
1403        });
1404    }
1405
1406    // 'Do not rebuild page during a route transition'.
1407    #[test]
1408    fn a_pushed_page_builds_once_through_its_route_transition() {
1409        test_widgets(|tester| {
1410            let build_counter = Rc::new(Cell::new(0));
1411            let next = count_page("Y", &build_counter);
1412            pump(tester, |_| {
1413                MaterialApp::new()
1414                    .home(Builder::new(|_app, context| {
1415                        Material::new()
1416                            .child(ElevatedButton::new(
1417                                Some(Listener::new(move |app| {
1418                                    Navigator::push_named(app, context, "/next", None);
1419                                })),
1420                                Some(Text::new("X")),
1421                            ))
1422                            .into_widget()
1423                    }))
1424                    .routes([("/next".to_string(), next)])
1425            });
1426
1427            assert_eq!(build_counter.get(), 0);
1428            let x = center_of_text(tester, "X");
1429            tester.tap_at(x, 1);
1430            assert_eq!(build_counter.get(), 0);
1431            tester.pump();
1432            assert_eq!(build_counter.get(), 1);
1433            for _ in 0..4 {
1434                tester.pump_by(Duration::from_millis(10));
1435                assert_eq!(build_counter.get(), 1);
1436            }
1437            tester.pump_by(Duration::from_secs(1));
1438            assert_eq!(build_counter.get(), 1);
1439            assert_eq!(onstage(tester, "Y"), 1);
1440        });
1441    }
1442
1443    // 'Do rebuild the home page if it changes'.
1444    #[test]
1445    fn the_home_page_rebuilds_when_it_changes() {
1446        test_widgets(|tester| {
1447            let build_counter = Rc::new(Cell::new(0));
1448            let home = |text: &'static str| {
1449                let build_counter = Rc::clone(&build_counter);
1450                Builder::new(move |_app, _context| {
1451                    build_counter.set(build_counter.get() + 1);
1452                    Text::new(text).into_widget()
1453                })
1454            };
1455            let a = home("A");
1456            pump(tester, |_| MaterialApp::new().home(a));
1457            assert_eq!(build_counter.get(), 1);
1458            assert_eq!(onstage(tester, "A"), 1);
1459            let b = home("B");
1460            pump(tester, |_| MaterialApp::new().home(b));
1461            assert_eq!(build_counter.get(), 2);
1462            assert_eq!(onstage(tester, "B"), 1);
1463        });
1464    }
1465
1466    // 'Do not rebuild the home page if it does not actually change'.
1467    #[test]
1468    fn the_home_page_does_not_rebuild_when_it_is_the_same_widget() {
1469        test_widgets(|tester| {
1470            let build_counter = Rc::new(Cell::new(0));
1471            let home: WidgetRef = {
1472                let build_counter = Rc::clone(&build_counter);
1473                Builder::new(move |_app, _context| {
1474                    build_counter.set(build_counter.get() + 1);
1475                    SizedBox::new().into_widget()
1476                })
1477                .into_widget()
1478            };
1479            pump(tester, |_| MaterialApp::new().home(home.clone()));
1480            assert_eq!(build_counter.get(), 1);
1481            pump(tester, |_| MaterialApp::new().home(home.clone()));
1482            assert_eq!(build_counter.get(), 1);
1483        });
1484    }
1485
1486    // 'Do rebuild pages that come from the routes table if the MaterialApp changes'.
1487    #[test]
1488    fn pages_from_the_routes_table_rebuild_when_the_app_changes() {
1489        test_widgets(|tester| {
1490            let build_counter = Rc::new(Cell::new(0));
1491            let routes = vec![("/".to_string(), count_page("page", &build_counter))];
1492            pump(tester, |_| MaterialApp::new().routes(routes.clone()));
1493            assert_eq!(build_counter.get(), 1);
1494            pump(tester, |_| MaterialApp::new().routes(routes.clone()));
1495            assert_eq!(build_counter.get(), 2);
1496        });
1497    }
1498
1499    // 'Cannot pop the initial route'.
1500    #[test]
1501    fn the_initial_route_cannot_be_popped() {
1502        test_widgets(|tester| {
1503            pump(tester, |_| MaterialApp::new().home(Text::new("Home")));
1504            assert_eq!(onstage(tester, "Home"), 1);
1505
1506            let navigator = navigator(tester);
1507            let result = navigator.maybe_pop(&mut tester.cell.borrow_mut(), None);
1508
1509            assert!(!result);
1510            assert_eq!(onstage(tester, "Home"), 1);
1511        });
1512    }
1513
1514    // 'Default initialRoute'.
1515    #[test]
1516    fn the_default_initial_route_is_the_slash_route() {
1517        test_widgets(|tester| {
1518            pump(tester, |_| MaterialApp::new().routes(route_table(&["/"])));
1519            assert_eq!(onstage(tester, "route \"/\""), 1);
1520        });
1521    }
1522
1523    // 'One-step initial route'.
1524    #[test]
1525    fn a_one_step_initial_route_is_pushed_over_the_slash_route() {
1526        test_widgets(|tester| {
1527            pump(tester, |_| {
1528                MaterialApp::new()
1529                    .initial_route("/a")
1530                    .routes(route_table(&["/", "/a", "/a/b", "/b"]))
1531            });
1532            assert_eq!(found(tester, "route \"/\""), 1);
1533            assert_eq!(onstage(tester, "route \"/a\""), 1);
1534            assert_eq!(found(tester, "route \"/a/b\""), 0);
1535            assert_eq!(found(tester, "route \"/b\""), 0);
1536        });
1537    }
1538
1539    // 'Two-step initial route'.
1540    #[test]
1541    fn a_two_step_initial_route_is_pushed_over_each_of_its_parents() {
1542        test_widgets(|tester| {
1543            pump(tester, |_| {
1544                MaterialApp::new()
1545                    .initial_route("/a/b")
1546                    .routes(route_table(&["/", "/a", "/a/b", "/b"]))
1547            });
1548            assert_eq!(found(tester, "route \"/\""), 1);
1549            assert_eq!(found(tester, "route \"/a\""), 1);
1550            assert_eq!(onstage(tester, "route \"/a/b\""), 1);
1551            assert_eq!(found(tester, "route \"/b\""), 0);
1552        });
1553    }
1554
1555    // 'Make sure initialRoute is only used the first time'.
1556    #[test]
1557    fn the_initial_route_is_only_used_the_first_time() {
1558        test_widgets(|tester| {
1559            let routes = route_table(&["/", "/a", "/b"]);
1560            let expect_a = |tester: &WidgetTester| {
1561                assert_eq!(found(tester, "route \"/\""), 1);
1562                assert_eq!(onstage(tester, "route \"/a\""), 1);
1563                assert_eq!(found(tester, "route \"/b\""), 0);
1564            };
1565
1566            pump(tester, |_| {
1567                MaterialApp::new()
1568                    .initial_route("/a")
1569                    .routes(routes.clone())
1570            });
1571            expect_a(tester);
1572
1573            // changing initialRoute has no effect
1574            pump(tester, |_| {
1575                MaterialApp::new()
1576                    .initial_route("/b")
1577                    .routes(routes.clone())
1578            });
1579            expect_a(tester);
1580
1581            // removing it has no effect
1582            pump(tester, |_| MaterialApp::new().routes(routes.clone()));
1583            expect_a(tester);
1584        });
1585    }
1586
1587    // 'MaterialApp with builder and no route information works.' and 'MaterialApp.builder can
1588    // build app without a Navigator'.
1589    #[test]
1590    fn a_builder_without_routes_builds_the_app_without_a_navigator() {
1591        test_widgets(|tester| {
1592            let builder_child = Rc::new(Cell::new(true));
1593            let seen = Rc::clone(&builder_child);
1594            pump(tester, |_| {
1595                MaterialApp::new().builder(move |_app, _context, child| {
1596                    seen.set(child.is_some());
1597                    SizedBox::new().into_widget()
1598                })
1599            });
1600            assert!(!builder_child.get());
1601            assert_eq!(count_of::<Navigator>(tester), 0);
1602        });
1603    }
1604
1605    // 'MaterialApp with builder works when themeAnimationStyle is AnimationStyle.noAnimation'.
1606    #[test]
1607    fn a_builder_works_without_the_theme_animation() {
1608        test_widgets(|tester| {
1609            pump(tester, |_| {
1610                MaterialApp::new()
1611                    .theme_animation_style(AnimationStyle::NO_ANIMATION)
1612                    .builder(|_app, _context, _child| Text::new("Works").into_widget())
1613            });
1614            assert_eq!(onstage(tester, "Works"), 1);
1615        });
1616    }
1617
1618    // 'MaterialApp.navigatorKey' and 'MaterialApp.navigatorKey can be updated'.
1619    #[test]
1620    fn the_navigator_key_names_the_navigator_while_the_app_is_given_it() {
1621        test_widgets(|tester| {
1622            let key = GlobalKey::new();
1623            let color = Color::new(0xFF112233);
1624            let current = |tester: &WidgetTester, key: &GlobalKey| {
1625                key.current_state::<NavigatorState>(&tester.cell.borrow_mut())
1626            };
1627
1628            pump(tester, |_| {
1629                MaterialApp::new()
1630                    .navigator_key(key.clone())
1631                    .color(color)
1632                    .home(SizedBox::new())
1633            });
1634            assert!(current(tester, &key).is_some());
1635            pump(tester, |_| {
1636                MaterialApp::new().color(color).home(SizedBox::new())
1637            });
1638            assert!(current(tester, &key).is_none());
1639            pump(tester, |_| {
1640                MaterialApp::new()
1641                    .navigator_key(key.clone())
1642                    .color(color)
1643                    .home(SizedBox::new())
1644            });
1645            assert!(current(tester, &key).is_some());
1646
1647            let key2 = GlobalKey::new();
1648            pump(tester, |_| {
1649                MaterialApp::new()
1650                    .navigator_key(key2.clone())
1651                    .home(SizedBox::new())
1652            });
1653            assert!(current(tester, &key2).is_some());
1654            assert!(current(tester, &key).is_none());
1655        });
1656    }
1657
1658    #[test]
1659    fn the_scaffold_messenger_key_names_the_apps_scaffold_messenger() {
1660        test_widgets(|tester| {
1661            let key = GlobalKey::new();
1662            pump(tester, |_| {
1663                MaterialApp::new()
1664                    .scaffold_messenger_key(key.clone())
1665                    .home(SizedBox::new())
1666            });
1667            assert!(
1668                key.current_state::<ScaffoldMessengerState>(&tester.cell.borrow_mut())
1669                    .is_some()
1670            );
1671        });
1672    }
1673
1674    // 'Has default material and cupertino localizations'.
1675    #[test]
1676    fn the_app_has_default_material_and_cupertino_localizations() {
1677        test_widgets(|tester| {
1678            let seen = Rc::new(Cell::new(None));
1679            let probe = context_probe(&seen);
1680            pump(tester, |_| MaterialApp::new().home(probe));
1681            let context = seen.get().expect("the probe built");
1682            let mut app = tester.cell.borrow_mut();
1683            // Default US "select all" text.
1684            assert_eq!(
1685                <dyn MaterialLocalizations>::of(&mut app, context).select_all_button_label(),
1686                "Select all"
1687            );
1688            // Default Cupertino US "select all" text.
1689            assert_eq!(
1690                <dyn CupertinoLocalizations>::of(&mut app, context).select_all_button_label(),
1691                "Select All"
1692            );
1693            assert!(Localizations::of::<dyn WidgetsLocalizations>(&mut app, context).is_some());
1694        });
1695    }
1696
1697    /// The brightness of the theme a page sees under `app`, on a host reporting
1698    /// `platform_brightness`.
1699    fn applied_brightness(
1700        platform_brightness: Brightness,
1701        app: impl FnOnce(&App, Builder) -> MaterialApp,
1702    ) -> Brightness {
1703        let mut tester = tester_with_brightness(platform_brightness);
1704        let seen = Rc::new(RefCell::new(None));
1705        let probe = theme_probe(&seen);
1706        pump(&mut tester, |cell_app| app(cell_app, probe));
1707        applied(&seen).brightness()
1708    }
1709
1710    // 'MaterialApp uses regular theme when themeMode is light'.
1711    #[test]
1712    fn a_light_theme_mode_uses_the_regular_theme() {
1713        for platform_brightness in [Brightness::Light, Brightness::Dark] {
1714            test_widgets(|_tester| {
1715                let brightness = applied_brightness(platform_brightness, |app, probe| {
1716                    MaterialApp::new()
1717                        .theme(brightness_theme(app, Brightness::Light))
1718                        .dark_theme(brightness_theme(app, Brightness::Dark))
1719                        .theme_mode(ThemeMode::Light)
1720                        .home(probe)
1721                });
1722                assert_eq!(brightness, Brightness::Light);
1723            });
1724        }
1725    }
1726
1727    // 'MaterialApp uses darkTheme when themeMode is dark'.
1728    #[test]
1729    fn a_dark_theme_mode_uses_the_dark_theme() {
1730        for platform_brightness in [Brightness::Light, Brightness::Dark] {
1731            test_widgets(|_tester| {
1732                let brightness = applied_brightness(platform_brightness, |app, probe| {
1733                    MaterialApp::new()
1734                        .theme(brightness_theme(app, Brightness::Light))
1735                        .dark_theme(brightness_theme(app, Brightness::Dark))
1736                        .theme_mode(ThemeMode::Dark)
1737                        .home(probe)
1738                });
1739                assert_eq!(brightness, Brightness::Dark);
1740            });
1741        }
1742    }
1743
1744    // 'MaterialApp uses regular theme when themeMode is system and platformBrightness is light',
1745    // 'MaterialApp uses darkTheme when themeMode is system and platformBrightness is dark' and
1746    // 'MaterialApp uses dark theme when platformBrightness is dark'.
1747    #[test]
1748    fn the_system_theme_mode_follows_the_platform_brightness() {
1749        for platform_brightness in [Brightness::Light, Brightness::Dark] {
1750            test_widgets(|_tester| {
1751                let brightness = applied_brightness(platform_brightness, |app, probe| {
1752                    MaterialApp::new()
1753                        .theme(brightness_theme(app, Brightness::Light))
1754                        .dark_theme(brightness_theme(app, Brightness::Dark))
1755                        .home(probe)
1756                });
1757                assert_eq!(brightness, platform_brightness);
1758            });
1759        }
1760    }
1761
1762    // 'MaterialApp uses light theme when platformBrightness is dark but no dark theme is
1763    // provided'.
1764    #[test]
1765    fn a_dark_platform_without_a_dark_theme_uses_the_regular_theme() {
1766        test_widgets(|_tester| {
1767            let brightness = applied_brightness(Brightness::Dark, |app, probe| {
1768                MaterialApp::new()
1769                    .theme(brightness_theme(app, Brightness::Light))
1770                    .home(probe)
1771            });
1772            assert_eq!(brightness, Brightness::Light);
1773        });
1774    }
1775
1776    // 'MaterialApp uses fallback light theme when platformBrightness is dark but no theme is
1777    // provided at all'.
1778    #[test]
1779    fn a_dark_platform_without_any_theme_uses_the_fallback_light_theme() {
1780        test_widgets(|_tester| {
1781            let brightness =
1782                applied_brightness(Brightness::Dark, |_, probe| MaterialApp::new().home(probe));
1783            assert_eq!(brightness, Brightness::Light);
1784        });
1785    }
1786
1787    // 'MaterialApp uses fallback light theme when platformBrightness is light and a dark theme
1788    // is provided'.
1789    #[test]
1790    fn a_light_platform_with_only_a_dark_theme_uses_the_fallback_light_theme() {
1791        test_widgets(|_tester| {
1792            let brightness = applied_brightness(Brightness::Light, |app, probe| {
1793                MaterialApp::new()
1794                    .dark_theme(brightness_theme(app, Brightness::Dark))
1795                    .home(probe)
1796            });
1797            assert_eq!(brightness, Brightness::Light);
1798        });
1799    }
1800
1801    /// The primary colour of the theme a page sees under `app`, on a host reporting
1802    /// `platform_brightness`, under a `MediaQuery` that asks for high contrast.
1803    fn applied_high_contrast_primary(
1804        platform_brightness: Brightness,
1805        app: impl FnOnce(&App, Builder) -> MaterialApp,
1806    ) -> Color {
1807        let mut tester = tester_with_brightness(platform_brightness);
1808        let seen = Rc::new(RefCell::new(None));
1809        let probe = theme_probe(&seen);
1810        let material_app: WidgetRef = app(&tester.cell.borrow(), probe).into_widget();
1811        let root = Builder::new(move |app, context| {
1812            MediaQuery::new(
1813                MediaQuery::of(app, context).high_contrast(true),
1814                material_app.clone(),
1815            )
1816            .into_widget()
1817        });
1818        tester.pump_widget(root.into_widget());
1819        applied(&seen).primary_color
1820    }
1821
1822    // 'MaterialApp uses high contrast theme when appropriate'.
1823    #[test]
1824    fn high_contrast_uses_the_high_contrast_theme() {
1825        test_widgets(|_tester| {
1826            let primary = applied_high_contrast_primary(Brightness::Light, |app, probe| {
1827                MaterialApp::new()
1828                    .theme(primary_theme(app, Colors::LIGHT_BLUE.primary()))
1829                    .high_contrast_theme(primary_theme(app, Colors::BLUE.primary()))
1830                    .home(probe)
1831            });
1832            assert_eq!(primary, Colors::BLUE.primary());
1833        });
1834    }
1835
1836    // 'MaterialApp uses high contrast dark theme when appropriate'.
1837    #[test]
1838    fn high_contrast_on_a_dark_platform_uses_the_high_contrast_dark_theme() {
1839        test_widgets(|_tester| {
1840            let primary = applied_high_contrast_primary(Brightness::Dark, |app, probe| {
1841                MaterialApp::new()
1842                    .theme(primary_theme(app, Colors::LIGHT_BLUE.primary()))
1843                    .dark_theme(primary_theme(app, Colors::LIGHT_GREEN.primary()))
1844                    .high_contrast_theme(primary_theme(app, Colors::BLUE.primary()))
1845                    .high_contrast_dark_theme(primary_theme(app, Colors::GREEN.primary()))
1846                    .home(probe)
1847            });
1848            assert_eq!(primary, Colors::GREEN.primary());
1849        });
1850    }
1851
1852    // 'MaterialApp uses dark theme when no high contrast dark theme is provided'.
1853    #[test]
1854    fn high_contrast_on_a_dark_platform_without_a_high_contrast_dark_theme_uses_the_dark_theme() {
1855        test_widgets(|_tester| {
1856            let primary = applied_high_contrast_primary(Brightness::Dark, |app, probe| {
1857                MaterialApp::new()
1858                    .theme(primary_theme(app, Colors::LIGHT_BLUE.primary()))
1859                    .dark_theme(primary_theme(app, Colors::LIGHT_GREEN.primary()))
1860                    .home(probe)
1861            });
1862            assert_eq!(primary, Colors::LIGHT_GREEN.primary());
1863        });
1864    }
1865
1866    // 'MaterialApp animates theme changes'.
1867    #[test]
1868    fn the_app_animates_theme_changes() {
1869        test_widgets(|tester| {
1870            let (light_theme, dark_theme) = {
1871                let app = tester.cell.borrow();
1872                (ThemeData::new(&app), ThemeData::dark(&app, None))
1873            };
1874            let scaffold = || Builder::new(|_app, _context| Scaffold::new().into_widget());
1875            let (light, dark) = (light_theme.clone(), dark_theme.clone());
1876            pump(tester, |_| {
1877                MaterialApp::new()
1878                    .theme(light)
1879                    .dark_theme(dark)
1880                    .theme_mode(ThemeMode::Light)
1881                    .home(scaffold())
1882            });
1883            assert_eq!(
1884                material_color(tester),
1885                Some(light_theme.scaffold_background_color)
1886            );
1887
1888            // Change to dark theme
1889            pump(tester, |app| {
1890                MaterialApp::new()
1891                    .dark_theme(ThemeData::dark(app, None))
1892                    .theme_mode(ThemeMode::Dark)
1893                    .home(scaffold())
1894            });
1895
1896            // Wait half kThemeAnimationDuration = 200ms.
1897            tester.pump_by(Duration::from_millis(100));
1898
1899            // Default curve is linear so background should be half way between
1900            // the two colors.
1901            let half_bg_color = Color::lerp(
1902                Some(light_theme.scaffold_background_color),
1903                Some(dark_theme.scaffold_background_color),
1904                0.5,
1905            );
1906            assert_eq!(material_color(tester), half_bg_color);
1907        });
1908    }
1909
1910    // 'MaterialApp theme animation can be turned off'.
1911    #[test]
1912    fn the_theme_animation_can_be_turned_off() {
1913        test_widgets(|tester| {
1914            let (light_theme, dark_theme) = {
1915                let app = tester.cell.borrow();
1916                (ThemeData::new(&app), ThemeData::dark(&app, None))
1917            };
1918            let scaffold_rebuilds = Rc::new(Cell::new(0));
1919            let scaffold: WidgetRef = {
1920                let scaffold_rebuilds = Rc::clone(&scaffold_rebuilds);
1921                Builder::new(move |app, context| {
1922                    scaffold_rebuilds.set(scaffold_rebuilds.get() + 1);
1923                    // Use Theme.of() to ensure we are building when the theme changes.
1924                    Scaffold::new()
1925                        .background_color(Theme::of(app, context).scaffold_background_color)
1926                        .into_widget()
1927                })
1928                .into_widget()
1929            };
1930
1931            let (light, dark) = (light_theme.clone(), dark_theme.clone());
1932            pump(tester, |_| {
1933                MaterialApp::new()
1934                    .theme(light)
1935                    .dark_theme(dark)
1936                    .theme_mode(ThemeMode::Light)
1937                    .theme_animation_duration(Duration::ZERO)
1938                    .home(scaffold.clone())
1939            });
1940            assert_eq!(
1941                material_color(tester),
1942                Some(light_theme.scaffold_background_color)
1943            );
1944            assert_eq!(scaffold_rebuilds.get(), 1);
1945
1946            // Change to dark theme
1947            pump(tester, |app| {
1948                MaterialApp::new()
1949                    .dark_theme(ThemeData::dark(app, None))
1950                    .theme_mode(ThemeMode::Dark)
1951                    .theme_animation_duration(Duration::ZERO)
1952                    .home(scaffold.clone())
1953            });
1954
1955            // Wait for any animation to finish.
1956            tester.pump_and_settle();
1957            assert_eq!(
1958                material_color(tester),
1959                Some(dark_theme.scaffold_background_color)
1960            );
1961            assert_eq!(scaffold_rebuilds.get(), 2);
1962        });
1963    }
1964
1965    // 'MaterialApp switches themes when the platformBrightness changes.'
1966    #[test]
1967    fn the_app_switches_themes_when_the_platform_brightness_changes() {
1968        test_widgets(|tester| {
1969            let platform = Rc::clone(tester.platform());
1970            let before: Rc<RefCell<Option<Brightness>>> = Rc::new(RefCell::new(None));
1971            let after: Rc<RefCell<Option<Brightness>>> = Rc::new(RefCell::new(None));
1972            let probe = {
1973                let (before, after) = (Rc::clone(&before), Rc::clone(&after));
1974                Builder::new(move |app, context| {
1975                    let brightness = Some(Theme::of(app, context).brightness());
1976                    if before.borrow().is_none() {
1977                        *before.borrow_mut() = brightness;
1978                    } else {
1979                        *after.borrow_mut() = brightness;
1980                    }
1981                    SizedBox::new().into_widget()
1982                })
1983            };
1984            pump(tester, |app| {
1985                MaterialApp::new()
1986                    .theme(brightness_theme(app, Brightness::Light))
1987                    .dark_theme(brightness_theme(app, Brightness::Dark))
1988                    .home(probe)
1989            });
1990
1991            // Switch the platformBrightness from light to dark and pump the widget tree
1992            // to process changes.
1993            platform.set_brightness(Brightness::Dark);
1994            {
1995                let mut app = tester.cell.borrow_mut();
1996                WidgetsBinding::instance(&mut app).handle_platform_brightness_changed(&mut app);
1997            }
1998            tester.pump_and_settle();
1999
2000            assert_eq!(*before.borrow(), Some(Brightness::Light));
2001            assert_eq!(*after.borrow(), Some(Brightness::Dark));
2002        });
2003    }
2004
2005    // 'MaterialApp can customize initial routes'.
2006    #[test]
2007    fn on_generate_initial_routes_replaces_the_initial_routes() {
2008        test_widgets(|tester| {
2009            let navigator_key = GlobalKey::new();
2010            let page = |text: &'static str| {
2011                move |app: &mut App| {
2012                    let page_builder: waft_widgets::RoutePageBuilder =
2013                        Rc::new(move |_app, _context, _animation, _secondary| {
2014                            Text::new(text).into_widget()
2015                        });
2016                    PageRouteBuilder::new(app, page_builder).into_erased()
2017                }
2018            };
2019            pump(tester, |_| {
2020                MaterialApp::new()
2021                    .navigator_key(navigator_key.clone())
2022                    .on_generate_initial_routes(move |app, initial_route| {
2023                        assert_eq!(initial_route, "/abc");
2024                        vec![
2025                            page("non-regular page one")(app),
2026                            page("non-regular page two")(app),
2027                        ]
2028                    })
2029                    .initial_route("/abc")
2030                    .routes([
2031                        ("/".to_string(), text_page("regular page one")),
2032                        ("/abc".to_string(), text_page("regular page two")),
2033                    ])
2034            });
2035            assert_eq!(onstage(tester, "non-regular page two"), 1);
2036            assert_eq!(onstage(tester, "non-regular page one"), 0);
2037            assert_eq!(onstage(tester, "regular page one"), 0);
2038            assert_eq!(onstage(tester, "regular page two"), 0);
2039            {
2040                let mut app = tester.cell.borrow_mut();
2041                let navigator = navigator_key
2042                    .current_state::<NavigatorState>(&app)
2043                    .expect("the navigator");
2044                navigator.pop(&mut app, None);
2045            }
2046            tester.pump_and_settle();
2047            assert_eq!(onstage(tester, "non-regular page two"), 0);
2048            assert_eq!(onstage(tester, "non-regular page one"), 1);
2049            assert_eq!(onstage(tester, "regular page one"), 0);
2050            assert_eq!(onstage(tester, "regular page two"), 0);
2051        });
2052    }
2053
2054    // 'MaterialApp does create HeroController with the MaterialRectArcTween', read by what the
2055    // tween answers, since a `RectTweenObject` has no type to test.
2056    #[test]
2057    fn the_hero_controller_tweens_rects_along_a_material_arc() {
2058        test_widgets(|tester| {
2059            let mut app = tester.cell.borrow_mut();
2060            let controller = MaterialApp::create_material_hero_controller(&mut app);
2061            let begin = Some(Rect::from_ltrb(0.0, 0.0, 10.0, 10.0));
2062            let end = Some(Rect::from_ltrb(0.0, 0.0, 20.0, 20.0));
2063            let create_rect_tween = app
2064                .get(&controller)
2065                .create_rect_tween
2066                .clone()
2067                .expect("the controller has a rect tween factory");
2068            let tween = create_rect_tween(&mut app, begin, end);
2069            let arc = MaterialRectArcTween::new(begin, end);
2070            for t in [0.25, 0.5, 0.75] {
2071                assert_eq!(tween.lerp(&app, t), Some(arc.lerp(t)));
2072            }
2073            assert_ne!(
2074                tween.lerp(&app, 0.5),
2075                Some(Rect::from_ltrb(0.0, 0.0, 15.0, 15.0)),
2076                "not a linear RectTween"
2077            );
2078            controller.dispose(&mut app);
2079        });
2080    }
2081
2082    /// The scroll configuration a page sees under `app`, and the page's context.
2083    fn page_scroll_behavior(
2084        tester: &mut WidgetTester,
2085        app: impl FnOnce(Builder) -> MaterialApp,
2086    ) -> (ScrollBehaviorRef, BuildContext) {
2087        let seen = Rc::new(Cell::new(None));
2088        let probe = context_probe(&seen);
2089        pump(tester, |_| app(probe));
2090        let context = seen.get().expect("the probe built");
2091        let behavior = ScrollConfiguration::of(&mut tester.cell.borrow_mut(), context);
2092        (behavior, context)
2093    }
2094
2095    // 'MaterialApp has correct default ScrollBehavior' and 'MaterialApp has correct default
2096    // KeyboardDismissBehavior'.
2097    #[test]
2098    fn the_default_scroll_behavior_is_a_material_scroll_behavior() {
2099        test_widgets(|tester| {
2100            let (behavior, context) =
2101                page_scroll_behavior(tester, |probe| MaterialApp::new().home(probe));
2102            assert_eq!(behavior.type_id(), TypeId::of::<MaterialScrollBehavior>());
2103            assert_eq!(
2104                behavior.get_keyboard_dismiss_behavior(&mut tester.cell.borrow_mut(), context),
2105                ScrollViewKeyboardDismissBehavior::Manual
2106            );
2107        });
2108    }
2109
2110    // 'MaterialApp can override default KeyboardDismissBehavior'.
2111    #[test]
2112    fn the_keyboard_dismiss_behavior_can_be_overridden() {
2113        test_widgets(|tester| {
2114            let (behavior, context) = page_scroll_behavior(tester, |probe| {
2115                MaterialApp::new()
2116                    .scroll_behavior(ScrollBehaviorRef::new(
2117                        ScrollBehaviorRef::new(MaterialScrollBehavior::new())
2118                            .copy_with()
2119                            .keyboard_dismiss_behavior(ScrollViewKeyboardDismissBehavior::OnDrag),
2120                    ))
2121                    .home(probe)
2122            });
2123            assert_eq!(
2124                behavior.get_keyboard_dismiss_behavior(&mut tester.cell.borrow_mut(), context),
2125                ScrollViewKeyboardDismissBehavior::OnDrag
2126            );
2127        });
2128    }
2129
2130    // Dart's `getPlatform` reads `Theme.of(context)`, so a page that asks depends on the theme.
2131    #[test]
2132    fn the_material_scroll_behavior_platform_follows_a_theme_change() {
2133        test_widgets(|tester| {
2134            let seen = Rc::new(RefCell::new(Vec::new()));
2135            let probe = {
2136                let seen = Rc::clone(&seen);
2137                Builder::new(move |app, context| {
2138                    seen.borrow_mut()
2139                        .push(MaterialScrollBehavior::new().get_platform(app, context));
2140                    SizedBox::new().into_widget()
2141                })
2142                .into_widget()
2143            };
2144            for platform in [TargetPlatform::Android, TargetPlatform::IOS] {
2145                let probe = probe.clone();
2146                pump(tester, |app| {
2147                    MaterialApp::new()
2148                        .theme(ThemeData::builder().platform(platform).build(app))
2149                        .home(probe)
2150                });
2151                tester.pump_and_settle();
2152            }
2153            assert_eq!(seen.borrow().first(), Some(&TargetPlatform::Android));
2154            assert_eq!(seen.borrow().last(), Some(&TargetPlatform::IOS));
2155        });
2156    }
2157
2158    /// Dart's `MockScrollBehavior`.
2159    #[derive(Debug)]
2160    struct MockScrollBehavior;
2161
2162    impl ScrollBehavior for MockScrollBehavior {
2163        fn as_any(&self) -> &dyn Any {
2164            self
2165        }
2166
2167        fn get_scroll_physics(&self, _app: &mut App, _context: BuildContext) -> ScrollPhysicsRef {
2168            Rc::new(NeverScrollableScrollPhysics::new())
2169        }
2170    }
2171
2172    // 'A ScrollBehavior can be set for MaterialApp'.
2173    #[test]
2174    fn a_scroll_behavior_can_be_set_for_the_app() {
2175        test_widgets(|tester| {
2176            let (behavior, context) = page_scroll_behavior(tester, |probe| {
2177                MaterialApp::new()
2178                    .scroll_behavior(ScrollBehaviorRef::new(MockScrollBehavior))
2179                    .home(probe)
2180            });
2181            assert_eq!(behavior.type_id(), TypeId::of::<MockScrollBehavior>());
2182            let physics = behavior.get_scroll_physics(&mut tester.cell.borrow_mut(), context);
2183            assert!(
2184                physics
2185                    .as_any()
2186                    .downcast_ref::<NeverScrollableScrollPhysics>()
2187                    .is_some()
2188            );
2189        });
2190    }
2191
2192    fn list_view() -> ListView {
2193        ListView::new().children([SizedBox::new()
2194            .height(1000.0)
2195            .width(1000.0)
2196            .child(Text::new("Test"))
2197            .into_widget()])
2198    }
2199
2200    /// How many stretching and glowing indicators an Android `ListView` gets under `app`.
2201    fn overscroll_indicators(
2202        app: impl FnOnce(&App, ListView) -> MaterialApp + Send,
2203    ) -> (usize, usize) {
2204        let mut result = (0, 0);
2205        test_widgets(|tester| {
2206            pump(tester, |cell_app| app(cell_app, list_view()));
2207            result = (
2208                count_of::<StretchingOverscrollIndicator>(tester),
2209                count_of::<GlowingOverscrollIndicator>(tester),
2210            );
2211        });
2212        result
2213    }
2214
2215    // 'Material2 - MaterialApp provides default overscroll color'. The painter is the glow's
2216    // own `CustomPaint`: Dart's first `CustomPaint` is that one because flutter_test turns the
2217    // debug banner, whose `CustomPaint` is above it, off.
2218    #[test]
2219    fn material_2_glows_in_the_color_scheme_secondary() {
2220        test_widgets(|tester| {
2221            // The overscroll color should be a transparent version of the colorScheme's
2222            // secondary color.
2223            let secondary_color = Color::new(0xff008800);
2224            #[allow(deprecated)]
2225            let glow_secondary_color = secondary_color.with_opacity(0.05);
2226            pump(tester, |app| {
2227                let theme =
2228                    ThemeData::from(crate::ColorScheme::light().with_secondary(secondary_color))
2229                        .use_material3(false)
2230                        .build(app);
2231                MaterialApp::new().theme(theme).home(
2232                    waft_widgets::SingleChildScrollView::new()
2233                        .child(SizedBox::new().height(2000.0)),
2234                )
2235            });
2236
2237            let glow = *find::by_type::<GlowingOverscrollIndicator>()
2238                .evaluate(tester)
2239                .first()
2240                .expect("a glowing indicator");
2241            let custom_paint = find::by_type::<waft_widgets::CustomPaint>()
2242                .evaluate(tester)
2243                .into_iter()
2244                .find(|custom_paint| tester.ancestors(*custom_paint).contains(&glow))
2245                .expect("the glow paints through a CustomPaint");
2246            let painter = tester.render_box_of(custom_paint).as_object();
2247            let mut gesture = TestPointer::touch(1);
2248            tester.down(&mut gesture, Offset::new(200.0, 200.0));
2249            for _ in 0..10 {
2250                let at = gesture.position + Offset::new(0.0, 5.0);
2251                tester.move_to(&mut gesture, at, true);
2252                tester.pump_by(Duration::from_millis(20));
2253            }
2254            tester.up(&gesture);
2255            assert!(
2256                paints(
2257                    &tester.painted_ops(painter),
2258                    &[PaintCall::circle(Some(glow_secondary_color))]
2259                )
2260                .is_ok(),
2261                "the glow paints a circle in the secondary colour"
2262            );
2263        });
2264    }
2265
2266    // 'Material3 - ListView clip behavior updates overscroll indicator clip behavior'.
2267    #[test]
2268    fn the_stretch_clips_as_the_list_view_does() {
2269        use waft_rendering::{RenderClipRect, RenderCustomClip};
2270
2271        test_widgets(|tester| {
2272            let build_frame = |clip_behavior: Clip| {
2273                MaterialApp::new()
2274                    .home(
2275                        waft_widgets::Column::new().children([
2276                            SizedBox::new()
2277                                .height(300.0)
2278                                .child(
2279                                    ListView::builder(|_app, _context, index| {
2280                                        Some(
2281                                            waft_widgets::Padding::new(
2282                                                waft_painting::EdgeInsetsGeometry::all(10.0),
2283                                            )
2284                                            .child(Text::new(format!("Index {index}")))
2285                                            .into_widget(),
2286                                        )
2287                                    })
2288                                    .item_count(20)
2289                                    .build()
2290                                    .clip_behavior(clip_behavior),
2291                                )
2292                                .into_widget(),
2293                            waft_widgets::Opacity::new(0.5)
2294                                .child(
2295                                    waft_widgets::Container::new()
2296                                        .color(Color::new(0xD0FF0000))
2297                                        .height(100.0),
2298                                )
2299                                .into_widget(),
2300                        ]),
2301                    )
2302                    .into_widget()
2303            };
2304            let clip_of = |tester: &WidgetTester| {
2305                let render_clip = tester.first::<RenderClipRect>();
2306                render_clip.clip_behavior(&tester.cell.borrow())
2307            };
2308            let overscroll_the_start = |tester: &mut WidgetTester, expected: Clip| {
2309                let mut gesture = TestPointer::touch(1);
2310                let center = center_of_text(tester, "Index 1");
2311                tester.down(&mut gesture, center);
2312                // Overscroll the start.
2313                let at = gesture.position + Offset::new(0.0, 200.0);
2314                tester.move_to(&mut gesture, at, true);
2315                tester.pump_and_settle();
2316                assert_eq!(onstage(tester, "Index 1"), 1);
2317                assert!(center_of_text(tester, "Index 1").dy() > 0.0);
2318                // Now clipping
2319                assert_eq!(clip_of(tester), expected);
2320
2321                tester.up(&gesture);
2322                tester.pump_and_settle();
2323            };
2324
2325            // Test default clip behavior.
2326            tester.pump_widget(build_frame(Clip::HardEdge));
2327
2328            assert_eq!(count_of::<StretchingOverscrollIndicator>(tester), 1);
2329            assert_eq!(count_of::<GlowingOverscrollIndicator>(tester), 0);
2330            assert_eq!(onstage(tester, "Index 1"), 1);
2331
2332            // Currently not clipping
2333            assert_eq!(clip_of(tester), Clip::None);
2334            overscroll_the_start(tester, Clip::HardEdge);
2335
2336            // Test custom clip behavior.
2337            tester.pump_widget(build_frame(Clip::None));
2338
2339            // Currently not clipping
2340            assert_eq!(clip_of(tester), Clip::None);
2341            overscroll_the_start(tester, Clip::None);
2342        });
2343    }
2344
2345    // 'Material2 - ScrollBehavior default android overscroll indicator'.
2346    #[test]
2347    fn material_2_glows_on_android() {
2348        let (stretching, glowing) = overscroll_indicators(|app, list| {
2349            MaterialApp::new()
2350                .theme(ThemeData::builder().use_material3(false).build(app))
2351                .scroll_behavior(ScrollBehaviorRef::new(MaterialScrollBehavior::new()))
2352                .home(list)
2353        });
2354        assert_eq!((stretching, glowing), (0, 1));
2355    }
2356
2357    // 'Material3 - ScrollBehavior default android overscroll indicator'.
2358    #[test]
2359    fn material_3_stretches_on_android() {
2360        let (stretching, glowing) = overscroll_indicators(|_, list| {
2361            MaterialApp::new()
2362                .scroll_behavior(ScrollBehaviorRef::new(MaterialScrollBehavior::new()))
2363                .home(list)
2364        });
2365        assert_eq!((stretching, glowing), (1, 0));
2366    }
2367
2368    // 'MaterialScrollBehavior default stretch android overscroll indicator'.
2369    #[test]
2370    fn the_default_behavior_stretches_on_android() {
2371        let (stretching, glowing) = overscroll_indicators(|_, list| MaterialApp::new().home(list));
2372        assert_eq!((stretching, glowing), (1, 0));
2373    }
2374
2375    // 'Overscroll indicator can be set by theme'.
2376    #[test]
2377    fn the_theme_sets_the_overscroll_indicator() {
2378        let (stretching, glowing) = overscroll_indicators(|app, list| {
2379            // The current default is M3 and stretch overscroll, setting via the theme should override.
2380            #[allow(deprecated)]
2381            let theme = ThemeData::new(app).copy_with().use_material3(false).build();
2382            MaterialApp::new().theme(theme).home(list)
2383        });
2384        assert_eq!((stretching, glowing), (0, 1));
2385    }
2386
2387    /// A page context under a `MaterialApp` on `platform`, inside a scroll view scrolling
2388    /// `axis` whose behavior has no scrollbars.
2389    fn scroll_view_context(tester: &mut WidgetTester, axis: Axis) -> BuildContext {
2390        let seen = Rc::new(Cell::new(None));
2391        let probe = {
2392            let seen = Rc::clone(&seen);
2393            Builder::new(move |_app, context| {
2394                seen.set(Some(context));
2395                SizedBox::new().height(1000.0).into_widget()
2396            })
2397        };
2398        pump(tester, |_| {
2399            MaterialApp::new().home(ScrollConfiguration::new(
2400                // Avoid the default ones here.
2401                ScrollBehaviorRef::new(
2402                    ScrollBehaviorRef::new(MaterialScrollBehavior::new())
2403                        .copy_with()
2404                        .scrollbars(false),
2405                ),
2406                waft_widgets::SingleChildScrollView::new()
2407                    .scroll_direction(axis)
2408                    .child(probe),
2409            ))
2410        });
2411        seen.get().expect("the probe built")
2412    }
2413
2414    /// Whether `build_scrollbar` over `details` panics with the controller assert.
2415    fn build_scrollbar_asserts(
2416        tester: &WidgetTester,
2417        context: BuildContext,
2418        details: &ScrollableDetails,
2419    ) -> bool {
2420        let mut app = tester.cell.borrow_mut();
2421        let child: WidgetRef = SizedBox::new().into_widget();
2422        let built = catch_unwind(AssertUnwindSafe(|| {
2423            MaterialScrollBehavior::new().build_scrollbar(&mut app, context, child, details)
2424        }));
2425        match built {
2426            Ok(_) => false,
2427            Err(panic) => {
2428                let message = panic
2429                    .downcast_ref::<&str>()
2430                    .map(|message| message.to_string())
2431                    .or_else(|| panic.downcast_ref::<String>().cloned())
2432                    .unwrap_or_default();
2433                assert!(
2434                    message.contains("details.controller.is_some()"),
2435                    "{message}"
2436                );
2437                true
2438            }
2439        }
2440    }
2441
2442    // 'Assert in buildScrollbar that controller != null when using it (vertical)'.
2443    #[test]
2444    fn a_vertical_scrollbar_asserts_its_controller_on_desktop() {
2445        for platform in ALL_PLATFORMS {
2446            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
2447                let context = scroll_view_context(tester, Axis::Vertical);
2448                let details = ScrollableDetails::vertical(false);
2449                let asserts = build_scrollbar_asserts(tester, context, &details);
2450                match platform {
2451                    TargetPlatform::Android | TargetPlatform::Fuchsia | TargetPlatform::IOS => {
2452                        // Does not throw if we aren't using it.
2453                        assert!(!asserts, "{platform:?}");
2454                    }
2455                    TargetPlatform::Linux | TargetPlatform::MacOS | TargetPlatform::Windows => {
2456                        assert!(asserts, "{platform:?}");
2457                    }
2458                }
2459            });
2460        }
2461    }
2462
2463    // 'Assert in buildScrollbar that controller != null when using it (horizontal)'.
2464    #[test]
2465    fn a_horizontal_scroll_view_gets_no_scrollbar_on_any_platform() {
2466        for platform in ALL_PLATFORMS {
2467            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
2468                let context = scroll_view_context(tester, Axis::Horizontal);
2469                let details = ScrollableDetails::horizontal(true);
2470                // Does not throw if we aren't using it.
2471                // Horizontal axis gets no scrollbars for all platforms.
2472                assert!(
2473                    !build_scrollbar_asserts(tester, context, &details),
2474                    "{platform:?}"
2475                );
2476            });
2477        }
2478    }
2479
2480    #[test]
2481    fn a_vertical_scroll_view_gets_a_material_scrollbar_on_desktop_only() {
2482        for platform in ALL_PLATFORMS {
2483            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
2484                let context = scroll_view_context(tester, Axis::Vertical);
2485                let mut app = tester.cell.borrow_mut();
2486                let controller = ScrollController::default(&mut app)
2487                    .into_erased::<waft_widgets::AnyScrollController>();
2488                let details = ScrollableDetails::vertical(false).controller(controller.clone());
2489                let child: WidgetRef = SizedBox::new().into_widget();
2490                let built = MaterialScrollBehavior::new().build_scrollbar(
2491                    &mut app,
2492                    context,
2493                    child.clone(),
2494                    &details,
2495                );
2496                let desktop = matches!(
2497                    platform,
2498                    TargetPlatform::Linux | TargetPlatform::MacOS | TargetPlatform::Windows
2499                );
2500                assert_eq!(
2501                    downcast_widget::<Scrollbar>(&*built).is_some(),
2502                    desktop,
2503                    "{platform:?}"
2504                );
2505                assert_eq!(!Rc::ptr_eq(&built, &child), desktop, "{platform:?}");
2506            });
2507        }
2508    }
2509
2510    // 'Override theme animation using AnimationStyle'.
2511    #[test]
2512    fn the_theme_animation_style_overrides_the_theme_animation() {
2513        test_widgets(|tester| {
2514            let (light_theme, dark_theme) = {
2515                let app = tester.cell.borrow();
2516                (ThemeData::new(&app), ThemeData::dark(&app, None))
2517            };
2518            let build_widget = |theme_mode: ThemeMode, animation_style: Option<AnimationStyle>| {
2519                let mut material_app = MaterialApp::new()
2520                    .theme(light_theme.clone())
2521                    .dark_theme(dark_theme.clone())
2522                    .theme_mode(theme_mode)
2523                    .home(Scaffold::new().body(Text::new("body")));
2524                material_app.theme_animation_style = animation_style;
2525                material_app.into_widget()
2526            };
2527            let surface_of = |tester: &WidgetTester| material_color(tester).expect("a colour");
2528
2529            // Test the initial Scaffold background color.
2530            tester.pump_widget(build_widget(ThemeMode::Light, None));
2531
2532            assert!(is_same_color_as(
2533                surface_of(tester),
2534                light_theme.color_scheme.surface()
2535            ));
2536
2537            // Test the Scaffold background color animation from light to dark theme.
2538            tester.pump_widget(build_widget(ThemeMode::Dark, None));
2539            tester.pump();
2540            tester.pump_by(Duration::from_millis(50)); // Advance animation by 50 milliseconds.
2541
2542            // Scaffold background color is slightly updated.
2543            assert!(is_same_color_as(surface_of(tester), Color::new(0xffc3bdc5)));
2544
2545            // Let the animation finish.
2546            tester.pump_and_settle();
2547
2548            // Scaffold background color is fully updated to dark theme.
2549            assert!(is_same_color_as(
2550                surface_of(tester),
2551                dark_theme.color_scheme.surface()
2552            ));
2553
2554            // Reset to light theme to compare the Scaffold background color animation
2555            // with the default animation curve.
2556            tester.pump_widget(build_widget(ThemeMode::Light, None));
2557            tester.pump_and_settle();
2558
2559            // Switch to dark theme with overridden animation curve.
2560            tester.pump_widget(build_widget(
2561                ThemeMode::Dark,
2562                Some(AnimationStyle::new(
2563                    Some(Curves::ease_in()),
2564                    None,
2565                    None,
2566                    None,
2567                )),
2568            ));
2569            tester.pump();
2570            tester.pump_by(Duration::from_millis(50));
2571
2572            // Scaffold background color is slightly updated but with a different
2573            // color than the default animation curve.
2574            assert!(is_same_color_as(surface_of(tester), Color::new(0xffe7e1e9)));
2575
2576            // Let the animation finish.
2577            tester.pump_and_settle();
2578
2579            // Scaffold background color is fully updated to dark theme.
2580            assert!(is_same_color_as(
2581                surface_of(tester),
2582                dark_theme.color_scheme.surface()
2583            ));
2584
2585            // Switch from dark to light theme with overridden animation duration.
2586            tester.pump_widget(build_widget(
2587                ThemeMode::Light,
2588                Some(AnimationStyle::NO_ANIMATION),
2589            ));
2590            tester.pump();
2591            tester.pump_by(Duration::from_millis(1));
2592
2593            assert_ne!(surface_of(tester), dark_theme.color_scheme.surface());
2594            assert!(is_same_color_as(
2595                surface_of(tester),
2596                light_theme.color_scheme.surface()
2597            ));
2598        });
2599    }
2600
2601    // 'AnimationStyle.noAnimation removes AnimatedTheme from the tree'.
2602    #[test]
2603    fn no_animation_removes_the_animated_theme_from_the_tree() {
2604        test_widgets(|tester| {
2605            pump(tester, |_| {
2606                MaterialApp::new()
2607                    .theme_animation_style(AnimationStyle::default())
2608                    .home(SizedBox::new())
2609            });
2610
2611            assert_eq!(count_of::<AnimatedTheme>(tester), 1);
2612            assert_eq!(count_of::<Theme>(tester), 1);
2613
2614            pump(tester, |_| {
2615                MaterialApp::new()
2616                    .theme_animation_style(AnimationStyle::NO_ANIMATION)
2617                    .home(SizedBox::new())
2618            });
2619
2620            assert_eq!(count_of::<AnimatedTheme>(tester), 0);
2621            assert_eq!(count_of::<Theme>(tester), 1);
2622        });
2623    }
2624
2625    fn material_app_size(tester: &WidgetTester) -> Size {
2626        let element: AnyElement = *find::by_type::<MaterialApp>()
2627            .evaluate(tester)
2628            .first()
2629            .expect("a MaterialApp");
2630        tester.render_box_of(element).size(&tester.cell.borrow())
2631    }
2632
2633    // 'MaterialApp works in an unconstrained environment'.
2634    #[test]
2635    fn the_app_takes_its_homes_size_when_unconstrained() {
2636        test_widgets(|tester| {
2637            let app = MaterialApp::new().home(SizedBox::new().width(123.0).height(456.0));
2638            tester.pump_widget(UnconstrainedBox::new().child(app).into_widget());
2639
2640            assert_eq!(material_app_size(tester), Size::new(123.0, 456.0));
2641        });
2642    }
2643
2644    // 'MaterialApp does not crash at zero area'.
2645    #[test]
2646    fn the_app_does_not_crash_at_zero_area() {
2647        test_widgets(|tester| {
2648            let app = MaterialApp::new().home(Text::new("X"));
2649            tester.pump_widget(
2650                Center::new()
2651                    .child(SizedBox::shrink().child(app))
2652                    .into_widget(),
2653            );
2654            assert_eq!(material_app_size(tester), Size::ZERO);
2655        });
2656    }
2657
2658    #[test]
2659    fn the_checked_mode_banner_shows_unless_turned_off() {
2660        test_widgets(|tester| {
2661            pump(tester, |_| MaterialApp::new().home(SizedBox::new()));
2662            assert_eq!(count_of::<CheckedModeBanner>(tester), 1);
2663
2664            pump(tester, |_| {
2665                MaterialApp::new()
2666                    .debug_show_checked_mode_banner(false)
2667                    .home(SizedBox::new())
2668            });
2669            assert_eq!(count_of::<CheckedModeBanner>(tester), 0);
2670        });
2671    }
2672
2673    #[test]
2674    fn the_default_selection_style_comes_from_the_color_scheme_primary() {
2675        test_widgets(|tester| {
2676            let seen = Rc::new(Cell::new(None));
2677            let probe = context_probe(&seen);
2678            pump(tester, |_| MaterialApp::new().home(probe));
2679            let context = seen.get().expect("the probe built");
2680            let mut app = tester.cell.borrow_mut();
2681            let primary = Theme::of(&mut app, context).color_scheme.primary();
2682            let style = DefaultSelectionStyle::of(&mut app, context);
2683            #[allow(deprecated)]
2684            let selection = primary.with_opacity(0.40);
2685            assert_eq!(
2686                style.selection_color.map(|color| color.color()),
2687                Some(selection)
2688            );
2689            assert_eq!(style.cursor_color.map(|color| color.color()), Some(primary));
2690        });
2691    }
2692
2693    #[test]
2694    fn can_place_app_inside_focus_scope() {
2695        test_widgets(|tester| {
2696            let focus_scope_node = FocusScopeNode::new(&mut tester.cell.borrow_mut());
2697
2698            tester.pump_widget(
2699                FocusScope::new(MaterialApp::new().home(Text::new("Home")))
2700                    .autofocus(true)
2701                    .node(focus_scope_node.clone())
2702                    .into_widget(),
2703            );
2704
2705            expect(tester, &find::text("Home"), finds_one_widget());
2706            focus_scope_node.dispose(&mut tester.cell.borrow_mut());
2707        });
2708    }
2709
2710    #[test]
2711    fn return_value_from_pop_is_correct() {
2712        test_widgets(|tester| {
2713            let result: Rc<RefCell<Option<CompleterFuture<RouteResult>>>> = Rc::default();
2714            let pushed = Rc::clone(&result);
2715            pump(tester, move |_| {
2716                MaterialApp::new()
2717                    .home(Builder::new(move |_app, context| {
2718                        let pushed = Rc::clone(&pushed);
2719                        Material::new()
2720                            .child(ElevatedButton::new(
2721                                Some(Listener::new(move |app| {
2722                                    *pushed.borrow_mut() =
2723                                        Some(Navigator::push_named(app, context, "/a", None));
2724                                })),
2725                                Some(Text::new("X")),
2726                            ))
2727                            .into_widget()
2728                    }))
2729                    .routes([(
2730                        "/a".to_string(),
2731                        Rc::new(|_app: &mut App, context: BuildContext| {
2732                            Material::new()
2733                                .child(ElevatedButton::new(
2734                                    Some(Listener::new(move |app| {
2735                                        Navigator::pop(
2736                                            app,
2737                                            context,
2738                                            Some(Rc::new("all done") as Rc<dyn Any>),
2739                                        );
2740                                    })),
2741                                    Some(Text::new("Y")),
2742                                ))
2743                                .into_widget()
2744                        }) as WidgetBuilder,
2745                    )])
2746            });
2747            tester.tap(find::text("X"));
2748            tester.pump();
2749            tester.pump_by(Duration::from_secs(1));
2750            expect(tester, &find::text("Y"), finds_one_widget());
2751            tester.tap(find::text("Y"));
2752            tester.pump();
2753
2754            let value = result
2755                .borrow()
2756                .as_ref()
2757                .expect("X pushed /a")
2758                .peek()
2759                .expect("the route completed");
2760            let value = value.expect("a result");
2761            assert_eq!(value.downcast_ref::<&str>(), Some(&"all done"));
2762        });
2763    }
2764
2765    #[test]
2766    fn when_use_inherited_media_query_is_true_an_existing_media_query_is_used_if_one_is_available()
2767    {
2768        test_widgets(|tester| {
2769            let captured_context: Rc<Cell<Option<BuildContext>>> = Rc::default();
2770            let unique_key: KeyRef = KeyRef::Local(Rc::new(waft_foundation::UniqueKey::new()));
2771            let captured = Rc::clone(&captured_context);
2772            #[allow(deprecated)]
2773            let app = MaterialApp::new()
2774                .use_inherited_media_query(true)
2775                .builder(move |_app, context, _child| {
2776                    captured.set(Some(context));
2777                    // Dart's `Placeholder`, which Waft does not have; the case reads only the context.
2778                    SizedBox::new().into_widget()
2779                })
2780                .color(Color::new(0xFF123456));
2781            tester.pump_widget(
2782                MediaQuery::new(MediaQueryData::new(), app)
2783                    .key(unique_key.clone())
2784                    .into_widget(),
2785            );
2786            let context = captured_context.get().expect("the builder ran");
2787            let mut app = tester.cell.borrow_mut();
2788            let key = context
2789                .depend_on_inherited_widget_of_exact_type::<MediaQuery>(&mut app)
2790                .and_then(|media_query| media_query.key.clone());
2791            assert_eq!(key, Some(unique_key));
2792        });
2793    }
2794}