Skip to main content

waft_material/
theme.rs

1//! Flutter counterpart: material_ui's `theme.dart`.
2
3use std::rc::Rc;
4use std::time::Duration;
5
6use waft_animation::Animatable;
7use waft_cupertino::{CupertinoTheme, CupertinoThemeData, InheritedCupertinoTheme};
8use waft_embedder::Brightness;
9use waft_foundation::{App, DiagnosticPropertiesBuilder, DiagnosticsProperty, Handle, Ref};
10use waft_painting::AnyColor;
11use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
12use waft_widgets::{
13    AnimatedWidgetBaseState, BuildContext, DefaultSelectionStyle, IconTheme,
14    ImplicitlyAnimatedWidget, ImplicitlyAnimatedWidgetData, ImplicitlyAnimatedWidgetState,
15    ImplicitlyAnimatedWidgetStateData, InheritedWidget, IntoWidget, KeyRef, Localizations,
16    MediaQuery, SingleTickerProviderStateMixin, SingleTickerProviderStateMixinData, State,
17    StateData, StatefulWidget, StatelessWidget, TweenSlot, TweenValue, TweenVisitor, WidgetRef,
18};
19
20use crate::material_localizations::MaterialLocalizations;
21use crate::theme_data::{
22    CupertinoBasedMaterialThemeData, MaterialBasedCupertinoThemeData, ThemeData,
23};
24use crate::typography::ScriptCategory;
25
26/// The duration over which theme changes animate by default.
27pub const K_THEME_ANIMATION_DURATION: Duration = Duration::from_millis(200);
28
29/// Applies a theme to descendant widgets.
30///
31/// A theme describes the colors and typographic choices of an application.
32///
33/// Learn more about [`Theme`] on the [Flutter YouTube channel](https://www.youtube.com/watch?v=oTvQDJOBXmM).
34///
35/// Descendant widgets obtain the current theme's [`ThemeData`] object using
36/// [`Theme::of`]. When a widget uses [`Theme::of`], it is automatically rebuilt if
37/// the theme later changes, so that the changes can be applied.
38///
39/// The [`Theme`] widget implies an [`IconTheme`] widget, set to the value of the
40/// [`ThemeData::icon_theme`] of the [`data`](Self::data) for the [`Theme`].
41///
42/// To interact seamlessly with descendant Cupertino widgets, the [`Theme`] widget
43/// provides a [`CupertinoTheme`] for its descendants with a [`CupertinoThemeData`] inherited
44/// from the nearest ancestor [`CupertinoTheme`] or if none exists, derived from the
45/// Material [`data`](Self::data) for the [`Theme`]. The values in the Material derived
46/// [`CupertinoThemeData`] are overridable through [`ThemeData::cupertino_override_theme`].
47/// The values from an inherited [`CupertinoThemeData`] can be overridden by wrapping the
48/// desired subtree with a [`CupertinoTheme`].
49///
50/// See also:
51///
52///  * [`ThemeData`], which describes the actual configuration of a theme.
53///  * [`AnimatedTheme`], which animates the [`ThemeData`] when it changes rather
54///    than changing the theme all at once.
55///  * `MaterialApp`, which includes an [`AnimatedTheme`] widget configured via
56///    the `MaterialApp.theme` argument.
57#[derive(Clone, Debug)]
58pub struct Theme {
59    pub key: Option<KeyRef>,
60    /// Specifies the color and typography values for descendant widgets.
61    ///
62    /// Shared, as Dart shares the one `ThemeData` object: [`Theme::of`] hands out this
63    /// value, and [`ThemeData::localize`] keys its cache on its identity.
64    pub data: Rc<ThemeData>,
65    /// The widget below this widget in the tree.
66    pub child: WidgetRef,
67}
68
69/// Dart's static `_cachedFallbackTheme`, one per app.
70#[derive(Default)]
71struct CachedFallbackTheme {
72    theme: Option<Rc<ThemeData>>,
73}
74
75impl Theme {
76    /// Applies the given theme `data` to `child`.
77    #[cfg_attr(debug_assertions, track_caller)]
78    pub fn new<K>(data: impl Into<Rc<ThemeData>>, child: impl IntoWidget<K>) -> Theme {
79        Theme {
80            key: None,
81            data: data.into(),
82            child: child.into_widget(),
83        }
84    }
85
86    /// Dart `Theme(key:)`.
87    pub fn key(mut self, key: KeyRef) -> Theme {
88        self.key = Some(key);
89        self
90    }
91
92    /// The theme [`Theme::of`] returns when there is no [`Theme`] ancestor.
93    ///
94    /// The fallback is cached because constructing a [`ThemeData`] is expensive,
95    /// but it is rebuilt whenever `defaultTargetPlatform` no longer matches the
96    /// platform it was built for (for example after a platform override), so a theme-less
97    /// subtree adapts to the current platform the same way a `MaterialApp` would.
98    fn fallback_theme(app: &mut App) -> Rc<ThemeData> {
99        let cache = app.singleton::<CachedFallbackTheme>();
100        let platform = app.platform().target_platform();
101        let stale = app
102            .get(cache)
103            .theme
104            .as_ref()
105            .is_none_or(|theme| theme.platform != platform);
106        if stale {
107            let theme = Rc::new(ThemeData::fallback(app, None));
108            app.get_mut(cache).theme = Some(theme);
109        }
110        app.get(cache).theme.clone().expect("filled above")
111    }
112
113    /// The data from the closest [`Theme`] instance that encloses the given
114    /// context.
115    ///
116    /// If the given context is enclosed in a `Localizations` widget providing
117    /// `MaterialLocalizations`, the returned data is localized according to the
118    /// nearest available `MaterialLocalizations`.
119    ///
120    /// Defaults to [`ThemeData::fallback`] if there is no [`Theme`] in the given
121    /// build context.
122    ///
123    /// When the [`Theme`] is actually created in the same `build` function
124    /// (possibly indirectly, e.g. as part of a `MaterialApp`), the `context`
125    /// argument to the `build` function can't be used to find the [`Theme`] (since
126    /// it's "above" the widget being returned). In such cases, a `Builder` can be used
127    /// to provide a new scope with a [`BuildContext`] that is "under" the [`Theme`].
128    ///
129    /// See also:
130    ///
131    /// * `ColorScheme::of`, a convenience method that returns [`ThemeData::color_scheme`]
132    ///   from the closest [`Theme`] ancestor. (equivalent to
133    ///   `Theme::of(app, context).color_scheme`).
134    /// * [`TextTheme::of`](crate::TextTheme::of), a convenience method that returns [`ThemeData::text_theme`]
135    ///   from the closest [`Theme`] ancestor. (equivalent to
136    ///   `Theme::of(app, context).text_theme`).
137    /// * [`IconTheme::of`], that returns [`ThemeData::icon_theme`] from the closest
138    ///   [`Theme`] or `IconThemeData::fallback` if there is no [`IconTheme`] ancestor.
139    pub fn of(app: &mut App, context: BuildContext) -> Rc<ThemeData> {
140        let inherited_theme = context
141            .depend_on_inherited_widget_of_exact_type::<InheritedTheme>(app)
142            .map(|inherited_theme| Rc::clone(&inherited_theme.theme.data));
143        let localizations = Localizations::of::<dyn MaterialLocalizations>(app, context);
144        let category = localizations
145            .map(|localizations| localizations.script_category())
146            .unwrap_or(ScriptCategory::EnglishLike);
147        // Depended on either way, as Dart's; its data is read only when there is no material
148        // theme, so it is not copied otherwise.
149        let inherited_cupertino_theme = context
150            .depend_on_inherited_widget_of_exact_type::<InheritedCupertinoTheme>(app)
151            .filter(|_| inherited_theme.is_none())
152            .map(|inherited_cupertino_theme| inherited_cupertino_theme.theme.data.clone());
153        let theme = match (inherited_theme, inherited_cupertino_theme) {
154            (Some(theme), _) => theme,
155            (None, Some(cupertino_theme)) => {
156                CupertinoBasedMaterialThemeData::new(app, &cupertino_theme).material_theme
157            }
158            (None, None) => Theme::fallback_theme(app),
159        };
160        let local_text_geometry = Rc::clone(theme.typography.geometry_theme_for(category));
161        ThemeData::localize(app, &theme, &local_text_geometry)
162    }
163
164    // The inherited themes in widgets library can not infer their values from
165    // Theme in material library. Wraps the child with these inherited themes to
166    // overrides their values directly.
167    fn wraps_widget_themes(
168        &self,
169        app: &mut App,
170        context: BuildContext,
171        child: WidgetRef,
172    ) -> WidgetRef {
173        let selection_style = DefaultSelectionStyle::of(app, context);
174        let text_selection_theme = &self.data.text_selection_theme;
175        let mut default_selection_style = DefaultSelectionStyle::new(child);
176        if let Some(selection_color) = text_selection_theme
177            .selection_color
178            .map(AnyColor::new)
179            .or(selection_style.selection_color)
180        {
181            default_selection_style = default_selection_style.selection_color(selection_color);
182        }
183        if let Some(cursor_color) = text_selection_theme
184            .cursor_color
185            .map(AnyColor::new)
186            .or(selection_style.cursor_color)
187        {
188            default_selection_style = default_selection_style.cursor_color(cursor_color);
189        }
190        IconTheme::new(self.data.icon_theme.clone(), default_selection_style).into_widget()
191    }
192
193    fn inherited_cupertino_theme_data(
194        &self,
195        app: &mut App,
196        context: BuildContext,
197    ) -> CupertinoThemeData {
198        let inherited_theme = context
199            .depend_on_inherited_widget_of_exact_type::<InheritedCupertinoTheme>(app)
200            .map(|inherited_theme| inherited_theme.theme.data.clone());
201        inherited_theme
202            .unwrap_or_else(|| MaterialBasedCupertinoThemeData::new(&self.data))
203            .resolve_from(app, context)
204    }
205
206    /// Retrieves the [`Brightness`] to use for descendant Material widgets, based
207    /// on the value of [`ThemeData::brightness`] in the given `context`.
208    ///
209    /// If no `InheritedTheme` can be found in the given `context`, or its `brightness`
210    /// is null, it will fall back to `MediaQueryData.platform_brightness`.
211    ///
212    /// See also:
213    ///
214    /// * [`maybe_brightness_of`](Self::maybe_brightness_of), which returns null if no valid
215    ///   `InheritedTheme` or [`MediaQuery`] exists.
216    /// * [`ThemeData::brightness`], the property that takes precedence over
217    ///   `MediaQueryData.platform_brightness` for descendant Material widgets.
218    pub fn brightness_of(app: &mut App, context: BuildContext) -> Brightness {
219        let brightness = context
220            .depend_on_inherited_widget_of_exact_type::<InheritedTheme>(app)
221            .map(|inherited_theme| inherited_theme.theme.data.brightness());
222        brightness.unwrap_or_else(|| MediaQuery::platform_brightness_of(app, context))
223    }
224
225    /// Retrieves the [`Brightness`] to use for descendant Material widgets, based
226    /// on the value of [`ThemeData::brightness`] in the given `context`.
227    ///
228    /// If no `InheritedTheme` or [`MediaQuery`] can be found in the given `context`, it will
229    /// return null.
230    ///
231    /// See also:
232    ///
233    /// * [`ThemeData::brightness`], the property that takes precedence over
234    ///   `MediaQueryData.platform_brightness` for descendant Material widgets.
235    /// * [`brightness_of`](Self::brightness_of), which return a default value if no valid
236    ///   `InheritedTheme` or [`MediaQuery`] exists, instead of returning null.
237    pub fn maybe_brightness_of(app: &mut App, context: BuildContext) -> Option<Brightness> {
238        let brightness = context
239            .depend_on_inherited_widget_of_exact_type::<InheritedTheme>(app)
240            .map(|inherited_theme| inherited_theme.theme.data.brightness());
241        brightness.or_else(|| MediaQuery::maybe_platform_brightness_of(app, context))
242    }
243}
244
245impl StatelessWidget for Theme {
246    fn key(&self) -> Option<&KeyRef> {
247        self.key.as_ref()
248    }
249
250    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
251        properties.add(
252            DiagnosticsProperty::<Rc<ThemeData>>::new("data", Rc::clone(&self.data))
253                .with_show_name(false),
254        );
255    }
256
257    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
258        // If a CupertinoThemeData doesn't exist, we're using a
259        // MaterialBasedCupertinoThemeData here instead of a CupertinoThemeData
260        // because it defers some properties to the Material ThemeData.
261        let cupertino_theme_data = self.inherited_cupertino_theme_data(app, context);
262        let child = self.wraps_widget_themes(app, context, self.child.clone());
263        InheritedTheme {
264            key: None,
265            theme: self.clone(),
266            child: CupertinoTheme::new(cupertino_theme_data, child).into_widget(),
267        }
268        .into_widget()
269    }
270}
271
272/// Dart's private `_InheritedTheme`.
273#[derive(Debug)]
274struct InheritedTheme {
275    key: Option<KeyRef>,
276    theme: Theme,
277    child: WidgetRef,
278}
279
280impl waft_widgets::InheritedTheme for InheritedTheme {
281    fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
282        Theme::new(Rc::clone(&self.theme.data), child).into_widget()
283    }
284}
285
286impl InheritedWidget for InheritedTheme {
287    fn key(&self) -> Option<&KeyRef> {
288        self.key.as_ref()
289    }
290
291    fn child(&self) -> &WidgetRef {
292        &self.child
293    }
294
295    fn update_should_notify(&self, old_widget: &InheritedTheme) -> bool {
296        self.theme.data != old_widget.theme.data
297    }
298
299    fn as_inherited_theme(&self) -> Option<&dyn waft_widgets::InheritedTheme> {
300        Some(self)
301    }
302}
303
304/// An interpolation between two [`ThemeData`]s.
305///
306/// This class specializes the interpolation of `Tween<ThemeData>` to call the
307/// [`ThemeData::lerp`] method.
308///
309/// See `Tween` for a discussion on how to use interpolation objects.
310#[derive(Clone, Debug)]
311pub struct ThemeDataTween {
312    /// The value this variable has at the beginning of the animation.
313    pub begin: Option<Rc<ThemeData>>,
314
315    /// The value this variable has at the end of the animation.
316    pub end: Option<Rc<ThemeData>>,
317}
318
319impl ThemeDataTween {
320    /// Creates a [`ThemeData`] tween.
321    ///
322    /// The [`begin`](Self::begin) and [`end`](Self::end) properties must be non-null before
323    /// the tween is first used, but the arguments can be null if the values are going to be
324    /// filled in later.
325    pub fn new(begin: Option<Rc<ThemeData>>, end: Option<Rc<ThemeData>>) -> ThemeDataTween {
326        ThemeDataTween { begin, end }
327    }
328
329    /// Returns the value this variable has at the given animation clock value.
330    pub fn lerp(&self, t: f64) -> Rc<ThemeData> {
331        Rc::new(ThemeData::lerp(
332            self.begin
333                .as_ref()
334                .expect("Tween.begin must be set before use"),
335            self.end.as_ref().expect("Tween.end must be set before use"),
336            t,
337        ))
338    }
339}
340
341impl Animatable<Rc<ThemeData>> for ThemeDataTween {
342    fn transform(&self, _app: &App, t: f64) -> Rc<ThemeData> {
343        if t == 0.0 {
344            return self
345                .begin
346                .clone()
347                .expect("Tween.begin must be set before use");
348        }
349        if t == 1.0 {
350            return self.end.clone().expect("Tween.end must be set before use");
351        }
352        self.lerp(t)
353    }
354}
355
356impl TweenValue for ThemeData {
357    fn same(&self, other: &ThemeData) -> bool {
358        self == other
359    }
360}
361
362impl TweenSlot for ThemeDataTween {
363    type Value = Rc<ThemeData>;
364
365    fn begin(&self, _app: &App) -> Option<Rc<ThemeData>> {
366        self.begin.clone()
367    }
368
369    fn set_begin(&mut self, _app: &mut App, begin: Option<Rc<ThemeData>>) {
370        self.begin = begin;
371    }
372
373    fn end(&self, _app: &App) -> Option<Rc<ThemeData>> {
374        self.end.clone()
375    }
376
377    fn set_end(&mut self, _app: &mut App, end: Option<Rc<ThemeData>>) {
378        self.end = end;
379    }
380}
381
382/// Animated version of [`Theme`] which automatically transitions the colors,
383/// etc, over a given duration whenever the given theme changes.
384///
385/// See also:
386///
387///  * [`Theme`], which [`AnimatedTheme`] uses to actually apply the interpolated
388///    theme.
389///  * [`ThemeData`], which describes the actual configuration of a theme.
390///  * `MaterialApp`, which includes an [`AnimatedTheme`] widget configured via
391///    the `MaterialApp.theme` argument.
392#[derive(Debug)]
393pub struct AnimatedTheme {
394    implicitly_animated_widget: ImplicitlyAnimatedWidgetData,
395
396    /// Specifies the color and typography values for descendant widgets.
397    pub data: Rc<ThemeData>,
398
399    /// The widget below this widget in the tree.
400    pub child: WidgetRef,
401}
402
403impl AnimatedTheme {
404    /// Creates an animated theme.
405    ///
406    /// By default, the theme transition uses a linear curve.
407    #[cfg_attr(debug_assertions, track_caller)]
408    pub fn new<K>(data: impl Into<Rc<ThemeData>>, child: impl IntoWidget<K>) -> AnimatedTheme {
409        AnimatedTheme {
410            implicitly_animated_widget: ImplicitlyAnimatedWidgetData::new(
411                K_THEME_ANIMATION_DURATION,
412            ),
413            data: data.into(),
414            child: child.into_widget(),
415        }
416    }
417
418    /// Dart `AnimatedTheme(duration:)`.
419    pub fn duration(mut self, duration: Duration) -> AnimatedTheme {
420        self.implicitly_animated_widget.duration = duration;
421        self
422    }
423
424    waft_widgets::implicitly_animated_widget_setters!(AnimatedTheme);
425}
426
427impl ImplicitlyAnimatedWidget for AnimatedTheme {
428    waft_widgets::implicitly_animated_widget_accessors!();
429}
430
431impl StatefulWidget for AnimatedTheme {
432    type State = AnimatedThemeState;
433
434    fn key(&self) -> Option<&KeyRef> {
435        self.implicitly_animated_widget.key.as_ref()
436    }
437
438    fn create_state(&self) -> AnimatedThemeState {
439        AnimatedThemeState {
440            state: StateData::new(),
441            single_ticker_provider: SingleTickerProviderStateMixinData::new(),
442            implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData::new(),
443            data: None,
444        }
445    }
446}
447
448/// Dart's `_AnimatedThemeState`.
449pub struct AnimatedThemeState {
450    state: StateData<AnimatedTheme>,
451    single_ticker_provider: SingleTickerProviderStateMixinData,
452    implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData,
453    data: Option<ThemeDataTween>,
454}
455
456impl SingleTickerProviderStateMixin for AnimatedThemeState {
457    fn single_ticker_provider_data(
458        self: Handle<Self>,
459        app: &App,
460    ) -> &SingleTickerProviderStateMixinData {
461        &app.get(self).single_ticker_provider
462    }
463
464    fn single_ticker_provider_data_mut(
465        self: Handle<Self>,
466        app: &mut App,
467    ) -> &mut SingleTickerProviderStateMixinData {
468        &mut app.get_mut(self).single_ticker_provider
469    }
470}
471
472impl TickerProviderObject for AnimatedThemeState {
473    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
474        SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
475    }
476}
477
478impl ImplicitlyAnimatedWidgetState for AnimatedThemeState {
479    waft_widgets::implicitly_animated_widget_state_accessors!();
480
481    fn for_each_tween<V: TweenVisitor>(self: Handle<Self>, app: &mut App, visitor: &mut V) {
482        let tween = app.get(self).data.clone();
483        let target = Some(Rc::clone(&self.widget(app).data));
484        app.get_mut(self).data = visitor.visit(app, tween, target, |_app, value| {
485            ThemeDataTween::new(Some(Rc::clone(value)), None)
486        });
487    }
488}
489
490impl AnimatedWidgetBaseState for AnimatedThemeState {}
491
492impl State for AnimatedThemeState {
493    type Widget = AnimatedTheme;
494    waft_widgets::state_accessors!();
495
496    fn init_state(self: Handle<Self>, app: &mut App) {
497        AnimatedWidgetBaseState::init_state(self, app);
498    }
499
500    fn debug_fill_properties(
501        self: Handle<Self>,
502        app: &App,
503        properties: &mut DiagnosticPropertiesBuilder,
504    ) {
505        ImplicitlyAnimatedWidgetData::debug_fill_properties(
506            &self.widget(app).implicitly_animated_widget,
507            properties,
508        );
509        properties.add(
510            DiagnosticsProperty::<String>::new(
511                "data",
512                app.get(self)
513                    .data
514                    .as_ref()
515                    .map(|_| "Instance of 'ThemeDataTween'".to_string()),
516            )
517            .with_show_name(false)
518            .default_value(None),
519        );
520    }
521
522    fn activate(self: Handle<Self>, app: &mut App) {
523        SingleTickerProviderStateMixin::activate(self, app);
524    }
525
526    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &AnimatedTheme) {
527        ImplicitlyAnimatedWidgetState::did_update_widget(self, app, old_widget);
528    }
529
530    fn dispose(self: Handle<Self>, app: &mut App) {
531        ImplicitlyAnimatedWidgetState::dispose(self, app);
532    }
533
534    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
535        let animation = self.animation(app);
536        let data = app
537            .get(self)
538            .data
539            .clone()
540            .expect("for_each_tween made the tween");
541        let child = self.widget(app).child.clone();
542        Theme::new(data.evaluate(app, animation), child).into_widget()
543    }
544}
545
546#[cfg(test)]
547mod tests {
548    use std::cell::{Cell, RefCell};
549    use std::rc::Rc;
550
551    use waft_cupertino::{CupertinoColors, CupertinoThemeData};
552    use waft_embedder::ViewRef;
553    use waft_embedder::{Color, TargetPlatform};
554    use waft_painting::AnyColor;
555    use waft_scheduler::{FrameTarget, SchedulerBinding};
556    use waft_widgets::{Builder, IconThemeData, MediaQueryData, RawView, SizedBox, WidgetsBinding};
557
558    use waft_widgets::testing::{
559        TargetPlatformVariant, WidgetTester, find, test_widgets, test_widgets_variant,
560    };
561
562    use super::*;
563    use crate::color_scheme::ColorScheme;
564    use crate::colors::{Colors, MaterialColor};
565    use crate::test_support::probe;
566    use crate::text_selection_theme::TextSelectionThemeData;
567    use crate::theme_data::ThemeDataBuilder;
568    use crate::typography::Typography;
569
570    fn themed(data: ThemeData) -> impl FnOnce(&App, WidgetRef) -> WidgetRef {
571        move |_app, child| Theme::new(data, child).into_widget()
572    }
573
574    /// Mounts `child` under a bare `RawView`, which, unlike `View`, adds no `MediaQuery`.
575    fn build_without_media_query(tester: &mut WidgetTester, child: WidgetRef) {
576        {
577            let mut app = tester.cell.borrow_mut();
578            let view = Rc::clone(tester.view()) as ViewRef;
579            let view_id = view.id();
580            let root = RawView::new(view, child).into_widget();
581            WidgetsBinding::instance(&mut app).attach_root_widget(&mut app, root);
582            SchedulerBinding::schedule_frame(&mut app, FrameTarget::View(view_id));
583        }
584        tester.pump();
585    }
586
587    #[test]
588    fn theme_data_tween_control_test() {
589        test_widgets(|tester| {
590            let app = tester.cell.borrow();
591            let light = Rc::new(ThemeData::new(&app));
592            let dark = Rc::new(ThemeData::dark(&app, None));
593            let tween = ThemeDataTween::new(Some(Rc::clone(&light)), Some(Rc::clone(&dark)));
594            assert_eq!(*tween.lerp(0.25), ThemeData::lerp(&light, &dark, 0.25));
595        });
596    }
597
598    #[test]
599    fn brightness_of_is_the_media_query_brightness_without_a_theme() {
600        test_widgets(|tester| {
601            let (brightness, maybe_brightness) = probe(
602                tester,
603                |_app, child| {
604                    MediaQuery::new(
605                        MediaQueryData::new().platform_brightness(Brightness::Dark),
606                        child,
607                    )
608                    .into_widget()
609                },
610                |app, context| {
611                    (
612                        Theme::brightness_of(app, context),
613                        Theme::maybe_brightness_of(app, context),
614                    )
615                },
616            );
617            assert_eq!(brightness, Brightness::Dark);
618            assert_eq!(maybe_brightness, Some(Brightness::Dark));
619        });
620    }
621
622    #[test]
623    fn brightness_of_prefers_the_theme_brightness_over_the_media_query() {
624        test_widgets(|tester| {
625            let (brightness, maybe_brightness) = probe(
626                tester,
627                |app, child| {
628                    let data = ThemeData::builder()
629                        .brightness(Brightness::Light)
630                        .build(app);
631                    MediaQuery::new(
632                        MediaQueryData::new().platform_brightness(Brightness::Dark),
633                        Theme::new(data, child),
634                    )
635                    .into_widget()
636                },
637                |app, context| {
638                    (
639                        Theme::brightness_of(app, context),
640                        Theme::maybe_brightness_of(app, context),
641                    )
642                },
643            );
644            assert_eq!(brightness, Brightness::Light);
645            assert_eq!(maybe_brightness, Some(Brightness::Light));
646        });
647    }
648
649    #[test]
650    fn brightness_of_is_light_and_maybe_brightness_of_is_none_without_a_theme_or_media_query() {
651        test_widgets(|tester| {
652            let seen = Rc::new(Cell::new(None));
653            let probe = Builder::new({
654                let seen = Rc::clone(&seen);
655                move |app, context| {
656                    seen.set(Some((
657                        Theme::brightness_of(app, context),
658                        Theme::maybe_brightness_of(app, context),
659                    )));
660                    SizedBox::shrink().into_widget()
661                }
662            });
663            build_without_media_query(tester, probe.into_widget());
664            assert_eq!(seen.get(), Some((Brightness::Light, None)));
665        });
666    }
667
668    #[test]
669    fn fallback_theme_is_the_localized_fallback() {
670        for use_material3 in [false, true] {
671            test_widgets(|tester| {
672                let theme = probe(
673                    tester,
674                    move |app, child| {
675                        let data = ThemeData::builder().use_material3(use_material3).build(app);
676                        Theme::new(data, child).into_widget()
677                    },
678                    Theme::of,
679                );
680                let mut app = tester.cell.borrow_mut();
681                let fallback = Rc::new(ThemeData::fallback(&app, Some(use_material3)));
682                let geometry = Rc::new(if use_material3 {
683                    Typography::english_like2021()
684                } else {
685                    Typography::english_like2014()
686                });
687                assert_eq!(theme, ThemeData::localize(&mut app, &fallback, &geometry));
688            });
689        }
690    }
691
692    #[test]
693    fn theme_data_localize_memoizes_the_result() {
694        test_widgets(|tester| {
695            let mut app = tester.cell.borrow_mut();
696            let light = Rc::new(ThemeData::new(&app));
697            let dark = Rc::new(ThemeData::dark(&app, None));
698            let default_geometry_theme = Rc::new(Typography::english_like2014());
699            let tall2014 = Rc::new(Typography::tall2014());
700
701            // Same input, same output.
702            let first = ThemeData::localize(&mut app, &light, &default_geometry_theme);
703            let second = ThemeData::localize(&mut app, &light, &default_geometry_theme);
704            assert!(Rc::ptr_eq(&first, &second));
705
706            // Different text geometry, different output.
707            let tall = ThemeData::localize(&mut app, &light, &tall2014);
708            assert!(!Rc::ptr_eq(&first, &tall));
709
710            // Different base theme, different output.
711            let dark_localized = ThemeData::localize(&mut app, &dark, &default_geometry_theme);
712            assert!(!Rc::ptr_eq(&first, &dark_localized));
713        });
714    }
715
716    #[test]
717    fn fallback_theme_follows_the_target_platform() {
718        for platform in [
719            TargetPlatform::Android,
720            TargetPlatform::Fuchsia,
721            TargetPlatform::IOS,
722            TargetPlatform::Linux,
723            TargetPlatform::MacOS,
724            TargetPlatform::Windows,
725        ] {
726            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
727                let theme = probe(tester, |_app, child| child, Theme::of);
728                assert_eq!(theme.platform, platform);
729            });
730        }
731    }
732
733    #[test]
734    fn theme_data_with_null_typography_uses_proper_defaults() {
735        test_widgets(|tester| {
736            let app = tester.cell.borrow();
737            let m2_theme = ThemeData::builder().use_material3(false).build(&app);
738            assert_eq!(m2_theme.typography, Typography::material2014().build());
739            let m3_theme = ThemeData::new(&app);
740            assert_eq!(
741                m3_theme.typography,
742                Typography::material2021()
743                    .color_scheme(m3_theme.color_scheme.clone())
744                    .build()
745            );
746        });
747    }
748
749    #[test]
750    fn icon_themes_are_applied_and_animated() {
751        test_widgets(|tester| {
752            let seen = Rc::new(Cell::new(None));
753            let child = Builder::new({
754                let seen = Rc::clone(&seen);
755                move |app, context| {
756                    let icon_theme = IconTheme::of(app, context);
757                    seen.set(Some((
758                        icon_theme.color.as_ref().map(AnyColor::color),
759                        icon_theme.size,
760                    )));
761                    SizedBox::shrink().into_widget()
762                }
763            })
764            .into_widget();
765            let animated = |app: &App, color: Color, size: f64| {
766                let data = ThemeData::builder()
767                    .icon_theme(IconThemeData::new().color(color).size(size))
768                    .build(app);
769                AnimatedTheme::new(data, child.clone()).into_widget()
770            };
771            let green = Colors::GREEN.primary();
772            let orange = Colors::ORANGE.primary();
773
774            let tree = animated(&tester.cell.borrow(), green, 10.0);
775            tester.pump_widget(tree);
776            assert_eq!(seen.get(), Some((Some(green), Some(10.0))));
777
778            let tree = animated(&tester.cell.borrow(), orange, 20.0);
779            tester.pump_widget(tree);
780            // Halfway through the theme transition
781            tester.pump_by(Duration::from_millis(100));
782            let (color, size) = seen.get().expect("the child built");
783            assert_eq!(color, Color::lerp(Some(green), Some(orange), 0.5));
784            assert_eq!(size, Some(15.0));
785
786            // Finish the transition
787            tester.pump_by(Duration::from_millis(100));
788            assert_eq!(seen.get(), Some((Some(orange), Some(20.0))));
789        });
790    }
791
792    #[test]
793    fn same_theme_data_reapplied_does_not_trigger_descendant_rebuilds() {
794        test_widgets(|tester| {
795            let builds = Rc::new(Cell::new(0));
796            let child = Builder::new({
797                let builds = Rc::clone(&builds);
798                move |app, context| {
799                    Theme::of(app, context);
800                    builds.set(builds.get() + 1);
801                    SizedBox::shrink().into_widget()
802                }
803            })
804            .into_widget();
805            let cell = Rc::clone(&tester.cell);
806            let build_theme = |primary_color: u32| {
807                let data = ThemeData::builder()
808                    .primary_color(Color::new(primary_color))
809                    .build(&cell.borrow());
810                Theme::new(data, child.clone()).into_widget()
811            };
812
813            tester.pump_widget(build_theme(0xFF000000));
814            assert_eq!(builds.get(), 1);
815
816            // New instance of theme data but still the same content.
817            tester.pump_widget(build_theme(0xFF000000));
818            // Still no repeated calls.
819            assert_eq!(builds.get(), 1);
820
821            // Different now.
822            tester.pump_widget(build_theme(0xFF222222));
823            // Should call build again.
824            assert_eq!(builds.get(), 2);
825        });
826    }
827
828    #[test]
829    fn text_geometry_set_in_theme_has_higher_precedence_than_that_of_localizations() {
830        test_widgets(|tester| {
831            let k_magic_font_size = 4321.0;
832            let custom_theme = {
833                let fallback = ThemeData::fallback(&tester.cell.borrow(), None);
834                let body_medium = fallback
835                    .primary_text_theme
836                    .body_medium
837                    .as_ref()
838                    .expect("a body style")
839                    .copy_with()
840                    .font_size(k_magic_font_size);
841                fallback
842                    .copy_with()
843                    .primary_text_theme(
844                        fallback
845                            .primary_text_theme
846                            .copy_with()
847                            .body_medium(body_medium),
848                    )
849                    .build()
850            };
851            let actual_font_size = probe(tester, themed(custom_theme), |app, context| {
852                Theme::of(app, context)
853                    .primary_text_theme
854                    .body_medium
855                    .as_ref()
856                    .and_then(|style| style.font_size)
857            });
858            assert_eq!(actual_font_size, Some(k_magic_font_size));
859        });
860    }
861
862    #[test]
863    fn material3_default_theme_provides_all_basic_text_style_properties() {
864        test_widgets(|tester| {
865            let theme = probe(
866                tester,
867                |app, child| themed(ThemeData::new(app))(app, child),
868                Theme::of,
869            );
870            for text_theme in [&theme.text_theme, &theme.primary_text_theme] {
871                let styles = [
872                    &text_theme.display_large,
873                    &text_theme.display_medium,
874                    &text_theme.display_small,
875                    &text_theme.headline_large,
876                    &text_theme.headline_medium,
877                    &text_theme.headline_small,
878                    &text_theme.title_large,
879                    &text_theme.title_medium,
880                    &text_theme.body_large,
881                    &text_theme.body_medium,
882                    &text_theme.body_small,
883                    &text_theme.label_large,
884                    &text_theme.label_medium,
885                ];
886                for style in styles {
887                    let style = style.as_ref().expect("a style");
888                    assert!(!style.inherit);
889                    assert!(style.color.is_some());
890                    assert!(style.font_family.is_some());
891                    assert!(style.font_size.is_some());
892                    assert!(style.font_weight.is_some());
893                    assert!(style.font_style.is_none());
894                    assert!(style.letter_spacing.is_some());
895                    assert!(style.word_spacing.is_none());
896                    assert!(style.text_baseline.is_some());
897                    assert!(style.height.is_some());
898                    assert_eq!(style.decoration, Some(waft_embedder::TextDecoration::NONE));
899                    assert!(style.decoration_color.is_some());
900                    assert!(style.decoration_style.is_none());
901                    assert!(style.debug_label.is_some());
902                    assert!(style.background.is_none());
903                }
904            }
905            assert_eq!(
906                theme
907                    .text_theme
908                    .display_large
909                    .as_ref()
910                    .and_then(|style| style.debug_label.clone())
911                    .as_deref(),
912                Some(
913                    "(englishLike displayLarge 2021).merge((blackMountainView displayLarge).apply)"
914                )
915            );
916        });
917    }
918
919    #[test]
920    fn inherited_theme_capture_reproduces_the_theme_elsewhere() {
921        test_widgets(|tester| {
922            let (captured, theme) = probe(
923                tester,
924                |app, child| {
925                    let data = ThemeData::builder()
926                        .primary_color(Colors::RED.primary())
927                        .build(app);
928                    Theme::new(data, child).into_widget()
929                },
930                |app, context| {
931                    (
932                        <dyn waft_widgets::InheritedTheme>::capture(app, context, None),
933                        Theme::of(app, context),
934                    )
935                },
936            );
937            let recaptured = probe(tester, |_app, child| captured.wrap(child), Theme::of);
938            assert_eq!(recaptured, theme);
939            assert_eq!(recaptured.primary_color, Colors::RED.primary());
940        });
941    }
942
943    /// The `CupertinoThemeData` a probe under `Theme(data:)` reads with `CupertinoTheme::of`.
944    fn cupertino_theme_of(
945        tester: &mut WidgetTester,
946        data: impl FnOnce(&App) -> ThemeData,
947    ) -> CupertinoThemeData {
948        probe(
949            tester,
950            |app, child| Theme::new(data(app), child).into_widget(),
951            CupertinoTheme::of,
952        )
953    }
954
955    fn any(color: Color) -> AnyColor {
956        AnyColor::new(color)
957    }
958
959    #[test]
960    fn material2_default_light_and_dark_cupertino_themes_have_defaults() {
961        test_widgets(|tester| {
962            let light = cupertino_theme_of(tester, |app| {
963                ThemeData::builder().use_material3(false).build(app)
964            });
965            assert_eq!(light.brightness(), Some(Brightness::Light));
966            assert_eq!(light.primary_color(), any(Colors::BLUE.primary()));
967            assert_eq!(
968                light.scaffold_background_color(),
969                any(Colors::GREY.shade50())
970            );
971            assert_eq!(light.primary_contrasting_color(), any(Colors::WHITE));
972            let text_style = light.text_theme().text_style();
973            assert_eq!(
974                text_style.font_family.as_deref(),
975                Some("CupertinoSystemText")
976            );
977            assert_eq!(text_style.font_size, Some(17.0));
978
979            let dark = cupertino_theme_of(tester, |app| ThemeData::dark(app, Some(false)));
980            assert_eq!(dark.brightness(), Some(Brightness::Dark));
981            assert_eq!(dark.primary_color(), any(Colors::BLUE.primary()));
982            assert_eq!(dark.primary_contrasting_color(), any(Colors::WHITE));
983            assert_eq!(
984                dark.scaffold_background_color(),
985                any(Colors::GREY.get(&850).expect("grey 850"))
986            );
987            let text_style = dark.text_theme().text_style();
988            assert_eq!(
989                text_style.font_family.as_deref(),
990                Some("CupertinoSystemText")
991            );
992            assert_eq!(text_style.font_size, Some(17.0));
993        });
994    }
995
996    #[test]
997    fn material3_default_light_and_dark_cupertino_themes_have_defaults() {
998        test_widgets(|tester| {
999            let light = cupertino_theme_of(tester, ThemeData::new);
1000            assert_eq!(light.brightness(), Some(Brightness::Light));
1001            assert_eq!(light.primary_color(), any(Color::new(0xff6750a4)));
1002            // ColorScheme.background
1003            assert_eq!(
1004                light.scaffold_background_color(),
1005                any(Color::new(0xfffef7ff))
1006            );
1007            assert_eq!(light.primary_contrasting_color(), any(Colors::WHITE));
1008            let text_style = light.text_theme().text_style();
1009            assert_eq!(
1010                text_style.font_family.as_deref(),
1011                Some("CupertinoSystemText")
1012            );
1013            assert_eq!(text_style.font_size, Some(17.0));
1014
1015            let dark = cupertino_theme_of(tester, |app| ThemeData::dark(app, None));
1016            assert_eq!(dark.brightness(), Some(Brightness::Dark));
1017            assert_eq!(dark.primary_color(), any(Color::new(0xffd0bcff)));
1018            assert_eq!(
1019                dark.primary_contrasting_color(),
1020                any(Color::new(0xff381e72))
1021            );
1022            assert_eq!(
1023                dark.scaffold_background_color(),
1024                any(Color::new(0xff141218))
1025            );
1026        });
1027    }
1028
1029    #[test]
1030    fn material_theme_overrides_the_cupertino_brightness() {
1031        test_widgets(|tester| {
1032            let mut brightness_of = |data: fn(&App) -> ThemeData| {
1033                probe(
1034                    tester,
1035                    |app, child| Theme::new(data(app), child).into_widget(),
1036                    CupertinoTheme::brightness_of,
1037                )
1038            };
1039            assert_eq!(
1040                brightness_of(|app| ThemeData::dark(app, None)),
1041                Brightness::Dark
1042            );
1043            assert_eq!(brightness_of(ThemeData::new), Brightness::Light);
1044
1045            // Overridable by cupertinoOverrideTheme.
1046            assert_eq!(
1047                brightness_of(|app| {
1048                    ThemeData::builder()
1049                        .brightness(Brightness::Light)
1050                        .cupertino_override_theme(
1051                            CupertinoThemeData::new()
1052                                .with_brightness(Brightness::Dark)
1053                                .no_default(),
1054                        )
1055                        .build(app)
1056                }),
1057                Brightness::Dark
1058            );
1059            assert_eq!(
1060                brightness_of(|app| {
1061                    ThemeData::builder()
1062                        .brightness(Brightness::Dark)
1063                        .cupertino_override_theme(
1064                            CupertinoThemeData::new()
1065                                .with_brightness(Brightness::Light)
1066                                .no_default(),
1067                        )
1068                        .build(app)
1069                }),
1070                Brightness::Light
1071            );
1072        });
1073    }
1074
1075    #[test]
1076    fn cupertino_override_theme_overrides_the_material_theme_and_keeps_the_rest_cascaded() {
1077        for use_material3 in [false, true] {
1078            test_widgets(|tester| {
1079                let theme = cupertino_theme_of(tester, move |app| {
1080                    ThemeData::builder()
1081                        .cupertino_override_theme(
1082                            CupertinoThemeData::new()
1083                                .with_scaffold_background_color(
1084                                    CupertinoColors::LIGHT_BACKGROUND_GRAY,
1085                                )
1086                                .no_default(),
1087                        )
1088                        .use_material3(use_material3)
1089                        .build(app)
1090                });
1091
1092                assert_eq!(theme.brightness(), Some(Brightness::Light));
1093                // We took the scaffold background override but the rest are still cascaded
1094                // to the material theme.
1095                let primary = if use_material3 {
1096                    Color::new(0xff6750a4)
1097                } else {
1098                    Colors::BLUE.primary()
1099                };
1100                assert_eq!(theme.primary_color(), any(primary));
1101                assert_eq!(theme.primary_contrasting_color(), any(Colors::WHITE));
1102                assert_eq!(
1103                    theme.scaffold_background_color(),
1104                    CupertinoColors::LIGHT_BACKGROUND_GRAY
1105                );
1106                let text_style = theme.text_theme().text_style();
1107                assert_eq!(
1108                    text_style.font_family.as_deref(),
1109                    Some("CupertinoSystemText")
1110                );
1111                assert_eq!(text_style.font_size, Some(17.0));
1112            });
1113        }
1114    }
1115
1116    #[test]
1117    fn cupertino_override_theme_overrides_properties_that_are_independent_of_material() {
1118        for use_material3 in [false, true] {
1119            test_widgets(|tester| {
1120                let theme = cupertino_theme_of(tester, move |app| {
1121                    ThemeData::builder()
1122                        .cupertino_override_theme(
1123                            CupertinoThemeData::new()
1124                                // The bar colors ignore all things material except brightness.
1125                                .with_bar_background_color(CupertinoColors::BLACK)
1126                                .no_default(),
1127                        )
1128                        .use_material3(use_material3)
1129                        .build(app)
1130                });
1131
1132                let primary = if use_material3 {
1133                    Color::new(0xff6750a4)
1134                } else {
1135                    Colors::BLUE.primary()
1136                };
1137                assert_eq!(theme.primary_color(), any(primary));
1138                // MaterialBasedCupertinoThemeData should also function like a normal
1139                // CupertinoThemeData.
1140                assert_eq!(theme.bar_background_color(), CupertinoColors::BLACK);
1141            });
1142        }
1143    }
1144
1145    #[test]
1146    fn changing_the_material_theme_rebuilds_cupertino_dependents() {
1147        test_widgets(|tester| {
1148            let builds = Rc::new(Cell::new(0));
1149            let primary = Rc::new(Cell::new(None));
1150            let child = Builder::new({
1151                let builds = Rc::clone(&builds);
1152                let primary = Rc::clone(&primary);
1153                move |app, context| {
1154                    builds.set(builds.get() + 1);
1155                    primary.set(Some(
1156                        CupertinoTheme::of(app, context).primary_color().color(),
1157                    ));
1158                    SizedBox::shrink().into_widget()
1159                }
1160            })
1161            .into_widget();
1162            let cell = Rc::clone(&tester.cell);
1163            let build_theme = |color: Color| {
1164                let data = ThemeData::builder()
1165                    .color_scheme(ColorScheme::light().with_primary(color))
1166                    .build(&cell.borrow());
1167                Theme::new(data, child.clone()).into_widget()
1168            };
1169
1170            tester.pump_widget(build_theme(Colors::RED.primary()));
1171            assert_eq!(builds.get(), 1);
1172            assert_eq!(primary.get(), Some(Colors::RED.primary()));
1173
1174            tester.pump_widget(build_theme(Colors::ORANGE.primary()));
1175            assert_eq!(builds.get(), 2);
1176            assert_eq!(primary.get(), Some(Colors::ORANGE.primary()));
1177        });
1178    }
1179
1180    #[test]
1181    fn cupertino_theme_data_does_not_override_the_material_icon_theme() {
1182        test_widgets(|tester| {
1183            let material_icon_color = Colors::BLUE.primary();
1184            let cupertino_icon_color = Colors::BLACK;
1185            let icon_color = probe(
1186                tester,
1187                move |app, child| {
1188                    let data = ThemeData::builder()
1189                        .icon_theme(IconThemeData::new().color(material_icon_color))
1190                        .cupertino_override_theme(
1191                            CupertinoThemeData::new()
1192                                .with_primary_color(cupertino_icon_color)
1193                                .no_default(),
1194                        )
1195                        .build(app);
1196                    Theme::new(data, child).into_widget()
1197                },
1198                |app, context| IconTheme::of(app, context).color,
1199            );
1200            assert_eq!(icon_color, Some(any(material_icon_color)));
1201        });
1202    }
1203
1204    /// Dart's `testTheme` over its `singletonThemeSubtree`: each call pumps `Theme(data:)` over
1205    /// the same subtree, which counts its builds and keeps the `CupertinoThemeData` it read.
1206    struct CupertinoThemeTester {
1207        build_count: Rc<Cell<usize>>,
1208        actual_theme: Rc<RefCell<Option<CupertinoThemeData>>>,
1209        singleton_theme_subtree: WidgetRef,
1210    }
1211
1212    impl CupertinoThemeTester {
1213        fn new() -> CupertinoThemeTester {
1214            let build_count = Rc::new(Cell::new(0));
1215            let actual_theme = Rc::new(RefCell::new(None));
1216            let singleton_theme_subtree = Builder::new({
1217                let build_count = Rc::clone(&build_count);
1218                let actual_theme = Rc::clone(&actual_theme);
1219                move |app, context| {
1220                    build_count.set(build_count.get() + 1);
1221                    *actual_theme.borrow_mut() = Some(CupertinoTheme::of(app, context));
1222                    SizedBox::shrink().into_widget()
1223                }
1224            })
1225            .into_widget();
1226            CupertinoThemeTester {
1227                build_count,
1228                actual_theme,
1229                singleton_theme_subtree,
1230            }
1231        }
1232
1233        fn test_theme(
1234            &self,
1235            tester: &mut WidgetTester,
1236            theme: impl FnOnce(&App) -> ThemeData,
1237        ) -> CupertinoThemeData {
1238            let data = theme(&tester.cell.borrow());
1239            tester
1240                .pump_widget(Theme::new(data, self.singleton_theme_subtree.clone()).into_widget());
1241            let actual_theme = self.actual_theme.borrow().clone();
1242            actual_theme.expect("the subtree built")
1243        }
1244
1245        fn build_count(&self) -> usize {
1246            self.build_count.get()
1247        }
1248    }
1249
1250    /// The Material theme whose primary colour is `primary`: Dart's `primarySwatch` with
1251    /// `useMaterial3: false` in Material 2, `ColorScheme.light(primary:)` in Material 3.
1252    fn material_theme_with_primary(
1253        use_material3: bool,
1254        primary: MaterialColor,
1255    ) -> ThemeDataBuilder {
1256        if use_material3 {
1257            ThemeData::builder().color_scheme(ColorScheme::light().with_primary(primary.primary()))
1258        } else {
1259            ThemeData::builder()
1260                .use_material3(false)
1261                .primary_swatch(primary)
1262        }
1263    }
1264
1265    #[test]
1266    fn changing_cupertino_theme_override_triggers_rebuilds() {
1267        test_widgets(|tester| {
1268            let subtree = CupertinoThemeTester::new();
1269            let theme = subtree.test_theme(tester, |app| {
1270                ThemeData::builder()
1271                    .primary_swatch(Colors::PURPLE)
1272                    .cupertino_override_theme(
1273                        CupertinoThemeData::new()
1274                            .with_primary_color(CupertinoColors::ACTIVE_ORANGE)
1275                            .no_default(),
1276                    )
1277                    .build(app)
1278            });
1279            assert_eq!(subtree.build_count(), 1);
1280            assert_eq!(theme.primary_color(), CupertinoColors::ACTIVE_ORANGE);
1281
1282            let theme = subtree.test_theme(tester, |app| {
1283                ThemeData::builder()
1284                    .primary_swatch(Colors::PURPLE)
1285                    .cupertino_override_theme(
1286                        CupertinoThemeData::new()
1287                            .with_primary_color(CupertinoColors::ACTIVE_GREEN)
1288                            .no_default(),
1289                    )
1290                    .build(app)
1291            });
1292            assert_eq!(subtree.build_count(), 2);
1293            assert_eq!(theme.primary_color(), CupertinoColors::ACTIVE_GREEN);
1294        });
1295    }
1296
1297    #[test]
1298    fn cupertino_theme_override_blocks_derivative_changes() {
1299        test_widgets(|tester| {
1300            let subtree = CupertinoThemeTester::new();
1301            let theme = subtree.test_theme(tester, |app| {
1302                ThemeData::builder()
1303                    .primary_swatch(Colors::PURPLE)
1304                    .cupertino_override_theme(
1305                        CupertinoThemeData::new()
1306                            .with_primary_color(CupertinoColors::ACTIVE_ORANGE)
1307                            .no_default(),
1308                    )
1309                    .build(app)
1310            });
1311            assert_eq!(subtree.build_count(), 1);
1312            assert_eq!(theme.primary_color(), CupertinoColors::ACTIVE_ORANGE);
1313
1314            // Change the upstream material primary color.
1315            let theme = subtree.test_theme(tester, |app| {
1316                ThemeData::builder()
1317                    .primary_swatch(Colors::BLUE)
1318                    .cupertino_override_theme(
1319                        CupertinoThemeData::new()
1320                            // But the primary material color is preempted by the override.
1321                            .with_primary_color(CupertinoColors::SYSTEM_RED)
1322                            .no_default(),
1323                    )
1324                    .build(app)
1325            });
1326            assert_eq!(subtree.build_count(), 2);
1327            assert_eq!(theme.primary_color(), CupertinoColors::SYSTEM_RED);
1328        });
1329    }
1330
1331    #[test]
1332    fn cupertino_overrides_do_not_block_derivatives_triggering_rebuilds_when_derivatives_are_not_overridden()
1333     {
1334        for use_material3 in [false, true] {
1335            test_widgets(|tester| {
1336                let subtree = CupertinoThemeTester::new();
1337                let theme = subtree.test_theme(tester, |app| {
1338                    material_theme_with_primary(use_material3, Colors::PURPLE)
1339                        .cupertino_override_theme(
1340                            CupertinoThemeData::new()
1341                                .with_primary_contrasting_color(CupertinoColors::DESTRUCTIVE_RED)
1342                                .no_default(),
1343                        )
1344                        .build(app)
1345                });
1346                assert_eq!(subtree.build_count(), 1);
1347                assert_eq!(
1348                    theme.text_theme().action_text_style().color,
1349                    Some(any(Colors::PURPLE.primary()))
1350                );
1351                assert_eq!(
1352                    theme.primary_contrasting_color(),
1353                    CupertinoColors::DESTRUCTIVE_RED
1354                );
1355
1356                let theme = subtree.test_theme(tester, |app| {
1357                    material_theme_with_primary(use_material3, Colors::GREEN)
1358                        .cupertino_override_theme(
1359                            CupertinoThemeData::new()
1360                                .with_primary_contrasting_color(CupertinoColors::DESTRUCTIVE_RED)
1361                                .no_default(),
1362                        )
1363                        .build(app)
1364                });
1365                assert_eq!(subtree.build_count(), 2);
1366                assert_eq!(
1367                    theme.text_theme().action_text_style().color,
1368                    Some(any(Colors::GREEN.primary()))
1369                );
1370                assert_eq!(
1371                    theme.primary_contrasting_color(),
1372                    CupertinoColors::DESTRUCTIVE_RED
1373                );
1374            });
1375        }
1376    }
1377
1378    #[test]
1379    fn copy_with_only_copies_the_overrides_not_the_material_or_cupertino_derivatives() {
1380        for use_material3 in [false, true] {
1381            test_widgets(|tester| {
1382                let subtree = CupertinoThemeTester::new();
1383                let original_theme = subtree.test_theme(tester, |app| {
1384                    material_theme_with_primary(use_material3, Colors::PURPLE)
1385                        .cupertino_override_theme(
1386                            CupertinoThemeData::new()
1387                                .with_primary_contrasting_color(CupertinoColors::ACTIVE_ORANGE)
1388                                .no_default(),
1389                        )
1390                        .build(app)
1391                });
1392
1393                let copied_theme = original_theme
1394                    .copy_with()
1395                    .with_bar_background_color(CupertinoColors::DESTRUCTIVE_RED);
1396
1397                let theme = subtree.test_theme(tester, |app| {
1398                    material_theme_with_primary(use_material3, Colors::BLUE)
1399                        .cupertino_override_theme(copied_theme.no_default())
1400                        .build(app)
1401                });
1402
1403                assert_eq!(theme.primary_color(), any(Colors::BLUE.primary()));
1404                assert_eq!(
1405                    theme.primary_contrasting_color(),
1406                    CupertinoColors::ACTIVE_ORANGE
1407                );
1408                assert_eq!(
1409                    theme.bar_background_color(),
1410                    CupertinoColors::DESTRUCTIVE_RED
1411                );
1412            });
1413        }
1414    }
1415
1416    #[test]
1417    fn material_themes_with_no_cupertino_overrides_can_also_be_copy_with_ed() {
1418        for use_material3 in [false, true] {
1419            test_widgets(|tester| {
1420                let subtree = CupertinoThemeTester::new();
1421                let original_theme = subtree.test_theme(tester, |app| {
1422                    material_theme_with_primary(use_material3, Colors::PURPLE).build(app)
1423                });
1424
1425                let copied_theme = original_theme
1426                    .copy_with()
1427                    .with_primary_contrasting_color(CupertinoColors::DESTRUCTIVE_RED);
1428
1429                let theme = subtree.test_theme(tester, |app| {
1430                    material_theme_with_primary(use_material3, Colors::BLUE)
1431                        .cupertino_override_theme(copied_theme.no_default())
1432                        .build(app)
1433                });
1434
1435                assert_eq!(theme.primary_color(), any(Colors::BLUE.primary()));
1436                assert_eq!(
1437                    theme.primary_contrasting_color(),
1438                    CupertinoColors::DESTRUCTIVE_RED
1439                );
1440            });
1441        }
1442    }
1443
1444    #[test]
1445    fn material_based_cupertino_theme_data_resolves_from_the_material_theme() {
1446        test_widgets(|tester| {
1447            let (material, resolved) = probe(
1448                tester,
1449                |_app, child| child,
1450                |app, context| {
1451                    let material = Rc::new(ThemeData::dark(app, None));
1452                    let resolved =
1453                        MaterialBasedCupertinoThemeData::new(&material).resolve_from(app, context);
1454                    (material, resolved)
1455                },
1456            );
1457            assert_eq!(resolved.brightness(), Some(Brightness::Dark));
1458            assert_eq!(
1459                resolved.primary_color(),
1460                any(material.color_scheme.primary())
1461            );
1462            assert_eq!(
1463                resolved.primary_contrasting_color(),
1464                any(material.color_scheme.on_primary())
1465            );
1466            assert_eq!(
1467                resolved.scaffold_background_color(),
1468                any(material.scaffold_background_color)
1469            );
1470            // The override theme part is what `no_default` reports: here only the text theme
1471            // `resolve_from` puts there.
1472            let no_default = resolved.no_default();
1473            assert!(no_default.primary_color.is_none());
1474            assert!(no_default.text_theme.is_some());
1475            // The text theme derives from the Material primary colour.
1476            assert_eq!(
1477                resolved.text_theme().action_text_style().color,
1478                Some(any(material.color_scheme.primary()))
1479            );
1480            assert_eq!(
1481                resolved
1482                    .copy_with()
1483                    .with_primary_color(Colors::RED.primary())
1484                    .primary_color(),
1485                any(Colors::RED.primary())
1486            );
1487            // The iOS defaults stay dynamic: only the override theme part is resolved.
1488            assert_eq!(
1489                resolved.bar_background_color(),
1490                CupertinoThemeData::new().bar_background_color()
1491            );
1492        });
1493    }
1494
1495    fn selection_colors(
1496        app: &mut App,
1497        context: BuildContext,
1498    ) -> (Option<AnyColor>, Option<AnyColor>) {
1499        let style = DefaultSelectionStyle::of(app, context);
1500        (style.selection_color, style.cursor_color)
1501    }
1502
1503    #[test]
1504    fn theme_provides_a_default_selection_style_from_its_text_selection_theme() {
1505        test_widgets(|tester| {
1506            let seen = probe(
1507                tester,
1508                |app, child| {
1509                    let data = ThemeData::builder()
1510                        .text_selection_theme(
1511                            TextSelectionThemeData::new()
1512                                .selection_color(Color::new(0x88888888))
1513                                .cursor_color(Color::new(0xffaabbcc)),
1514                        )
1515                        .build(app);
1516                    Theme::new(data, child).into_widget()
1517                },
1518                selection_colors,
1519            );
1520            assert_eq!(
1521                seen,
1522                (
1523                    Some(any(Color::new(0x88888888))),
1524                    Some(any(Color::new(0xffaabbcc)))
1525                )
1526            );
1527        });
1528    }
1529
1530    #[test]
1531    fn theme_keeps_the_ambient_selection_style_where_its_text_selection_theme_is_unset() {
1532        test_widgets(|tester| {
1533            let seen = probe(
1534                tester,
1535                |app, child| {
1536                    let data = ThemeData::builder()
1537                        .text_selection_theme(
1538                            TextSelectionThemeData::new().cursor_color(Color::new(0xffaabbcc)),
1539                        )
1540                        .build(app);
1541                    DefaultSelectionStyle::new(Theme::new(data, child))
1542                        .selection_color(Color::new(0xffaa1111))
1543                        .cursor_color(Color::new(0x00cc2222))
1544                        .into_widget()
1545                },
1546                selection_colors,
1547            );
1548            assert_eq!(
1549                seen,
1550                (
1551                    Some(any(Color::new(0xffaa1111))),
1552                    Some(any(Color::new(0xffaabbcc)))
1553                )
1554            );
1555        });
1556    }
1557
1558    #[test]
1559    fn material_based_cupertino_theme_data_takes_the_selection_handle_color_from_the_text_selection_theme()
1560     {
1561        test_widgets(|tester| {
1562            let (from_material, overridden) = probe(
1563                tester,
1564                |_app, child| child,
1565                |app, _context| {
1566                    let material = ThemeData::builder()
1567                        .text_selection_theme(
1568                            TextSelectionThemeData::new()
1569                                .selection_handle_color(Color::new(0xaabbccdd)),
1570                        )
1571                        .build(app);
1572                    let theme = MaterialBasedCupertinoThemeData::new(&Rc::new(material));
1573                    (
1574                        theme.selection_handle_color(),
1575                        theme
1576                            .copy_with()
1577                            .with_selection_handle_color(Colors::RED.primary())
1578                            .selection_handle_color(),
1579                    )
1580                },
1581            );
1582            assert_eq!(from_material, any(Color::new(0xaabbccdd)));
1583            assert_eq!(overridden, any(Colors::RED.primary()));
1584        });
1585    }
1586
1587    #[test]
1588    fn cupertino_widgets_correctly_get_the_right_text_theme_in_dark_mode() {
1589        test_widgets(|tester| {
1590            let text_field_key = waft_widgets::GlobalKey::new();
1591            let theme = ThemeData::dark(&tester.cell.borrow(), None);
1592            tester.pump_widget(crate::test_support::material_app(
1593                theme,
1594                waft_cupertino::CupertinoTextField::new()
1595                    .key(text_field_key.clone().into())
1596                    .into_widget(),
1597            ));
1598            tester.pump_and_settle();
1599
1600            let editable_text = find::by_type::<waft_widgets::EditableText>().evaluate(tester);
1601            assert_eq!(editable_text.len(), 1);
1602            let style_color = tester
1603                .widget::<waft_widgets::EditableText, _>(editable_text[0], |editable_text| {
1604                    editable_text.style.color.clone()
1605                });
1606
1607            // Default CupertinoTextStyle color is a CupertinoDynamicColor.
1608            let cupertino_theme_data = {
1609                let mut app = tester.cell.borrow_mut();
1610                let context = text_field_key
1611                    .current_context(&app)
1612                    .expect("the text field is mounted");
1613                CupertinoTheme::of(&mut app, context)
1614            };
1615            let text_style_color = cupertino_theme_data
1616                .text_theme()
1617                .text_style()
1618                .color
1619                .expect("a text colour");
1620            let theme_text_style_color = text_style_color
1621                .extension::<waft_cupertino::CupertinoDynamicColor>()
1622                .expect("a CupertinoDynamicColor");
1623
1624            // The value of the textfield's color should resolve to the theme's dark color.
1625            assert_eq!(
1626                style_color.map(|color| color.to_argb32()),
1627                Some(theme_text_style_color.dark_color.to_argb32())
1628            );
1629        });
1630    }
1631}