Skip to main content

waft_widgets/widgets/
media_query.rs

1//! Flutter counterpart: `widgets/media_query.dart`.
2//!
3//! [`MediaQuery::from_view`] derives its data from the view when its dependencies or its
4//! widget change, and again at each change of the platform its `WidgetsBindingObserver` hears:
5//! the metrics, the accessibility features, the text scale factor, the brightness, and the
6//! user's caption style, which Flutter's data has no counterpart of. `DisplayFeature`,
7//! `SystemTextScaler`, `debugBrightnessOverride`, and the deprecated `textScaleFactor`
8//! members are absent; see `PORTING.md`.
9
10use std::collections::HashSet;
11use std::fmt::{self, Debug};
12use std::rc::Rc;
13
14use waft_embedder::{
15    Brightness, CaptionStyle, Size, TitleBarArea, View as EmbedderView, ViewPadding, ViewRef,
16};
17use waft_foundation::{App, DiagnosticPropertiesBuilder, DiagnosticsProperty, Handle};
18use waft_gestures::{DeviceGestureSettings, K_TOUCH_SLOP};
19use waft_painting::{BorderRadius, EdgeInsets, TextScaler};
20
21use crate::binding::{WidgetsBinding, WidgetsBindingObserverObject, WidgetsBindingObserverRef};
22use crate::framework::{
23    BuildContext, InheritedModel, InheritedModelKind, InheritedWidget, IntoWidget, KeyRef, State,
24    StateData, StatefulWidget, WidgetRef,
25};
26use crate::widgets::basic::Builder;
27
28/// Whether in portrait or landscape.
29#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
30pub enum Orientation {
31    /// Taller than wide.
32    Portrait,
33
34    /// Wider than tall.
35    Landscape,
36}
37
38/// Specifies a part of [`MediaQueryData`] to depend on.
39///
40/// [`MediaQuery`] contains a large number of related properties. Widgets frequently depend
41/// on only a few of these attributes. For example, a widget that needs to rebuild when the
42/// [`MediaQueryData::text_scaler`] changes does not need to be notified when the
43/// [`MediaQueryData::size`] changes. Specifying an aspect avoids unnecessary rebuilds.
44///
45/// Dart's private `_MediaQueryAspect`; public here because it is the [`InheritedModel`]
46/// aspect type of [`MediaQuery`].
47#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
48pub enum MediaQueryAspect {
49    /// Specifies the aspect corresponding to [`MediaQueryData::size`].
50    Size,
51
52    /// Specifies the aspect corresponding to the width of [`MediaQueryData::size`].
53    Width,
54
55    /// Specifies the aspect corresponding to the height of [`MediaQueryData::size`].
56    Height,
57
58    /// Specifies the aspect corresponding to [`MediaQueryData::orientation`].
59    Orientation,
60
61    /// Specifies the aspect corresponding to [`MediaQueryData::device_pixel_ratio`].
62    DevicePixelRatio,
63
64    /// Specifies the aspect corresponding to [`MediaQueryData::text_scaler`].
65    TextScaler,
66
67    /// Specifies the aspect corresponding to [`MediaQueryData::platform_brightness`].
68    PlatformBrightness,
69
70    /// Specifies the aspect corresponding to [`MediaQueryData::padding`].
71    Padding,
72
73    /// Specifies the aspect corresponding to [`MediaQueryData::view_insets`].
74    ViewInsets,
75
76    /// Specifies the aspect corresponding to [`MediaQueryData::system_gesture_insets`].
77    SystemGestureInsets,
78
79    /// Specifies the aspect corresponding to [`MediaQueryData::view_padding`].
80    ViewPadding,
81
82    /// Specifies the aspect corresponding to [`MediaQueryData::always_use_24_hour_format`].
83    AlwaysUse24HourFormat,
84
85    /// Specifies the aspect corresponding to [`MediaQueryData::accessible_navigation`].
86    AccessibleNavigation,
87
88    /// Specifies the aspect corresponding to [`MediaQueryData::invert_colors`].
89    InvertColors,
90
91    /// Specifies the aspect corresponding to [`MediaQueryData::high_contrast`].
92    HighContrast,
93
94    /// Specifies the aspect corresponding to [`MediaQueryData::on_off_switch_labels`].
95    OnOffSwitchLabels,
96
97    /// Specifies the aspect corresponding to [`MediaQueryData::disable_animations`].
98    DisableAnimations,
99
100    /// Specifies the aspect corresponding to [`MediaQueryData::reduce_motion`].
101    ReduceMotion,
102
103    /// Specifies the aspect corresponding to [`MediaQueryData::bold_text`].
104    BoldText,
105
106    /// Specifies the aspect corresponding to [`MediaQueryData::supports_announce`].
107    SupportsAnnounce,
108
109    /// Specifies the aspect corresponding to [`MediaQueryData::navigation_mode`].
110    NavigationMode,
111
112    /// Specifies the aspect corresponding to [`MediaQueryData::gesture_settings`].
113    GestureSettings,
114
115    /// Specifies the aspect corresponding to
116    /// [`MediaQueryData::supports_showing_system_context_menu`].
117    SupportsShowingSystemContextMenu,
118
119    /// Specifies the aspect corresponding to
120    /// [`MediaQueryData::line_height_scale_factor_override`].
121    LineHeightScaleFactorOverride,
122
123    /// Specifies the aspect corresponding to [`MediaQueryData::letter_spacing_override`].
124    LetterSpacingOverride,
125
126    /// Specifies the aspect corresponding to [`MediaQueryData::word_spacing_override`].
127    WordSpacingOverride,
128
129    /// Specifies the aspect corresponding to [`MediaQueryData::paragraph_spacing_override`].
130    ParagraphSpacingOverride,
131
132    /// Specifies the aspect corresponding to [`MediaQueryData::display_corner_radii`].
133    DisplayCornerRadii,
134
135    /// Specifies the aspect corresponding to [`MediaQueryData::caption_style`].
136    CaptionStyle,
137
138    /// Specifies the aspect corresponding to [`MediaQueryData::title_bar_area`].
139    TitleBarArea,
140}
141
142// ---------------------------------------------------------------------------------------------
143// MediaQueryData
144
145/// Information about a piece of media (e.g., a window).
146///
147/// For example, the [`size`](Self::size) property contains the width and height of the
148/// current window.
149///
150/// To obtain individual attributes in a [`MediaQueryData`], prefer to use the
151/// attribute-specific functions of [`MediaQuery`] over obtaining the entire
152/// [`MediaQueryData`] and accessing its members. Querying using [`MediaQuery::of`] will cause
153/// your widget to rebuild automatically whenever _any_ field of the [`MediaQueryData`]
154/// changes (e.g., if the user rotates their device). Therefore, unless you are concerned
155/// with the entire [`MediaQueryData`] object changing, prefer using the specific methods
156/// (for example: [`MediaQuery::size_of`] and [`MediaQuery::padding_of`]), as it will rebuild
157/// more efficiently.
158///
159/// To obtain the entire current [`MediaQueryData`] for a given [`BuildContext`], use the
160/// [`MediaQuery::of`] function. This can be useful if you are going to use
161/// [`copy_with`](Self::copy_with) to replace the [`MediaQueryData`] with one with an updated
162/// property.
163///
164/// ## Insets and Padding
165///
166/// [`padding`](Self::padding) relates to [`view_padding`](Self::view_padding) and
167/// [`view_insets`](Self::view_insets), in the simplest configuration, as the difference
168/// between the two. In cases when the view insets exceed the view padding, like when a
169/// software keyboard is shown below, padding goes to zero rather than a negative value.
170/// Therefore, padding is calculated by taking `max(0.0, viewPadding - viewInsets)`.
171///
172/// [`MediaQueryData`] includes three [`EdgeInsets`] values: [`padding`](Self::padding),
173/// [`view_padding`](Self::view_padding), and [`view_insets`](Self::view_insets). These
174/// values reflect the configuration of the device and are used and optionally consumed by
175/// widgets that position content within these insets. The padding value defines areas that
176/// might not be completely visible, like the display "notch" on the iPhone X. The
177/// view insets value defines areas that aren't visible at all, typically because they're
178/// obscured by the device's keyboard. Similar to view insets, view padding does not
179/// differentiate padding in areas that may be obscured. For example, by using the view
180/// padding property, padding would defer to the iPhone "safe area" regardless of whether a
181/// keyboard is showing.
182///
183/// The view insets and view padding are independent values, they're measured from the
184/// edges of the [`MediaQuery`] widget's bounds. Together they inform the
185/// [`padding`](Self::padding) property. The bounds of the top level [`MediaQuery`] created
186/// by `WidgetsApp` are the same as the window that contains the app.
187///
188/// Widgets whose layouts consume space defined by [`view_insets`](Self::view_insets),
189/// [`view_padding`](Self::view_padding), or [`padding`](Self::padding) should enclose their
190/// children in secondary [`MediaQuery`] widgets that reduce those properties by the same
191/// amount. The [`remove_padding`](Self::remove_padding),
192/// [`remove_view_padding`](Self::remove_view_padding), and
193/// [`remove_view_insets`](Self::remove_view_insets) methods are useful for this.
194///
195/// Dart's named constructor arguments are the fluent setters
196/// (`MediaQueryData::new().size(size).padding(padding)`); [`copy_with`](Self::copy_with)
197/// clones for the same chain.
198#[derive(Clone)]
199pub struct MediaQueryData {
200    /// The size of the media in logical pixels (e.g, the size of the screen).
201    ///
202    /// Logical pixels are roughly the same visual size across devices. Physical pixels are
203    /// the size of the actual hardware pixels on the device. The number of physical pixels
204    /// per logical pixel is described by the [`device_pixel_ratio`](Self::device_pixel_ratio).
205    ///
206    /// Prefer using [`MediaQuery::size_of`] over [`MediaQuery::of`]`.size` to get the size,
207    /// since the former will only notify of changes in [`size`](Self::size), while the latter
208    /// will notify for all [`MediaQueryData`] changes.
209    ///
210    /// For widgets drawn in an `Overlay`, do not assume that the size of the `Overlay` is
211    /// the size of the [`MediaQuery`]'s size. Nested overlays can have different sizes.
212    ///
213    /// ## Troubleshooting
214    ///
215    /// It is considered bad practice to cache and later use the size returned by
216    /// `MediaQuery::size_of(app, context)`. It will make the application non-responsive and
217    /// might lead to unexpected behaviors.
218    ///
219    /// For instance, during startup, especially in release mode, the first returned size
220    /// might be [`Size::ZERO`]. The size will be updated when the native platform reports
221    /// the actual resolution. Using [`MediaQuery::size_of`] will ensure that when the size
222    /// changes, any widgets depending on the size are automatically rebuilt.
223    pub size: Size,
224
225    /// The number of device pixels for each logical pixel of the encompassing view. This
226    /// number might not be a power of two. Indeed, it might not even be an integer. For
227    /// example, the Nexus 6 has a device pixel ratio of 3.5.
228    ///
229    /// This property is typically only informational. Overriding this property does not
230    /// rescale the app as the framework or its rendering pipeline usually does not read this
231    /// value.
232    pub device_pixel_ratio: f64,
233
234    /// The font scaling strategy to use for laying out textual contents.
235    ///
236    /// If this [`MediaQueryData`] is created by the [`from_view`](Self::from_view)
237    /// constructor, this property reflects the platform's preferred text scaling strategy,
238    /// and may change as the user changes the scaling factor in the operating system's
239    /// accessibility settings.
240    ///
241    /// See also:
242    ///
243    ///  * [`MediaQuery::text_scaler_of`], a method to find and depend on the
244    ///    [`text_scaler`](Self::text_scaler) defined for a [`BuildContext`].
245    ///  * `TextPainter`, a class that lays out and paints text.
246    pub text_scaler: TextScaler,
247
248    /// The current brightness mode of the host platform.
249    ///
250    /// For example, starting in Android Pie, battery saver mode asks all apps to render in
251    /// a "dark mode".
252    ///
253    /// Not all platforms necessarily support a concept of brightness mode. Those platforms
254    /// will report [`Brightness::Light`] in this property.
255    ///
256    /// See also:
257    ///
258    ///  * [`MediaQuery::platform_brightness_of`], a method to find and depend on the
259    ///    platform brightness defined for a [`BuildContext`].
260    pub platform_brightness: Brightness,
261
262    /// The parts of the display that are completely obscured by system UI, typically by the
263    /// device's keyboard.
264    ///
265    /// When a mobile device's keyboard is visible `view_insets.bottom` corresponds to the
266    /// top of the keyboard.
267    ///
268    /// This value is independent of the [`padding`](Self::padding) and
269    /// [`view_padding`](Self::view_padding). View padding is measured from the edges of the
270    /// [`MediaQuery`] widget's bounds. Padding is calculated based on the view padding and
271    /// view insets. The bounds of the top level [`MediaQuery`] created by `WidgetsApp` are
272    /// the same as the window (often the mobile device screen) that contains the app.
273    pub view_insets: EdgeInsets,
274
275    /// The parts of the display that are partially obscured by system UI, typically by the
276    /// hardware display "notches" or the system status bar.
277    ///
278    /// If you consumed this padding (e.g. by building a widget that envelops or accounts for
279    /// this padding in its layout in such a way that children are no longer exposed to this
280    /// padding), you should remove this padding for subsequent descendants in the widget
281    /// tree by inserting a new [`MediaQuery`] widget using the [`MediaQuery::remove_padding`]
282    /// constructor.
283    ///
284    /// Padding is derived from the values of [`view_insets`](Self::view_insets) and
285    /// [`view_padding`](Self::view_padding).
286    ///
287    /// See also:
288    ///
289    ///  * `SafeArea`, a widget that consumes this padding with a `Padding` widget and
290    ///    automatically removes it from the [`MediaQuery`] for its child.
291    pub padding: EdgeInsets,
292
293    /// The parts of the display that are partially obscured by system UI, typically by the
294    /// hardware display "notches" or the system status bar.
295    ///
296    /// This value remains the same regardless of whether the system is reporting other
297    /// obstructions in the same physical area of the screen. For example, a software
298    /// keyboard on the bottom of the screen that may cover and consume the same area that
299    /// requires bottom padding will not affect this value.
300    ///
301    /// This value is independent of the [`padding`](Self::padding) and
302    /// [`view_insets`](Self::view_insets): their values are measured from the edges of the
303    /// [`MediaQuery`] widget's bounds. The bounds of the top level [`MediaQuery`] created by
304    /// `WidgetsApp` are the same as the window that contains the app. On mobile devices,
305    /// this will typically be the full screen.
306    pub view_padding: EdgeInsets,
307
308    /// The areas along the edges of the display where the system consumes certain input
309    /// events and blocks delivery of those events to the app.
310    ///
311    /// Starting with Android Q, simple swipe gestures that start within the
312    /// [`system_gesture_insets`](Self::system_gesture_insets) areas are used by the system
313    /// for page navigation and may not be delivered to the app. Taps and swipe gestures that
314    /// begin with a long-press are delivered to the app, but simple press-drag-release swipe
315    /// gestures which begin within the area defined by
316    /// [`system_gesture_insets`](Self::system_gesture_insets) may not be.
317    ///
318    /// Apps should avoid locating gesture detectors within the system gesture insets area.
319    /// Apps should feel free to put visual elements within this area.
320    ///
321    /// This property is currently only expected to be set to a non-default value on Android
322    /// starting with version Q.
323    pub system_gesture_insets: EdgeInsets,
324
325    /// Whether to use 24-hour format when formatting time.
326    ///
327    /// The behavior of this flag is different across platforms:
328    ///
329    /// - On Android this flag is reported directly from the user settings called "Use
330    ///   24-hour format". It applies to any locale used by the application, whether it is
331    ///   the system-wide locale, or the custom locale set by the application.
332    /// - On iOS this flag is set to true when the user setting called "24-Hour Time" is set
333    ///   or the system-wide locale's default uses 24-hour formatting.
334    /// - On macOS this flag reflects the current system locale's time format, which
335    ///   incorporates the "24-Hour Time" preference in System Settings. As on iOS, this only
336    ///   takes effect for the system locale; a custom locale passed to the application will
337    ///   ignore the 24-hour preference.
338    /// - On Windows this flag is derived from the user's "Short time" format in the Region
339    ///   settings; it is true when the configured format uses a 24-hour pattern.
340    /// - On Linux this flag reflects the desktop environment's clock-format setting where
341    ///   available (for example, `org.gnome.desktop.interface.clock-format` on GNOME). On
342    ///   desktops that do not expose such a setting, it defaults to true (24-hour).
343    /// - On Web this flag is always false.
344    pub always_use_24_hour_format: bool,
345
346    /// Whether the user is using an accessibility service like TalkBack or VoiceOver to
347    /// interact with the application.
348    ///
349    /// When this setting is true, features such as timeouts should be disabled or have
350    /// minimum durations increased.
351    pub accessible_navigation: bool,
352
353    /// Whether the operating system is currently inverting the colors of the platform.
354    ///
355    /// This flag indicates that the underlying OS is already performing a global color
356    /// inversion at the screen level. It does not mean the framework will automatically
357    /// invert its own layout painting.
358    ///
359    /// Instead, this flag allows the application to react to the inversion. For example, by
360    /// selectively re-inverting images, maps, or video playback so that they display with
361    /// natural colors instead of looking like a film negative.
362    ///
363    /// This flag is currently only updated on iOS devices.
364    pub invert_colors: bool,
365
366    /// Whether the platform is requesting a high contrast between foreground and background
367    /// content.
368    ///
369    /// On iOS, this corresponds to the "Increase Contrast" setting in Settings ->
370    /// Accessibility. On Android, this corresponds to the "High contrast text" or similar
371    /// accessibility settings.
372    ///
373    /// This flag indicates that the operating system is already performing high-contrast
374    /// adjustments or expects the application to adjust its color palette to meet higher
375    /// accessibility standards.
376    ///
377    /// This flag is currently only updated on iOS devices running iOS 13+ and Android
378    /// devices running API 34+.
379    pub high_contrast: bool,
380
381    /// Whether the user requested to show on/off labels inside switches on iOS, via Settings
382    /// -> Accessibility -> Display & Text Size -> On/Off Labels.
383    pub on_off_switch_labels: bool,
384
385    /// Whether the platform is requesting that animations be disabled or reduced as much as
386    /// possible.
387    ///
388    /// This corresponds to Android's "Remove animations" accessibility setting.
389    ///
390    /// On iOS, reduced motion is exposed separately via
391    /// [`reduce_motion`](Self::reduce_motion) and does not set this flag.
392    ///
393    /// Manually overriding this value in a [`MediaQuery`] widget will not affect framework
394    /// animations (for example those driven by `AnimationController`). However, it can still
395    /// be useful for testing or for custom widgets that explicitly read
396    /// [`disable_animations`](Self::disable_animations).
397    ///
398    /// When implementing custom explicit animations, you should check this property and
399    /// adjust behavior accordingly (for example, by reducing duration or skipping
400    /// non-essential animations when it is true).
401    pub disable_animations: bool,
402
403    /// Whether the platform is requesting that animations be reduced or replaced with
404    /// cross-fades in preference to motion effects.
405    ///
406    /// This corresponds to the iOS "Reduce Motion" accessibility setting.
407    ///
408    /// Unlike [`disable_animations`](Self::disable_animations), this flag does not
409    /// automatically alter framework animations such as those controlled via
410    /// `AnimationController`. Instead, it is intended to be read by widgets that want to
411    /// tone down or replace non-essential motion, for example by substituting a cross-fade
412    /// for a slide transition.
413    ///
414    /// When implementing custom animations, you should check this property and adjust
415    /// behavior accordingly; for example, by preferring a fade over movement when it is
416    /// true.
417    pub reduce_motion: bool,
418
419    /// Whether the platform is requesting that text be drawn with a bold font weight.
420    pub bold_text: bool,
421
422    /// Whether accessibility announcements (like `SemanticsService.sendAnnouncement`) are
423    /// supported on the current platform.
424    ///
425    /// Returns `false` on platforms where announcements are deprecated or unsupported by the
426    /// underlying platform.
427    ///
428    /// Returns `true` on platforms where such announcements are generally supported without
429    /// discouragement. (iOS, web etc)
430    pub supports_announce: bool,
431
432    /// Describes the navigation mode requested by the platform.
433    ///
434    /// Some user interfaces are better navigated using a directional pad (DPAD) or arrow
435    /// keys, and for those interfaces, some widgets need to handle these directional events
436    /// differently. In order to know when to do that, these widgets will look for the
437    /// navigation mode in effect for their context.
438    ///
439    /// For instance, in a television interface, [`NavigationMode::Directional`] should be
440    /// set, so that directional navigation is used to navigate away from a text field using
441    /// the DPAD. In contrast, on a regular desktop application with the
442    /// [`navigation_mode`](Self::navigation_mode) set to [`NavigationMode::Traditional`],
443    /// the arrow keys are used to move the cursor instead of navigating away.
444    ///
445    /// The [`NavigationMode`] values indicate the type of navigation to be used in a widget
446    /// subtree for those widgets sensitive to it.
447    pub navigation_mode: NavigationMode,
448
449    /// The gesture settings for the view this media query is derived from.
450    ///
451    /// This contains platform specific configuration for gesture behavior, such as touch
452    /// slop. These settings should be favored for configuring gesture behavior over the
453    /// framework constants.
454    pub gesture_settings: DeviceGestureSettings,
455
456    /// Whether showing the system context menu is supported.
457    ///
458    /// For example, on iOS 16.0 and above, the system text selection context menu may be
459    /// shown instead of the framework-drawn context menu in order to avoid the iOS clipboard
460    /// access notification when the "Paste" button is pressed.
461    pub supports_showing_system_context_menu: bool,
462
463    /// Overrides the height of the text, as a multiple of the font size.
464    ///
465    /// `None` when the platform has not set an override for text height.
466    ///
467    /// See also:
468    ///
469    ///  * `Text`, `SelectableText`, and `EditableText`, all of whose `TextStyle.height` and
470    ///    `StrutStyle.height` are overridden by this.
471    pub line_height_scale_factor_override: Option<f64>,
472
473    /// Overrides the amount of space (in logical pixels) to add between each letter in a
474    /// piece of text.
475    ///
476    /// A negative value can be used to bring the letters closer.
477    ///
478    /// `None` when the platform has not set an override for text letter spacing.
479    pub letter_spacing_override: Option<f64>,
480
481    /// Overrides the amount of space (in logical pixels) to add at each sequence of
482    /// white-space (i.e. between each word) in a piece of text.
483    ///
484    /// A negative value can be used to bring the words closer.
485    ///
486    /// `None` when the platform has not set an override for text word spacing.
487    pub word_spacing_override: Option<f64>,
488
489    /// The amount of space (in logical pixels) to add following each paragraph in a piece of
490    /// text.
491    ///
492    /// `None` when the platform has not set an override for text paragraph spacing.
493    pub paragraph_spacing_override: Option<f64>,
494
495    /// The radii of the display corners in logical pixels.
496    ///
497    /// This is currently populated only on Android API 31+. On earlier Android versions,
498    /// iOS, and other platforms, this value is `None`.
499    pub display_corner_radii: Option<BorderRadius>,
500
501    /// How the user's system-wide settings say subtitles and captions look, which a
502    /// `SubtitleView` merges into each cue it draws.
503    ///
504    /// If this [`MediaQueryData`] is created by the [`from_view`](Self::from_view)
505    /// constructor, this property is the platform's caption settings' style, and changes as
506    /// the user changes them; `None` where the platform keeps no caption settings, as Linux
507    /// and the web keep none.
508    ///
509    /// See also:
510    ///
511    ///  * [`MediaQuery::maybe_caption_style_of`], a method to find and depend on the caption
512    ///    style defined for a [`BuildContext`].
513    pub caption_style: Option<CaptionStyle>,
514
515    /// The strip along the top that the system's window buttons sit in, in logical pixels, for a
516    /// title bar to draw its items beside them: on an iPad window, the close, minimize and zoom
517    /// buttons at its top left.
518    ///
519    /// [`padding`](Self::padding) and [`view_padding`](Self::view_padding) already reach below the
520    /// strip, so content laid out within them is clear of the buttons; only a widget that draws
521    /// in the strip itself reads this. Removing the top padding removes it too, since what is laid
522    /// out below the top is not in the strip.
523    ///
524    /// If this [`MediaQueryData`] is created by the [`from_view`](Self::from_view) constructor,
525    /// this property is the view's title bar area, and changes as the window enters or leaves full
526    /// screen; `None` while no buttons are over the view.
527    ///
528    /// See also:
529    ///
530    ///  * [`MediaQuery::title_bar_area_of`], a method to find and depend on the title bar area
531    ///    defined for a [`BuildContext`].
532    pub title_bar_area: Option<TitleBarArea>,
533}
534
535/// Dart's `MediaQueryData.toString`, which a `MediaQuery` dump prints.
536impl fmt::Display for MediaQueryData {
537    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
538        fmt::Debug::fmt(self, f)
539    }
540}
541
542impl MediaQueryData {
543    /// Creates data for a media query with explicit values.
544    ///
545    /// In a typical application, calling this constructor directly is rarely needed.
546    /// Consider using [`from_view`](Self::from_view) to create data based on a view, or
547    /// [`copy_with`](Self::copy_with) to create a new copy of [`MediaQueryData`] with
548    /// updated properties from a base [`MediaQueryData`].
549    pub fn new() -> MediaQueryData {
550        MediaQueryData {
551            size: Size::ZERO,
552            device_pixel_ratio: 1.0,
553            text_scaler: TextScaler::NO_SCALING,
554            platform_brightness: Brightness::Light,
555            view_insets: EdgeInsets::ZERO,
556            padding: EdgeInsets::ZERO,
557            view_padding: EdgeInsets::ZERO,
558            system_gesture_insets: EdgeInsets::ZERO,
559            always_use_24_hour_format: false,
560            accessible_navigation: false,
561            invert_colors: false,
562            high_contrast: false,
563            on_off_switch_labels: false,
564            disable_animations: false,
565            reduce_motion: false,
566            bold_text: false,
567            supports_announce: false,
568            navigation_mode: NavigationMode::Traditional,
569            gesture_settings: DeviceGestureSettings::new(Some(K_TOUCH_SLOP)),
570            supports_showing_system_context_menu: false,
571            line_height_scale_factor_override: None,
572            letter_spacing_override: None,
573            word_spacing_override: None,
574            paragraph_spacing_override: None,
575            display_corner_radii: None,
576            caption_style: None,
577            title_bar_area: None,
578        }
579    }
580
581    /// Creates data for a [`MediaQuery`] based on the given `view`.
582    ///
583    /// If provided, the `platform_data` is used to fill in the platform-specific aspects of
584    /// the newly created [`MediaQueryData`]. If `platform_data` is `None`, the platform
585    /// (`app.platform()`, Dart's `view.platformDispatcher`) is consulted to construct the
586    /// platform-specific data.
587    ///
588    /// Data which is exposed directly on the view is considered view-specific. Data which is
589    /// only exposed via the platform is considered platform-specific.
590    ///
591    /// Callers of this method should ensure that they also register for notifications so
592    /// that the [`MediaQueryData`] can be updated when any data used to construct it changes
593    /// (Dart's `WidgetsBindingObserver.didChangeMetrics`, `didChangeAccessibilityFeatures`,
594    /// `didChangeTextScaleFactor`, and `didChangePlatformBrightness`, which wait with the
595    /// observer). The last three notifications are only relevant if no `platform_data` is
596    /// provided. If `platform_data` is provided, callers should ensure to call this method
597    /// again when it changes to keep the constructed [`MediaQueryData`] updated.
598    ///
599    /// The platform here reports its brightness, its system context menu support, and the
600    /// user's caption style: the accessibility features, the 24-hour format, the text scale
601    /// factor, and the text style overrides, as well as the view's system gesture insets and
602    /// display corner radii, keep their defaults until the embedder exposes them (see
603    /// `PORTING.md`).
604    ///
605    /// In general, [`MediaQuery::of`], and its associated "...Of" methods, are the
606    /// appropriate way to obtain [`MediaQueryData`] from a widget. This `from_view`
607    /// constructor is primarily for use in the implementation of the framework itself.
608    ///
609    /// See also:
610    ///
611    ///  * [`MediaQuery::from_view`], which constructs [`MediaQueryData`] from a provided
612    ///    view, makes it available to descendant widgets, and sets up the appropriate
613    ///    notification listeners to keep the data updated.
614    pub fn from_view(
615        app: &App,
616        view: &dyn EmbedderView,
617        platform_data: Option<&MediaQueryData>,
618    ) -> MediaQueryData {
619        let metrics = view.metrics();
620        let device_pixel_ratio = metrics.device_pixel_ratio;
621        MediaQueryData {
622            size: Size::new(metrics.physical_size[0], metrics.physical_size[1])
623                / device_pixel_ratio,
624            device_pixel_ratio,
625            text_scaler: Self::text_scaler_from_view(platform_data),
626            platform_brightness: platform_data.map_or_else(
627                || app.platform().platform_brightness(),
628                |data| data.platform_brightness,
629            ),
630            padding: edge_insets_from_view_padding(metrics.padding, device_pixel_ratio),
631            view_padding: edge_insets_from_view_padding(metrics.view_padding, device_pixel_ratio),
632            view_insets: edge_insets_from_view_padding(metrics.view_insets, device_pixel_ratio),
633            system_gesture_insets: edge_insets_from_view_padding(
634                metrics.system_gesture_insets,
635                device_pixel_ratio,
636            ),
637            accessible_navigation: platform_data.is_some_and(|data| data.accessible_navigation),
638            invert_colors: platform_data.is_some_and(|data| data.invert_colors),
639            disable_animations: platform_data.is_some_and(|data| data.disable_animations),
640            reduce_motion: platform_data.is_some_and(|data| data.reduce_motion),
641            bold_text: platform_data.is_some_and(|data| data.bold_text),
642            supports_announce: platform_data.is_some_and(|data| data.supports_announce),
643            high_contrast: platform_data.is_some_and(|data| data.high_contrast),
644            on_off_switch_labels: platform_data.is_some_and(|data| data.on_off_switch_labels),
645            always_use_24_hour_format: platform_data
646                .is_some_and(|data| data.always_use_24_hour_format),
647            navigation_mode: platform_data
648                .map_or(NavigationMode::Traditional, |data| data.navigation_mode),
649            gesture_settings: DeviceGestureSettings::from_view(view),
650            supports_showing_system_context_menu: platform_data.map_or_else(
651                || app.platform().system_context_menu().is_some(),
652                |data| data.supports_showing_system_context_menu,
653            ),
654            line_height_scale_factor_override: platform_data
655                .and_then(|data| data.line_height_scale_factor_override),
656            letter_spacing_override: platform_data.and_then(|data| data.letter_spacing_override),
657            word_spacing_override: platform_data.and_then(|data| data.word_spacing_override),
658            paragraph_spacing_override: platform_data
659                .and_then(|data| data.paragraph_spacing_override),
660            display_corner_radii: None,
661            caption_style: platform_data.map_or_else(
662                || Self::caption_style_from_platform(app),
663                |data| data.caption_style.clone(),
664            ),
665            title_bar_area: metrics
666                .title_bar_area
667                .map(|area| title_bar_area_from_view(area, device_pixel_ratio)),
668        }
669    }
670
671    /// The style of the platform's caption settings, or `None` where it keeps none.
672    fn caption_style_from_platform(app: &App) -> Option<CaptionStyle> {
673        let platform = app.platform();
674        Some(platform.caption_settings()?.style())
675    }
676
677    /// Dart's `_textScalerFromView`: the parent's scaler, else the platform's.
678    /// `SystemTextScaler` waits for the embedder's text scale factor; a platform that
679    /// reports none scales by 1.0, which is [`TextScaler::NO_SCALING`].
680    fn text_scaler_from_view(platform_data: Option<&MediaQueryData>) -> TextScaler {
681        platform_data.map_or(TextScaler::NO_SCALING, |data| data.text_scaler.clone())
682    }
683
684    /// Dart `MediaQueryData(size:)`.
685    pub fn size(mut self, size: Size) -> MediaQueryData {
686        self.size = size;
687        self
688    }
689
690    /// Dart `MediaQueryData(devicePixelRatio:)`.
691    pub fn device_pixel_ratio(mut self, device_pixel_ratio: f64) -> MediaQueryData {
692        self.device_pixel_ratio = device_pixel_ratio;
693        self
694    }
695
696    /// Dart `MediaQueryData(textScaler:)`.
697    pub fn text_scaler(mut self, text_scaler: TextScaler) -> MediaQueryData {
698        self.text_scaler = text_scaler;
699        self
700    }
701
702    /// Dart `MediaQueryData(platformBrightness:)`.
703    pub fn platform_brightness(mut self, platform_brightness: Brightness) -> MediaQueryData {
704        self.platform_brightness = platform_brightness;
705        self
706    }
707
708    /// Dart `MediaQueryData(padding:)`.
709    pub fn padding(mut self, padding: EdgeInsets) -> MediaQueryData {
710        self.padding = padding;
711        self
712    }
713
714    /// Dart `MediaQueryData(viewInsets:)`.
715    pub fn view_insets(mut self, view_insets: EdgeInsets) -> MediaQueryData {
716        self.view_insets = view_insets;
717        self
718    }
719
720    /// Dart `MediaQueryData(systemGestureInsets:)`.
721    pub fn system_gesture_insets(mut self, system_gesture_insets: EdgeInsets) -> MediaQueryData {
722        self.system_gesture_insets = system_gesture_insets;
723        self
724    }
725
726    /// Dart `MediaQueryData(viewPadding:)`.
727    pub fn view_padding(mut self, view_padding: EdgeInsets) -> MediaQueryData {
728        self.view_padding = view_padding;
729        self
730    }
731
732    /// Dart `MediaQueryData(alwaysUse24HourFormat:)`.
733    pub fn always_use_24_hour_format(mut self, always_use_24_hour_format: bool) -> MediaQueryData {
734        self.always_use_24_hour_format = always_use_24_hour_format;
735        self
736    }
737
738    /// Dart `MediaQueryData(accessibleNavigation:)`.
739    pub fn accessible_navigation(mut self, accessible_navigation: bool) -> MediaQueryData {
740        self.accessible_navigation = accessible_navigation;
741        self
742    }
743
744    /// Dart `MediaQueryData(invertColors:)`.
745    pub fn invert_colors(mut self, invert_colors: bool) -> MediaQueryData {
746        self.invert_colors = invert_colors;
747        self
748    }
749
750    /// Dart `MediaQueryData(highContrast:)`.
751    pub fn high_contrast(mut self, high_contrast: bool) -> MediaQueryData {
752        self.high_contrast = high_contrast;
753        self
754    }
755
756    /// Dart `MediaQueryData(onOffSwitchLabels:)`.
757    pub fn on_off_switch_labels(mut self, on_off_switch_labels: bool) -> MediaQueryData {
758        self.on_off_switch_labels = on_off_switch_labels;
759        self
760    }
761
762    /// Dart `MediaQueryData(disableAnimations:)`.
763    pub fn disable_animations(mut self, disable_animations: bool) -> MediaQueryData {
764        self.disable_animations = disable_animations;
765        self
766    }
767
768    /// Dart `MediaQueryData(reduceMotion:)`.
769    pub fn reduce_motion(mut self, reduce_motion: bool) -> MediaQueryData {
770        self.reduce_motion = reduce_motion;
771        self
772    }
773
774    /// Dart `MediaQueryData(boldText:)`.
775    pub fn bold_text(mut self, bold_text: bool) -> MediaQueryData {
776        self.bold_text = bold_text;
777        self
778    }
779
780    /// Dart `MediaQueryData(supportsAnnounce:)`.
781    pub fn supports_announce(mut self, supports_announce: bool) -> MediaQueryData {
782        self.supports_announce = supports_announce;
783        self
784    }
785
786    /// Dart `MediaQueryData(navigationMode:)`.
787    pub fn navigation_mode(mut self, navigation_mode: NavigationMode) -> MediaQueryData {
788        self.navigation_mode = navigation_mode;
789        self
790    }
791
792    /// Dart `MediaQueryData(gestureSettings:)`.
793    pub fn gesture_settings(mut self, gesture_settings: DeviceGestureSettings) -> MediaQueryData {
794        self.gesture_settings = gesture_settings;
795        self
796    }
797
798    /// Dart `MediaQueryData(supportsShowingSystemContextMenu:)`.
799    pub fn supports_showing_system_context_menu(
800        mut self,
801        supports_showing_system_context_menu: bool,
802    ) -> MediaQueryData {
803        self.supports_showing_system_context_menu = supports_showing_system_context_menu;
804        self
805    }
806
807    /// Dart `MediaQueryData(lineHeightScaleFactorOverride:)`.
808    pub fn line_height_scale_factor_override(
809        mut self,
810        line_height_scale_factor_override: f64,
811    ) -> MediaQueryData {
812        self.line_height_scale_factor_override = Some(line_height_scale_factor_override);
813        self
814    }
815
816    /// Dart `MediaQueryData(letterSpacingOverride:)`.
817    pub fn letter_spacing_override(mut self, letter_spacing_override: f64) -> MediaQueryData {
818        self.letter_spacing_override = Some(letter_spacing_override);
819        self
820    }
821
822    /// The user's caption style; [`MediaQueryData`] has no counterpart in Dart.
823    pub fn caption_style(mut self, caption_style: CaptionStyle) -> MediaQueryData {
824        self.caption_style = Some(caption_style);
825        self
826    }
827
828    /// The strip the window buttons sit in; [`MediaQueryData`] has no counterpart in Dart.
829    pub fn title_bar_area(mut self, title_bar_area: TitleBarArea) -> MediaQueryData {
830        self.title_bar_area = Some(title_bar_area);
831        self
832    }
833
834    /// Dart `MediaQueryData(wordSpacingOverride:)`.
835    pub fn word_spacing_override(mut self, word_spacing_override: f64) -> MediaQueryData {
836        self.word_spacing_override = Some(word_spacing_override);
837        self
838    }
839
840    /// Dart `MediaQueryData(paragraphSpacingOverride:)`.
841    pub fn paragraph_spacing_override(mut self, paragraph_spacing_override: f64) -> MediaQueryData {
842        self.paragraph_spacing_override = Some(paragraph_spacing_override);
843        self
844    }
845
846    /// Dart `MediaQueryData(displayCornerRadii:)`.
847    pub fn display_corner_radii(mut self, display_corner_radii: BorderRadius) -> MediaQueryData {
848        self.display_corner_radii = Some(display_corner_radii);
849        self
850    }
851
852    /// The orientation of the media (e.g., whether the device is in landscape or portrait
853    /// mode).
854    pub fn orientation(&self) -> Orientation {
855        if self.size.width() > self.size.height() {
856            Orientation::Landscape
857        } else {
858            Orientation::Portrait
859        }
860    }
861
862    /// Creates a copy of this media query data but with the given fields replaced with the
863    /// new values: chain the field setters on the result
864    /// (`data.copy_with().text_scaler(TextScaler::NO_SCALING)`).
865    pub fn copy_with(&self) -> MediaQueryData {
866        self.clone()
867    }
868
869    /// Creates a copy of this media query data but with the
870    /// `line_height_scale_factor_override`, `letter_spacing_override`,
871    /// `word_spacing_override`, and `paragraph_spacing_override` replaced with the given
872    /// values.
873    ///
874    /// If an argument is `None`, then this [`MediaQueryData`] is returned with the
875    /// corresponding override set to `None`.
876    ///
877    /// See also:
878    ///
879    ///  * [`MediaQuery::apply_text_style_overrides`], which uses this method to apply text
880    ///    style overrides to the ambient [`MediaQuery`].
881    pub fn apply_text_style_overrides(
882        &self,
883        line_height_scale_factor_override: Option<f64>,
884        letter_spacing_override: Option<f64>,
885        word_spacing_override: Option<f64>,
886        paragraph_spacing_override: Option<f64>,
887    ) -> MediaQueryData {
888        MediaQueryData {
889            line_height_scale_factor_override,
890            letter_spacing_override,
891            word_spacing_override,
892            paragraph_spacing_override,
893            ..self.clone()
894        }
895    }
896
897    /// Creates a copy of this media query data but with the `display_corner_radii` replaced
898    /// with the given value.
899    ///
900    /// If the argument is `None`, then this [`MediaQueryData`] is returned with the
901    /// `display_corner_radii` set to `None`.
902    pub fn apply_display_corner_radii(
903        &self,
904        display_corner_radii: Option<BorderRadius>,
905    ) -> MediaQueryData {
906        MediaQueryData {
907            display_corner_radii,
908            ..self.clone()
909        }
910    }
911
912    /// Creates a copy of this media query data but with the given [`padding`](Self::padding)s
913    /// replaced with zero.
914    ///
915    /// If all four of the `remove_left`, `remove_top`, `remove_right`, and `remove_bottom`
916    /// arguments are false, then this [`MediaQueryData`] is returned unmodified.
917    ///
918    /// See also:
919    ///
920    ///  * [`MediaQuery::remove_padding`], which uses this method to remove
921    ///    [`padding`](Self::padding) from the ambient [`MediaQuery`].
922    ///  * `SafeArea`, which both removes the padding from the [`MediaQuery`] and adds a
923    ///    `Padding` widget.
924    ///  * [`remove_view_insets`](Self::remove_view_insets), the same thing but for
925    ///    [`view_insets`](Self::view_insets).
926    ///  * [`remove_view_padding`](Self::remove_view_padding), the same thing but for
927    ///    [`view_padding`](Self::view_padding).
928    pub fn remove_padding(
929        &self,
930        remove_left: bool,
931        remove_top: bool,
932        remove_right: bool,
933        remove_bottom: bool,
934    ) -> MediaQueryData {
935        if !(remove_left || remove_top || remove_right || remove_bottom) {
936            return self.clone();
937        }
938        self.copy_with()
939            .padding(self.padding.copy_with(
940                remove_left.then_some(0.0),
941                remove_top.then_some(0.0),
942                remove_right.then_some(0.0),
943                remove_bottom.then_some(0.0),
944            ))
945            .view_padding(self.view_padding.copy_with(
946                remove_left.then(|| (self.view_padding.left - self.padding.left).max(0.0)),
947                remove_top.then(|| (self.view_padding.top - self.padding.top).max(0.0)),
948                remove_right.then(|| (self.view_padding.right - self.padding.right).max(0.0)),
949                remove_bottom.then(|| (self.view_padding.bottom - self.padding.bottom).max(0.0)),
950            ))
951            .without_title_bar_area_if(remove_top)
952    }
953
954    /// Creates a copy of this media query data but with the given
955    /// [`view_insets`](Self::view_insets) replaced with zero.
956    ///
957    /// If all four of the `remove_left`, `remove_top`, `remove_right`, and `remove_bottom`
958    /// arguments are false, then this [`MediaQueryData`] is returned unmodified.
959    ///
960    /// See also:
961    ///
962    ///  * [`MediaQuery::remove_view_insets`], which uses this method to remove
963    ///    [`view_insets`](Self::view_insets) from the ambient [`MediaQuery`].
964    ///  * [`remove_padding`](Self::remove_padding), the same thing but for
965    ///    [`padding`](Self::padding).
966    ///  * [`remove_view_padding`](Self::remove_view_padding), the same thing but for
967    ///    [`view_padding`](Self::view_padding).
968    pub fn remove_view_insets(
969        &self,
970        remove_left: bool,
971        remove_top: bool,
972        remove_right: bool,
973        remove_bottom: bool,
974    ) -> MediaQueryData {
975        if !(remove_left || remove_top || remove_right || remove_bottom) {
976            return self.clone();
977        }
978        self.copy_with()
979            .view_padding(
980                self.view_padding.copy_with(
981                    remove_left.then(|| (self.view_padding.left - self.view_insets.left).max(0.0)),
982                    remove_top.then(|| (self.view_padding.top - self.view_insets.top).max(0.0)),
983                    remove_right
984                        .then(|| (self.view_padding.right - self.view_insets.right).max(0.0)),
985                    remove_bottom
986                        .then(|| (self.view_padding.bottom - self.view_insets.bottom).max(0.0)),
987                ),
988            )
989            .view_insets(self.view_insets.copy_with(
990                remove_left.then_some(0.0),
991                remove_top.then_some(0.0),
992                remove_right.then_some(0.0),
993                remove_bottom.then_some(0.0),
994            ))
995    }
996
997    /// Creates a copy of this media query data but with the given
998    /// [`view_padding`](Self::view_padding) replaced with zero.
999    ///
1000    /// If all four of the `remove_left`, `remove_top`, `remove_right`, and `remove_bottom`
1001    /// arguments are false, then this [`MediaQueryData`] is returned unmodified.
1002    ///
1003    /// See also:
1004    ///
1005    ///  * [`MediaQuery::remove_view_padding`], which uses this method to remove
1006    ///    [`view_padding`](Self::view_padding) from the ambient [`MediaQuery`].
1007    ///  * [`remove_padding`](Self::remove_padding), the same thing but for
1008    ///    [`padding`](Self::padding).
1009    ///  * [`remove_view_insets`](Self::remove_view_insets), the same thing but for
1010    ///    [`view_insets`](Self::view_insets).
1011    pub fn remove_view_padding(
1012        &self,
1013        remove_left: bool,
1014        remove_top: bool,
1015        remove_right: bool,
1016        remove_bottom: bool,
1017    ) -> MediaQueryData {
1018        if !(remove_left || remove_top || remove_right || remove_bottom) {
1019            return self.clone();
1020        }
1021        self.copy_with()
1022            .padding(self.padding.copy_with(
1023                remove_left.then_some(0.0),
1024                remove_top.then_some(0.0),
1025                remove_right.then_some(0.0),
1026                remove_bottom.then_some(0.0),
1027            ))
1028            .view_padding(self.view_padding.copy_with(
1029                remove_left.then_some(0.0),
1030                remove_top.then_some(0.0),
1031                remove_right.then_some(0.0),
1032                remove_bottom.then_some(0.0),
1033            ))
1034            .without_title_bar_area_if(remove_top)
1035    }
1036
1037    /// This data with no title bar area when `top_removed`: a child that no longer touches the top
1038    /// is not in the strip the window buttons sit in.
1039    fn without_title_bar_area_if(mut self, top_removed: bool) -> MediaQueryData {
1040        if top_removed {
1041            self.title_bar_area = None;
1042        }
1043        self
1044    }
1045}
1046
1047impl Default for MediaQueryData {
1048    fn default() -> MediaQueryData {
1049        MediaQueryData::new()
1050    }
1051}
1052
1053/// Dart's `==`: the scalers compare by their `textScaleFactor`, not as scalers.
1054impl PartialEq for MediaQueryData {
1055    fn eq(&self, other: &MediaQueryData) -> bool {
1056        other.size == self.size
1057            && other.device_pixel_ratio == self.device_pixel_ratio
1058            && other.text_scaler.text_scale_factor() == self.text_scaler.text_scale_factor()
1059            && other.platform_brightness == self.platform_brightness
1060            && other.padding == self.padding
1061            && other.view_padding == self.view_padding
1062            && other.view_insets == self.view_insets
1063            && other.system_gesture_insets == self.system_gesture_insets
1064            && other.always_use_24_hour_format == self.always_use_24_hour_format
1065            && other.high_contrast == self.high_contrast
1066            && other.on_off_switch_labels == self.on_off_switch_labels
1067            && other.disable_animations == self.disable_animations
1068            && other.reduce_motion == self.reduce_motion
1069            && other.invert_colors == self.invert_colors
1070            && other.accessible_navigation == self.accessible_navigation
1071            && other.bold_text == self.bold_text
1072            && other.supports_announce == self.supports_announce
1073            && other.navigation_mode == self.navigation_mode
1074            && other.gesture_settings == self.gesture_settings
1075            && other.supports_showing_system_context_menu
1076                == self.supports_showing_system_context_menu
1077            && other.line_height_scale_factor_override == self.line_height_scale_factor_override
1078            && other.letter_spacing_override == self.letter_spacing_override
1079            && other.word_spacing_override == self.word_spacing_override
1080            && other.paragraph_spacing_override == self.paragraph_spacing_override
1081            && other.display_corner_radii == self.display_corner_radii
1082            && other.caption_style == self.caption_style
1083            && other.title_bar_area == self.title_bar_area
1084    }
1085}
1086
1087impl Debug for MediaQueryData {
1088    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1089        let properties = [
1090            format!("size: {:?}", self.size),
1091            format!("devicePixelRatio: {:.1}", self.device_pixel_ratio),
1092            format!("textScaler: {:?}", self.text_scaler),
1093            format!(
1094                "platformBrightness: {}",
1095                waft_foundation::DartEnum(self.platform_brightness)
1096            ),
1097            format!("padding: {:?}", self.padding),
1098            format!("viewPadding: {:?}", self.view_padding),
1099            format!("viewInsets: {:?}", self.view_insets),
1100            format!("systemGestureInsets: {:?}", self.system_gesture_insets),
1101            format!("alwaysUse24HourFormat: {}", self.always_use_24_hour_format),
1102            format!("accessibleNavigation: {}", self.accessible_navigation),
1103            format!("highContrast: {}", self.high_contrast),
1104            format!("onOffSwitchLabels: {}", self.on_off_switch_labels),
1105            format!("disableAnimations: {}", self.disable_animations),
1106            format!("reduceMotion: {}", self.reduce_motion),
1107            format!("invertColors: {}", self.invert_colors),
1108            format!("boldText: {}", self.bold_text),
1109            format!(
1110                "navigationMode: {}",
1111                waft_foundation::describe_enum(&self.navigation_mode)
1112            ),
1113            format!("gestureSettings: {:?}", self.gesture_settings),
1114            format!(
1115                "supportsShowingSystemContextMenu: {}",
1116                self.supports_showing_system_context_menu
1117            ),
1118            format!(
1119                "lineHeightScaleFactorOverride: {}",
1120                nullable(self.line_height_scale_factor_override.as_ref())
1121            ),
1122            format!(
1123                "letterSpacingOverride: {}",
1124                nullable(self.letter_spacing_override.as_ref())
1125            ),
1126            format!(
1127                "wordSpacingOverride: {}",
1128                nullable(self.word_spacing_override.as_ref())
1129            ),
1130            format!(
1131                "paragraphSpacingOverride: {}",
1132                nullable(self.paragraph_spacing_override.as_ref())
1133            ),
1134            format!(
1135                "displayCornerRadii: {}",
1136                nullable(self.display_corner_radii.as_ref())
1137            ),
1138        ];
1139        write!(f, "MediaQueryData({})", properties.join(", "))
1140    }
1141}
1142
1143/// Dart's string interpolation of a nullable value.
1144fn nullable(value: Option<&impl Debug>) -> String {
1145    value.map_or_else(|| "null".to_owned(), |value| format!("{value:?}"))
1146}
1147
1148/// Dart's `EdgeInsets.fromViewPadding`: the physical `padding` scaled into logical pixels.
1149/// Owed to painting's `EdgeInsets`, whose `Deferred` trigger is this file.
1150fn edge_insets_from_view_padding(padding: ViewPadding, device_pixel_ratio: f64) -> EdgeInsets {
1151    EdgeInsets::from_ltrb(
1152        padding.left / device_pixel_ratio,
1153        padding.top / device_pixel_ratio,
1154        padding.right / device_pixel_ratio,
1155        padding.bottom / device_pixel_ratio,
1156    )
1157}
1158
1159/// The view's physical title bar `area` scaled into logical pixels, as
1160/// [`edge_insets_from_view_padding`] scales its padding.
1161fn title_bar_area_from_view(area: TitleBarArea, device_pixel_ratio: f64) -> TitleBarArea {
1162    TitleBarArea {
1163        height: area.height / device_pixel_ratio,
1164        left_inset: area.left_inset / device_pixel_ratio,
1165        right_inset: area.right_inset / device_pixel_ratio,
1166    }
1167}
1168
1169// ---------------------------------------------------------------------------------------------
1170// MediaQuery
1171
1172/// Establishes a subtree in which media queries resolve to the given data.
1173///
1174/// For example, to learn the size of the current view (e.g., the view containing your app),
1175/// you can use [`MediaQuery::size_of`]: `MediaQuery::size_of(app, context)`.
1176///
1177/// Querying the current media using specific methods (for example, [`MediaQuery::size_of`]
1178/// or [`MediaQuery::padding_of`]) will cause your widget to rebuild automatically whenever
1179/// that specific property changes.
1180///
1181/// Querying using [`MediaQuery::of`] will cause your widget to rebuild automatically
1182/// whenever _any_ field of the [`MediaQueryData`] changes (e.g., if the user rotates their
1183/// device). Therefore, unless you are concerned with the entire [`MediaQueryData`] object
1184/// changing, prefer using the specific methods (for example: [`MediaQuery::size_of`] and
1185/// [`MediaQuery::padding_of`]), as it will rebuild more efficiently.
1186///
1187/// If no [`MediaQuery`] is in scope then [`MediaQuery::of`] and the "...Of" methods similar
1188/// to [`MediaQuery::size_of`] will panic. Alternatively, the "maybe-" variant methods (such
1189/// as [`MediaQuery::maybe_of`] and [`MediaQuery::maybe_size_of`]) can be used, which return
1190/// `None`, instead of panicking, when no [`MediaQuery`] is in scope.
1191///
1192/// See also:
1193///
1194///  * `WidgetsApp` and `MaterialApp`, which introduce a [`MediaQuery`] and keep it up to
1195///    date with the current screen metrics as they change.
1196///  * [`MediaQueryData`], the data structure that represents the metrics.
1197#[derive(Debug)]
1198pub struct MediaQuery {
1199    /// See [`InheritedWidget::key`].
1200    pub key: Option<KeyRef>,
1201    /// Contains information about the current media.
1202    ///
1203    /// For example, the [`MediaQueryData::size`] property contains the width and height of
1204    /// the current window.
1205    pub data: MediaQueryData,
1206    /// The widget below this widget in the tree.
1207    pub child: WidgetRef,
1208}
1209
1210impl MediaQuery {
1211    /// Creates a widget that provides [`MediaQueryData`] to its descendants.
1212    #[cfg_attr(debug_assertions, track_caller)]
1213    pub fn new<K>(data: MediaQueryData, child: impl IntoWidget<K>) -> MediaQuery {
1214        MediaQuery {
1215            key: None,
1216            data,
1217            child: child.into_widget(),
1218        }
1219    }
1220
1221    /// Dart `MediaQuery(key:)`.
1222    pub fn key(mut self, key: KeyRef) -> MediaQuery {
1223        self.key = Some(key);
1224        self
1225    }
1226
1227    /// The tree node for this widget.
1228    ///
1229    /// A model is both an [`InheritedWidget`] and an [`InheritedModel`], so the kind tag of
1230    /// [`IntoWidget`] cannot be inferred for it; this names the conversion.
1231    pub fn into_widget(self) -> WidgetRef {
1232        IntoWidget::<InheritedModelKind>::into_widget(self)
1233    }
1234
1235    /// Creates a new [`MediaQuery`] that inherits from the ambient [`MediaQuery`] from the
1236    /// given context, but removes the specified padding.
1237    ///
1238    /// This should be inserted into the widget tree when the [`MediaQuery`] padding is
1239    /// consumed by a widget in such a way that the padding is no longer exposed to the
1240    /// widget's descendants or siblings.
1241    ///
1242    /// The `context` argument must have a [`MediaQuery`] in scope.
1243    ///
1244    /// If all four of the `remove_left`, `remove_top`, `remove_right`, and `remove_bottom`
1245    /// arguments are false, then the returned [`MediaQuery`] reuses the ambient
1246    /// [`MediaQueryData`] unmodified, which is not particularly useful.
1247    ///
1248    /// See also:
1249    ///
1250    ///  * `SafeArea`, which both removes the padding from the [`MediaQuery`] and adds a
1251    ///    `Padding` widget.
1252    ///  * [`MediaQueryData::padding`], the affected property of the [`MediaQueryData`].
1253    ///  * [`remove_view_insets`](Self::remove_view_insets), the same thing but for
1254    ///    [`MediaQueryData::view_insets`].
1255    ///  * [`remove_view_padding`](Self::remove_view_padding), the same thing but for
1256    ///    [`MediaQueryData::view_padding`].
1257    #[cfg_attr(debug_assertions, track_caller)]
1258    pub fn remove_padding<K>(
1259        app: &mut App,
1260        context: BuildContext,
1261        remove_left: bool,
1262        remove_top: bool,
1263        remove_right: bool,
1264        remove_bottom: bool,
1265        child: impl IntoWidget<K>,
1266    ) -> MediaQuery {
1267        MediaQuery::new(
1268            MediaQuery::of(app, context).remove_padding(
1269                remove_left,
1270                remove_top,
1271                remove_right,
1272                remove_bottom,
1273            ),
1274            child,
1275        )
1276    }
1277
1278    /// Creates a new [`MediaQuery`] that inherits from the ambient [`MediaQuery`] from the
1279    /// given context, but removes the specified view insets.
1280    ///
1281    /// This should be inserted into the widget tree when the [`MediaQuery`] view insets are
1282    /// consumed by a widget in such a way that the view insets are no longer exposed to the
1283    /// widget's descendants or siblings.
1284    ///
1285    /// The `context` argument must have a [`MediaQuery`] in scope.
1286    ///
1287    /// If all four of the `remove_left`, `remove_top`, `remove_right`, and `remove_bottom`
1288    /// arguments are false, then the returned [`MediaQuery`] reuses the ambient
1289    /// [`MediaQueryData`] unmodified, which is not particularly useful.
1290    ///
1291    /// See also:
1292    ///
1293    ///  * [`MediaQueryData::view_insets`], the affected property of the [`MediaQueryData`].
1294    ///  * [`remove_padding`](Self::remove_padding), the same thing but for
1295    ///    [`MediaQueryData::padding`].
1296    ///  * [`remove_view_padding`](Self::remove_view_padding), the same thing but for
1297    ///    [`MediaQueryData::view_padding`].
1298    #[cfg_attr(debug_assertions, track_caller)]
1299    pub fn remove_view_insets<K>(
1300        app: &mut App,
1301        context: BuildContext,
1302        remove_left: bool,
1303        remove_top: bool,
1304        remove_right: bool,
1305        remove_bottom: bool,
1306        child: impl IntoWidget<K>,
1307    ) -> MediaQuery {
1308        MediaQuery::new(
1309            MediaQuery::of(app, context).remove_view_insets(
1310                remove_left,
1311                remove_top,
1312                remove_right,
1313                remove_bottom,
1314            ),
1315            child,
1316        )
1317    }
1318
1319    /// Creates a new [`MediaQuery`] that inherits from the ambient [`MediaQuery`] from the
1320    /// given context, but removes the specified view padding.
1321    ///
1322    /// This should be inserted into the widget tree when the [`MediaQuery`] view padding is
1323    /// consumed by a widget in such a way that the view padding is no longer exposed to the
1324    /// widget's descendants or siblings.
1325    ///
1326    /// The `context` argument must have a [`MediaQuery`] in scope.
1327    ///
1328    /// If all four of the `remove_left`, `remove_top`, `remove_right`, and `remove_bottom`
1329    /// arguments are false, then the returned [`MediaQuery`] reuses the ambient
1330    /// [`MediaQueryData`] unmodified, which is not particularly useful.
1331    ///
1332    /// See also:
1333    ///
1334    ///  * [`MediaQueryData::view_padding`], the affected property of the
1335    ///    [`MediaQueryData`].
1336    ///  * [`remove_padding`](Self::remove_padding), the same thing but for
1337    ///    [`MediaQueryData::padding`].
1338    ///  * [`remove_view_insets`](Self::remove_view_insets), the same thing but for
1339    ///    [`MediaQueryData::view_insets`].
1340    #[cfg_attr(debug_assertions, track_caller)]
1341    pub fn remove_view_padding<K>(
1342        app: &mut App,
1343        context: BuildContext,
1344        remove_left: bool,
1345        remove_top: bool,
1346        remove_right: bool,
1347        remove_bottom: bool,
1348        child: impl IntoWidget<K>,
1349    ) -> MediaQuery {
1350        MediaQuery::new(
1351            MediaQuery::of(app, context).remove_view_padding(
1352                remove_left,
1353                remove_top,
1354                remove_right,
1355                remove_bottom,
1356            ),
1357            child,
1358        )
1359    }
1360
1361    /// Wraps the `child` in a [`MediaQuery`] with its
1362    /// [`MediaQueryData::line_height_scale_factor_override`],
1363    /// [`MediaQueryData::letter_spacing_override`],
1364    /// [`MediaQueryData::word_spacing_override`],
1365    /// [`MediaQueryData::paragraph_spacing_override`] set to the specified values.
1366    ///
1367    /// If a text style override argument is `None`, then the corresponding override in the
1368    /// updated [`MediaQueryData`] is set to `None`.
1369    ///
1370    /// The returned widget must be inserted in a widget tree below an existing
1371    /// [`MediaQuery`] widget.
1372    ///
1373    /// See also:
1374    ///
1375    ///  * [`MediaQueryData::line_height_scale_factor_override`],
1376    ///    [`MediaQueryData::letter_spacing_override`],
1377    ///    [`MediaQueryData::word_spacing_override`],
1378    ///    [`MediaQueryData::paragraph_spacing_override`], the affected properties of the
1379    ///    [`MediaQueryData`].
1380    #[cfg_attr(debug_assertions, track_caller)]
1381    pub fn apply_text_style_overrides<K>(
1382        key: Option<KeyRef>,
1383        line_height_scale_factor_override: Option<f64>,
1384        letter_spacing_override: Option<f64>,
1385        word_spacing_override: Option<f64>,
1386        paragraph_spacing_override: Option<f64>,
1387        child: impl IntoWidget<K>,
1388    ) -> WidgetRef {
1389        let child = child.into_widget();
1390        let builder = Builder::new(move |app, context| {
1391            MediaQuery::new(
1392                MediaQuery::of(app, context).apply_text_style_overrides(
1393                    line_height_scale_factor_override,
1394                    letter_spacing_override,
1395                    word_spacing_override,
1396                    paragraph_spacing_override,
1397                ),
1398                child.clone(),
1399            )
1400            .into_widget()
1401        });
1402        Self::keyed(builder, key).into_widget()
1403    }
1404
1405    /// Wraps the `child` in a [`MediaQuery`] which is built using data from the provided
1406    /// `view`.
1407    ///
1408    /// The [`MediaQuery`] is constructed using the platform-specific data of the surrounding
1409    /// [`MediaQuery`] and the view-specific data of the provided `view`. If no surrounding
1410    /// [`MediaQuery`] exists, the platform-specific data is generated from the platform
1411    /// associated with the provided `view`. Any information that's exposed via the platform
1412    /// is considered platform-specific. Data exposed directly on the view is considered
1413    /// view-specific.
1414    ///
1415    /// The injected [`MediaQuery`] updates when the surrounding [`MediaQuery`] or the `view`
1416    /// changes, and when the platform tells the binding's observers its data changed.
1417    #[cfg_attr(debug_assertions, track_caller)]
1418    pub fn from_view<K>(
1419        key: Option<KeyRef>,
1420        view: ViewRef,
1421        child: impl IntoWidget<K>,
1422    ) -> WidgetRef {
1423        let from_view = MediaQueryFromView::new(view, child);
1424        match key {
1425            Some(key) => from_view.key(key),
1426            None => from_view,
1427        }
1428        .into_widget()
1429    }
1430
1431    /// Wraps the `child` in a [`MediaQuery`] with its [`MediaQueryData::text_scaler`] set to
1432    /// [`TextScaler::NO_SCALING`].
1433    ///
1434    /// The returned widget must be inserted in a widget tree below an existing
1435    /// [`MediaQuery`] widget.
1436    ///
1437    /// This can be used to prevent, for example, icon fonts from scaling as the user adjusts
1438    /// the platform's text scaling value.
1439    #[cfg_attr(debug_assertions, track_caller)]
1440    pub fn with_no_text_scaling<K>(key: Option<KeyRef>, child: impl IntoWidget<K>) -> WidgetRef {
1441        let child = child.into_widget();
1442        let builder = Builder::new(move |app, context| {
1443            MediaQuery::new(
1444                MediaQuery::of(app, context)
1445                    .copy_with()
1446                    .text_scaler(TextScaler::NO_SCALING),
1447                child.clone(),
1448            )
1449            .into_widget()
1450        });
1451        Self::keyed(builder, key).into_widget()
1452    }
1453
1454    /// Wraps the `child` in a [`MediaQuery`] and applies [`TextScaler::clamp`] on the current
1455    /// [`MediaQueryData::text_scaler`].
1456    ///
1457    /// The returned widget must be inserted in a widget tree below an existing
1458    /// [`MediaQuery`] widget.
1459    ///
1460    /// This is a convenience function to restrict the range of the scaled text size to
1461    /// `[min_scale_factor * font_size, max_scale_factor * font_size]` (to prevent excessive
1462    /// text scaling that would break the UI, for example). When `min_scale_factor` equals
1463    /// `max_scale_factor`, the scaler becomes `TextScaler::linear(min_scale_factor)`.
1464    ///
1465    /// Dart accepts a `key` here and does not pass it to its `Builder`; neither does this.
1466    #[cfg_attr(debug_assertions, track_caller)]
1467    pub fn with_clamped_text_scaling<K>(
1468        _key: Option<KeyRef>,
1469        min_scale_factor: f64,
1470        max_scale_factor: f64,
1471        child: impl IntoWidget<K>,
1472    ) -> WidgetRef {
1473        debug_assert!(max_scale_factor >= min_scale_factor);
1474        debug_assert!(!max_scale_factor.is_nan());
1475        debug_assert!(min_scale_factor.is_finite());
1476        debug_assert!(min_scale_factor >= 0.0);
1477
1478        let child = child.into_widget();
1479        Builder::new(move |app, context| {
1480            let data = MediaQuery::of(app, context);
1481            let text_scaler = data.text_scaler.clamp(min_scale_factor, max_scale_factor);
1482            MediaQuery::new(data.copy_with().text_scaler(text_scaler), child.clone()).into_widget()
1483        })
1484        .into_widget()
1485    }
1486
1487    /// The `Builder` behind a static `MediaQuery` wrapper, under Dart's `Key? key`.
1488    fn keyed(builder: Builder, key: Option<KeyRef>) -> Builder {
1489        match key {
1490            Some(key) => builder.key(key),
1491            None => builder,
1492        }
1493    }
1494
1495    /// The data from the closest instance of this class that encloses the given context.
1496    ///
1497    /// You can use this function to query the entire set of data held in the current
1498    /// [`MediaQueryData`] object. When any of that information changes, your widget will be
1499    /// scheduled to be rebuilt, keeping your widget up-to-date.
1500    ///
1501    /// Since it is typical that the widget only requires a subset of properties of the
1502    /// [`MediaQueryData`] object, prefer using the more specific methods (for example:
1503    /// [`size_of`](Self::size_of) and [`padding_of`](Self::padding_of)), as those methods
1504    /// will not cause a widget to rebuild when unrelated properties are updated.
1505    ///
1506    /// Typical usage is as follows:
1507    ///
1508    /// ```text
1509    /// let media = MediaQuery::of(app, context);
1510    /// ```
1511    ///
1512    /// If there is no [`MediaQuery`] in scope, this method panics.
1513    ///
1514    /// See also:
1515    ///
1516    /// * [`maybe_of`](Self::maybe_of), which doesn't panic if it doesn't find a
1517    ///   [`MediaQuery`] ancestor. It returns `None` instead.
1518    /// * [`size_of`](Self::size_of) and other specific methods for retrieving and depending
1519    ///   on changes of a specific value.
1520    pub fn of(app: &mut App, context: BuildContext) -> MediaQueryData {
1521        Self::of_aspect(app, context, None)
1522    }
1523
1524    /// Dart's `_of`: the ambient data, depending on `aspect`; panics with
1525    /// `debugCheckHasMediaQuery`'s summary when there is none.
1526    fn of_aspect(
1527        app: &mut App,
1528        context: BuildContext,
1529        aspect: Option<MediaQueryAspect>,
1530    ) -> MediaQueryData {
1531        Self::maybe_of_aspect(app, context, aspect).expect(
1532            "No MediaQuery widget ancestor found. No MediaQuery ancestor could be found \
1533             starting from the context that was passed to MediaQuery.of(). This can happen \
1534             because the context used is not a descendant of a View widget, which introduces \
1535             a MediaQuery.",
1536        )
1537    }
1538
1539    /// The data from the closest instance of this class that encloses the given context, if
1540    /// any.
1541    ///
1542    /// Use this function if you want to allow situations where no [`MediaQuery`] is in
1543    /// scope. Prefer using [`of`](Self::of) in situations where a media query is always
1544    /// expected to exist.
1545    ///
1546    /// If there is no [`MediaQuery`] in scope, then this function will return `None`.
1547    ///
1548    /// You can use this function to query the entire set of data held in the current
1549    /// [`MediaQueryData`] object. When any of that information changes, your widget will be
1550    /// scheduled to be rebuilt, keeping your widget up-to-date.
1551    ///
1552    /// Since it is typical that the widget only requires a subset of properties of the
1553    /// [`MediaQueryData`] object, prefer using the more specific methods (for example:
1554    /// [`maybe_size_of`](Self::maybe_size_of) and
1555    /// [`maybe_padding_of`](Self::maybe_padding_of)), as those methods will not cause a
1556    /// widget to rebuild when unrelated properties are updated.
1557    ///
1558    /// Typical usage is as follows:
1559    ///
1560    /// ```text
1561    /// let Some(media_query) = MediaQuery::maybe_of(app, context) else {
1562    ///     // Do something else instead.
1563    /// };
1564    /// ```
1565    ///
1566    /// See also:
1567    ///
1568    /// * [`of`](Self::of), which will panic if it doesn't find a [`MediaQuery`] ancestor,
1569    ///   instead of returning `None`.
1570    /// * [`maybe_size_of`](Self::maybe_size_of) and other specific methods for retrieving
1571    ///   and depending on changes of a specific value.
1572    pub fn maybe_of(app: &mut App, context: BuildContext) -> Option<MediaQueryData> {
1573        Self::maybe_of_aspect(app, context, None)
1574    }
1575
1576    /// Dart's `_maybeOf`: the ambient data, depending on `aspect`, if any.
1577    fn maybe_of_aspect(
1578        app: &mut App,
1579        context: BuildContext,
1580        aspect: Option<MediaQueryAspect>,
1581    ) -> Option<MediaQueryData> {
1582        MediaQuery::inherit_from(app, context, aspect).map(|media_query| media_query.data.clone())
1583    }
1584
1585    /// Returns [`MediaQueryData::size`] from the nearest [`MediaQuery`] ancestor or panics,
1586    /// if no such ancestor exists.
1587    ///
1588    /// Use of this method will cause the given `context` to rebuild any time that the
1589    /// [`MediaQueryData::size`] property of the ancestor [`MediaQuery`] changes.
1590    ///
1591    /// Prefer using this function over getting the attribute directly from the
1592    /// [`MediaQueryData`] returned from [`of`](Self::of), because using this function will
1593    /// only rebuild the `context` when this specific attribute changes, not when _any_
1594    /// attribute changes.
1595    pub fn size_of(app: &mut App, context: BuildContext) -> Size {
1596        Self::of_aspect(app, context, Some(MediaQueryAspect::Size)).size
1597    }
1598
1599    /// Returns [`MediaQueryData::size`] from the nearest [`MediaQuery`] ancestor or `None`,
1600    /// if no such ancestor exists.
1601    ///
1602    /// Use of this method will cause the given `context` to rebuild any time that the
1603    /// [`MediaQueryData::size`] property of the ancestor [`MediaQuery`] changes.
1604    ///
1605    /// Prefer using this function over getting the attribute directly from the
1606    /// [`MediaQueryData`] returned from [`maybe_of`](Self::maybe_of), because using this
1607    /// function will only rebuild the `context` when this specific attribute changes, not
1608    /// when _any_ attribute changes.
1609    pub fn maybe_size_of(app: &mut App, context: BuildContext) -> Option<Size> {
1610        Self::maybe_of_aspect(app, context, Some(MediaQueryAspect::Size)).map(|data| data.size)
1611    }
1612
1613    /// Returns width of [`MediaQueryData::size`] from the nearest [`MediaQuery`] ancestor or
1614    /// panics, if no such ancestor exists.
1615    ///
1616    /// Use of this method will cause the given `context` to rebuild any time that the width
1617    /// of [`MediaQueryData::size`] property of the ancestor [`MediaQuery`] changes.
1618    pub fn width_of(app: &mut App, context: BuildContext) -> f64 {
1619        Self::of_aspect(app, context, Some(MediaQueryAspect::Width))
1620            .size
1621            .width()
1622    }
1623
1624    /// Returns width of [`MediaQueryData::size`] from the nearest [`MediaQuery`] ancestor or
1625    /// `None`, if no such ancestor exists.
1626    ///
1627    /// Use of this method will cause the given `context` to rebuild any time that the width
1628    /// of [`MediaQueryData::size`] property of the ancestor [`MediaQuery`] changes.
1629    pub fn maybe_width_of(app: &mut App, context: BuildContext) -> Option<f64> {
1630        Self::maybe_of_aspect(app, context, Some(MediaQueryAspect::Width))
1631            .map(|data| data.size.width())
1632    }
1633
1634    /// Returns height of [`MediaQueryData::size`] from the nearest [`MediaQuery`] ancestor
1635    /// or panics, if no such ancestor exists.
1636    ///
1637    /// Use of this method will cause the given `context` to rebuild any time that the height
1638    /// of [`MediaQueryData::size`] property of the ancestor [`MediaQuery`] changes.
1639    pub fn height_of(app: &mut App, context: BuildContext) -> f64 {
1640        Self::of_aspect(app, context, Some(MediaQueryAspect::Height))
1641            .size
1642            .height()
1643    }
1644
1645    /// Returns height of [`MediaQueryData::size`] from the nearest [`MediaQuery`] ancestor
1646    /// or `None`, if no such ancestor exists.
1647    ///
1648    /// Use of this method will cause the given `context` to rebuild any time that the height
1649    /// of [`MediaQueryData::size`] property of the ancestor [`MediaQuery`] changes.
1650    pub fn maybe_height_of(app: &mut App, context: BuildContext) -> Option<f64> {
1651        Self::maybe_of_aspect(app, context, Some(MediaQueryAspect::Height))
1652            .map(|data| data.size.height())
1653    }
1654
1655    /// Returns [`MediaQueryData::orientation`] for the nearest [`MediaQuery`] ancestor or
1656    /// panics, if no such ancestor exists.
1657    ///
1658    /// Use of this method will cause the given `context` to rebuild any time that the
1659    /// [`MediaQueryData::orientation`] property of the ancestor [`MediaQuery`] changes.
1660    pub fn orientation_of(app: &mut App, context: BuildContext) -> Orientation {
1661        Self::of_aspect(app, context, Some(MediaQueryAspect::Orientation)).orientation()
1662    }
1663
1664    /// Returns [`MediaQueryData::orientation`] for the nearest [`MediaQuery`] ancestor or
1665    /// `None`, if no such ancestor exists.
1666    ///
1667    /// Use of this method will cause the given `context` to rebuild any time that the
1668    /// [`MediaQueryData::orientation`] property of the ancestor [`MediaQuery`] changes.
1669    pub fn maybe_orientation_of(app: &mut App, context: BuildContext) -> Option<Orientation> {
1670        Self::maybe_of_aspect(app, context, Some(MediaQueryAspect::Orientation))
1671            .map(|data| data.orientation())
1672    }
1673
1674    /// Returns [`MediaQueryData::device_pixel_ratio`] for the nearest [`MediaQuery`]
1675    /// ancestor or panics, if no such ancestor exists.
1676    ///
1677    /// Use of this method will cause the given `context` to rebuild any time that the
1678    /// [`MediaQueryData::device_pixel_ratio`] property of the ancestor [`MediaQuery`]
1679    /// changes.
1680    pub fn device_pixel_ratio_of(app: &mut App, context: BuildContext) -> f64 {
1681        Self::of_aspect(app, context, Some(MediaQueryAspect::DevicePixelRatio)).device_pixel_ratio
1682    }
1683
1684    /// Returns [`MediaQueryData::device_pixel_ratio`] for the nearest [`MediaQuery`]
1685    /// ancestor or `None`, if no such ancestor exists.
1686    ///
1687    /// Use of this method will cause the given `context` to rebuild any time that the
1688    /// [`MediaQueryData::device_pixel_ratio`] property of the ancestor [`MediaQuery`]
1689    /// changes.
1690    pub fn maybe_device_pixel_ratio_of(app: &mut App, context: BuildContext) -> Option<f64> {
1691        Self::maybe_of_aspect(app, context, Some(MediaQueryAspect::DevicePixelRatio))
1692            .map(|data| data.device_pixel_ratio)
1693    }
1694
1695    /// Returns the [`MediaQueryData::text_scaler`] for the nearest [`MediaQuery`] ancestor
1696    /// or [`TextScaler::NO_SCALING`] if no such ancestor exists.
1697    ///
1698    /// Use of this method will cause the given `context` to rebuild any time that the
1699    /// [`MediaQueryData::text_scaler`] property of the ancestor [`MediaQuery`] changes.
1700    pub fn text_scaler_of(app: &mut App, context: BuildContext) -> TextScaler {
1701        Self::maybe_text_scaler_of(app, context).unwrap_or(TextScaler::NO_SCALING)
1702    }
1703
1704    /// Returns the [`MediaQueryData::text_scaler`] for the nearest [`MediaQuery`] ancestor
1705    /// or `None` if no such ancestor exists.
1706    ///
1707    /// Use of this method will cause the given `context` to rebuild any time that the
1708    /// [`MediaQueryData::text_scaler`] property of the ancestor [`MediaQuery`] changes.
1709    pub fn maybe_text_scaler_of(app: &mut App, context: BuildContext) -> Option<TextScaler> {
1710        Self::maybe_of_aspect(app, context, Some(MediaQueryAspect::TextScaler))
1711            .map(|data| data.text_scaler)
1712    }
1713
1714    /// Returns [`MediaQueryData::platform_brightness`] for the nearest [`MediaQuery`]
1715    /// ancestor or [`Brightness::Light`], if no such ancestor exists.
1716    ///
1717    /// Use of this method will cause the given `context` to rebuild any time that the
1718    /// [`MediaQueryData::platform_brightness`] property of the ancestor [`MediaQuery`]
1719    /// changes.
1720    pub fn platform_brightness_of(app: &mut App, context: BuildContext) -> Brightness {
1721        Self::maybe_platform_brightness_of(app, context).unwrap_or(Brightness::Light)
1722    }
1723
1724    /// Returns [`MediaQueryData::platform_brightness`] for the nearest [`MediaQuery`]
1725    /// ancestor or `None`, if no such ancestor exists.
1726    ///
1727    /// Use of this method will cause the given `context` to rebuild any time that the
1728    /// [`MediaQueryData::platform_brightness`] property of the ancestor [`MediaQuery`]
1729    /// changes.
1730    pub fn maybe_platform_brightness_of(
1731        app: &mut App,
1732        context: BuildContext,
1733    ) -> Option<Brightness> {
1734        Self::maybe_of_aspect(app, context, Some(MediaQueryAspect::PlatformBrightness))
1735            .map(|data| data.platform_brightness)
1736    }
1737
1738    /// Returns [`MediaQueryData::padding`] for the nearest [`MediaQuery`] ancestor or panics,
1739    /// if no such ancestor exists.
1740    ///
1741    /// Use of this method will cause the given `context` to rebuild any time that the
1742    /// [`MediaQueryData::padding`] property of the ancestor [`MediaQuery`] changes.
1743    pub fn padding_of(app: &mut App, context: BuildContext) -> EdgeInsets {
1744        Self::of_aspect(app, context, Some(MediaQueryAspect::Padding)).padding
1745    }
1746
1747    /// Returns [`MediaQueryData::padding`] for the nearest [`MediaQuery`] ancestor or
1748    /// `None`, if no such ancestor exists.
1749    ///
1750    /// Use of this method will cause the given `context` to rebuild any time that the
1751    /// [`MediaQueryData::padding`] property of the ancestor [`MediaQuery`] changes.
1752    pub fn maybe_padding_of(app: &mut App, context: BuildContext) -> Option<EdgeInsets> {
1753        Self::maybe_of_aspect(app, context, Some(MediaQueryAspect::Padding))
1754            .map(|data| data.padding)
1755    }
1756
1757    /// Returns [`MediaQueryData::view_insets`] for the nearest [`MediaQuery`] ancestor or
1758    /// panics, if no such ancestor exists.
1759    ///
1760    /// Use of this method will cause the given `context` to rebuild any time that the
1761    /// [`MediaQueryData::view_insets`] property of the ancestor [`MediaQuery`] changes.
1762    pub fn view_insets_of(app: &mut App, context: BuildContext) -> EdgeInsets {
1763        Self::of_aspect(app, context, Some(MediaQueryAspect::ViewInsets)).view_insets
1764    }
1765
1766    /// Returns [`MediaQueryData::view_insets`] for the nearest [`MediaQuery`] ancestor or
1767    /// `None`, if no such ancestor exists.
1768    ///
1769    /// Use of this method will cause the given `context` to rebuild any time that the
1770    /// [`MediaQueryData::view_insets`] property of the ancestor [`MediaQuery`] changes.
1771    pub fn maybe_view_insets_of(app: &mut App, context: BuildContext) -> Option<EdgeInsets> {
1772        Self::maybe_of_aspect(app, context, Some(MediaQueryAspect::ViewInsets))
1773            .map(|data| data.view_insets)
1774    }
1775
1776    /// Returns [`MediaQueryData::system_gesture_insets`] for the nearest [`MediaQuery`]
1777    /// ancestor or panics, if no such ancestor exists.
1778    ///
1779    /// Use of this method will cause the given `context` to rebuild any time that the
1780    /// [`MediaQueryData::system_gesture_insets`] property of the ancestor [`MediaQuery`]
1781    /// changes.
1782    pub fn system_gesture_insets_of(app: &mut App, context: BuildContext) -> EdgeInsets {
1783        Self::of_aspect(app, context, Some(MediaQueryAspect::SystemGestureInsets))
1784            .system_gesture_insets
1785    }
1786
1787    /// Returns [`MediaQueryData::system_gesture_insets`] for the nearest [`MediaQuery`]
1788    /// ancestor or `None`, if no such ancestor exists.
1789    ///
1790    /// Use of this method will cause the given `context` to rebuild any time that the
1791    /// [`MediaQueryData::system_gesture_insets`] property of the ancestor [`MediaQuery`]
1792    /// changes.
1793    pub fn maybe_system_gesture_insets_of(
1794        app: &mut App,
1795        context: BuildContext,
1796    ) -> Option<EdgeInsets> {
1797        Self::maybe_of_aspect(app, context, Some(MediaQueryAspect::SystemGestureInsets))
1798            .map(|data| data.system_gesture_insets)
1799    }
1800
1801    /// Returns [`MediaQueryData::view_padding`] for the nearest [`MediaQuery`] ancestor or
1802    /// panics, if no such ancestor exists.
1803    ///
1804    /// Use of this method will cause the given `context` to rebuild any time that the
1805    /// [`MediaQueryData::view_padding`] property of the ancestor [`MediaQuery`] changes.
1806    pub fn view_padding_of(app: &mut App, context: BuildContext) -> EdgeInsets {
1807        Self::of_aspect(app, context, Some(MediaQueryAspect::ViewPadding)).view_padding
1808    }
1809
1810    /// Returns [`MediaQueryData::view_padding`] for the nearest [`MediaQuery`] ancestor or
1811    /// `None`, if no such ancestor exists.
1812    ///
1813    /// Use of this method will cause the given `context` to rebuild any time that the
1814    /// [`MediaQueryData::view_padding`] property of the ancestor [`MediaQuery`] changes.
1815    pub fn maybe_view_padding_of(app: &mut App, context: BuildContext) -> Option<EdgeInsets> {
1816        Self::maybe_of_aspect(app, context, Some(MediaQueryAspect::ViewPadding))
1817            .map(|data| data.view_padding)
1818    }
1819
1820    /// Returns [`MediaQueryData::always_use_24_hour_format`] for the nearest [`MediaQuery`]
1821    /// ancestor or panics, if no such ancestor exists.
1822    ///
1823    /// Use of this method will cause the given `context` to rebuild any time that the
1824    /// [`MediaQueryData::always_use_24_hour_format`] property of the ancestor
1825    /// [`MediaQuery`] changes.
1826    pub fn always_use_24_hour_format_of(app: &mut App, context: BuildContext) -> bool {
1827        Self::of_aspect(app, context, Some(MediaQueryAspect::AlwaysUse24HourFormat))
1828            .always_use_24_hour_format
1829    }
1830
1831    /// Returns [`MediaQueryData::always_use_24_hour_format`] for the nearest [`MediaQuery`]
1832    /// ancestor or `None`, if no such ancestor exists.
1833    ///
1834    /// Use of this method will cause the given `context` to rebuild any time that the
1835    /// [`MediaQueryData::always_use_24_hour_format`] property of the ancestor
1836    /// [`MediaQuery`] changes.
1837    pub fn maybe_always_use_24_hour_format_of(
1838        app: &mut App,
1839        context: BuildContext,
1840    ) -> Option<bool> {
1841        Self::maybe_of_aspect(app, context, Some(MediaQueryAspect::AlwaysUse24HourFormat))
1842            .map(|data| data.always_use_24_hour_format)
1843    }
1844
1845    /// Returns [`MediaQueryData::accessible_navigation`] for the nearest [`MediaQuery`]
1846    /// ancestor or panics, if no such ancestor exists.
1847    ///
1848    /// Use of this method will cause the given `context` to rebuild any time that the
1849    /// [`MediaQueryData::accessible_navigation`] property of the ancestor [`MediaQuery`]
1850    /// changes.
1851    pub fn accessible_navigation_of(app: &mut App, context: BuildContext) -> bool {
1852        Self::of_aspect(app, context, Some(MediaQueryAspect::AccessibleNavigation))
1853            .accessible_navigation
1854    }
1855
1856    /// Returns [`MediaQueryData::accessible_navigation`] for the nearest [`MediaQuery`]
1857    /// ancestor or `None`, if no such ancestor exists.
1858    ///
1859    /// Use of this method will cause the given `context` to rebuild any time that the
1860    /// [`MediaQueryData::accessible_navigation`] property of the ancestor [`MediaQuery`]
1861    /// changes.
1862    pub fn maybe_accessible_navigation_of(app: &mut App, context: BuildContext) -> Option<bool> {
1863        Self::maybe_of_aspect(app, context, Some(MediaQueryAspect::AccessibleNavigation))
1864            .map(|data| data.accessible_navigation)
1865    }
1866
1867    /// Returns [`MediaQueryData::invert_colors`] for the nearest [`MediaQuery`] ancestor or
1868    /// panics, if no such ancestor exists.
1869    ///
1870    /// Use of this method will cause the given `context` to rebuild any time that the
1871    /// [`MediaQueryData::invert_colors`] property of the ancestor [`MediaQuery`] changes.
1872    pub fn invert_colors_of(app: &mut App, context: BuildContext) -> bool {
1873        Self::of_aspect(app, context, Some(MediaQueryAspect::InvertColors)).invert_colors
1874    }
1875
1876    /// Returns [`MediaQueryData::invert_colors`] for the nearest [`MediaQuery`] ancestor or
1877    /// `None`, if no such ancestor exists.
1878    ///
1879    /// Use of this method will cause the given `context` to rebuild any time that the
1880    /// [`MediaQueryData::invert_colors`] property of the ancestor [`MediaQuery`] changes.
1881    pub fn maybe_invert_colors_of(app: &mut App, context: BuildContext) -> Option<bool> {
1882        Self::maybe_of_aspect(app, context, Some(MediaQueryAspect::InvertColors))
1883            .map(|data| data.invert_colors)
1884    }
1885
1886    /// Returns [`MediaQueryData::high_contrast`] for the nearest [`MediaQuery`] ancestor or
1887    /// false, if no such ancestor exists.
1888    ///
1889    /// Use of this method will cause the given `context` to rebuild any time that the
1890    /// [`MediaQueryData::high_contrast`] property of the ancestor [`MediaQuery`] changes.
1891    pub fn high_contrast_of(app: &mut App, context: BuildContext) -> bool {
1892        Self::maybe_high_contrast_of(app, context).unwrap_or(false)
1893    }
1894
1895    /// Returns [`MediaQueryData::high_contrast`] for the nearest [`MediaQuery`] ancestor or
1896    /// `None`, if no such ancestor exists.
1897    ///
1898    /// Use of this method will cause the given `context` to rebuild any time that the
1899    /// [`MediaQueryData::high_contrast`] property of the ancestor [`MediaQuery`] changes.
1900    pub fn maybe_high_contrast_of(app: &mut App, context: BuildContext) -> Option<bool> {
1901        Self::maybe_of_aspect(app, context, Some(MediaQueryAspect::HighContrast))
1902            .map(|data| data.high_contrast)
1903    }
1904
1905    /// Returns [`MediaQueryData::on_off_switch_labels`] for the nearest [`MediaQuery`]
1906    /// ancestor or false, if no such ancestor exists.
1907    ///
1908    /// Use of this method will cause the given `context` to rebuild any time that the
1909    /// [`MediaQueryData::on_off_switch_labels`] property of the ancestor [`MediaQuery`]
1910    /// changes.
1911    pub fn on_off_switch_labels_of(app: &mut App, context: BuildContext) -> bool {
1912        Self::maybe_on_off_switch_labels_of(app, context).unwrap_or(false)
1913    }
1914
1915    /// Returns [`MediaQueryData::on_off_switch_labels`] for the nearest [`MediaQuery`]
1916    /// ancestor or `None`, if no such ancestor exists.
1917    ///
1918    /// Use of this method will cause the given `context` to rebuild any time that the
1919    /// [`MediaQueryData::on_off_switch_labels`] property of the ancestor [`MediaQuery`]
1920    /// changes.
1921    pub fn maybe_on_off_switch_labels_of(app: &mut App, context: BuildContext) -> Option<bool> {
1922        Self::maybe_of_aspect(app, context, Some(MediaQueryAspect::OnOffSwitchLabels))
1923            .map(|data| data.on_off_switch_labels)
1924    }
1925
1926    /// Returns [`MediaQueryData::disable_animations`] for the nearest [`MediaQuery`]
1927    /// ancestor or false, if no such ancestor exists.
1928    ///
1929    /// Use of this method will cause the given `context` to rebuild any time that the
1930    /// [`MediaQueryData::disable_animations`] property of the ancestor [`MediaQuery`]
1931    /// changes.
1932    pub fn disable_animations_of(app: &mut App, context: BuildContext) -> bool {
1933        Self::of_aspect(app, context, Some(MediaQueryAspect::DisableAnimations)).disable_animations
1934    }
1935
1936    /// Returns [`MediaQueryData::disable_animations`] for the nearest [`MediaQuery`]
1937    /// ancestor or `None`, if no such ancestor exists.
1938    ///
1939    /// Use of this method will cause the given `context` to rebuild any time that the
1940    /// [`MediaQueryData::disable_animations`] property of the ancestor [`MediaQuery`]
1941    /// changes.
1942    pub fn maybe_disable_animations_of(app: &mut App, context: BuildContext) -> Option<bool> {
1943        Self::maybe_of_aspect(app, context, Some(MediaQueryAspect::DisableAnimations))
1944            .map(|data| data.disable_animations)
1945    }
1946
1947    /// Returns [`MediaQueryData::reduce_motion`] for the nearest [`MediaQuery`] ancestor or
1948    /// false, if no such ancestor exists.
1949    ///
1950    /// Use of this method will cause the given `context` to rebuild any time that the
1951    /// [`MediaQueryData::reduce_motion`] property of the ancestor [`MediaQuery`] changes.
1952    pub fn reduce_motion_of(app: &mut App, context: BuildContext) -> bool {
1953        Self::of_aspect(app, context, Some(MediaQueryAspect::ReduceMotion)).reduce_motion
1954    }
1955
1956    /// Returns [`MediaQueryData::reduce_motion`] for the nearest [`MediaQuery`] ancestor or
1957    /// `None`, if no such ancestor exists.
1958    ///
1959    /// Use of this method will cause the given `context` to rebuild any time that the
1960    /// [`MediaQueryData::reduce_motion`] property of the ancestor [`MediaQuery`] changes.
1961    pub fn maybe_reduce_motion_of(app: &mut App, context: BuildContext) -> Option<bool> {
1962        Self::maybe_of_aspect(app, context, Some(MediaQueryAspect::ReduceMotion))
1963            .map(|data| data.reduce_motion)
1964    }
1965
1966    /// Returns the [`MediaQueryData::bold_text`] accessibility setting for the nearest
1967    /// [`MediaQuery`] ancestor or false, if no such ancestor exists.
1968    ///
1969    /// Use of this method will cause the given `context` to rebuild any time that the
1970    /// [`MediaQueryData::bold_text`] property of the ancestor [`MediaQuery`] changes.
1971    pub fn bold_text_of(app: &mut App, context: BuildContext) -> bool {
1972        Self::maybe_bold_text_of(app, context).unwrap_or(false)
1973    }
1974
1975    /// Returns the [`MediaQueryData::bold_text`] accessibility setting for the nearest
1976    /// [`MediaQuery`] ancestor or `None`, if no such ancestor exists.
1977    ///
1978    /// Use of this method will cause the given `context` to rebuild any time that the
1979    /// [`MediaQueryData::bold_text`] property of the ancestor [`MediaQuery`] changes.
1980    pub fn maybe_bold_text_of(app: &mut App, context: BuildContext) -> Option<bool> {
1981        Self::maybe_of_aspect(app, context, Some(MediaQueryAspect::BoldText))
1982            .map(|data| data.bold_text)
1983    }
1984
1985    /// Returns the [`MediaQueryData::supports_announce`] accessibility setting for the
1986    /// nearest [`MediaQuery`] ancestor or false, if no such ancestor exists.
1987    ///
1988    /// Use of this method will cause the given `context` to rebuild any time that the
1989    /// [`MediaQueryData::supports_announce`] property of the ancestor [`MediaQuery`]
1990    /// changes. This is especially important for `supports_announce` because it has a low
1991    /// frequency change rate. The performance difference between rebuilding for all media
1992    /// query data changes and only rebuilding for `supports_announce` is a dramatic
1993    /// difference.
1994    pub fn supports_announce_of(app: &mut App, context: BuildContext) -> bool {
1995        Self::maybe_supports_announce_of(app, context).unwrap_or(false)
1996    }
1997
1998    /// Returns the [`MediaQueryData::supports_announce`] accessibility setting for the
1999    /// nearest [`MediaQuery`] ancestor or `None`, if no such ancestor exists.
2000    ///
2001    /// Use of this method will cause the given `context` to rebuild any time that the
2002    /// [`MediaQueryData::supports_announce`] property of the ancestor [`MediaQuery`]
2003    /// changes.
2004    pub fn maybe_supports_announce_of(app: &mut App, context: BuildContext) -> Option<bool> {
2005        Self::maybe_of_aspect(app, context, Some(MediaQueryAspect::SupportsAnnounce))
2006            .map(|data| data.supports_announce)
2007    }
2008
2009    /// Returns [`MediaQueryData::navigation_mode`] for the nearest [`MediaQuery`] ancestor
2010    /// or panics, if no such ancestor exists.
2011    ///
2012    /// Use of this method will cause the given `context` to rebuild any time that the
2013    /// [`MediaQueryData::navigation_mode`] property of the ancestor [`MediaQuery`] changes.
2014    pub fn navigation_mode_of(app: &mut App, context: BuildContext) -> NavigationMode {
2015        Self::of_aspect(app, context, Some(MediaQueryAspect::NavigationMode)).navigation_mode
2016    }
2017
2018    /// Returns [`MediaQueryData::navigation_mode`] for the nearest [`MediaQuery`] ancestor
2019    /// or `None`, if no such ancestor exists.
2020    ///
2021    /// Use of this method will cause the given `context` to rebuild any time that the
2022    /// [`MediaQueryData::navigation_mode`] property of the ancestor [`MediaQuery`] changes.
2023    pub fn maybe_navigation_mode_of(
2024        app: &mut App,
2025        context: BuildContext,
2026    ) -> Option<NavigationMode> {
2027        Self::maybe_of_aspect(app, context, Some(MediaQueryAspect::NavigationMode))
2028            .map(|data| data.navigation_mode)
2029    }
2030
2031    /// Returns [`MediaQueryData::gesture_settings`] for the nearest [`MediaQuery`] ancestor
2032    /// or panics, if no such ancestor exists.
2033    ///
2034    /// Use of this method will cause the given `context` to rebuild any time that the
2035    /// [`MediaQueryData::gesture_settings`] property of the ancestor [`MediaQuery`] changes.
2036    pub fn gesture_settings_of(app: &mut App, context: BuildContext) -> DeviceGestureSettings {
2037        Self::of_aspect(app, context, Some(MediaQueryAspect::GestureSettings)).gesture_settings
2038    }
2039
2040    /// Returns [`MediaQueryData::gesture_settings`] for the nearest [`MediaQuery`] ancestor
2041    /// or `None`, if no such ancestor exists.
2042    ///
2043    /// Use of this method will cause the given `context` to rebuild any time that the
2044    /// [`MediaQueryData::gesture_settings`] property of the ancestor [`MediaQuery`] changes.
2045    pub fn maybe_gesture_settings_of(
2046        app: &mut App,
2047        context: BuildContext,
2048    ) -> Option<DeviceGestureSettings> {
2049        Self::maybe_of_aspect(app, context, Some(MediaQueryAspect::GestureSettings))
2050            .map(|data| data.gesture_settings)
2051    }
2052
2053    /// Returns [`MediaQueryData::supports_showing_system_context_menu`] for the nearest
2054    /// [`MediaQuery`] ancestor or panics, if no such ancestor exists.
2055    ///
2056    /// Use of this method will cause the given `context` to rebuild any time that the
2057    /// [`MediaQueryData::supports_showing_system_context_menu`] property of the ancestor
2058    /// [`MediaQuery`] changes.
2059    pub fn supports_showing_system_context_menu(app: &mut App, context: BuildContext) -> bool {
2060        Self::of_aspect(
2061            app,
2062            context,
2063            Some(MediaQueryAspect::SupportsShowingSystemContextMenu),
2064        )
2065        .supports_showing_system_context_menu
2066    }
2067
2068    /// Returns [`MediaQueryData::supports_showing_system_context_menu`] for the nearest
2069    /// [`MediaQuery`] ancestor or `None`, if no such ancestor exists.
2070    ///
2071    /// Use of this method will cause the given `context` to rebuild any time that the
2072    /// [`MediaQueryData::supports_showing_system_context_menu`] property of the ancestor
2073    /// [`MediaQuery`] changes.
2074    pub fn maybe_supports_showing_system_context_menu(
2075        app: &mut App,
2076        context: BuildContext,
2077    ) -> Option<bool> {
2078        Self::maybe_of_aspect(
2079            app,
2080            context,
2081            Some(MediaQueryAspect::SupportsShowingSystemContextMenu),
2082        )
2083        .map(|data| data.supports_showing_system_context_menu)
2084    }
2085
2086    /// Returns the [`MediaQueryData::line_height_scale_factor_override`] for the nearest
2087    /// [`MediaQuery`] ancestor or `None`, if no such ancestor exists or if the platform has
2088    /// not specified an override.
2089    ///
2090    /// Use of this method will cause the given `context` to rebuild any time that the
2091    /// [`MediaQueryData::line_height_scale_factor_override`] property of the ancestor
2092    /// [`MediaQuery`] changes.
2093    pub fn maybe_line_height_scale_factor_override_of(
2094        app: &mut App,
2095        context: BuildContext,
2096    ) -> Option<f64> {
2097        Self::maybe_of_aspect(
2098            app,
2099            context,
2100            Some(MediaQueryAspect::LineHeightScaleFactorOverride),
2101        )
2102        .and_then(|data| data.line_height_scale_factor_override)
2103    }
2104
2105    /// Returns the [`MediaQueryData::letter_spacing_override`] for the nearest
2106    /// [`MediaQuery`] ancestor or `None`, if no such ancestor exists or if the platform has
2107    /// not specified an override.
2108    ///
2109    /// Use of this method will cause the given `context` to rebuild any time that the
2110    /// [`MediaQueryData::letter_spacing_override`] property of the ancestor [`MediaQuery`]
2111    /// changes.
2112    pub fn maybe_letter_spacing_override_of(app: &mut App, context: BuildContext) -> Option<f64> {
2113        Self::maybe_of_aspect(app, context, Some(MediaQueryAspect::LetterSpacingOverride))
2114            .and_then(|data| data.letter_spacing_override)
2115    }
2116
2117    /// Returns the [`MediaQueryData::word_spacing_override`] for the nearest [`MediaQuery`]
2118    /// ancestor or `None`, if no such ancestor exists or if the platform has not specified
2119    /// an override.
2120    ///
2121    /// Use of this method will cause the given `context` to rebuild any time that the
2122    /// [`MediaQueryData::word_spacing_override`] property of the ancestor [`MediaQuery`]
2123    /// changes.
2124    pub fn maybe_word_spacing_override_of(app: &mut App, context: BuildContext) -> Option<f64> {
2125        Self::maybe_of_aspect(app, context, Some(MediaQueryAspect::WordSpacingOverride))
2126            .and_then(|data| data.word_spacing_override)
2127    }
2128
2129    /// Returns the [`MediaQueryData::paragraph_spacing_override`] for the nearest
2130    /// [`MediaQuery`] ancestor or `None`, if no such ancestor exists or if the platform has
2131    /// not specified an override.
2132    ///
2133    /// Use of this method will cause the given `context` to rebuild any time that the
2134    /// [`MediaQueryData::paragraph_spacing_override`] property of the ancestor
2135    /// [`MediaQuery`] changes.
2136    pub fn maybe_paragraph_spacing_override_of(
2137        app: &mut App,
2138        context: BuildContext,
2139    ) -> Option<f64> {
2140        Self::maybe_of_aspect(
2141            app,
2142            context,
2143            Some(MediaQueryAspect::ParagraphSpacingOverride),
2144        )
2145        .and_then(|data| data.paragraph_spacing_override)
2146    }
2147
2148    /// Returns [`MediaQueryData::display_corner_radii`] for the nearest [`MediaQuery`]
2149    /// ancestor or panics, if no such ancestor exists.
2150    ///
2151    /// Use of this method will cause the given `context` to rebuild any time that the
2152    /// [`MediaQueryData::display_corner_radii`] property of the ancestor [`MediaQuery`]
2153    /// changes.
2154    pub fn display_corner_radii_of(app: &mut App, context: BuildContext) -> Option<BorderRadius> {
2155        Self::of_aspect(app, context, Some(MediaQueryAspect::DisplayCornerRadii))
2156            .display_corner_radii
2157    }
2158
2159    /// Returns [`MediaQueryData::display_corner_radii`] for the nearest [`MediaQuery`]
2160    /// ancestor or `None`, if no such ancestor exists.
2161    ///
2162    /// Use of this method will cause the given `context` to rebuild any time that the
2163    /// [`MediaQueryData::display_corner_radii`] property of the ancestor [`MediaQuery`]
2164    /// changes.
2165    pub fn maybe_display_corner_radii_of(
2166        app: &mut App,
2167        context: BuildContext,
2168    ) -> Option<BorderRadius> {
2169        Self::maybe_of_aspect(app, context, Some(MediaQueryAspect::DisplayCornerRadii))
2170            .and_then(|data| data.display_corner_radii)
2171    }
2172
2173    /// Returns [`MediaQueryData::caption_style`] for the nearest [`MediaQuery`] ancestor or
2174    /// panics, if no such ancestor exists.
2175    ///
2176    /// Use of this method will cause the given `context` to rebuild any time that the
2177    /// [`MediaQueryData::caption_style`] property of the ancestor [`MediaQuery`] changes.
2178    pub fn caption_style_of(app: &mut App, context: BuildContext) -> Option<CaptionStyle> {
2179        Self::of_aspect(app, context, Some(MediaQueryAspect::CaptionStyle)).caption_style
2180    }
2181
2182    /// Returns [`MediaQueryData::caption_style`] for the nearest [`MediaQuery`] ancestor or
2183    /// `None`, if no such ancestor exists.
2184    ///
2185    /// Use of this method will cause the given `context` to rebuild any time that the
2186    /// [`MediaQueryData::caption_style`] property of the ancestor [`MediaQuery`] changes.
2187    pub fn maybe_caption_style_of(app: &mut App, context: BuildContext) -> Option<CaptionStyle> {
2188        Self::maybe_of_aspect(app, context, Some(MediaQueryAspect::CaptionStyle))
2189            .and_then(|data| data.caption_style)
2190    }
2191
2192    /// Returns [`MediaQueryData::title_bar_area`] for the nearest [`MediaQuery`] ancestor or
2193    /// panics, if no such ancestor exists.
2194    ///
2195    /// Use of this method will cause the given `context` to rebuild any time that the
2196    /// [`MediaQueryData::title_bar_area`] property of the ancestor [`MediaQuery`] changes.
2197    pub fn title_bar_area_of(app: &mut App, context: BuildContext) -> Option<TitleBarArea> {
2198        Self::of_aspect(app, context, Some(MediaQueryAspect::TitleBarArea)).title_bar_area
2199    }
2200
2201    /// Returns [`MediaQueryData::title_bar_area`] for the nearest [`MediaQuery`] ancestor or
2202    /// `None`, if no such ancestor exists.
2203    ///
2204    /// Use of this method will cause the given `context` to rebuild any time that the
2205    /// [`MediaQueryData::title_bar_area`] property of the ancestor [`MediaQuery`] changes.
2206    pub fn maybe_title_bar_area_of(app: &mut App, context: BuildContext) -> Option<TitleBarArea> {
2207        Self::maybe_of_aspect(app, context, Some(MediaQueryAspect::TitleBarArea))
2208            .and_then(|data| data.title_bar_area)
2209    }
2210}
2211
2212impl InheritedWidget for MediaQuery {
2213    fn key(&self) -> Option<&KeyRef> {
2214        self.key.as_ref()
2215    }
2216
2217    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
2218        properties.add(DiagnosticsProperty::new("data", self.data.clone()).with_show_name(false));
2219    }
2220
2221    fn child(&self) -> &WidgetRef {
2222        &self.child
2223    }
2224
2225    fn update_should_notify(&self, old_widget: &MediaQuery) -> bool {
2226        self.data != old_widget.data
2227    }
2228}
2229
2230impl InheritedModel for MediaQuery {
2231    type Aspect = MediaQueryAspect;
2232
2233    fn update_should_notify_dependent(
2234        &self,
2235        old_widget: &MediaQuery,
2236        dependencies: &HashSet<MediaQueryAspect>,
2237    ) -> bool {
2238        let (data, old) = (&self.data, &old_widget.data);
2239        dependencies.iter().any(|dependency| match dependency {
2240            MediaQueryAspect::Size => data.size != old.size,
2241            MediaQueryAspect::Width => data.size.width() != old.size.width(),
2242            MediaQueryAspect::Height => data.size.height() != old.size.height(),
2243            MediaQueryAspect::Orientation => data.orientation() != old.orientation(),
2244            MediaQueryAspect::DevicePixelRatio => data.device_pixel_ratio != old.device_pixel_ratio,
2245            MediaQueryAspect::TextScaler => data.text_scaler != old.text_scaler,
2246            MediaQueryAspect::PlatformBrightness => {
2247                data.platform_brightness != old.platform_brightness
2248            }
2249            MediaQueryAspect::Padding => data.padding != old.padding,
2250            MediaQueryAspect::ViewInsets => data.view_insets != old.view_insets,
2251            MediaQueryAspect::ViewPadding => data.view_padding != old.view_padding,
2252            MediaQueryAspect::InvertColors => data.invert_colors != old.invert_colors,
2253            MediaQueryAspect::HighContrast => data.high_contrast != old.high_contrast,
2254            MediaQueryAspect::OnOffSwitchLabels => {
2255                data.on_off_switch_labels != old.on_off_switch_labels
2256            }
2257            MediaQueryAspect::DisableAnimations => {
2258                data.disable_animations != old.disable_animations
2259            }
2260            MediaQueryAspect::ReduceMotion => data.reduce_motion != old.reduce_motion,
2261            MediaQueryAspect::BoldText => data.bold_text != old.bold_text,
2262            MediaQueryAspect::SupportsAnnounce => data.supports_announce != old.supports_announce,
2263            MediaQueryAspect::NavigationMode => data.navigation_mode != old.navigation_mode,
2264            MediaQueryAspect::GestureSettings => data.gesture_settings != old.gesture_settings,
2265            MediaQueryAspect::SystemGestureInsets => {
2266                data.system_gesture_insets != old.system_gesture_insets
2267            }
2268            MediaQueryAspect::AccessibleNavigation => {
2269                data.accessible_navigation != old.accessible_navigation
2270            }
2271            MediaQueryAspect::AlwaysUse24HourFormat => {
2272                data.always_use_24_hour_format != old.always_use_24_hour_format
2273            }
2274            MediaQueryAspect::SupportsShowingSystemContextMenu => {
2275                data.supports_showing_system_context_menu
2276                    != old.supports_showing_system_context_menu
2277            }
2278            MediaQueryAspect::LineHeightScaleFactorOverride => {
2279                data.line_height_scale_factor_override != old.line_height_scale_factor_override
2280            }
2281            MediaQueryAspect::LetterSpacingOverride => {
2282                data.letter_spacing_override != old.letter_spacing_override
2283            }
2284            MediaQueryAspect::WordSpacingOverride => {
2285                data.word_spacing_override != old.word_spacing_override
2286            }
2287            MediaQueryAspect::ParagraphSpacingOverride => {
2288                data.paragraph_spacing_override != old.paragraph_spacing_override
2289            }
2290            MediaQueryAspect::DisplayCornerRadii => {
2291                data.display_corner_radii != old.display_corner_radii
2292            }
2293            MediaQueryAspect::CaptionStyle => data.caption_style != old.caption_style,
2294            MediaQueryAspect::TitleBarArea => data.title_bar_area != old.title_bar_area,
2295        })
2296    }
2297}
2298
2299/// Describes the navigation mode to be set by a [`MediaQuery`] widget.
2300///
2301/// The different modes indicate the type of navigation to be used in a widget subtree for
2302/// those widgets sensitive to it.
2303///
2304/// Use `MediaQuery::navigation_mode_of(app, context)` to determine the navigation mode in
2305/// effect for the given context. Use a [`MediaQuery`] widget to set the navigation mode for
2306/// its descendant widgets.
2307#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2308pub enum NavigationMode {
2309    /// This indicates a traditional keyboard-and-mouse navigation modality.
2310    ///
2311    /// This navigation mode is where the arrow keys can be used for secondary modification
2312    /// operations, like moving sliders or cursors, and disabled controls will lose focus and
2313    /// not be traversable.
2314    Traditional,
2315
2316    /// This indicates a directional-based navigation mode.
2317    ///
2318    /// This navigation mode indicates that arrow keys should be reserved for navigation
2319    /// operations, and secondary modifications operations, like moving sliders or cursors,
2320    /// will use alternative bindings or be disabled.
2321    ///
2322    /// Some behaviors are also affected by this mode. For instance, disabled controls will
2323    /// retain focus when disabled, and will be able to receive focus (although they remain
2324    /// disabled) when traversed.
2325    Directional,
2326}
2327
2328// ---------------------------------------------------------------------------------------------
2329// _MediaQueryFromView
2330
2331/// Dart's `_MediaQueryFromView`: the widget behind [`MediaQuery::from_view`].
2332struct MediaQueryFromView {
2333    key: Option<KeyRef>,
2334    view: ViewRef,
2335    ignore_parent_data: bool,
2336    child: WidgetRef,
2337}
2338
2339impl MediaQueryFromView {
2340    /// Creates a `MediaQueryFromView`; Dart's optional named arguments are the setters.
2341    #[cfg_attr(debug_assertions, track_caller)]
2342    fn new<K>(view: ViewRef, child: impl IntoWidget<K>) -> MediaQueryFromView {
2343        MediaQueryFromView {
2344            key: None,
2345            view,
2346            ignore_parent_data: false,
2347            child: child.into_widget(),
2348        }
2349    }
2350
2351    /// Dart `_MediaQueryFromView(key:)`.
2352    fn key(mut self, key: KeyRef) -> MediaQueryFromView {
2353        self.key = Some(key);
2354        self
2355    }
2356}
2357
2358impl Debug for MediaQueryFromView {
2359    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2360        f.debug_struct("MediaQueryFromView")
2361            .field("view", &self.view.id())
2362            .field("ignore_parent_data", &self.ignore_parent_data)
2363            .finish_non_exhaustive()
2364    }
2365}
2366
2367impl StatefulWidget for MediaQueryFromView {
2368    type State = MediaQueryFromViewState;
2369
2370    fn key(&self) -> Option<&KeyRef> {
2371        self.key.as_ref()
2372    }
2373
2374    fn create_state(&self) -> MediaQueryFromViewState {
2375        MediaQueryFromViewState {
2376            state: StateData::new(),
2377            parent_data: None,
2378            data: None,
2379            observer: None,
2380        }
2381    }
2382}
2383
2384/// Dart's `_MediaQueryFromViewState`: the data is re-derived when a dependency or the widget
2385/// changes, and at each change of the platform the binding's observers hear.
2386struct MediaQueryFromViewState {
2387    state: StateData<MediaQueryFromView>,
2388    parent_data: Option<MediaQueryData>,
2389    data: Option<MediaQueryData>,
2390    /// The `Rc` registered with the binding, kept to remove it by identity.
2391    observer: Option<WidgetsBindingObserverRef>,
2392}
2393
2394impl MediaQueryFromViewState {
2395    fn update_parent_data(self: Handle<Self>, app: &mut App) {
2396        let parent_data = if self.widget(app).ignore_parent_data {
2397            None
2398        } else {
2399            MediaQuery::maybe_of(app, self.context(app))
2400        };
2401        let this = app.get_mut(self);
2402        this.parent_data = parent_data;
2403        this.data = None; // _updateData must be called again after changing parent data.
2404    }
2405
2406    fn update_data(self: Handle<Self>, app: &mut App) {
2407        let view = Rc::clone(&self.widget(app).view);
2408        let parent_data = app.get(self).parent_data.clone();
2409        let new_data = MediaQueryData::from_view(app, &*view, parent_data.as_ref());
2410        if app.get(self).data.as_ref() != Some(&new_data) {
2411            self.set_state(app, |state| state.data = Some(new_data));
2412        }
2413    }
2414}
2415
2416/// Dart's `_MediaQueryFromViewState with WidgetsBindingObserver`: every platform change
2417/// re-derives the data from the view.
2418impl WidgetsBindingObserverObject for MediaQueryFromViewState {
2419    fn did_change_accessibility_features(self: Handle<Self>, app: &mut App) {
2420        // If this is a MediaQueryFromView that was created by an app, the MediaQueryData
2421        // is derived from the parent's data (if any) and the view: recompute.
2422        self.update_data(app);
2423    }
2424
2425    fn did_change_metrics(self: Handle<Self>, app: &mut App) {
2426        self.update_data(app);
2427    }
2428
2429    fn did_change_text_scale_factor(self: Handle<Self>, app: &mut App) {
2430        self.update_data(app);
2431    }
2432
2433    fn did_change_platform_brightness(self: Handle<Self>, app: &mut App) {
2434        self.update_data(app);
2435    }
2436
2437    fn did_change_caption_style(self: Handle<Self>, app: &mut App) {
2438        self.update_data(app);
2439    }
2440}
2441
2442impl State for MediaQueryFromViewState {
2443    type Widget = MediaQueryFromView;
2444    crate::state_accessors!();
2445
2446    fn init_state(self: Handle<Self>, app: &mut App) {
2447        let observer: WidgetsBindingObserverRef = Rc::new(self);
2448        WidgetsBinding::instance(app).add_observer(app, Rc::clone(&observer));
2449        app.get_mut(self).observer = Some(observer);
2450    }
2451
2452    fn dispose(self: Handle<Self>, app: &mut App) {
2453        if let Some(observer) = app.get_mut(self).observer.take() {
2454            WidgetsBinding::instance(app).remove_observer(app, &observer);
2455        }
2456    }
2457
2458    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
2459        self.update_parent_data(app);
2460        self.update_data(app);
2461        debug_assert!(app.get(self).data.is_some());
2462    }
2463
2464    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &MediaQueryFromView) {
2465        let (ignore_parent_data_changed, view_changed) = {
2466            let widget = self.widget(app);
2467            (
2468                widget.ignore_parent_data != old_widget.ignore_parent_data,
2469                !std::ptr::addr_eq(Rc::as_ptr(&old_widget.view), Rc::as_ptr(&widget.view)),
2470            )
2471        };
2472        if ignore_parent_data_changed {
2473            self.update_parent_data(app);
2474        }
2475        if app.get(self).data.is_none() || view_changed {
2476            self.update_data(app);
2477        }
2478        debug_assert!(app.get(self).data.is_some());
2479    }
2480
2481    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
2482        // Dart replaces a platform-sourced brightness with `debugBrightnessOverride` in
2483        // non-release mode; foundation's `debug.dart` waits.
2484        let effective_data = app
2485            .get(self)
2486            .data
2487            .clone()
2488            .expect("did_change_dependencies derives the data before the first build");
2489        MediaQuery::new(effective_data, self.widget(app).child.clone()).into_widget()
2490    }
2491}
2492
2493#[cfg(test)]
2494mod tests {
2495    use std::cell::{Cell, RefCell};
2496    use std::rc::Rc;
2497    use waft_foundation::AppCell;
2498
2499    use waft_embedder::TargetPlatform;
2500    use waft_test::{TestPlatform, TestView};
2501
2502    use super::*;
2503    use crate::framework::StatelessWidget;
2504    use crate::test_harness::Harness;
2505    use crate::testing::WidgetTester;
2506    use crate::widgets::basic::SizedBox;
2507
2508    /// Gives `view` a phone's insets: a status bar, a home indicator, a keyboard, and the system's
2509    /// gesture zones along the sides and the bottom.
2510    fn give_phone_insets(view: &TestView) {
2511        let safe_area = ViewPadding {
2512            left: 0.0,
2513            top: 40.0,
2514            right: 0.0,
2515            bottom: 68.0,
2516        };
2517        view.set_padding(safe_area);
2518        view.set_view_padding(safe_area);
2519        view.set_view_insets(ViewPadding {
2520            bottom: 20.0,
2521            ..ViewPadding::ZERO
2522        });
2523        view.set_system_gesture_insets(ViewPadding {
2524            left: 60.0,
2525            top: 0.0,
2526            right: 60.0,
2527            bottom: 112.0,
2528        });
2529    }
2530
2531    /// An 800x600 physical view at 2x with a phone's insets.
2532    fn phone_view() -> TestView {
2533        let view = TestView::with_pixel_ratio(800.0, 600.0, 2.0);
2534        give_phone_insets(&view);
2535        view
2536    }
2537
2538    /// What a [`Reader`] does with its context on every build.
2539    type ReadAccessor = Rc<dyn Fn(&mut App, BuildContext)>;
2540
2541    /// Reads one `MediaQuery` accessor on every build, counts its builds, and builds its
2542    /// child unchanged, so only its own dependencies decide its rebuilds.
2543    struct Reader {
2544        builds: Rc<Cell<u32>>,
2545        read: ReadAccessor,
2546        child: Option<WidgetRef>,
2547    }
2548
2549    impl Reader {
2550        /// The erased reader and its build counter.
2551        fn counting(
2552            read: impl Fn(&mut App, BuildContext) + 'static,
2553            child: Option<WidgetRef>,
2554        ) -> (WidgetRef, Rc<Cell<u32>>) {
2555            let builds = Rc::new(Cell::new(0));
2556            let reader = Reader {
2557                builds: Rc::clone(&builds),
2558                read: Rc::new(read),
2559                child,
2560            }
2561            .into_widget();
2562            (reader, builds)
2563        }
2564    }
2565
2566    impl Debug for Reader {
2567        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2568            f.debug_struct("Reader").finish_non_exhaustive()
2569        }
2570    }
2571
2572    impl StatelessWidget for Reader {
2573        fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
2574            self.builds.set(self.builds.get() + 1);
2575            (self.read)(app, context);
2576            self.child
2577                .clone()
2578                .unwrap_or_else(|| SizedBox::shrink().into_widget())
2579        }
2580    }
2581
2582    /// A reader that records what `MediaQuery::of` returns on each build.
2583    fn data_reader() -> (WidgetRef, Rc<RefCell<Vec<MediaQueryData>>>) {
2584        let seen = Rc::new(RefCell::new(Vec::new()));
2585        let (reader, _) = Reader::counting(
2586            {
2587                let seen = Rc::clone(&seen);
2588                move |app, context| seen.borrow_mut().push(MediaQuery::of(app, context))
2589            },
2590            None,
2591        );
2592        (reader, seen)
2593    }
2594
2595    fn mount(app: &mut App, child: WidgetRef) -> Harness {
2596        let harness = Harness::mount(app, child);
2597        harness.pump(app);
2598        harness
2599    }
2600
2601    #[test]
2602    fn from_view_computes_logical_size_and_padding() {
2603        let cell = AppCell::new();
2604        let app = cell.borrow();
2605        let data = MediaQueryData::from_view(&app, &phone_view(), None);
2606        assert_eq!(data.size, Size::new(400.0, 300.0));
2607        assert_eq!(data.device_pixel_ratio, 2.0);
2608        assert_eq!(data.padding, EdgeInsets::from_ltrb(0.0, 20.0, 0.0, 34.0));
2609        assert_eq!(
2610            data.view_padding,
2611            EdgeInsets::from_ltrb(0.0, 20.0, 0.0, 34.0)
2612        );
2613        assert_eq!(data.view_insets, EdgeInsets::from_ltrb(0.0, 0.0, 0.0, 10.0));
2614        assert_eq!(
2615            data.system_gesture_insets,
2616            EdgeInsets::from_ltrb(30.0, 0.0, 30.0, 56.0)
2617        );
2618        assert_eq!(data.orientation(), Orientation::Landscape);
2619        assert_eq!(data.platform_brightness, Brightness::Light);
2620        assert_eq!(data.text_scaler, TextScaler::NO_SCALING);
2621        assert_eq!(data.gesture_settings, DeviceGestureSettings::new(None));
2622    }
2623
2624    #[test]
2625    fn from_view_takes_the_platform_specific_data_from_platform_data() {
2626        let cell = AppCell::new();
2627        let app = cell.borrow();
2628        let platform_data = MediaQueryData::new()
2629            .platform_brightness(Brightness::Dark)
2630            .bold_text(true)
2631            .text_scaler(TextScaler::linear(2.0))
2632            .size(Size::new(1.0, 1.0));
2633        let data = MediaQueryData::from_view(&app, &phone_view(), Some(&platform_data));
2634        assert_eq!(data.platform_brightness, Brightness::Dark);
2635        assert!(data.bold_text);
2636        assert_eq!(data.text_scaler, TextScaler::linear(2.0));
2637        assert_eq!(
2638            data.size,
2639            Size::new(400.0, 300.0),
2640            "the size is view-specific"
2641        );
2642    }
2643
2644    #[test]
2645    fn size_of_depends_only_on_the_size_aspect() {
2646        let cell = AppCell::new();
2647        let mut app = cell.borrow_mut();
2648        let (whole, whole_builds) = Reader::counting(
2649            |app, context| {
2650                MediaQuery::of(app, context);
2651            },
2652            None,
2653        );
2654        let (padding, padding_builds) = Reader::counting(
2655            |app, context| {
2656                MediaQuery::padding_of(app, context);
2657            },
2658            Some(whole),
2659        );
2660        let (size, size_builds) = Reader::counting(
2661            |app, context| {
2662                MediaQuery::size_of(app, context);
2663            },
2664            Some(padding),
2665        );
2666        let builds = || (size_builds.get(), padding_builds.get(), whole_builds.get());
2667        let query = |data: MediaQueryData| MediaQuery::new(data, size.clone()).into_widget();
2668        let portrait = MediaQueryData::new().size(Size::new(100.0, 200.0));
2669        let padded = portrait.copy_with().padding(EdgeInsets::all(10.0));
2670
2671        let harness = mount(&mut app, query(portrait.clone()));
2672        assert_eq!(builds(), (1, 1, 1));
2673
2674        harness.set_child(&mut app, query(padded.clone()));
2675        harness.pump(&mut app);
2676        assert_eq!(
2677            builds(),
2678            (1, 2, 2),
2679            "a padding-only change spares the size reader"
2680        );
2681
2682        let landscape = padded.copy_with().size(Size::new(200.0, 100.0));
2683        harness.set_child(&mut app, query(landscape.clone()));
2684        harness.pump(&mut app);
2685        assert_eq!(
2686            builds(),
2687            (2, 2, 3),
2688            "a size-only change spares the padding reader"
2689        );
2690
2691        harness.set_child(&mut app, query(landscape));
2692        harness.pump(&mut app);
2693        assert_eq!(builds(), (2, 2, 3), "equal data does not notify");
2694    }
2695
2696    #[test]
2697    fn remove_padding_zeroes_the_requested_sides() {
2698        let data = MediaQueryData::new()
2699            .padding(EdgeInsets::from_ltrb(1.0, 2.0, 3.0, 4.0))
2700            .view_padding(EdgeInsets::from_ltrb(5.0, 6.0, 7.0, 8.0));
2701        let removed = data.remove_padding(true, false, true, false);
2702        assert_eq!(removed.padding, EdgeInsets::from_ltrb(0.0, 2.0, 0.0, 4.0));
2703        assert_eq!(
2704            removed.view_padding,
2705            EdgeInsets::from_ltrb(4.0, 6.0, 4.0, 8.0),
2706            "the view padding loses the removed padding"
2707        );
2708        assert_eq!(data.remove_padding(false, false, false, false), data);
2709    }
2710
2711    /// The strip a windowed iPad reports at 2x: 53 points tall, its buttons 66 points from the
2712    /// left.
2713    fn ipad_title_bar_area() -> TitleBarArea {
2714        TitleBarArea {
2715            height: 106.0,
2716            left_inset: 132.0,
2717            right_inset: 0.0,
2718        }
2719    }
2720
2721    #[test]
2722    fn from_view_scales_the_title_bar_area_into_logical_pixels() {
2723        let cell = AppCell::new();
2724        let app = cell.borrow();
2725        let view = phone_view();
2726        view.set_title_bar_area(Some(ipad_title_bar_area()));
2727        let data = MediaQueryData::from_view(&app, &view, None);
2728        assert_eq!(
2729            data.title_bar_area,
2730            Some(TitleBarArea {
2731                height: 53.0,
2732                left_inset: 66.0,
2733                right_inset: 0.0,
2734            })
2735        );
2736    }
2737
2738    #[test]
2739    fn removing_the_top_padding_removes_the_title_bar_area() {
2740        let data = MediaQueryData::new().title_bar_area(ipad_title_bar_area());
2741        assert_eq!(
2742            data.remove_padding(true, false, true, true).title_bar_area,
2743            Some(ipad_title_bar_area()),
2744            "a child still at the top is still in the strip"
2745        );
2746        assert_eq!(
2747            data.remove_padding(false, true, false, false)
2748                .title_bar_area,
2749            None
2750        );
2751        assert_eq!(
2752            data.remove_view_padding(false, true, false, false)
2753                .title_bar_area,
2754            None
2755        );
2756    }
2757
2758    #[test]
2759    fn remove_view_insets_zeroes_the_requested_sides() {
2760        let data = MediaQueryData::new()
2761            .view_insets(EdgeInsets::from_ltrb(1.0, 2.0, 3.0, 4.0))
2762            .view_padding(EdgeInsets::from_ltrb(5.0, 6.0, 7.0, 8.0));
2763        let removed = data.remove_view_insets(false, true, false, true);
2764        assert_eq!(
2765            removed.view_insets,
2766            EdgeInsets::from_ltrb(1.0, 0.0, 3.0, 0.0)
2767        );
2768        assert_eq!(
2769            removed.view_padding,
2770            EdgeInsets::from_ltrb(5.0, 4.0, 7.0, 4.0)
2771        );
2772        assert_eq!(data.remove_view_insets(false, false, false, false), data);
2773    }
2774
2775    #[test]
2776    fn remove_view_padding_zeroes_the_requested_sides() {
2777        let data = MediaQueryData::new()
2778            .padding(EdgeInsets::from_ltrb(1.0, 2.0, 3.0, 4.0))
2779            .view_padding(EdgeInsets::from_ltrb(5.0, 6.0, 7.0, 8.0));
2780        let removed = data.remove_view_padding(true, true, false, false);
2781        assert_eq!(removed.padding, EdgeInsets::from_ltrb(0.0, 0.0, 3.0, 4.0));
2782        assert_eq!(
2783            removed.view_padding,
2784            EdgeInsets::from_ltrb(0.0, 0.0, 7.0, 8.0)
2785        );
2786        assert_eq!(data.remove_view_padding(false, false, false, false), data);
2787    }
2788
2789    #[test]
2790    #[should_panic(expected = "No MediaQuery widget ancestor found")]
2791    fn of_panics_with_darts_message_when_absent() {
2792        let cell = AppCell::new();
2793        let mut app = cell.borrow_mut();
2794        let (reader, _) = data_reader();
2795        mount(&mut app, reader);
2796    }
2797
2798    #[test]
2799    fn maybe_of_and_the_defaulted_accessors_tolerate_a_missing_media_query() {
2800        let cell = AppCell::new();
2801        let mut app = cell.borrow_mut();
2802        let seen = Rc::new(RefCell::new(Vec::new()));
2803        let (reader, _) = Reader::counting(
2804            {
2805                let seen = Rc::clone(&seen);
2806                move |app, context| {
2807                    seen.borrow_mut().push((
2808                        MediaQuery::maybe_of(app, context),
2809                        MediaQuery::text_scaler_of(app, context),
2810                        MediaQuery::platform_brightness_of(app, context),
2811                        MediaQuery::bold_text_of(app, context),
2812                    ));
2813                }
2814            },
2815            None,
2816        );
2817        mount(&mut app, reader);
2818        assert_eq!(
2819            seen.borrow().as_slice(),
2820            [(None, TextScaler::NO_SCALING, Brightness::Light, false)]
2821        );
2822    }
2823
2824    #[test]
2825    fn with_clamped_text_scaling_and_with_no_text_scaling_wrap_the_ambient_scaler() {
2826        let cell = AppCell::new();
2827        let mut app = cell.borrow_mut();
2828        let seen = Rc::new(RefCell::new(Vec::new()));
2829        let (reader, _) = Reader::counting(
2830            {
2831                let seen = Rc::clone(&seen);
2832                move |app, context| {
2833                    seen.borrow_mut()
2834                        .push(MediaQuery::text_scaler_of(app, context));
2835                }
2836            },
2837            None,
2838        );
2839        let ambient = |child: WidgetRef| {
2840            MediaQuery::new(
2841                MediaQueryData::new().text_scaler(TextScaler::linear(2.0)),
2842                child,
2843            )
2844            .into_widget()
2845        };
2846
2847        let harness = mount(
2848            &mut app,
2849            ambient(MediaQuery::with_clamped_text_scaling(
2850                None,
2851                0.0,
2852                1.5,
2853                reader.clone(),
2854            )),
2855        );
2856        assert_eq!(seen.borrow().last(), Some(&TextScaler::linear(1.5)));
2857
2858        harness.set_child(
2859            &mut app,
2860            ambient(MediaQuery::with_no_text_scaling(None, reader)),
2861        );
2862        harness.pump(&mut app);
2863        assert_eq!(seen.borrow().last(), Some(&TextScaler::NO_SCALING));
2864    }
2865
2866    #[test]
2867    fn from_view_yields_the_views_metrics_and_takes_platform_data_from_the_ambient_query() {
2868        let cell = AppCell::new();
2869        let mut app = cell.borrow_mut();
2870        let view: ViewRef = Rc::new(phone_view());
2871        let (reader, seen) = data_reader();
2872        let from_view = MediaQuery::from_view(None, Rc::clone(&view), reader);
2873
2874        let harness = mount(&mut app, from_view.clone());
2875        assert_eq!(seen.borrow().len(), 1);
2876        let data = seen.borrow()[0].clone();
2877        assert_eq!(data, MediaQueryData::from_view(&app, &*view, None));
2878        assert_eq!(data.size, Size::new(400.0, 300.0));
2879        assert_eq!(data.platform_brightness, Brightness::Light);
2880
2881        let ambient = |brightness: Brightness| {
2882            MediaQuery::new(
2883                MediaQueryData::new().platform_brightness(brightness),
2884                from_view.clone(),
2885            )
2886            .into_widget()
2887        };
2888        harness.set_child(&mut app, ambient(Brightness::Dark));
2889        harness.pump(&mut app);
2890        assert_eq!(seen.borrow().len(), 2);
2891        let data = seen.borrow()[1].clone();
2892        assert_eq!(
2893            data.platform_brightness,
2894            Brightness::Dark,
2895            "the ambient query supplies the platform data"
2896        );
2897        assert_eq!(
2898            data.size,
2899            Size::new(400.0, 300.0),
2900            "the view's own data stays"
2901        );
2902
2903        harness.set_child(&mut app, ambient(Brightness::Light));
2904        harness.pump(&mut app);
2905        assert_eq!(seen.borrow().len(), 3, "a changed ambient query re-derives");
2906        assert_eq!(seen.borrow()[2].platform_brightness, Brightness::Light);
2907    }
2908
2909    #[test]
2910    fn from_view_under_a_view_yields_the_views_metrics() {
2911        // A dark-themed host, so the view's own data and the platform's can be told apart.
2912        let tester = &mut WidgetTester::with_platform(
2913            TestPlatform::new()
2914                .on(TargetPlatform::IOS)
2915                .with_brightness(Brightness::Dark),
2916        );
2917        tester.view().set_physical_size(Size::new(800.0, 600.0));
2918        tester.view().set_device_pixel_ratio(2.0);
2919        give_phone_insets(tester.view());
2920        let view = Rc::clone(tester.view()) as ViewRef;
2921        let (reader, seen) = data_reader();
2922        tester.pump_widget(MediaQuery::from_view(None, Rc::clone(&view), reader));
2923
2924        assert_eq!(seen.borrow().len(), 1);
2925        let data = seen.borrow()[0].clone();
2926        assert_eq!(
2927            data,
2928            MediaQueryData::from_view(&tester.cell.borrow(), &*view, None)
2929        );
2930        assert_eq!(data.size, Size::new(400.0, 300.0));
2931        assert_eq!(data.padding, EdgeInsets::from_ltrb(0.0, 20.0, 0.0, 34.0));
2932        assert_eq!(
2933            data.system_gesture_insets,
2934            EdgeInsets::from_ltrb(30.0, 0.0, 30.0, 56.0)
2935        );
2936        assert_eq!(
2937            data.platform_brightness,
2938            Brightness::Dark,
2939            "the platform's brightness"
2940        );
2941    }
2942}
2943
2944#[cfg(test)]
2945mod diagnostics_tests {
2946    use super::*;
2947    use crate::testing::has_one_line_description;
2948
2949    /// `media_query_test.dart`, "MediaQueryData.fromView is sane": the one-line description.
2950    #[test]
2951    fn media_query_data_has_a_one_line_description() {
2952        assert!(has_one_line_description(&MediaQueryData::new()));
2953    }
2954}