Skip to main content

waft_painting/
box_shadow.rs

1//! Flutter counterpart: `painting/box_shadow.dart`.
2
3use std::fmt::{self, Debug};
4
5use waft_embedder::{BlurStyle, MaskBlur, Paint};
6use waft_embedder::{Color, Offset, Shadow, lerp_double};
7
8/// A shadow cast by a box.
9///
10/// [`BoxShadow`] can cast non-rectangular shadows if the box is non-rectangular
11/// (e.g., has a border radius or a circular shape).
12///
13/// This class is similar to CSS box-shadow.
14///
15/// Dart: `extends ui.Shadow`. Separate struct; convert with [`From`].
16#[derive(Clone, Copy, PartialEq)]
17pub struct BoxShadow {
18    /// Color that the shadow will be drawn with.
19    pub color: Color,
20    /// The displacement of the shadow from the casting element.
21    pub offset: Offset,
22    /// The standard deviation of the Gaussian to convolve with the shadow's shape.
23    pub blur_radius: f64,
24    /// The amount the box should be inflated prior to applying the blur.
25    pub spread_radius: f64,
26    /// The [`BlurStyle`] to use for this shadow.
27    ///
28    /// Defaults to [`BlurStyle::Normal`].
29    pub blur_style: BlurStyle,
30}
31
32impl BoxShadow {
33    /// Creates a box shadow.
34    ///
35    /// By default, the shadow is solid black with zero [`offset`](Self::offset),
36    /// zero [`blur_radius`](Self::blur_radius), zero [`spread_radius`](Self::spread_radius),
37    /// and [`BlurStyle::Normal`].
38    pub fn new(
39        color: Color,
40        offset: Offset,
41        blur_radius: f64,
42        spread_radius: f64,
43        blur_style: BlurStyle,
44    ) -> BoxShadow {
45        debug_assert!(
46            blur_radius >= 0.0,
47            "Text shadow blur radius should be non-negative."
48        );
49        BoxShadow {
50            color,
51            offset,
52            blur_radius,
53            spread_radius,
54            blur_style,
55        }
56    }
57
58    /// The [`blur_radius`](Self::blur_radius) in sigmas instead of logical pixels.
59    pub fn blur_sigma(&self) -> f64 {
60        Shadow::convert_radius_to_sigma(self.blur_radius)
61    }
62
63    /// Create the [`Paint`] object that corresponds to this shadow description.
64    ///
65    /// The [`offset`](Self::offset) and [`spread_radius`](Self::spread_radius) are
66    /// not represented in the [`Paint`] object. To honor those as well, the shape
67    /// should be inflated by [`spread_radius`](Self::spread_radius) pixels in every
68    /// direction and then translated by [`offset`](Self::offset) before being
69    /// filled using this [`Paint`].
70    pub fn to_paint(&self) -> Paint {
71        let sigma = self.blur_sigma() as f32;
72        let mask_blur = match self.blur_style {
73            BlurStyle::Normal => MaskBlur::new(sigma),
74            BlurStyle::Solid => MaskBlur::solid(sigma),
75            BlurStyle::Inner => MaskBlur::inner(sigma),
76            BlurStyle::Outer => MaskBlur::outer(sigma),
77        };
78        Paint {
79            color: self.color.into(),
80            mask_blur: Some(mask_blur),
81            ..Paint::default()
82        }
83    }
84
85    /// Returns a new box shadow with its offset, blurRadius, and spreadRadius
86    /// scaled by the given factor.
87    pub fn scale(&self, factor: f64) -> BoxShadow {
88        BoxShadow::new(
89            self.color,
90            self.offset * factor,
91            self.blur_radius * factor,
92            self.spread_radius * factor,
93            self.blur_style,
94        )
95    }
96
97    /// Creates a copy of this object but with the given fields replaced with the
98    /// new values.
99    pub fn copy_with(
100        &self,
101        color: Option<Color>,
102        offset: Option<Offset>,
103        blur_radius: Option<f64>,
104        spread_radius: Option<f64>,
105        blur_style: Option<BlurStyle>,
106    ) -> BoxShadow {
107        BoxShadow::new(
108            color.unwrap_or(self.color),
109            offset.unwrap_or(self.offset),
110            blur_radius.unwrap_or(self.blur_radius),
111            spread_radius.unwrap_or(self.spread_radius),
112            blur_style.unwrap_or(self.blur_style),
113        )
114    }
115
116    /// Linearly interpolate between two box shadows.
117    ///
118    /// If either box shadow is null, this function linearly interpolates from
119    /// a box shadow that matches the other box shadow in color but has a zero
120    /// offset and a zero blurRadius.
121    pub fn lerp(a: Option<BoxShadow>, b: Option<BoxShadow>, t: f64) -> Option<BoxShadow> {
122        if a == b {
123            return a;
124        }
125        match (a, b) {
126            (None, None) => None,
127            (None, Some(b)) => Some(b.scale(t)),
128            (Some(a), None) => Some(a.scale(1.0 - t)),
129            (Some(a), Some(b)) => Some(BoxShadow::new(
130                Color::lerp(Some(a.color), Some(b.color), t).unwrap(),
131                Offset::lerp(Some(a.offset), Some(b.offset), t).unwrap(),
132                lerp_double(Some(a.blur_radius), Some(b.blur_radius), t).unwrap(),
133                lerp_double(Some(a.spread_radius), Some(b.spread_radius), t).unwrap(),
134                if a.blur_style == BlurStyle::Normal {
135                    b.blur_style
136                } else {
137                    a.blur_style
138                },
139            )),
140        }
141    }
142
143    /// Linearly interpolate between two lists of box shadows.
144    ///
145    /// If the lists differ in length, excess items are lerped with null.
146    pub fn lerp_list(
147        a: Option<&[BoxShadow]>,
148        b: Option<&[BoxShadow]>,
149        t: f64,
150    ) -> Option<Vec<BoxShadow>> {
151        if let (Some(a), Some(b)) = (a, b) {
152            if a == b {
153                return Some(a.to_vec());
154            }
155        } else if a.is_none() && b.is_none() {
156            return None;
157        }
158        let a = a.unwrap_or(&[]);
159        let b = b.unwrap_or(&[]);
160        let common_length = a.len().min(b.len());
161        let mut result = Vec::new();
162        for i in 0..common_length {
163            result.push(BoxShadow::lerp(Some(a[i]), Some(b[i]), t).unwrap());
164        }
165        for shadow in &a[common_length..] {
166            result.push(shadow.scale(1.0 - t));
167        }
168        for shadow in &b[common_length..] {
169            result.push(shadow.scale(t));
170        }
171        Some(result)
172    }
173}
174
175impl Default for BoxShadow {
176    fn default() -> BoxShadow {
177        BoxShadow::new(
178            Color::new(0xFF000000),
179            Offset::ZERO,
180            0.0,
181            0.0,
182            BlurStyle::Normal,
183        )
184    }
185}
186
187impl From<BoxShadow> for Shadow {
188    fn from(shadow: BoxShadow) -> Shadow {
189        Shadow::new(shadow.color, shadow.offset, shadow.blur_radius)
190    }
191}
192
193impl Debug for BoxShadow {
194    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
195        write!(
196            f,
197            "BoxShadow({:?}, {:?}, {:.1}, {:.1}, {})",
198            self.color,
199            self.offset,
200            self.blur_radius,
201            self.spread_radius,
202            blur_style_name(self.blur_style)
203        )
204    }
205}
206
207/// Dart's `$blurStyle`: the enum's name as `<Enum>.<variant>`.
208fn blur_style_name(blur_style: BlurStyle) -> &'static str {
209    match blur_style {
210        BlurStyle::Normal => "BlurStyle.normal",
211        BlurStyle::Solid => "BlurStyle.solid",
212        BlurStyle::Inner => "BlurStyle.inner",
213        BlurStyle::Outer => "BlurStyle.outer",
214    }
215}
216
217/// Dart's `BoxShadow.toString`, which [`Debug`] already renders.
218impl fmt::Display for BoxShadow {
219    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220        Debug::fmt(self, f)
221    }
222}
223
224#[cfg(test)]
225mod tests {
226    use super::*;
227
228    #[test]
229    fn lerp_null_arms_and_list_padding_match_dart() {
230        let shadow1 = BoxShadow {
231            blur_radius: 4.0,
232            ..BoxShadow::default()
233        };
234        let shadow2 = BoxShadow::lerp(None, Some(shadow1), 0.25).unwrap();
235        let shadow3 = BoxShadow::lerp(Some(shadow1), None, 0.25).unwrap();
236        assert_eq!(
237            shadow2,
238            BoxShadow {
239                blur_radius: 1.0,
240                ..BoxShadow::default()
241            }
242        );
243        assert_eq!(
244            shadow3,
245            BoxShadow {
246                blur_radius: 3.0,
247                ..BoxShadow::default()
248            }
249        );
250        assert_eq!(
251            shadow1,
252            BoxShadow {
253                blur_radius: 4.0,
254                ..BoxShadow::default()
255            }
256        );
257
258        let shadow4 = BoxShadow::lerp(Some(shadow2), Some(shadow3), 0.5).unwrap();
259        assert_eq!(
260            shadow4,
261            BoxShadow {
262                blur_radius: 2.0,
263                ..BoxShadow::default()
264            }
265        );
266
267        let shadow_list =
268            BoxShadow::lerp_list(Some(&[shadow2, shadow1]), Some(&[shadow3]), 0.5).unwrap();
269        assert_eq!(shadow_list, vec![shadow4, shadow1.scale(0.5)]);
270        let shadow_list =
271            BoxShadow::lerp_list(Some(&[shadow2]), Some(&[shadow3, shadow1]), 0.5).unwrap();
272        assert_eq!(shadow_list, vec![shadow4, shadow1.scale(0.5)]);
273    }
274
275    #[test]
276    fn lerp_identical_a_b() {
277        assert_eq!(BoxShadow::lerp(None, None, 0.0), None);
278        let border = BoxShadow::default();
279        assert_eq!(
280            BoxShadow::lerp(Some(border), Some(border), 0.5),
281            Some(border)
282        );
283    }
284
285    #[test]
286    fn lerp_list_identical_a_b() {
287        assert_eq!(BoxShadow::lerp_list(None, None, 0.0), None);
288        let border = [BoxShadow::default()];
289        assert_eq!(
290            BoxShadow::lerp_list(Some(&border), Some(&border), 0.5),
291            Some(border.to_vec())
292        );
293    }
294
295    #[test]
296    fn blur_style_lerp_keeps_non_normal() {
297        let shadow1 = BoxShadow {
298            blur_radius: 4.0,
299            ..BoxShadow::default()
300        };
301        let shadow2 = BoxShadow {
302            blur_radius: 4.0,
303            blur_style: BlurStyle::Outer,
304            ..BoxShadow::default()
305        };
306        let shadow5 = BoxShadow::lerp(Some(shadow1), Some(shadow2), 0.25).unwrap();
307        assert_eq!(shadow5.blur_style, BlurStyle::Outer);
308        let shadow6 = BoxShadow::lerp(
309            Some(BoxShadow {
310                blur_style: BlurStyle::Solid,
311                ..BoxShadow::default()
312            }),
313            Some(shadow1),
314            0.25,
315        )
316        .unwrap();
317        assert_eq!(shadow6.blur_style, BlurStyle::Solid);
318    }
319
320    #[test]
321    fn copy_with_replaces_one_field() {
322        assert_ne!(
323            BoxShadow::default(),
324            BoxShadow {
325                color: Color::new(0xFF112233),
326                ..BoxShadow::default()
327            }
328        );
329        assert_eq!(
330            BoxShadow::default().copy_with(Some(Color::new(0xFF112233)), None, None, None, None),
331            BoxShadow {
332                color: Color::new(0xFF112233),
333                ..BoxShadow::default()
334            }
335        );
336        assert_eq!(
337            BoxShadow::default().copy_with(None, Some(Offset::new(1.0, 2.0)), None, None, None),
338            BoxShadow {
339                offset: Offset::new(1.0, 2.0),
340                ..BoxShadow::default()
341            }
342        );
343        assert_eq!(
344            BoxShadow::default().copy_with(None, None, Some(123.0), None, None),
345            BoxShadow {
346                blur_radius: 123.0,
347                ..BoxShadow::default()
348            }
349        );
350        assert_eq!(
351            BoxShadow::default().copy_with(None, None, None, Some(123.0), None),
352            BoxShadow {
353                spread_radius: 123.0,
354                ..BoxShadow::default()
355            }
356        );
357        assert_eq!(
358            BoxShadow::default().copy_with(None, None, None, None, Some(BlurStyle::Outer)),
359            BoxShadow {
360                blur_style: BlurStyle::Outer,
361                ..BoxShadow::default()
362            }
363        );
364    }
365}