Skip to main content

waft_painting/
continuous_rectangle_border.rs

1//! Flutter counterpart: `painting/continuous_rectangle_border.dart`.
2
3use std::any::Any;
4use std::fmt::{Debug, Formatter, Result as FmtResult};
5use std::rc::Rc;
6
7use waft_embedder::{Canvas, Path, PathBuilder, RRect};
8use waft_embedder::{Offset, Rect};
9
10use crate::basic_types::TextDirection;
11use crate::border_radius::{BorderRadius, BorderRadiusGeometry};
12use crate::borders::{
13    BorderSide, BorderStyle, OutlinedBorder, OutlinedBorderRef, ShapeBorder, ShapeBorderRef,
14};
15use crate::edge_insets::{EdgeInsets, EdgeInsetsGeometry};
16
17/// A rectangular border with smooth continuous transitions between the straight
18/// sides and the rounded corners.
19///
20/// See also:
21///
22///  * [`RoundedRectangleBorder`](crate::RoundedRectangleBorder), which creates
23///    rectangles with rounded corners, however its straight sides change into a
24///    rounded corner with a circular radius in a step function instead of
25///    gradually like the [`ContinuousRectangleBorder`].
26#[derive(Clone, Copy, PartialEq)]
27pub struct ContinuousRectangleBorder {
28    /// The border outline's color and weight.
29    pub side: BorderSide,
30    /// The radius for each corner.
31    ///
32    /// Negative radius values are clamped to 0.0 by [`get_inner_path`](ShapeBorder::get_inner_path)
33    /// and [`get_outer_path`](ShapeBorder::get_outer_path).
34    pub border_radius: BorderRadiusGeometry,
35}
36
37impl ContinuousRectangleBorder {
38    /// Creates a [`ContinuousRectangleBorder`].
39    pub fn new(side: BorderSide, border_radius: BorderRadiusGeometry) -> ContinuousRectangleBorder {
40        ContinuousRectangleBorder {
41            side,
42            border_radius,
43        }
44    }
45
46    /// Creates a copy of this border, scaled by the factor `t`.
47    pub fn scale(&self, t: f64) -> ContinuousRectangleBorder {
48        ContinuousRectangleBorder::new(self.side.scale(t), self.border_radius * t)
49    }
50
51    /// Returns a copy of this ContinuousRectangleBorder with the given fields
52    /// replaced with the new values.
53    pub fn copy_with(
54        &self,
55        side: Option<BorderSide>,
56        border_radius: Option<BorderRadiusGeometry>,
57    ) -> ContinuousRectangleBorder {
58        ContinuousRectangleBorder::new(
59            side.unwrap_or(self.side),
60            border_radius.unwrap_or(self.border_radius),
61        )
62    }
63
64    fn clamp_to_shortest(rrect: RRect, value: f64) -> f64 {
65        if value > rrect.shortest_side() {
66            rrect.shortest_side()
67        } else {
68            value
69        }
70    }
71
72    fn get_path(rrect: RRect) -> Path {
73        let left = rrect.left;
74        let right = rrect.right;
75        let top = rrect.top;
76        let bottom = rrect.bottom;
77        // Radii will be clamped to the value of the shortest side of rrect to
78        // avoid strange tie-fighter shapes.
79        let tl_radius_x = Self::clamp_to_shortest(rrect, rrect.tl_radius_x).max(0.0);
80        let tl_radius_y = Self::clamp_to_shortest(rrect, rrect.tl_radius_y).max(0.0);
81        let tr_radius_x = Self::clamp_to_shortest(rrect, rrect.tr_radius_x).max(0.0);
82        let tr_radius_y = Self::clamp_to_shortest(rrect, rrect.tr_radius_y).max(0.0);
83        let bl_radius_x = Self::clamp_to_shortest(rrect, rrect.bl_radius_x).max(0.0);
84        let bl_radius_y = Self::clamp_to_shortest(rrect, rrect.bl_radius_y).max(0.0);
85        let br_radius_x = Self::clamp_to_shortest(rrect, rrect.br_radius_x).max(0.0);
86        let br_radius_y = Self::clamp_to_shortest(rrect, rrect.br_radius_y).max(0.0);
87
88        let mut path = PathBuilder::new();
89        path.move_to(Offset::new(left, top + tl_radius_x))
90            .cubic_to(
91                Offset::new(left, top),
92                Offset::new(left, top),
93                Offset::new(left + tl_radius_y, top),
94            )
95            .line_to(Offset::new(right - tr_radius_x, top))
96            .cubic_to(
97                Offset::new(right, top),
98                Offset::new(right, top),
99                Offset::new(right, top + tr_radius_y),
100            )
101            .line_to(Offset::new(right, bottom - br_radius_x))
102            .cubic_to(
103                Offset::new(right, bottom),
104                Offset::new(right, bottom),
105                Offset::new(right - br_radius_y, bottom),
106            )
107            .line_to(Offset::new(left + bl_radius_x, bottom))
108            .cubic_to(
109                Offset::new(left, bottom),
110                Offset::new(left, bottom),
111                Offset::new(left, bottom - bl_radius_y),
112            )
113            .close();
114        path.build().into()
115    }
116}
117
118impl Default for ContinuousRectangleBorder {
119    fn default() -> ContinuousRectangleBorder {
120        ContinuousRectangleBorder::new(BorderSide::NONE, BorderRadius::ZERO.into())
121    }
122}
123
124impl ShapeBorder for ContinuousRectangleBorder {
125    fn dimensions(&self) -> EdgeInsetsGeometry {
126        EdgeInsets::all(self.side.width).into()
127    }
128
129    fn scale(&self, t: f64) -> ShapeBorderRef {
130        ShapeBorderRef::new(ContinuousRectangleBorder::scale(self, t))
131    }
132
133    fn lerp_from(&self, a: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
134        if let Some(a) = a.and_then(|a| a.as_any().downcast_ref::<ContinuousRectangleBorder>()) {
135            Some(ShapeBorderRef::new(ContinuousRectangleBorder::new(
136                BorderSide::lerp(a.side, self.side, t),
137                BorderRadiusGeometry::lerp(Some(a.border_radius), Some(self.border_radius), t)
138                    .unwrap(),
139            )))
140        } else if a.is_none() {
141            Some(ShapeBorder::scale(self, t))
142        } else {
143            None
144        }
145    }
146
147    fn lerp_to(&self, b: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
148        if let Some(b) = b.and_then(|b| b.as_any().downcast_ref::<ContinuousRectangleBorder>()) {
149            Some(ShapeBorderRef::new(ContinuousRectangleBorder::new(
150                BorderSide::lerp(self.side, b.side, t),
151                BorderRadiusGeometry::lerp(Some(self.border_radius), Some(b.border_radius), t)
152                    .unwrap(),
153            )))
154        } else if b.is_none() {
155            Some(ShapeBorder::scale(self, 1.0 - t))
156        } else {
157            None
158        }
159    }
160
161    fn get_inner_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
162        Self::get_path(
163            self.border_radius
164                .resolve(text_direction)
165                .to_rrect(rect)
166                .deflate(self.side.width),
167        )
168    }
169
170    fn get_outer_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
171        Self::get_path(self.border_radius.resolve(text_direction).to_rrect(rect))
172    }
173
174    fn paint(&self, canvas: &mut Canvas, rect: Rect, text_direction: Option<TextDirection>) {
175        if rect.is_empty() {
176            return;
177        }
178        match self.side.style {
179            BorderStyle::None => {}
180            BorderStyle::Solid => {
181                let path = self.get_outer_path(rect, text_direction);
182                canvas.draw_path(path.as_valo(), path.fill_type, &self.side.to_paint());
183            }
184        }
185    }
186
187    fn as_any(&self) -> &dyn Any {
188        self
189    }
190
191    fn as_outlined_border(&self) -> Option<&dyn OutlinedBorder> {
192        Some(self)
193    }
194
195    fn into_outlined_border(self: Rc<Self>) -> Option<Rc<dyn OutlinedBorder>> {
196        Some(self)
197    }
198
199    fn eq_shape(&self, other: &dyn ShapeBorder) -> bool {
200        other
201            .as_any()
202            .downcast_ref::<ContinuousRectangleBorder>()
203            .is_some_and(|other| other == self)
204    }
205}
206
207impl OutlinedBorder for ContinuousRectangleBorder {
208    fn side(&self) -> BorderSide {
209        self.side
210    }
211
212    fn copy_with(&self, side: Option<BorderSide>) -> OutlinedBorderRef {
213        OutlinedBorderRef::new(ContinuousRectangleBorder::copy_with(self, side, None))
214    }
215}
216
217impl Debug for ContinuousRectangleBorder {
218    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
219        write!(
220            f,
221            "ContinuousRectangleBorder({:?}, {:?})",
222            self.side, self.border_radius
223        )
224    }
225}
226
227#[cfg(test)]
228mod tests {
229    use super::*;
230    use waft_embedder::{Color, Radius};
231
232    use crate::border_radius::BorderRadiusDirectional;
233
234    fn contains(path: &Path, x: f64, y: f64) -> bool {
235        path.contains(Offset::new(x, y))
236    }
237
238    fn side_width(width: f64) -> BorderSide {
239        BorderSide {
240            width,
241            ..BorderSide::default()
242        }
243    }
244
245    #[test]
246    fn defaults() {
247        let border = ContinuousRectangleBorder::default();
248        assert_eq!(border.side, BorderSide::NONE);
249        assert_eq!(border.border_radius, BorderRadius::ZERO.into());
250    }
251
252    #[test]
253    fn copy_with_eq() {
254        assert_eq!(
255            ContinuousRectangleBorder::default(),
256            ContinuousRectangleBorder::default().copy_with(None, None)
257        );
258        let side = BorderSide {
259            width: 10.0,
260            color: Color::new(0xFF123456),
261            ..BorderSide::default()
262        };
263        let radius = BorderRadius::all(Radius::circular(16.0));
264        let directional = BorderRadiusDirectional::all(Radius::circular(16.0));
265        assert_eq!(
266            ContinuousRectangleBorder::default().copy_with(Some(side), Some(radius.into())),
267            ContinuousRectangleBorder::new(side, radius.into())
268        );
269        assert_eq!(
270            ContinuousRectangleBorder::default().copy_with(Some(side), Some(directional.into())),
271            ContinuousRectangleBorder::new(side, directional.into())
272        );
273    }
274
275    #[test]
276    fn scale_lerp_dimensions() {
277        let c10 = ContinuousRectangleBorder::new(
278            side_width(10.0),
279            BorderRadius::all(Radius::circular(100.0)).into(),
280        );
281        let c15 = ContinuousRectangleBorder::new(
282            side_width(15.0),
283            BorderRadius::all(Radius::circular(150.0)).into(),
284        );
285        let c20 = ContinuousRectangleBorder::new(
286            side_width(20.0),
287            BorderRadius::all(Radius::circular(200.0)).into(),
288        );
289        assert_eq!(c10.dimensions(), EdgeInsetsGeometry::all(10.0));
290        assert_eq!(c10.scale(2.0), c20);
291        assert_eq!(c20.scale(0.5), c10);
292        assert!(
293            ShapeBorderRef::lerp(
294                Some(&ShapeBorderRef::new(c10)),
295                Some(&ShapeBorderRef::new(c20)),
296                0.0
297            )
298            .unwrap()
299            .eq_shape(&c10)
300        );
301        assert!(
302            ShapeBorderRef::lerp(
303                Some(&ShapeBorderRef::new(c10)),
304                Some(&ShapeBorderRef::new(c20)),
305                0.5
306            )
307            .unwrap()
308            .eq_shape(&c15)
309        );
310        assert!(
311            ShapeBorderRef::lerp(
312                Some(&ShapeBorderRef::new(c10)),
313                Some(&ShapeBorderRef::new(c20)),
314                1.0
315            )
316            .unwrap()
317            .eq_shape(&c20)
318        );
319    }
320
321    #[test]
322    fn border_radius_zero() {
323        let rect1 = Rect::from_ltrb(10.0, 20.0, 30.0, 40.0);
324        let border = ContinuousRectangleBorder::default();
325        let outer = border.get_outer_path(rect1, None);
326        assert!(contains(&outer, 10.0, 20.0));
327        assert!(contains(&outer, 20.0, 30.0));
328        assert!(!contains(&outer, 9.0, 19.0));
329        assert!(!contains(&outer, 31.0, 41.0));
330
331        let with_side = ContinuousRectangleBorder::new(side_width(4.0), BorderRadius::ZERO.into());
332        let inner = with_side.get_inner_path(rect1, None);
333        assert!(contains(&inner, 14.0, 24.0));
334        assert!(contains(&inner, 16.0, 26.0));
335        assert!(!contains(&inner, 9.0, 23.0));
336        assert!(!contains(&inner, 27.0, 37.0));
337    }
338
339    #[test]
340    fn non_zero_border_radius() {
341        let rect = Rect::from_ltrb(10.0, 20.0, 30.0, 40.0);
342        let border = ContinuousRectangleBorder::new(
343            BorderSide::NONE,
344            BorderRadius::all(Radius::circular(5.0)).into(),
345        );
346        let path = border.get_outer_path(rect, None);
347        assert!(contains(&path, 15.0, 25.0));
348        assert!(contains(&path, 20.0, 30.0));
349        assert!(!contains(&path, 10.0, 20.0));
350        assert!(!contains(&path, 30.0, 40.0));
351    }
352
353    #[test]
354    fn border_radius_directional() {
355        let rect = Rect::from_ltrb(10.0, 20.0, 30.0, 40.0);
356        let border = ContinuousRectangleBorder::new(
357            BorderSide::NONE,
358            BorderRadiusDirectional::only(
359                Radius::circular(5.0),
360                Radius::ZERO,
361                Radius::circular(5.0),
362                Radius::ZERO,
363            )
364            .into(),
365        );
366        let ltr = border.get_outer_path(rect, Some(TextDirection::Ltr));
367        assert!(contains(&ltr, 15.0, 25.0));
368        assert!(contains(&ltr, 20.0, 30.0));
369        assert!(!contains(&ltr, 10.0, 20.0));
370        assert!(!contains(&ltr, 10.0, 40.0));
371        let rtl = border.get_outer_path(rect, Some(TextDirection::Rtl));
372        assert!(contains(&rtl, 25.0, 35.0));
373        assert!(contains(&rtl, 25.0, 25.0));
374        assert!(!contains(&rtl, 30.0, 20.0));
375        assert!(!contains(&rtl, 30.0, 40.0));
376    }
377}