Skip to main content

waft_painting/
rounded_rectangle_border.rs

1//! Flutter counterpart: `painting/rounded_rectangle_border.dart`.
2
3use std::any::Any;
4use std::fmt::{Debug, Formatter, Result as FmtResult};
5use std::rc::Rc;
6
7use waft_embedder::{
8    Canvas, Offset, Paint, Path, PathBuilder, RSuperellipse, Radius, Rect, lerp_double,
9    rsuperellipse_radii_elliptical,
10};
11
12use crate::basic_types::TextDirection;
13use crate::border_radius::{BorderRadius, BorderRadiusGeometry};
14use crate::borders::{
15    BorderSide, BorderStyle, OutlinedBorder, OutlinedBorderRef, ShapeBorder, ShapeBorderRef,
16    outlined_border_dimensions,
17};
18use crate::circle_border::rrect_path;
19use crate::draw::{draw_drrect, draw_rrect, draw_rsuperellipse};
20use crate::edge_insets::EdgeInsetsGeometry;
21use crate::oval_border::as_circle_border;
22
23/// A rectangular border with rounded corners.
24///
25/// Typically used with `ShapeDecoration` to draw a box with a rounded
26/// rectangle.
27///
28/// This shape can interpolate to and from `CircleBorder`.
29#[derive(Clone, Copy, PartialEq)]
30pub struct RoundedRectangleBorder {
31    /// The border outline's color and weight.
32    pub side: BorderSide,
33    /// The radii for each corner.
34    pub border_radius: BorderRadiusGeometry,
35}
36
37impl RoundedRectangleBorder {
38    /// Creates a rounded rectangle border.
39    pub fn new(side: BorderSide, border_radius: BorderRadiusGeometry) -> RoundedRectangleBorder {
40        RoundedRectangleBorder {
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) -> RoundedRectangleBorder {
48        RoundedRectangleBorder::new(self.side.scale(t), self.border_radius * t)
49    }
50
51    /// Returns a copy of this RoundedRectangleBorder 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    ) -> RoundedRectangleBorder {
58        RoundedRectangleBorder::new(
59            side.unwrap_or(self.side),
60            border_radius.unwrap_or(self.border_radius),
61        )
62    }
63}
64
65impl Default for RoundedRectangleBorder {
66    fn default() -> RoundedRectangleBorder {
67        RoundedRectangleBorder::new(BorderSide::NONE, BorderRadius::ZERO.into())
68    }
69}
70
71impl ShapeBorder for RoundedRectangleBorder {
72    fn dimensions(&self) -> EdgeInsetsGeometry {
73        outlined_border_dimensions(self.side)
74    }
75
76    fn scale(&self, t: f64) -> ShapeBorderRef {
77        ShapeBorderRef::new(RoundedRectangleBorder::scale(self, t))
78    }
79
80    fn lerp_from(&self, a: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
81        if let Some(a) = a.and_then(|a| a.as_any().downcast_ref::<RoundedRectangleBorder>()) {
82            Some(ShapeBorderRef::new(RoundedRectangleBorder::new(
83                BorderSide::lerp(a.side, self.side, t),
84                BorderRadiusGeometry::lerp(Some(a.border_radius), Some(self.border_radius), t)
85                    .unwrap(),
86            )))
87        } else if let Some(a) = a.and_then(as_circle_border) {
88            Some(ShapeBorderRef::new(RoundedRectangleToCircleBorder {
89                side: BorderSide::lerp(a.side, self.side, t),
90                border_radius: self.border_radius,
91                circularity: 1.0 - t,
92                eccentricity: a.eccentricity,
93            }))
94        } else if a.is_none() {
95            Some(ShapeBorder::scale(self, t))
96        } else {
97            None
98        }
99    }
100
101    fn lerp_to(&self, b: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
102        if let Some(b) = b.and_then(|b| b.as_any().downcast_ref::<RoundedRectangleBorder>()) {
103            Some(ShapeBorderRef::new(RoundedRectangleBorder::new(
104                BorderSide::lerp(self.side, b.side, t),
105                BorderRadiusGeometry::lerp(Some(self.border_radius), Some(b.border_radius), t)
106                    .unwrap(),
107            )))
108        } else if let Some(b) = b.and_then(as_circle_border) {
109            Some(ShapeBorderRef::new(RoundedRectangleToCircleBorder {
110                side: BorderSide::lerp(self.side, b.side, t),
111                border_radius: self.border_radius,
112                circularity: t,
113                eccentricity: b.eccentricity,
114            }))
115        } else if b.is_none() {
116            Some(ShapeBorder::scale(self, 1.0 - t))
117        } else {
118            None
119        }
120    }
121
122    fn get_inner_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
123        let border_rect = self.border_radius.resolve(text_direction).to_rrect(rect);
124        rrect_path(border_rect.deflate(self.side.stroke_inset()))
125    }
126
127    fn get_outer_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
128        rrect_path(self.border_radius.resolve(text_direction).to_rrect(rect))
129    }
130
131    fn hit_test(
132        &self,
133        rect: Rect,
134        position: Offset,
135        text_direction: Option<TextDirection>,
136    ) -> bool {
137        let resolved_border_radius = self.border_radius.resolve(text_direction);
138        if resolved_border_radius == BorderRadius::ZERO {
139            return rect.contains(position);
140        }
141        resolved_border_radius.to_rrect(rect).contains(position)
142    }
143
144    fn paint_interior(
145        &self,
146        canvas: &mut Canvas,
147        rect: Rect,
148        paint: &Paint,
149        text_direction: Option<TextDirection>,
150    ) {
151        if self.border_radius == BorderRadius::ZERO.into() {
152            canvas.draw_rect(rect, paint);
153        } else {
154            draw_rrect(
155                canvas,
156                self.border_radius.resolve(text_direction).to_rrect(rect),
157                paint,
158            );
159        }
160    }
161
162    fn prefer_paint_interior(&self) -> bool {
163        true
164    }
165
166    fn paint(&self, canvas: &mut Canvas, rect: Rect, text_direction: Option<TextDirection>) {
167        match self.side.style {
168            BorderStyle::None => {}
169            BorderStyle::Solid => {
170                if self.side.width == 0.0 {
171                    draw_rrect(
172                        canvas,
173                        self.border_radius.resolve(text_direction).to_rrect(rect),
174                        &self.side.to_paint(),
175                    );
176                } else {
177                    let paint = Paint {
178                        color: self.side.color.into(),
179                        ..Paint::default()
180                    };
181                    let border_rect = self.border_radius.resolve(text_direction).to_rrect(rect);
182                    let inner = border_rect.deflate(self.side.stroke_inset());
183                    let outer = border_rect.inflate(self.side.stroke_outset());
184                    draw_drrect(canvas, outer, inner, &paint);
185                }
186            }
187        }
188    }
189
190    fn as_any(&self) -> &dyn Any {
191        self
192    }
193
194    fn as_outlined_border(&self) -> Option<&dyn OutlinedBorder> {
195        Some(self)
196    }
197
198    fn into_outlined_border(self: Rc<Self>) -> Option<Rc<dyn OutlinedBorder>> {
199        Some(self)
200    }
201
202    fn eq_shape(&self, other: &dyn ShapeBorder) -> bool {
203        other
204            .as_any()
205            .downcast_ref::<RoundedRectangleBorder>()
206            .is_some_and(|other| other == self)
207    }
208}
209
210impl OutlinedBorder for RoundedRectangleBorder {
211    fn side(&self) -> BorderSide {
212        self.side
213    }
214
215    fn copy_with(&self, side: Option<BorderSide>) -> OutlinedBorderRef {
216        OutlinedBorderRef::new(RoundedRectangleBorder::copy_with(self, side, None))
217    }
218}
219
220impl Debug for RoundedRectangleBorder {
221    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
222        write!(
223            f,
224            "RoundedRectangleBorder({:?}, {:?})",
225            self.side, self.border_radius
226        )
227    }
228}
229
230/// A rectangular border with rounded corners following the shape of an
231/// [`RSuperellipse`].
232#[derive(Clone, Copy, PartialEq)]
233pub struct RoundedSuperellipseBorder {
234    /// The border outline's color and weight.
235    pub side: BorderSide,
236    /// The radii for each corner.
237    pub border_radius: BorderRadiusGeometry,
238}
239
240impl RoundedSuperellipseBorder {
241    /// Creates a rounded rectangle border.
242    ///
243    /// If `border_radius` is None, it defaults to [`BorderRadius::ZERO`].
244    pub fn new(
245        side: BorderSide,
246        border_radius: Option<BorderRadiusGeometry>,
247    ) -> RoundedSuperellipseBorder {
248        RoundedSuperellipseBorder {
249            side,
250            border_radius: border_radius.unwrap_or(BorderRadius::ZERO.into()),
251        }
252    }
253
254    /// Creates a copy of this border, scaled by the factor `t`.
255    pub fn scale(&self, t: f64) -> RoundedSuperellipseBorder {
256        RoundedSuperellipseBorder::new(self.side.scale(t), Some(self.border_radius * t))
257    }
258
259    /// Returns a copy of this RoundedSuperellipseBorder with the given fields
260    /// replaced with the new values.
261    pub fn copy_with(
262        &self,
263        side: Option<BorderSide>,
264        border_radius: Option<BorderRadiusGeometry>,
265    ) -> RoundedSuperellipseBorder {
266        RoundedSuperellipseBorder::new(
267            side.unwrap_or(self.side),
268            Some(border_radius.unwrap_or(self.border_radius)),
269        )
270    }
271}
272
273impl Default for RoundedSuperellipseBorder {
274    fn default() -> RoundedSuperellipseBorder {
275        RoundedSuperellipseBorder::new(BorderSide::NONE, None)
276    }
277}
278
279impl ShapeBorder for RoundedSuperellipseBorder {
280    fn dimensions(&self) -> EdgeInsetsGeometry {
281        outlined_border_dimensions(self.side)
282    }
283
284    fn scale(&self, t: f64) -> ShapeBorderRef {
285        ShapeBorderRef::new(RoundedSuperellipseBorder::scale(self, t))
286    }
287
288    fn lerp_from(&self, a: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
289        if let Some(a) = a.and_then(|a| a.as_any().downcast_ref::<RoundedSuperellipseBorder>()) {
290            Some(ShapeBorderRef::new(RoundedSuperellipseBorder::new(
291                BorderSide::lerp(a.side, self.side, t),
292                BorderRadiusGeometry::lerp(Some(a.border_radius), Some(self.border_radius), t),
293            )))
294        } else if let Some(a) = a.and_then(as_circle_border) {
295            Some(ShapeBorderRef::new(RoundedSuperellipseToCircleBorder {
296                side: BorderSide::lerp(a.side, self.side, t),
297                border_radius: self.border_radius,
298                circularity: 1.0 - t,
299                eccentricity: a.eccentricity,
300            }))
301        } else if a.is_none() {
302            Some(ShapeBorder::scale(self, t))
303        } else {
304            None
305        }
306    }
307
308    fn lerp_to(&self, b: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
309        if let Some(b) = b.and_then(|b| b.as_any().downcast_ref::<RoundedSuperellipseBorder>()) {
310            Some(ShapeBorderRef::new(RoundedSuperellipseBorder::new(
311                BorderSide::lerp(self.side, b.side, t),
312                BorderRadiusGeometry::lerp(Some(self.border_radius), Some(b.border_radius), t),
313            )))
314        } else if let Some(b) = b.and_then(as_circle_border) {
315            Some(ShapeBorderRef::new(RoundedSuperellipseToCircleBorder {
316                side: BorderSide::lerp(self.side, b.side, t),
317                border_radius: self.border_radius,
318                circularity: t,
319                eccentricity: b.eccentricity,
320            }))
321        } else if b.is_none() {
322            Some(ShapeBorder::scale(self, 1.0 - t))
323        } else {
324            None
325        }
326    }
327
328    fn get_inner_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
329        if self.border_radius == BorderRadius::ZERO.into() {
330            rect_path(rect.deflate(self.side.stroke_inset()))
331        } else {
332            let border_rect = self
333                .border_radius
334                .resolve(text_direction)
335                .to_r_superellipse(rect);
336            rsuperellipse_path(border_rect.deflate(self.side.stroke_inset()))
337        }
338    }
339
340    fn get_outer_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
341        if self.border_radius == BorderRadius::ZERO.into() {
342            rect_path(rect)
343        } else {
344            rsuperellipse_path(
345                self.border_radius
346                    .resolve(text_direction)
347                    .to_r_superellipse(rect),
348            )
349        }
350    }
351
352    fn hit_test(
353        &self,
354        rect: Rect,
355        position: Offset,
356        text_direction: Option<TextDirection>,
357    ) -> bool {
358        let resolved_border_radius = self.border_radius.resolve(text_direction);
359        if resolved_border_radius == BorderRadius::ZERO {
360            return rect.contains(position);
361        }
362        resolved_border_radius
363            .to_r_superellipse(rect)
364            .contains(position)
365    }
366
367    fn paint_interior(
368        &self,
369        canvas: &mut Canvas,
370        rect: Rect,
371        paint: &Paint,
372        text_direction: Option<TextDirection>,
373    ) {
374        if self.border_radius == BorderRadius::ZERO.into() {
375            canvas.draw_rect(rect, paint);
376        } else {
377            draw_rsuperellipse(
378                canvas,
379                self.border_radius
380                    .resolve(text_direction)
381                    .to_r_superellipse(rect),
382                paint,
383            );
384        }
385    }
386
387    fn prefer_paint_interior(&self) -> bool {
388        true
389    }
390
391    fn paint(&self, canvas: &mut Canvas, rect: Rect, text_direction: Option<TextDirection>) {
392        match self.side.style {
393            BorderStyle::None => {}
394            BorderStyle::Solid => {
395                let stroke_offset = (self.side.stroke_outset() - self.side.stroke_inset()) / 2.0;
396                if self.border_radius == BorderRadius::ZERO.into() {
397                    let base = rect.inflate(stroke_offset);
398                    canvas.draw_rect(base, &self.side.to_paint());
399                } else {
400                    let base = self
401                        .border_radius
402                        .resolve(text_direction)
403                        .to_r_superellipse(rect)
404                        .inflate(stroke_offset);
405                    draw_rsuperellipse(canvas, base, &self.side.to_paint());
406                }
407            }
408        }
409    }
410
411    fn as_any(&self) -> &dyn Any {
412        self
413    }
414
415    fn as_outlined_border(&self) -> Option<&dyn OutlinedBorder> {
416        Some(self)
417    }
418
419    fn into_outlined_border(self: Rc<Self>) -> Option<Rc<dyn OutlinedBorder>> {
420        Some(self)
421    }
422
423    fn eq_shape(&self, other: &dyn ShapeBorder) -> bool {
424        other
425            .as_any()
426            .downcast_ref::<RoundedSuperellipseBorder>()
427            .is_some_and(|other| other == self)
428    }
429}
430
431impl OutlinedBorder for RoundedSuperellipseBorder {
432    fn side(&self) -> BorderSide {
433        self.side
434    }
435
436    fn copy_with(&self, side: Option<BorderSide>) -> OutlinedBorderRef {
437        OutlinedBorderRef::new(RoundedSuperellipseBorder::copy_with(self, side, None))
438    }
439}
440
441impl Debug for RoundedSuperellipseBorder {
442    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
443        write!(
444            f,
445            "RoundedSuperellipseBorder({:?}, {:?})",
446            self.side, self.border_radius
447        )
448    }
449}
450
451fn rect_path(rect: Rect) -> Path {
452    let mut path = PathBuilder::new();
453    path.rect(rect.into());
454    path.build().into()
455}
456
457fn rsuperellipse_path(rse: RSuperellipse) -> Path {
458    let mut path = PathBuilder::new();
459    path.rsuperellipse_radii(rse.outer_rect().into(), rsuperellipse_radii_elliptical(rse));
460    path.build().into()
461}
462
463fn shape_to_circle_adjust_rect(rect: Rect, circularity: f64, eccentricity: f64) -> Rect {
464    if circularity == 0.0 || rect.width() == rect.height() {
465        return rect;
466    }
467    if rect.width() < rect.height() {
468        let partial_delta = (rect.height() - rect.width()) / 2.0;
469        let delta = circularity * partial_delta * (1.0 - eccentricity);
470        Rect::from_ltrb(rect.left, rect.top + delta, rect.right, rect.bottom - delta)
471    } else {
472        let partial_delta = (rect.width() - rect.height()) / 2.0;
473        let delta = circularity * partial_delta * (1.0 - eccentricity);
474        Rect::from_ltrb(rect.left + delta, rect.top, rect.right - delta, rect.bottom)
475    }
476}
477
478fn shape_to_circle_adjust_border_radius(
479    rect: Rect,
480    text_direction: Option<TextDirection>,
481    border_radius: BorderRadiusGeometry,
482    circularity: f64,
483    eccentricity: f64,
484) -> BorderRadius {
485    let resolved_radius = border_radius.resolve(text_direction);
486    if circularity == 0.0 {
487        return resolved_radius;
488    }
489    if eccentricity != 0.0 {
490        if rect.width() < rect.height() {
491            BorderRadius::lerp(
492                Some(resolved_radius),
493                Some(BorderRadius::all(Radius::elliptical(
494                    rect.width() / 2.0,
495                    (0.5 + eccentricity / 2.0) * rect.height() / 2.0,
496                ))),
497                circularity,
498            )
499            .unwrap()
500        } else {
501            BorderRadius::lerp(
502                Some(resolved_radius),
503                Some(BorderRadius::all(Radius::elliptical(
504                    (0.5 + eccentricity / 2.0) * rect.width() / 2.0,
505                    rect.height() / 2.0,
506                ))),
507                circularity,
508            )
509            .unwrap()
510        }
511    } else {
512        BorderRadius::lerp(
513            Some(resolved_radius),
514            Some(BorderRadius::circular(rect.shortest_side() / 2.0)),
515            circularity,
516        )
517        .unwrap()
518    }
519}
520
521#[derive(Clone, Copy)]
522struct RoundedRectangleToCircleBorder {
523    side: BorderSide,
524    border_radius: BorderRadiusGeometry,
525    circularity: f64,
526    eccentricity: f64,
527}
528
529impl RoundedRectangleToCircleBorder {
530    fn copy_with(
531        &self,
532        side: Option<BorderSide>,
533        border_radius: Option<BorderRadiusGeometry>,
534        circularity: Option<f64>,
535        eccentricity: Option<f64>,
536    ) -> RoundedRectangleToCircleBorder {
537        RoundedRectangleToCircleBorder {
538            side: side.unwrap_or(self.side),
539            border_radius: border_radius.unwrap_or(self.border_radius),
540            circularity: circularity.unwrap_or(self.circularity),
541            eccentricity: eccentricity.unwrap_or(self.eccentricity),
542        }
543    }
544
545    fn draw_shape(
546        canvas: &mut Canvas,
547        rect: Rect,
548        radius: BorderRadius,
549        paint: &Paint,
550        inflation: Option<f64>,
551    ) {
552        let mut rrect = radius.to_rrect(rect);
553        if let Some(inflation) = inflation {
554            rrect = rrect.inflate(inflation);
555        }
556        draw_rrect(canvas, rrect, paint);
557    }
558
559    fn build_path(rect: Rect, radius: BorderRadius, inflation: Option<f64>) -> Path {
560        let mut rrect = radius.to_rrect(rect);
561        if let Some(inflation) = inflation {
562            rrect = rrect.inflate(inflation);
563        }
564        rrect_path(rrect)
565    }
566}
567
568impl ShapeBorder for RoundedRectangleToCircleBorder {
569    fn dimensions(&self) -> EdgeInsetsGeometry {
570        outlined_border_dimensions(self.side)
571    }
572
573    fn scale(&self, t: f64) -> ShapeBorderRef {
574        ShapeBorderRef::new(self.copy_with(
575            Some(self.side.scale(t)),
576            Some(self.border_radius * t),
577            Some(t),
578            None,
579        ))
580    }
581
582    fn lerp_from(&self, a: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
583        if let Some(a) = a.and_then(|a| a.as_any().downcast_ref::<RoundedRectangleBorder>()) {
584            Some(ShapeBorderRef::new(self.copy_with(
585                Some(BorderSide::lerp(a.side, self.side, t)),
586                BorderRadiusGeometry::lerp(Some(a.border_radius), Some(self.border_radius), t),
587                Some(self.circularity * t),
588                None,
589            )))
590        } else if let Some(a) = a.and_then(as_circle_border) {
591            Some(ShapeBorderRef::new(self.copy_with(
592                Some(BorderSide::lerp(a.side, self.side, t)),
593                Some(self.border_radius),
594                Some(self.circularity + (1.0 - self.circularity) * (1.0 - t)),
595                Some(a.eccentricity),
596            )))
597        } else if let Some(a) =
598            a.and_then(|a| a.as_any().downcast_ref::<RoundedRectangleToCircleBorder>())
599        {
600            Some(ShapeBorderRef::new(self.copy_with(
601                Some(BorderSide::lerp(a.side, self.side, t)),
602                BorderRadiusGeometry::lerp(Some(a.border_radius), Some(self.border_radius), t),
603                lerp_double(Some(a.circularity), Some(self.circularity), t),
604                None,
605            )))
606        } else if a.is_none() {
607            Some(ShapeBorder::scale(self, t))
608        } else {
609            None
610        }
611    }
612
613    fn lerp_to(&self, b: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
614        if let Some(b) = b.and_then(|b| b.as_any().downcast_ref::<RoundedRectangleBorder>()) {
615            Some(ShapeBorderRef::new(self.copy_with(
616                Some(BorderSide::lerp(self.side, b.side, t)),
617                BorderRadiusGeometry::lerp(Some(self.border_radius), Some(b.border_radius), t),
618                Some(self.circularity * (1.0 - t)),
619                None,
620            )))
621        } else if let Some(b) = b.and_then(as_circle_border) {
622            Some(ShapeBorderRef::new(self.copy_with(
623                Some(BorderSide::lerp(self.side, b.side, t)),
624                Some(self.border_radius),
625                Some(self.circularity + (1.0 - self.circularity) * t),
626                Some(b.eccentricity),
627            )))
628        } else if let Some(b) =
629            b.and_then(|b| b.as_any().downcast_ref::<RoundedRectangleToCircleBorder>())
630        {
631            Some(ShapeBorderRef::new(self.copy_with(
632                Some(BorderSide::lerp(self.side, b.side, t)),
633                BorderRadiusGeometry::lerp(Some(self.border_radius), Some(b.border_radius), t),
634                lerp_double(Some(self.circularity), Some(b.circularity), t),
635                None,
636            )))
637        } else if b.is_none() {
638            Some(ShapeBorder::scale(self, 1.0 - t))
639        } else {
640            None
641        }
642    }
643
644    fn get_inner_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
645        Self::build_path(
646            shape_to_circle_adjust_rect(rect, self.circularity, self.eccentricity),
647            shape_to_circle_adjust_border_radius(
648                rect,
649                text_direction,
650                self.border_radius,
651                self.circularity,
652                self.eccentricity,
653            ),
654            Some(-lerp_double(Some(self.side.width), Some(0.0), self.side.stroke_align).unwrap()),
655        )
656    }
657
658    fn get_outer_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
659        Self::build_path(
660            shape_to_circle_adjust_rect(rect, self.circularity, self.eccentricity),
661            shape_to_circle_adjust_border_radius(
662                rect,
663                text_direction,
664                self.border_radius,
665                self.circularity,
666                self.eccentricity,
667            ),
668            None,
669        )
670    }
671
672    fn hit_test(
673        &self,
674        rect: Rect,
675        position: Offset,
676        text_direction: Option<TextDirection>,
677    ) -> bool {
678        let adjusted_rect = shape_to_circle_adjust_rect(rect, self.circularity, self.eccentricity);
679        let adjusted_border_radius = shape_to_circle_adjust_border_radius(
680            rect,
681            text_direction,
682            self.border_radius,
683            self.circularity,
684            self.eccentricity,
685        );
686        if adjusted_border_radius == BorderRadius::ZERO {
687            return adjusted_rect.contains(position);
688        }
689        adjusted_border_radius
690            .to_rrect(adjusted_rect)
691            .contains(position)
692    }
693
694    fn paint_interior(
695        &self,
696        canvas: &mut Canvas,
697        rect: Rect,
698        paint: &Paint,
699        text_direction: Option<TextDirection>,
700    ) {
701        let adjusted_border_radius = shape_to_circle_adjust_border_radius(
702            rect,
703            text_direction,
704            self.border_radius,
705            self.circularity,
706            self.eccentricity,
707        );
708        if adjusted_border_radius == BorderRadius::ZERO {
709            canvas.draw_rect(
710                shape_to_circle_adjust_rect(rect, self.circularity, self.eccentricity),
711                paint,
712            );
713        } else {
714            Self::draw_shape(
715                canvas,
716                shape_to_circle_adjust_rect(rect, self.circularity, self.eccentricity),
717                adjusted_border_radius,
718                paint,
719                None,
720            );
721        }
722    }
723
724    fn prefer_paint_interior(&self) -> bool {
725        true
726    }
727
728    fn paint(&self, canvas: &mut Canvas, rect: Rect, text_direction: Option<TextDirection>) {
729        match self.side.style {
730            BorderStyle::None => {}
731            BorderStyle::Solid => {
732                Self::draw_shape(
733                    canvas,
734                    shape_to_circle_adjust_rect(rect, self.circularity, self.eccentricity),
735                    shape_to_circle_adjust_border_radius(
736                        rect,
737                        text_direction,
738                        self.border_radius,
739                        self.circularity,
740                        self.eccentricity,
741                    ),
742                    &self.side.to_paint(),
743                    Some(self.side.stroke_offset() / 2.0),
744                );
745            }
746        }
747    }
748
749    fn as_any(&self) -> &dyn Any {
750        self
751    }
752
753    fn as_outlined_border(&self) -> Option<&dyn OutlinedBorder> {
754        Some(self)
755    }
756
757    fn into_outlined_border(self: Rc<Self>) -> Option<Rc<dyn OutlinedBorder>> {
758        Some(self)
759    }
760
761    fn eq_shape(&self, other: &dyn ShapeBorder) -> bool {
762        other
763            .as_any()
764            .downcast_ref::<RoundedRectangleToCircleBorder>()
765            .is_some_and(|other| {
766                other.side == self.side
767                    && other.border_radius == self.border_radius
768                    && other.circularity == self.circularity
769            })
770    }
771}
772
773impl OutlinedBorder for RoundedRectangleToCircleBorder {
774    fn side(&self) -> BorderSide {
775        self.side
776    }
777
778    fn copy_with(&self, side: Option<BorderSide>) -> OutlinedBorderRef {
779        OutlinedBorderRef::new(RoundedRectangleToCircleBorder::copy_with(
780            self, side, None, None, None,
781        ))
782    }
783}
784
785impl Debug for RoundedRectangleToCircleBorder {
786    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
787        if self.eccentricity != 0.0 {
788            write!(
789                f,
790                "RoundedRectangleBorder({:?}, {:?}, {:.1}% of the way to being a CircleBorder that is {:.1}% oval)",
791                self.side,
792                self.border_radius,
793                self.circularity * 100.0,
794                self.eccentricity * 100.0
795            )
796        } else {
797            write!(
798                f,
799                "RoundedRectangleBorder({:?}, {:?}, {:.1}% of the way to being a CircleBorder)",
800                self.side,
801                self.border_radius,
802                self.circularity * 100.0
803            )
804        }
805    }
806}
807
808#[derive(Clone, Copy)]
809struct RoundedSuperellipseToCircleBorder {
810    side: BorderSide,
811    border_radius: BorderRadiusGeometry,
812    circularity: f64,
813    eccentricity: f64,
814}
815
816impl RoundedSuperellipseToCircleBorder {
817    fn copy_with(
818        &self,
819        side: Option<BorderSide>,
820        border_radius: Option<BorderRadiusGeometry>,
821        circularity: Option<f64>,
822        eccentricity: Option<f64>,
823    ) -> RoundedSuperellipseToCircleBorder {
824        RoundedSuperellipseToCircleBorder {
825            side: side.unwrap_or(self.side),
826            border_radius: border_radius.unwrap_or(self.border_radius),
827            circularity: circularity.unwrap_or(self.circularity),
828            eccentricity: eccentricity.unwrap_or(self.eccentricity),
829        }
830    }
831
832    fn draw_shape(
833        canvas: &mut Canvas,
834        rect: Rect,
835        radius: BorderRadius,
836        paint: &Paint,
837        inflation: Option<f64>,
838    ) {
839        let mut rsuperellipse = radius.to_r_superellipse(rect);
840        if let Some(inflation) = inflation {
841            rsuperellipse = rsuperellipse.inflate(inflation);
842        }
843        draw_rsuperellipse(canvas, rsuperellipse, paint);
844    }
845
846    fn build_path(rect: Rect, radius: BorderRadius, inflation: Option<f64>) -> Path {
847        let mut rsuperellipse = radius.to_r_superellipse(rect);
848        if let Some(inflation) = inflation {
849            rsuperellipse = rsuperellipse.inflate(inflation);
850        }
851        rsuperellipse_path(rsuperellipse)
852    }
853}
854
855impl ShapeBorder for RoundedSuperellipseToCircleBorder {
856    fn dimensions(&self) -> EdgeInsetsGeometry {
857        outlined_border_dimensions(self.side)
858    }
859
860    fn scale(&self, t: f64) -> ShapeBorderRef {
861        ShapeBorderRef::new(self.copy_with(
862            Some(self.side.scale(t)),
863            Some(self.border_radius * t),
864            Some(t),
865            None,
866        ))
867    }
868
869    fn lerp_from(&self, a: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
870        if let Some(a) = a.and_then(|a| a.as_any().downcast_ref::<RoundedSuperellipseBorder>()) {
871            Some(ShapeBorderRef::new(self.copy_with(
872                Some(BorderSide::lerp(a.side, self.side, t)),
873                BorderRadiusGeometry::lerp(Some(a.border_radius), Some(self.border_radius), t),
874                Some(self.circularity * t),
875                None,
876            )))
877        } else if let Some(a) = a.and_then(as_circle_border) {
878            Some(ShapeBorderRef::new(self.copy_with(
879                Some(BorderSide::lerp(a.side, self.side, t)),
880                Some(self.border_radius),
881                Some(self.circularity + (1.0 - self.circularity) * (1.0 - t)),
882                Some(a.eccentricity),
883            )))
884        } else if let Some(a) = a.and_then(|a| {
885            a.as_any()
886                .downcast_ref::<RoundedSuperellipseToCircleBorder>()
887        }) {
888            Some(ShapeBorderRef::new(self.copy_with(
889                Some(BorderSide::lerp(a.side, self.side, t)),
890                BorderRadiusGeometry::lerp(Some(a.border_radius), Some(self.border_radius), t),
891                lerp_double(Some(a.circularity), Some(self.circularity), t),
892                None,
893            )))
894        } else if a.is_none() {
895            Some(ShapeBorder::scale(self, t))
896        } else {
897            None
898        }
899    }
900
901    fn lerp_to(&self, b: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
902        if let Some(b) = b.and_then(|b| b.as_any().downcast_ref::<RoundedSuperellipseBorder>()) {
903            Some(ShapeBorderRef::new(self.copy_with(
904                Some(BorderSide::lerp(self.side, b.side, t)),
905                BorderRadiusGeometry::lerp(Some(self.border_radius), Some(b.border_radius), t),
906                Some(self.circularity * (1.0 - t)),
907                None,
908            )))
909        } else if let Some(b) = b.and_then(as_circle_border) {
910            Some(ShapeBorderRef::new(self.copy_with(
911                Some(BorderSide::lerp(self.side, b.side, t)),
912                Some(self.border_radius),
913                Some(self.circularity + (1.0 - self.circularity) * t),
914                Some(b.eccentricity),
915            )))
916        } else if let Some(b) = b.and_then(|b| {
917            b.as_any()
918                .downcast_ref::<RoundedSuperellipseToCircleBorder>()
919        }) {
920            Some(ShapeBorderRef::new(self.copy_with(
921                Some(BorderSide::lerp(self.side, b.side, t)),
922                BorderRadiusGeometry::lerp(Some(self.border_radius), Some(b.border_radius), t),
923                lerp_double(Some(self.circularity), Some(b.circularity), t),
924                None,
925            )))
926        } else if b.is_none() {
927            Some(ShapeBorder::scale(self, 1.0 - t))
928        } else {
929            None
930        }
931    }
932
933    fn get_inner_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
934        Self::build_path(
935            shape_to_circle_adjust_rect(rect, self.circularity, self.eccentricity),
936            shape_to_circle_adjust_border_radius(
937                rect,
938                text_direction,
939                self.border_radius,
940                self.circularity,
941                self.eccentricity,
942            ),
943            Some(-lerp_double(Some(self.side.width), Some(0.0), self.side.stroke_align).unwrap()),
944        )
945    }
946
947    fn get_outer_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
948        Self::build_path(
949            shape_to_circle_adjust_rect(rect, self.circularity, self.eccentricity),
950            shape_to_circle_adjust_border_radius(
951                rect,
952                text_direction,
953                self.border_radius,
954                self.circularity,
955                self.eccentricity,
956            ),
957            None,
958        )
959    }
960
961    fn hit_test(
962        &self,
963        rect: Rect,
964        position: Offset,
965        text_direction: Option<TextDirection>,
966    ) -> bool {
967        let adjusted_rect = shape_to_circle_adjust_rect(rect, self.circularity, self.eccentricity);
968        let adjusted_border_radius = shape_to_circle_adjust_border_radius(
969            rect,
970            text_direction,
971            self.border_radius,
972            self.circularity,
973            self.eccentricity,
974        );
975        if adjusted_border_radius == BorderRadius::ZERO {
976            return adjusted_rect.contains(position);
977        }
978        adjusted_border_radius
979            .to_r_superellipse(adjusted_rect)
980            .contains(position)
981    }
982
983    fn paint_interior(
984        &self,
985        canvas: &mut Canvas,
986        rect: Rect,
987        paint: &Paint,
988        text_direction: Option<TextDirection>,
989    ) {
990        let adjusted_border_radius = shape_to_circle_adjust_border_radius(
991            rect,
992            text_direction,
993            self.border_radius,
994            self.circularity,
995            self.eccentricity,
996        );
997        if adjusted_border_radius == BorderRadius::ZERO {
998            canvas.draw_rect(
999                shape_to_circle_adjust_rect(rect, self.circularity, self.eccentricity),
1000                paint,
1001            );
1002        } else {
1003            Self::draw_shape(
1004                canvas,
1005                shape_to_circle_adjust_rect(rect, self.circularity, self.eccentricity),
1006                adjusted_border_radius,
1007                paint,
1008                None,
1009            );
1010        }
1011    }
1012
1013    fn prefer_paint_interior(&self) -> bool {
1014        true
1015    }
1016
1017    fn paint(&self, canvas: &mut Canvas, rect: Rect, text_direction: Option<TextDirection>) {
1018        match self.side.style {
1019            BorderStyle::None => {}
1020            BorderStyle::Solid => {
1021                Self::draw_shape(
1022                    canvas,
1023                    shape_to_circle_adjust_rect(rect, self.circularity, self.eccentricity),
1024                    shape_to_circle_adjust_border_radius(
1025                        rect,
1026                        text_direction,
1027                        self.border_radius,
1028                        self.circularity,
1029                        self.eccentricity,
1030                    ),
1031                    &self.side.to_paint(),
1032                    Some(self.side.stroke_offset() / 2.0),
1033                );
1034            }
1035        }
1036    }
1037
1038    fn as_any(&self) -> &dyn Any {
1039        self
1040    }
1041
1042    fn as_outlined_border(&self) -> Option<&dyn OutlinedBorder> {
1043        Some(self)
1044    }
1045
1046    fn into_outlined_border(self: Rc<Self>) -> Option<Rc<dyn OutlinedBorder>> {
1047        Some(self)
1048    }
1049
1050    fn eq_shape(&self, other: &dyn ShapeBorder) -> bool {
1051        other
1052            .as_any()
1053            .downcast_ref::<RoundedSuperellipseToCircleBorder>()
1054            .is_some_and(|other| {
1055                other.side == self.side
1056                    && other.border_radius == self.border_radius
1057                    && other.circularity == self.circularity
1058            })
1059    }
1060}
1061
1062impl OutlinedBorder for RoundedSuperellipseToCircleBorder {
1063    fn side(&self) -> BorderSide {
1064        self.side
1065    }
1066
1067    fn copy_with(&self, side: Option<BorderSide>) -> OutlinedBorderRef {
1068        OutlinedBorderRef::new(RoundedSuperellipseToCircleBorder::copy_with(
1069            self, side, None, None, None,
1070        ))
1071    }
1072}
1073
1074impl Debug for RoundedSuperellipseToCircleBorder {
1075    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
1076        if self.eccentricity != 0.0 {
1077            write!(
1078                f,
1079                "RoundedSuperellipseBorder({:?}, {:?}, {:.1}% of the way to being a CircleBorder that is {:.1}% oval)",
1080                self.side,
1081                self.border_radius,
1082                self.circularity * 100.0,
1083                self.eccentricity * 100.0
1084            )
1085        } else {
1086            write!(
1087                f,
1088                "RoundedSuperellipseBorder({:?}, {:?}, {:.1}% of the way to being a CircleBorder)",
1089                self.side,
1090                self.border_radius,
1091                self.circularity * 100.0
1092            )
1093        }
1094    }
1095}
1096
1097#[cfg(test)]
1098mod tests {
1099    use super::*;
1100    use waft_embedder::{Color, Radius};
1101
1102    use crate::border_radius::BorderRadiusDirectional;
1103    use crate::circle_border::CircleBorder;
1104
1105    fn side_width(width: f64) -> BorderSide {
1106        BorderSide {
1107            width,
1108            ..BorderSide::default()
1109        }
1110    }
1111
1112    fn contains(path: &Path, x: f64, y: f64) -> bool {
1113        path.contains(Offset::new(x, y))
1114    }
1115
1116    #[test]
1117    fn rounded_rectangle_defaults_copy_with_scale_lerp() {
1118        let border = RoundedRectangleBorder::default();
1119        assert_eq!(border.side, BorderSide::NONE);
1120        assert_eq!(border.border_radius, BorderRadius::ZERO.into());
1121        assert_eq!(border, border.copy_with(None, None));
1122
1123        let side = BorderSide {
1124            width: 10.0,
1125            color: Color::new(0xFF123456),
1126            ..BorderSide::default()
1127        };
1128        let radius = BorderRadius::all(Radius::circular(16.0));
1129        let directional = BorderRadiusDirectional::all(Radius::circular(16.0));
1130        assert_eq!(
1131            RoundedRectangleBorder::default().copy_with(Some(side), Some(radius.into())),
1132            RoundedRectangleBorder::new(side, radius.into())
1133        );
1134        assert_eq!(
1135            RoundedRectangleBorder::default().copy_with(Some(side), Some(directional.into())),
1136            RoundedRectangleBorder::new(side, directional.into())
1137        );
1138
1139        let c10 = RoundedRectangleBorder::new(
1140            side_width(10.0),
1141            BorderRadius::all(Radius::circular(100.0)).into(),
1142        );
1143        let c15 = RoundedRectangleBorder::new(
1144            side_width(15.0),
1145            BorderRadius::all(Radius::circular(150.0)).into(),
1146        );
1147        let c20 = RoundedRectangleBorder::new(
1148            side_width(20.0),
1149            BorderRadius::all(Radius::circular(200.0)).into(),
1150        );
1151        assert_eq!(c10.dimensions(), EdgeInsetsGeometry::all(10.0));
1152        assert_eq!(c10.scale(2.0), c20);
1153        assert_eq!(c20.scale(0.5), c10);
1154        let as10 = ShapeBorderRef::new(c10);
1155        let as20 = ShapeBorderRef::new(c20);
1156        assert!(
1157            ShapeBorderRef::lerp(Some(&as10), Some(&as20), 0.0)
1158                .unwrap()
1159                .eq_shape(&c10)
1160        );
1161        assert!(
1162            ShapeBorderRef::lerp(Some(&as10), Some(&as20), 0.5)
1163                .unwrap()
1164                .eq_shape(&c15)
1165        );
1166        assert!(
1167            ShapeBorderRef::lerp(Some(&as10), Some(&as20), 1.0)
1168                .unwrap()
1169                .eq_shape(&c20)
1170        );
1171    }
1172
1173    #[test]
1174    fn rounded_rectangle_lerps_with_circle() {
1175        let r = RoundedRectangleBorder::new(
1176            BorderSide::NONE,
1177            BorderRadius::all(Radius::circular(10.0)).into(),
1178        );
1179        let c = CircleBorder::default();
1180        let rect = Rect::from_ltwh(0.0, 0.0, 100.0, 20.0);
1181        let r_path = r.get_outer_path(rect, None);
1182        assert!(contains(&r_path, 30.0, 10.0));
1183        assert!(contains(&r_path, 50.0, 10.0));
1184        assert!(!contains(&r_path, 1.0, 1.0));
1185        assert!(!contains(&r_path, 99.0, 19.0));
1186
1187        let c_path = c.get_outer_path(rect, None);
1188        assert!(contains(&c_path, 50.0, 10.0));
1189        assert!(!contains(&c_path, 1.0, 1.0));
1190        assert!(!contains(&c_path, 30.0, 10.0));
1191        assert!(!contains(&c_path, 99.0, 19.0));
1192
1193        let at_01 = ShapeBorderRef::lerp(
1194            Some(&ShapeBorderRef::new(r)),
1195            Some(&ShapeBorderRef::new(c)),
1196            0.1,
1197        )
1198        .unwrap()
1199        .get_outer_path(rect, None);
1200        assert!(contains(&at_01, 30.0, 10.0));
1201        let at_09 = ShapeBorderRef::lerp(
1202            Some(&ShapeBorderRef::new(r)),
1203            Some(&ShapeBorderRef::new(c)),
1204            0.9,
1205        )
1206        .unwrap()
1207        .get_outer_path(rect, None);
1208        assert!(contains(&at_09, 50.0, 10.0));
1209        assert!(!contains(&at_09, 30.0, 10.0));
1210    }
1211
1212    #[test]
1213    fn rounded_superellipse_defaults_copy_with_scale_lerp() {
1214        let border = RoundedSuperellipseBorder::default();
1215        assert_eq!(border.side, BorderSide::NONE);
1216        assert_eq!(border.border_radius, BorderRadius::ZERO.into());
1217        assert_eq!(border, border.copy_with(None, None));
1218
1219        let c10 = RoundedSuperellipseBorder::new(
1220            side_width(10.0),
1221            Some(BorderRadius::all(Radius::circular(100.0)).into()),
1222        );
1223        let c15 = RoundedSuperellipseBorder::new(
1224            side_width(15.0),
1225            Some(BorderRadius::all(Radius::circular(150.0)).into()),
1226        );
1227        let c20 = RoundedSuperellipseBorder::new(
1228            side_width(20.0),
1229            Some(BorderRadius::all(Radius::circular(200.0)).into()),
1230        );
1231        assert_eq!(c10.dimensions(), EdgeInsetsGeometry::all(10.0));
1232        assert_eq!(c10.scale(2.0), c20);
1233        assert_eq!(c20.scale(0.5), c10);
1234        let as10 = ShapeBorderRef::new(c10);
1235        let as20 = ShapeBorderRef::new(c20);
1236        assert!(
1237            ShapeBorderRef::lerp(Some(&as10), Some(&as20), 0.0)
1238                .unwrap()
1239                .eq_shape(&c10)
1240        );
1241        assert!(
1242            ShapeBorderRef::lerp(Some(&as10), Some(&as20), 0.5)
1243                .unwrap()
1244                .eq_shape(&c15)
1245        );
1246        assert!(
1247            ShapeBorderRef::lerp(Some(&as10), Some(&as20), 1.0)
1248                .unwrap()
1249                .eq_shape(&c20)
1250        );
1251    }
1252}