Skip to main content

waft_widgets/widgets/
icon_theme_data.rs

1//! Flutter counterpart: `widgets/icon_theme_data.dart`.
2//!
3//! [`IconThemeData::resolve`] is an inherent method here, not an override point: a
4//! `CupertinoIconThemeData` that resolves its color against the [`BuildContext`] waits.
5
6use std::fmt;
7use std::rc::Rc;
8
9use waft_embedder::{Color, Shadow, clamp_double, lerp_double};
10use waft_foundation::{App, DiagnosticPropertiesBuilder, DiagnosticsProperty, DoubleProperty};
11use waft_painting::{AnyColor, ColorProperty};
12
13use crate::framework::BuildContext;
14
15/// Defines the size, font variations, color, opacity, and shadows of icons.
16///
17/// Used by [`IconTheme`](crate::IconTheme) to control those properties in a widget subtree.
18///
19/// To obtain the current icon theme, use [`IconTheme::of`](crate::IconTheme::of). To convert
20/// an icon theme to a version with all the fields filled in, use
21/// [`IconThemeData::fallback`].
22///
23/// Dart's named constructor arguments are the fluent setters
24/// (`IconThemeData::new().size(16.0).opacity(0.5)`).
25#[derive(Clone)]
26pub struct IconThemeData {
27    /// The default for `Icon.size`.
28    ///
29    /// Falls back to 24.0.
30    pub size: Option<f64>,
31    /// The default for `Icon.fill`.
32    ///
33    /// Falls back to 0.0.
34    pub fill: Option<f64>,
35    /// The default for `Icon.weight`.
36    ///
37    /// Falls back to 400.0.
38    pub weight: Option<f64>,
39    /// The default for `Icon.grade`.
40    ///
41    /// Falls back to 0.0.
42    pub grade: Option<f64>,
43    /// The default for `Icon.opticalSize`.
44    ///
45    /// Falls back to 48.0.
46    pub optical_size: Option<f64>,
47    /// The default for `Icon.color`.
48    ///
49    /// In material apps, if there is a `Theme` without any [`IconTheme`](crate::IconTheme)s
50    /// specified, icon colors default to white if `ThemeData.brightness` is dark and black if
51    /// `ThemeData.brightness` is light.
52    ///
53    /// Otherwise, falls back to black.
54    pub color: Option<AnyColor>,
55    /// An opacity to apply to both explicit and default icon colors.
56    ///
57    /// Falls back to 1.0. Dart clamps its private `_opacity` in this getter; here the value is
58    /// clamped between 0.0 and 1.0 when it is set.
59    pub opacity: Option<f64>,
60    /// The default for `Icon.shadows`.
61    pub shadows: Option<Vec<Shadow>>,
62    /// The default for `Icon.applyTextScaling`.
63    pub apply_text_scaling: Option<bool>,
64    /// A subclass's [`resolve`](Self::resolve) override (`CupertinoIconThemeData.resolve`);
65    /// `None` is the base class.
66    resolver: Option<IconThemeDataResolver>,
67}
68
69/// Dart's `IconThemeData.resolve(BuildContext)` override: given the data, returns the data
70/// that fits the context.
71pub type IconThemeDataResolver =
72    Rc<dyn Fn(&IconThemeData, &mut App, BuildContext) -> IconThemeData>;
73
74/// Dart's list `toString` for a shadow list, which an icon theme's dump prints.
75pub(crate) fn describe_shadows(shadows: &[Shadow]) -> String {
76    format!(
77        "[{}]",
78        shadows
79            .iter()
80            .map(|shadow| format!("{shadow:?}"))
81            .collect::<Vec<String>>()
82            .join(", ")
83    )
84}
85
86impl IconThemeData {
87    /// Dart's `IconThemeData.debugFillProperties`, which [`IconTheme`](crate::IconTheme)'s own
88    /// body calls where Dart writes `super`.
89    pub fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
90        properties.add(DoubleProperty::new("size", self.size).default_value(None));
91        properties.add(DoubleProperty::new("fill", self.fill).default_value(None));
92        properties.add(DoubleProperty::new("weight", self.weight).default_value(None));
93        properties.add(DoubleProperty::new("grade", self.grade).default_value(None));
94        properties.add(DoubleProperty::new("opticalSize", self.optical_size).default_value(None));
95        properties.add(
96            ColorProperty::new("color", self.color.as_ref().map(|color| color.color()))
97                .default_value(None),
98        );
99        properties.add(DoubleProperty::new("opacity", self.opacity).default_value(None));
100        properties.add(
101            DiagnosticsProperty::<String>::new(
102                "shadows",
103                self.shadows.as_deref().map(describe_shadows),
104            )
105            .default_value(None),
106        );
107        properties.add(
108            DiagnosticsProperty::<bool>::new("applyTextScaling", self.apply_text_scaling)
109                .default_value(None),
110        );
111    }
112
113    /// Creates an icon theme data.
114    ///
115    /// The opacity applies to both explicit and default icon colors. The value is clamped
116    /// between 0.0 and 1.0.
117    pub fn new() -> IconThemeData {
118        IconThemeData {
119            size: None,
120            fill: None,
121            weight: None,
122            grade: None,
123            optical_size: None,
124            color: None,
125            opacity: None,
126            shadows: None,
127            apply_text_scaling: None,
128            resolver: None,
129        }
130    }
131
132    /// Creates an icon theme with some reasonable default values.
133    ///
134    /// The [`size`](Self::size) is 24.0, [`fill`](Self::fill) is 0.0, [`weight`](Self::weight)
135    /// is 400.0, [`grade`](Self::grade) is 0.0, opticalSize is 48.0, [`color`](Self::color) is
136    /// black, and [`opacity`](Self::opacity) is 1.0.
137    pub fn fallback() -> IconThemeData {
138        IconThemeData {
139            size: Some(24.0),
140            fill: Some(0.0),
141            weight: Some(400.0),
142            grade: Some(0.0),
143            optical_size: Some(48.0),
144            color: Some(AnyColor::new(Color::new(0xFF000000))),
145            opacity: Some(1.0),
146            shadows: None,
147            apply_text_scaling: Some(false),
148            resolver: None,
149        }
150    }
151
152    /// Dart `IconThemeData(size:)`.
153    pub fn size(mut self, size: f64) -> IconThemeData {
154        self.size = Some(size);
155        self
156    }
157
158    /// Dart `IconThemeData(fill:)`. Must be between 0.0 and 1.0 inclusive.
159    pub fn fill(mut self, fill: f64) -> IconThemeData {
160        self.fill = Some(fill);
161        self.debug_assert_ranges();
162        self
163    }
164
165    /// Dart `IconThemeData(weight:)`. Must be greater than 0.0.
166    pub fn weight(mut self, weight: f64) -> IconThemeData {
167        self.weight = Some(weight);
168        self.debug_assert_ranges();
169        self
170    }
171
172    /// Dart `IconThemeData(grade:)`.
173    pub fn grade(mut self, grade: f64) -> IconThemeData {
174        self.grade = Some(grade);
175        self
176    }
177
178    /// Dart `IconThemeData(opticalSize:)`. Must be greater than 0.0.
179    pub fn optical_size(mut self, optical_size: f64) -> IconThemeData {
180        self.optical_size = Some(optical_size);
181        self.debug_assert_ranges();
182        self
183    }
184
185    /// Dart `IconThemeData(color:)`.
186    pub fn color(mut self, color: impl Into<AnyColor>) -> IconThemeData {
187        self.color = Some(color.into());
188        self
189    }
190
191    /// Dart `IconThemeData(opacity:)`. The value is clamped between 0.0 and 1.0.
192    pub fn opacity(mut self, opacity: f64) -> IconThemeData {
193        self.opacity = Some(clamp_opacity(opacity));
194        self
195    }
196
197    /// Dart `IconThemeData(shadows:)`.
198    pub fn shadows(mut self, shadows: Vec<Shadow>) -> IconThemeData {
199        self.shadows = Some(shadows);
200        self
201    }
202
203    /// Dart `IconThemeData(applyTextScaling:)`.
204    pub fn apply_text_scaling(mut self, apply_text_scaling: bool) -> IconThemeData {
205        self.apply_text_scaling = Some(apply_text_scaling);
206        self
207    }
208
209    /// Makes this data a subclass instance whose [`resolve`](Self::resolve) runs `resolver`:
210    /// Dart's `class CupertinoIconThemeData extends IconThemeData` overriding `resolve`.
211    /// `copy_with` and `merge` keep it, as the subclass's `copyWith` does; `lerp` drops it,
212    /// as Dart's `IconThemeData.lerp` returns the base class.
213    pub fn resolver(mut self, resolver: IconThemeDataResolver) -> IconThemeData {
214        self.resolver = Some(resolver);
215        self
216    }
217
218    /// Dart's constructor asserts on `fill`, `weight`, and `optical_size`.
219    fn debug_assert_ranges(&self) {
220        debug_assert!(self.fill.is_none_or(|fill| (0.0..=1.0).contains(&fill)));
221        debug_assert!(self.weight.is_none_or(|weight| 0.0 < weight));
222        debug_assert!(
223            self.optical_size
224                .is_none_or(|optical_size| 0.0 < optical_size)
225        );
226    }
227
228    /// Creates a copy of this icon theme but with the given fields replaced with the new
229    /// values.
230    ///
231    /// Dart's named arguments are the fluent setters on the copy
232    /// (`data.copy_with().size(20.0)`).
233    pub fn copy_with(&self) -> IconThemeData {
234        self.clone()
235    }
236
237    /// Returns a new icon theme that matches this icon theme but with some values replaced by
238    /// the non-null parameters of the given icon theme. If the given icon theme is null,
239    /// returns this icon theme.
240    pub fn merge(&self, other: Option<&IconThemeData>) -> IconThemeData {
241        let Some(other) = other else {
242            return self.clone();
243        };
244        let mut merged = self.copy_with();
245        merged.size = other.size.or(self.size);
246        merged.fill = other.fill.or(self.fill);
247        merged.weight = other.weight.or(self.weight);
248        merged.grade = other.grade.or(self.grade);
249        merged.optical_size = other.optical_size.or(self.optical_size);
250        merged.color = other.color.clone().or_else(|| self.color.clone());
251        merged.opacity = other.opacity.or(self.opacity);
252        merged.shadows = other.shadows.clone().or_else(|| self.shadows.clone());
253        merged.apply_text_scaling = other.apply_text_scaling.or(self.apply_text_scaling);
254        merged
255    }
256
257    /// Called by [`IconTheme::of`](crate::IconTheme::of) to convert this instance to an
258    /// [`IconThemeData`] that fits the given [`BuildContext`].
259    ///
260    /// This method gives the ambient [`IconThemeData`] a chance to update itself, after it's
261    /// been retrieved by [`IconTheme::of`](crate::IconTheme::of), and before being returned as
262    /// the final result. For instance, `CupertinoIconThemeData` overrides this method to
263    /// resolve [`color`](Self::color), in case [`color`](Self::color) is a
264    /// `CupertinoDynamicColor` and needs to be resolved against the given [`BuildContext`]
265    /// before it can be used as a regular [`Color`].
266    ///
267    /// The default implementation returns this [`IconThemeData`] as-is.
268    ///
269    /// See also:
270    ///
271    ///  * `CupertinoIconThemeData.resolve` an implementation that resolves the color of
272    ///    `CupertinoIconThemeData` before returning.
273    pub fn resolve(&self, app: &mut App, context: BuildContext) -> IconThemeData {
274        match &self.resolver {
275            Some(resolver) => resolver(self, app, context),
276            None => self.clone(),
277        }
278    }
279
280    /// Whether all the properties (except shadows) of this object are non-null.
281    pub fn is_concrete(&self) -> bool {
282        self.size.is_some()
283            && self.fill.is_some()
284            && self.weight.is_some()
285            && self.grade.is_some()
286            && self.optical_size.is_some()
287            && self.color.is_some()
288            && self.opacity.is_some()
289            && self.apply_text_scaling.is_some()
290    }
291
292    /// Linearly interpolate between two icon theme data objects.
293    ///
294    /// The `t` argument represents position on the timeline, with 0.0 meaning that the
295    /// interpolation has not started, returning `a` (or something equivalent to `a`), 1.0
296    /// meaning that the interpolation has finished, returning `b` (or something equivalent to
297    /// `b`), and values in between meaning that the interpolation is at the relevant point on
298    /// the timeline between `a` and `b`. The interpolation can be extrapolated beyond 0.0 and
299    /// 1.0, so negative values and values greater than 1.0 are valid (and can easily be
300    /// generated by curves such as `Curves.elasticInOut`).
301    ///
302    /// Values for `t` are usually obtained from an `Animation<f64>`, such as an
303    /// `AnimationController`.
304    pub fn lerp(a: Option<&IconThemeData>, b: Option<&IconThemeData>, t: f64) -> IconThemeData {
305        if let (Some(a), Some(b)) = (a, b)
306            && std::ptr::eq(a, b)
307        {
308            return a.clone();
309        }
310        let lerped = IconThemeData {
311            size: lerp_double(a.and_then(|a| a.size), b.and_then(|b| b.size), t),
312            fill: lerp_double(a.and_then(|a| a.fill), b.and_then(|b| b.fill), t),
313            weight: lerp_double(a.and_then(|a| a.weight), b.and_then(|b| b.weight), t),
314            grade: lerp_double(a.and_then(|a| a.grade), b.and_then(|b| b.grade), t),
315            optical_size: lerp_double(
316                a.and_then(|a| a.optical_size),
317                b.and_then(|b| b.optical_size),
318                t,
319            ),
320            color: AnyColor::lerp(
321                a.and_then(|a| a.color.as_ref()),
322                b.and_then(|b| b.color.as_ref()),
323                t,
324            )
325            .map(AnyColor::from),
326            opacity: lerp_double(a.and_then(|a| a.opacity), b.and_then(|b| b.opacity), t)
327                .map(clamp_opacity),
328            shadows: Shadow::lerp_list(
329                a.and_then(|a| a.shadows.as_deref()),
330                b.and_then(|b| b.shadows.as_deref()),
331                t,
332            ),
333            apply_text_scaling: if t < 0.5 {
334                a.and_then(|a| a.apply_text_scaling)
335            } else {
336                b.and_then(|b| b.apply_text_scaling)
337            },
338            resolver: None,
339        };
340        lerped.debug_assert_ranges();
341        lerped
342    }
343}
344
345impl Default for IconThemeData {
346    fn default() -> IconThemeData {
347        IconThemeData::new()
348    }
349}
350
351/// Dart's `opacity` getter: `clampDouble(_opacity, 0.0, 1.0)`.
352fn clamp_opacity(opacity: f64) -> f64 {
353    clamp_double(opacity, 0.0, 1.0)
354}
355
356/// Dart's `==` checks `runtimeType` first: a subclass instance never equals a base one.
357impl PartialEq for IconThemeData {
358    fn eq(&self, other: &IconThemeData) -> bool {
359        self.resolver.is_some() == other.resolver.is_some()
360            && self.size == other.size
361            && self.fill == other.fill
362            && self.weight == other.weight
363            && self.grade == other.grade
364            && self.optical_size == other.optical_size
365            && self.color == other.color
366            && self.opacity == other.opacity
367            && self.shadows == other.shadows
368            && self.apply_text_scaling == other.apply_text_scaling
369    }
370}
371
372impl waft_foundation::Diagnosticable for IconThemeData {
373    fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
374        IconThemeData::debug_fill_properties(self, properties);
375    }
376}
377
378/// Dart's `Diagnosticable.toString`, which a property holding an icon theme prints.
379impl fmt::Display for IconThemeData {
380    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
381        f.write_str(&waft_foundation::Diagnosticable::to_string(self))
382    }
383}
384
385impl fmt::Debug for IconThemeData {
386    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
387        f.debug_struct("IconThemeData")
388            .field("size", &self.size)
389            .field("fill", &self.fill)
390            .field("weight", &self.weight)
391            .field("grade", &self.grade)
392            .field("optical_size", &self.optical_size)
393            .field("color", &self.color)
394            .field("opacity", &self.opacity)
395            .field("shadows", &self.shadows)
396            .field("apply_text_scaling", &self.apply_text_scaling)
397            .field("resolver", &self.resolver.as_ref().map(|_| "override"))
398            .finish()
399    }
400}
401
402#[cfg(test)]
403mod tests {
404    use waft_embedder::Offset;
405
406    use super::*;
407
408    /// Flutter's `isSameColorAs`: equal to within a channel step, since `Color::lerp` works in
409    /// floating point.
410    fn assert_same_color(actual: Option<Color>, expected: u32) {
411        let actual = actual.expect("a color");
412        let expected = Color::new(expected);
413        let step = 1.0 / 255.0;
414        assert!(
415            (actual.a - expected.a).abs() < step
416                && (actual.r - expected.r).abs() < step
417                && (actual.g - expected.g).abs() < step
418                && (actual.b - expected.b).abs() < step,
419            "{actual:?} is not {expected:?}"
420        );
421    }
422
423    fn shadow(argb: u32, blur_radius: f64, offset: f64) -> Shadow {
424        Shadow::new(Color::new(argb), Offset::new(offset, offset), blur_radius)
425    }
426
427    /// Flutter's `IconThemeData lerp` group's fixture.
428    fn white_data() -> IconThemeData {
429        IconThemeData::new()
430            .size(16.0)
431            .fill(0.5)
432            .weight(600.0)
433            .grade(25.0)
434            .optical_size(45.0)
435            .color(Color::new(0xFFFFFFFF))
436            .opacity(1.0)
437            .shadows(vec![shadow(0xFFFFFFFF, 1.0, 1.0)])
438    }
439
440    #[test]
441    fn control_test() {
442        let data = IconThemeData::new()
443            .size(16.0)
444            .fill(0.5)
445            .weight(600.0)
446            .grade(25.0)
447            .optical_size(45.0)
448            .color(Color::new(0xAAAAAAAA))
449            .opacity(0.5)
450            .shadows(vec![shadow(0xAAAAAAAA, 1.0, 1.0)]);
451        assert_eq!(data, data.copy_with());
452
453        let lerped = IconThemeData::lerp(Some(&data), Some(&IconThemeData::fallback()), 0.25);
454        assert_eq!(lerped.size, Some(18.0));
455        assert_eq!(lerped.fill, Some(0.375));
456        assert_eq!(lerped.weight, Some(550.0));
457        assert_eq!(lerped.grade, Some(18.75));
458        assert_eq!(lerped.optical_size, Some(45.75));
459        assert_same_color(lerped.color.as_ref().map(AnyColor::color), 0xBF7F7F7F);
460        assert_eq!(lerped.opacity, Some(0.625));
461        assert_eq!(lerped.shadows, Some(vec![shadow(0xAAAAAAAA, 0.75, 0.75)]));
462    }
463
464    #[test]
465    fn lerp_with_first_null() {
466        let lerped = IconThemeData::lerp(None, Some(&white_data()), 0.25);
467        assert_eq!(lerped.size, Some(4.0));
468        assert_eq!(lerped.fill, Some(0.125));
469        assert_eq!(lerped.weight, Some(150.0));
470        assert_eq!(lerped.grade, Some(6.25));
471        assert_eq!(lerped.optical_size, Some(11.25));
472        assert_same_color(lerped.color.as_ref().map(AnyColor::color), 0x40FFFFFF);
473        assert_eq!(lerped.opacity, Some(0.25));
474        assert_eq!(lerped.shadows, Some(vec![shadow(0xFFFFFFFF, 0.25, 0.25)]));
475    }
476
477    #[test]
478    fn lerp_with_second_null() {
479        let lerped = IconThemeData::lerp(Some(&white_data()), None, 0.25);
480        assert_eq!(lerped.size, Some(12.0));
481        assert_eq!(lerped.fill, Some(0.375));
482        assert_eq!(lerped.weight, Some(450.0));
483        assert_eq!(lerped.grade, Some(18.75));
484        assert_eq!(lerped.optical_size, Some(33.75));
485        assert_same_color(lerped.color.as_ref().map(AnyColor::color), 0xBFFFFFFF);
486        assert_eq!(lerped.opacity, Some(0.75));
487        assert_eq!(lerped.shadows, Some(vec![shadow(0xFFFFFFFF, 0.75, 0.75)]));
488    }
489
490    #[test]
491    fn lerp_with_both_null_and_special_cases() {
492        assert_eq!(IconThemeData::lerp(None, None, 0.25), IconThemeData::new());
493        let data = IconThemeData::new();
494        assert_eq!(IconThemeData::lerp(Some(&data), Some(&data), 0.5), data);
495    }
496
497    #[test]
498    fn merge_takes_the_other_values_where_it_has_them() {
499        let black = Color::new(0xFF000000);
500        let base = IconThemeData::new().size(16.0).color(black).opacity(0.5);
501        let other = IconThemeData::new().size(20.0).fill(1.0);
502        let merged = base.merge(Some(&other));
503        assert_eq!(merged.size, Some(20.0));
504        assert_eq!(merged.fill, Some(1.0));
505        assert_eq!(merged.color, Some(black.into()));
506        assert_eq!(merged.opacity, Some(0.5));
507        assert_eq!(merged.weight, None);
508        assert_eq!(base.merge(None), base);
509    }
510
511    #[test]
512    fn opacity_is_clamped_and_compared_clamped() {
513        assert_eq!(IconThemeData::new().opacity(1.5).opacity, Some(1.0));
514        assert_eq!(IconThemeData::new().opacity(-1.0).opacity, Some(0.0));
515        assert_eq!(
516            IconThemeData::new().opacity(1.5),
517            IconThemeData::new().opacity(1.0)
518        );
519    }
520
521    #[test]
522    fn is_concrete_ignores_shadows() {
523        assert!(IconThemeData::fallback().is_concrete());
524        assert!(IconThemeData::fallback().shadows(Vec::new()).is_concrete());
525        assert!(!IconThemeData::new().is_concrete());
526        assert!(!IconThemeData::new().size(16.0).is_concrete());
527    }
528
529    #[test]
530    #[should_panic]
531    fn throws_if_given_invalid_values() {
532        let _ = IconThemeData::new().fill(1.1);
533    }
534}