Skip to main content

waft_painting/
box_border.rs

1//! Flutter counterpart: `painting/box_border.dart`.
2
3use std::any::Any;
4use std::fmt::{self, Debug, Formatter, Result as FmtResult};
5use std::rc::Rc;
6
7use waft_embedder::{Canvas, Paint, PaintStyle, Path, PathBuilder, Stroke};
8use waft_embedder::{Color, Offset, RRect, Radius, Rect};
9
10use crate::basic_types::TextDirection;
11use crate::border_radius::BorderRadius;
12use crate::borders::{BorderSide, BorderStyle, ShapeBorder, ShapeBorderRef, paint_border};
13use crate::draw::{draw_drrect, draw_rrect};
14use crate::edge_insets::{EdgeInsets, EdgeInsetsDirectional, EdgeInsetsGeometry};
15
16/// The shape to use when rendering a [`Border`] or `BoxDecoration`.
17///
18/// Consider using [`ShapeBorder`] subclasses directly (with `ShapeDecoration`),
19/// instead of using [`BoxShape`] and [`Border`], if the shapes will need to be
20/// interpolated or animated. The [`Border`] class cannot interpolate between
21/// different shapes.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum BoxShape {
24    /// An axis-aligned rectangle, optionally with rounded corners.
25    Rectangle,
26    /// A circle centered in the middle of the box.
27    Circle,
28}
29
30/// Base class for box borders that can paint as rectangles, circles, or rounded
31/// rectangles.
32///
33/// The only API difference that this class introduces over [`ShapeBorder`] is
34/// that its [`paint`](Self::paint) method takes additional arguments.
35pub trait BoxBorder: ShapeBorder {
36    /// The top side of this border.
37    fn top(&self) -> BorderSide;
38
39    /// The bottom side of this border.
40    fn bottom(&self) -> BorderSide;
41
42    /// Whether all four sides of the border are identical. Uniform borders are
43    /// typically more efficient to paint.
44    fn is_uniform(&self) -> bool;
45
46    /// Paints the border within the given [`Rect`] on the given [`Canvas`].
47    ///
48    /// This is an extension of the [`ShapeBorder::paint`] method. It allows
49    /// [`BoxBorder`] borders to be applied to different [`BoxShape`]s and with
50    /// different `border_radius` parameters, without changing the [`BoxBorder`]
51    /// object itself.
52    fn paint(
53        &self,
54        canvas: &mut Canvas,
55        rect: Rect,
56        text_direction: Option<TextDirection>,
57        shape: BoxShape,
58        border_radius: Option<BorderRadius>,
59    );
60}
61
62/// A [`BoxBorder`] held by value: what a Dart field or parameter typed `BoxBorder` becomes;
63/// [`ShapeBorderRef`]'s sharing and equality, for the narrower type.
64#[derive(Clone)]
65pub struct BoxBorderRef(Rc<dyn BoxBorder>);
66
67impl BoxBorderRef {
68    /// Erases a [`BoxBorder`].
69    pub fn new(border: impl BoxBorder) -> BoxBorderRef {
70        BoxBorderRef(Rc::new(border))
71    }
72
73    pub(crate) fn from_rc(border: Rc<dyn BoxBorder>) -> BoxBorderRef {
74        BoxBorderRef(border)
75    }
76
77    /// Linearly interpolate between two borders.
78    ///
79    /// If a border is null, it is treated as having four [`BorderSide::NONE`]
80    /// borders.
81    pub fn lerp(
82        a: Option<&BoxBorderRef>,
83        b: Option<&BoxBorderRef>,
84        t: f64,
85    ) -> Option<BoxBorderRef> {
86        match (a, b) {
87            (None, None) => return None,
88            (Some(a), Some(b)) if Rc::ptr_eq(&a.0, &b.0) => return Some(a.clone()),
89            _ => {}
90        }
91        let (a_ref, b_ref) = (a, b);
92        let (a, b) = (a.map(|a| &*a.0), b.map(|b| &*b.0));
93        let a_is_border = a.is_none()
94            || a.and_then(|border| border.as_any().downcast_ref::<Border>())
95                .is_some();
96        let b_is_border = b.is_none()
97            || b.and_then(|border| border.as_any().downcast_ref::<Border>())
98                .is_some();
99        if a_is_border && b_is_border {
100            return Border::lerp(
101                a.and_then(|border| border.as_any().downcast_ref::<Border>())
102                    .copied(),
103                b.and_then(|border| border.as_any().downcast_ref::<Border>())
104                    .copied(),
105                t,
106            )
107            .map(BoxBorderRef::new);
108        }
109        let a_is_directional = a.is_none()
110            || a.and_then(|border| border.as_any().downcast_ref::<BorderDirectional>())
111                .is_some();
112        let b_is_directional = b.is_none()
113            || b.and_then(|border| border.as_any().downcast_ref::<BorderDirectional>())
114                .is_some();
115        if a_is_directional && b_is_directional {
116            return BorderDirectional::lerp(
117                a.and_then(|border| border.as_any().downcast_ref::<BorderDirectional>())
118                    .copied(),
119                b.and_then(|border| border.as_any().downcast_ref::<BorderDirectional>())
120                    .copied(),
121                t,
122            )
123            .map(BoxBorderRef::new);
124        }
125        let flip = b
126            .and_then(|border| border.as_any().downcast_ref::<Border>())
127            .is_some()
128            && a.and_then(|border| border.as_any().downcast_ref::<BorderDirectional>())
129                .is_some();
130        let (a_ref, b_ref, t) = if flip {
131            (b_ref, a_ref, 1.0 - t)
132        } else {
133            (a_ref, b_ref, t)
134        };
135        let (a, b) = (a_ref.map(|a| &*a.0), b_ref.map(|b| &*b.0));
136        if let (Some(a), Some(b)) = (
137            a.and_then(|border| border.as_any().downcast_ref::<Border>())
138                .copied(),
139            b.and_then(|border| border.as_any().downcast_ref::<BorderDirectional>())
140                .copied(),
141        ) {
142            return Some(lerp_border_to_directional(a, b, t));
143        }
144        let result = b
145            .and_then(|b| b.lerp_from(a.map(|a| a as &dyn ShapeBorder), t))
146            .or_else(|| a.and_then(|a| a.lerp_to(b.map(|b| b as &dyn ShapeBorder), t)));
147        // Dart's `result as BoxBorder? ?? (t < 0.5 ? a : b)`: a lerp of two box borders that
148        // gives another kind of border is a type error.
149        match result {
150            Some(result) => Some(
151                result
152                    .as_box_border_ref()
153                    .expect("the lerp of two box borders is a BoxBorder"),
154            ),
155            None if t < 0.5 => a_ref.cloned(),
156            None => b_ref.cloned(),
157        }
158    }
159}
160
161impl<T: BoxBorder> From<T> for BoxBorderRef {
162    fn from(border: T) -> BoxBorderRef {
163        BoxBorderRef::new(border)
164    }
165}
166
167impl From<BoxBorderRef> for ShapeBorderRef {
168    fn from(border: BoxBorderRef) -> ShapeBorderRef {
169        ShapeBorderRef::from_shared(border.0)
170    }
171}
172
173impl std::ops::Deref for BoxBorderRef {
174    type Target = dyn BoxBorder;
175
176    fn deref(&self) -> &dyn BoxBorder {
177        &*self.0
178    }
179}
180
181impl PartialEq for BoxBorderRef {
182    fn eq(&self, other: &BoxBorderRef) -> bool {
183        Rc::ptr_eq(&self.0, &other.0) || self.0.eq_shape(&*other.0)
184    }
185}
186
187impl Debug for BoxBorderRef {
188    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
189        Debug::fmt(&*self.0, f)
190    }
191}
192
193/// Dart's `BoxBorder.toString`, which the inner border's [`Debug`] already renders.
194impl fmt::Display for BoxBorderRef {
195    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
196        Debug::fmt(self, f)
197    }
198}
199
200impl dyn BoxBorder {
201    /// Creates a [`Border`].
202    pub fn from_ltrb(
203        top: BorderSide,
204        right: BorderSide,
205        bottom: BorderSide,
206        left: BorderSide,
207    ) -> Border {
208        Border {
209            top,
210            right,
211            bottom,
212            left,
213        }
214    }
215
216    /// A uniform [`Border`] with all sides the same color and width.
217    pub fn all(color: Color, width: f64, style: BorderStyle, stroke_align: f64) -> Border {
218        Border::all(color, width, style, stroke_align)
219    }
220
221    /// Creates a [`Border`] whose sides are all the same.
222    pub fn from_border_side(side: BorderSide) -> Border {
223        Border::from_border_side(side)
224    }
225
226    /// Creates a [`Border`] with symmetrical vertical and horizontal sides.
227    pub fn symmetric(vertical: BorderSide, horizontal: BorderSide) -> Border {
228        Border::symmetric(vertical, horizontal)
229    }
230
231    /// Creates a [`BorderDirectional`].
232    pub fn from_steb(
233        top: BorderSide,
234        start: BorderSide,
235        end: BorderSide,
236        bottom: BorderSide,
237    ) -> BorderDirectional {
238        BorderDirectional {
239            top,
240            start,
241            end,
242            bottom,
243        }
244    }
245
246    /// Paints a Border with different widths, styles and strokeAligns, on any
247    /// borderRadius while using a single color.
248    #[allow(clippy::too_many_arguments)]
249    pub fn paint_non_uniform_border(
250        canvas: &mut Canvas,
251        rect: Rect,
252        border_radius: Option<BorderRadius>,
253        text_direction: Option<TextDirection>,
254        shape: BoxShape,
255        top: BorderSide,
256        right: BorderSide,
257        bottom: BorderSide,
258        left: BorderSide,
259        color: Color,
260    ) {
261        let border_rect = match shape {
262            BoxShape::Rectangle => border_radius
263                .unwrap_or(BorderRadius::ZERO)
264                .resolve(text_direction)
265                .to_rrect(rect),
266            BoxShape::Circle => {
267                debug_assert!(
268                    border_radius.is_none(),
269                    "A circle cannot have a border radius. Remove either the shape or the borderRadius argument."
270                );
271                RRect::from_rect_and_radius(
272                    Rect::from_circle(rect.center(), rect.shortest_side() / 2.0),
273                    Radius::circular(rect.width()),
274                )
275            }
276        };
277        let paint = Paint {
278            color: color.into(),
279            ..Paint::default()
280        };
281        let inner = EdgeInsets::from_ltrb(
282            left.stroke_inset(),
283            top.stroke_inset(),
284            right.stroke_inset(),
285            bottom.stroke_inset(),
286        )
287        .deflate_rrect(border_rect);
288        let outer = EdgeInsets::from_ltrb(
289            left.stroke_outset(),
290            top.stroke_outset(),
291            right.stroke_outset(),
292            bottom.stroke_outset(),
293        )
294        .inflate_rrect(border_rect);
295        draw_drrect(canvas, outer, inner, &paint);
296    }
297}
298
299fn lerp_border_to_directional(a: Border, b: BorderDirectional, t: f64) -> BoxBorderRef {
300    if b.start == BorderSide::NONE && b.end == BorderSide::NONE {
301        return BoxBorderRef::new(Border {
302            top: BorderSide::lerp(a.top, b.top, t),
303            right: BorderSide::lerp(a.right, BorderSide::NONE, t),
304            bottom: BorderSide::lerp(a.bottom, b.bottom, t),
305            left: BorderSide::lerp(a.left, BorderSide::NONE, t),
306        });
307    }
308    if a.left == BorderSide::NONE && a.right == BorderSide::NONE {
309        return BoxBorderRef::new(BorderDirectional {
310            top: BorderSide::lerp(a.top, b.top, t),
311            start: BorderSide::lerp(BorderSide::NONE, b.start, t),
312            end: BorderSide::lerp(BorderSide::NONE, b.end, t),
313            bottom: BorderSide::lerp(a.bottom, b.bottom, t),
314        });
315    }
316    if t < 0.5 {
317        BoxBorderRef::new(Border {
318            top: BorderSide::lerp(a.top, b.top, t),
319            right: BorderSide::lerp(a.right, BorderSide::NONE, t * 2.0),
320            bottom: BorderSide::lerp(a.bottom, b.bottom, t),
321            left: BorderSide::lerp(a.left, BorderSide::NONE, t * 2.0),
322        })
323    } else {
324        BoxBorderRef::new(BorderDirectional {
325            top: BorderSide::lerp(a.top, b.top, t),
326            start: BorderSide::lerp(BorderSide::NONE, b.start, (t - 0.5) * 2.0),
327            end: BorderSide::lerp(BorderSide::NONE, b.end, (t - 0.5) * 2.0),
328            bottom: BorderSide::lerp(a.bottom, b.bottom, t),
329        })
330    }
331}
332
333fn paint_uniform_border_with_radius(
334    canvas: &mut Canvas,
335    rect: Rect,
336    side: BorderSide,
337    border_radius: BorderRadius,
338) {
339    debug_assert!(side.style != BorderStyle::None);
340    let width = side.width;
341    if width == 0.0 {
342        let paint = Paint {
343            color: side.color.into(),
344            style: PaintStyle::Stroke(Stroke::new(0.0)),
345            ..Paint::default()
346        };
347        draw_rrect(canvas, border_radius.to_rrect(rect), &paint);
348    } else {
349        let paint = Paint {
350            color: side.color.into(),
351            ..Paint::default()
352        };
353        let border_rect = border_radius.to_rrect(rect);
354        let inner = border_rect.deflate(side.stroke_inset());
355        let outer = border_rect.inflate(side.stroke_outset());
356        draw_drrect(canvas, outer, inner, &paint);
357    }
358}
359
360fn paint_uniform_border_with_circle(canvas: &mut Canvas, rect: Rect, side: BorderSide) {
361    debug_assert!(side.style != BorderStyle::None);
362    let radius = (rect.shortest_side() + side.stroke_offset()) / 2.0;
363    canvas.draw_circle(rect.center(), radius as f32, &side.to_paint());
364}
365
366fn paint_uniform_border_with_rectangle(canvas: &mut Canvas, rect: Rect, side: BorderSide) {
367    debug_assert!(side.style != BorderStyle::None);
368    canvas.draw_rect(rect.inflate(side.stroke_offset() / 2.0), &side.to_paint());
369}
370
371fn rect_path(rect: Rect) -> Path {
372    let mut path = PathBuilder::new();
373    path.rect(rect.into());
374    path.build().into()
375}
376
377fn box_get_inner_path(
378    dimensions: EdgeInsetsGeometry,
379    rect: Rect,
380    text_direction: Option<TextDirection>,
381) -> Path {
382    debug_assert!(
383        text_direction.is_some(),
384        "The textDirection argument to getInnerPath must not be null."
385    );
386    rect_path(dimensions.resolve(text_direction).deflate_rect(rect))
387}
388
389fn box_get_outer_path(rect: Rect, text_direction: Option<TextDirection>) -> Path {
390    debug_assert!(
391        text_direction.is_some(),
392        "The textDirection argument to getOuterPath must not be null."
393    );
394    let _ = text_direction;
395    rect_path(rect)
396}
397
398/// A border of a box, comprised of four sides: top, right, bottom, left.
399#[derive(Clone, Copy, PartialEq)]
400pub struct Border {
401    /// The top side of this border.
402    pub top: BorderSide,
403    /// The right side of this border.
404    pub right: BorderSide,
405    /// The bottom side of this border.
406    pub bottom: BorderSide,
407    /// The left side of this border.
408    pub left: BorderSide,
409}
410
411impl Border {
412    /// Creates a border whose sides are all the same.
413    pub const fn from_border_side(side: BorderSide) -> Border {
414        Border {
415            top: side,
416            right: side,
417            bottom: side,
418            left: side,
419        }
420    }
421
422    /// Creates a border with symmetrical vertical and horizontal sides.
423    pub const fn symmetric(vertical: BorderSide, horizontal: BorderSide) -> Border {
424        Border {
425            left: vertical,
426            top: horizontal,
427            right: vertical,
428            bottom: horizontal,
429        }
430    }
431
432    /// A uniform border with all sides the same color and width.
433    pub fn all(color: Color, width: f64, style: BorderStyle, stroke_align: f64) -> Border {
434        Border::from_border_side(BorderSide::new(color, width, style, stroke_align))
435    }
436
437    /// Creates a [`Border`] that represents the addition of the two given
438    /// [`Border`]s.
439    pub fn merge(a: Border, b: Border) -> Border {
440        debug_assert!(BorderSide::can_merge(a.top, b.top));
441        debug_assert!(BorderSide::can_merge(a.right, b.right));
442        debug_assert!(BorderSide::can_merge(a.bottom, b.bottom));
443        debug_assert!(BorderSide::can_merge(a.left, b.left));
444        Border {
445            top: BorderSide::merge(a.top, b.top),
446            right: BorderSide::merge(a.right, b.right),
447            bottom: BorderSide::merge(a.bottom, b.bottom),
448            left: BorderSide::merge(a.left, b.left),
449        }
450    }
451
452    /// Linearly interpolate between two borders.
453    pub fn lerp(a: Option<Border>, b: Option<Border>, t: f64) -> Option<Border> {
454        if a == b {
455            return a;
456        }
457        match (a, b) {
458            (None, None) => None,
459            (None, Some(b)) => Some(b.scale(t)),
460            (Some(a), None) => Some(a.scale(1.0 - t)),
461            (Some(a), Some(b)) => Some(Border {
462                top: BorderSide::lerp(a.top, b.top, t),
463                right: BorderSide::lerp(a.right, b.right, t),
464                bottom: BorderSide::lerp(a.bottom, b.bottom, t),
465                left: BorderSide::lerp(a.left, b.left, t),
466            }),
467        }
468    }
469
470    /// Creates a copy of this border, scaled by the factor `t`.
471    pub fn scale(self, t: f64) -> Border {
472        Border {
473            top: self.top.scale(t),
474            right: self.right.scale(t),
475            bottom: self.bottom.scale(t),
476            left: self.left.scale(t),
477        }
478    }
479
480    fn color_is_uniform(self) -> bool {
481        let top_color = self.top.color;
482        self.left.color == top_color
483            && self.bottom.color == top_color
484            && self.right.color == top_color
485    }
486
487    fn width_is_uniform(self) -> bool {
488        let top_width = self.top.width;
489        self.left.width == top_width
490            && self.bottom.width == top_width
491            && self.right.width == top_width
492    }
493
494    fn style_is_uniform(self) -> bool {
495        let top_style = self.top.style;
496        self.left.style == top_style
497            && self.bottom.style == top_style
498            && self.right.style == top_style
499    }
500
501    fn stroke_align_is_uniform(self) -> bool {
502        let top_stroke_align = self.top.stroke_align;
503        self.left.stroke_align == top_stroke_align
504            && self.bottom.stroke_align == top_stroke_align
505            && self.right.stroke_align == top_stroke_align
506    }
507
508    fn distinct_visible_colors(self) -> Vec<Color> {
509        let mut colors = Vec::new();
510        for side in [self.top, self.right, self.bottom, self.left] {
511            if side.style != BorderStyle::None && !colors.contains(&side.color) {
512                colors.push(side.color);
513            }
514        }
515        colors
516    }
517
518    fn has_hairline_border(self) -> bool {
519        (self.top.style == BorderStyle::Solid && self.top.width == 0.0)
520            || (self.right.style == BorderStyle::Solid && self.right.width == 0.0)
521            || (self.bottom.style == BorderStyle::Solid && self.bottom.width == 0.0)
522            || (self.left.style == BorderStyle::Solid && self.left.width == 0.0)
523    }
524}
525
526impl Default for Border {
527    fn default() -> Border {
528        Border {
529            top: BorderSide::NONE,
530            right: BorderSide::NONE,
531            bottom: BorderSide::NONE,
532            left: BorderSide::NONE,
533        }
534    }
535}
536
537impl ShapeBorder for Border {
538    fn dimensions(&self) -> EdgeInsetsGeometry {
539        EdgeInsets::from_ltrb(
540            self.left.stroke_inset(),
541            self.top.stroke_inset(),
542            self.right.stroke_inset(),
543            self.bottom.stroke_inset(),
544        )
545        .into()
546    }
547
548    fn add(&self, other: &ShapeBorderRef, _reversed: bool) -> Option<ShapeBorderRef> {
549        other.as_any().downcast_ref::<Border>().and_then(|other| {
550            if BorderSide::can_merge(self.top, other.top)
551                && BorderSide::can_merge(self.right, other.right)
552                && BorderSide::can_merge(self.bottom, other.bottom)
553                && BorderSide::can_merge(self.left, other.left)
554            {
555                Some(ShapeBorderRef::new(Border::merge(*self, *other)))
556            } else {
557                None
558            }
559        })
560    }
561
562    fn scale(&self, t: f64) -> ShapeBorderRef {
563        ShapeBorderRef::new(Border::scale(*self, t))
564    }
565
566    fn lerp_from(&self, a: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
567        if let Some(a) = a.and_then(|a| a.as_any().downcast_ref::<Border>()) {
568            Border::lerp(Some(*a), Some(*self), t).map(|border| ShapeBorderRef::new(border) as _)
569        } else if a.is_none() {
570            Some(ShapeBorderRef::new(Border::scale(*self, t)))
571        } else {
572            None
573        }
574    }
575
576    fn lerp_to(&self, b: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
577        if let Some(b) = b.and_then(|b| b.as_any().downcast_ref::<Border>()) {
578            Border::lerp(Some(*self), Some(*b), t).map(|border| ShapeBorderRef::new(border) as _)
579        } else if b.is_none() {
580            Some(ShapeBorderRef::new(Border::scale(*self, 1.0 - t)))
581        } else {
582            None
583        }
584    }
585
586    fn get_outer_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
587        box_get_outer_path(rect, text_direction)
588    }
589
590    fn get_inner_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
591        box_get_inner_path(self.dimensions(), rect, text_direction)
592    }
593
594    fn hit_test(
595        &self,
596        rect: Rect,
597        position: Offset,
598        _text_direction: Option<TextDirection>,
599    ) -> bool {
600        rect.contains(position)
601    }
602
603    fn paint_interior(
604        &self,
605        canvas: &mut Canvas,
606        rect: Rect,
607        paint: &Paint,
608        _text_direction: Option<TextDirection>,
609    ) {
610        canvas.draw_rect(rect, paint);
611    }
612
613    fn prefer_paint_interior(&self) -> bool {
614        true
615    }
616
617    fn paint(&self, canvas: &mut Canvas, rect: Rect, text_direction: Option<TextDirection>) {
618        <Self as BoxBorder>::paint(
619            self,
620            canvas,
621            rect,
622            text_direction,
623            BoxShape::Rectangle,
624            None,
625        );
626    }
627
628    fn as_any(&self) -> &dyn Any {
629        self
630    }
631
632    fn as_box_border(&self) -> Option<&dyn BoxBorder> {
633        Some(self)
634    }
635
636    fn into_box_border(self: Rc<Self>) -> Option<Rc<dyn BoxBorder>> {
637        Some(self)
638    }
639
640    fn eq_shape(&self, other: &dyn ShapeBorder) -> bool {
641        other
642            .as_any()
643            .downcast_ref::<Border>()
644            .is_some_and(|other| other == self)
645    }
646}
647
648impl BoxBorder for Border {
649    fn top(&self) -> BorderSide {
650        self.top
651    }
652
653    fn bottom(&self) -> BorderSide {
654        self.bottom
655    }
656
657    fn is_uniform(&self) -> bool {
658        self.color_is_uniform()
659            && self.width_is_uniform()
660            && self.style_is_uniform()
661            && self.stroke_align_is_uniform()
662    }
663
664    fn paint(
665        &self,
666        canvas: &mut Canvas,
667        rect: Rect,
668        text_direction: Option<TextDirection>,
669        shape: BoxShape,
670        border_radius: Option<BorderRadius>,
671    ) {
672        if self.is_uniform() {
673            match self.top.style {
674                BorderStyle::None => return,
675                BorderStyle::Solid => {
676                    match shape {
677                        BoxShape::Circle => {
678                            debug_assert!(
679                                border_radius.is_none(),
680                                "A circle cannot have a border radius. Remove either the shape or the borderRadius argument."
681                            );
682                            paint_uniform_border_with_circle(canvas, rect, self.top);
683                        }
684                        BoxShape::Rectangle => {
685                            if let Some(border_radius) = border_radius
686                                && border_radius != BorderRadius::ZERO
687                            {
688                                paint_uniform_border_with_radius(
689                                    canvas,
690                                    rect,
691                                    self.top,
692                                    border_radius,
693                                );
694                                return;
695                            }
696                            paint_uniform_border_with_rectangle(canvas, rect, self.top);
697                        }
698                    }
699                    return;
700                }
701            }
702        }
703
704        if self.style_is_uniform() && self.top.style == BorderStyle::None {
705            return;
706        }
707
708        let visible_colors = self.distinct_visible_colors();
709        let has_hairline_border = self.has_hairline_border();
710        if visible_colors.len() == 1
711            && !has_hairline_border
712            && (shape == BoxShape::Circle
713                || border_radius.is_some_and(|radius| radius != BorderRadius::ZERO))
714        {
715            <dyn BoxBorder>::paint_non_uniform_border(
716                canvas,
717                rect,
718                border_radius,
719                text_direction,
720                shape,
721                if self.top.style == BorderStyle::None {
722                    BorderSide::NONE
723                } else {
724                    self.top
725                },
726                if self.right.style == BorderStyle::None {
727                    BorderSide::NONE
728                } else {
729                    self.right
730                },
731                if self.bottom.style == BorderStyle::None {
732                    BorderSide::NONE
733                } else {
734                    self.bottom
735                },
736                if self.left.style == BorderStyle::None {
737                    BorderSide::NONE
738                } else {
739                    self.left
740                },
741                visible_colors[0],
742            );
743            return;
744        }
745
746        if cfg!(debug_assertions) {
747            if has_hairline_border {
748                debug_assert!(
749                    border_radius.is_none() || border_radius == Some(BorderRadius::ZERO),
750                    "A hairline border like `BorderSide(width: 0.0, style: BorderStyle.solid)` can only be drawn when BorderRadius is zero or null."
751                );
752            }
753            if border_radius.is_some_and(|radius| radius != BorderRadius::ZERO) {
754                panic!("A borderRadius can only be given on borders with uniform colors.");
755            }
756            if shape != BoxShape::Rectangle {
757                panic!("A Border can only be drawn as a circle on borders with uniform colors.");
758            }
759            if !self.stroke_align_is_uniform()
760                || self.top.stroke_align != BorderSide::STROKE_ALIGN_INSIDE
761            {
762                panic!(
763                    "A Border can only draw strokeAlign different than BorderSide.strokeAlignInside on borders with uniform colors."
764                );
765            }
766        }
767
768        paint_border(canvas, rect, self.top, self.right, self.bottom, self.left);
769    }
770}
771
772impl Debug for Border {
773    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
774        if self.is_uniform() {
775            return write!(f, "Border.all({:?})", self.top);
776        }
777        let mut arguments = Vec::new();
778        if self.top != BorderSide::NONE {
779            arguments.push(format!("top: {:?}", self.top));
780        }
781        if self.right != BorderSide::NONE {
782            arguments.push(format!("right: {:?}", self.right));
783        }
784        if self.bottom != BorderSide::NONE {
785            arguments.push(format!("bottom: {:?}", self.bottom));
786        }
787        if self.left != BorderSide::NONE {
788            arguments.push(format!("left: {:?}", self.left));
789        }
790        write!(f, "Border({})", arguments.join(", "))
791    }
792}
793
794/// A border of a box, comprised of four sides, the lateral sides of which
795/// flip over based on the reading direction.
796#[derive(Clone, Copy, PartialEq)]
797pub struct BorderDirectional {
798    /// The top side of this border.
799    pub top: BorderSide,
800    /// The start side of this border.
801    pub start: BorderSide,
802    /// The end side of this border.
803    pub end: BorderSide,
804    /// The bottom side of this border.
805    pub bottom: BorderSide,
806}
807
808impl BorderDirectional {
809    /// Creates a [`BorderDirectional`] that represents the addition of the two
810    /// given [`BorderDirectional`]s.
811    pub fn merge(a: BorderDirectional, b: BorderDirectional) -> BorderDirectional {
812        debug_assert!(BorderSide::can_merge(a.top, b.top));
813        debug_assert!(BorderSide::can_merge(a.start, b.start));
814        debug_assert!(BorderSide::can_merge(a.end, b.end));
815        debug_assert!(BorderSide::can_merge(a.bottom, b.bottom));
816        BorderDirectional {
817            top: BorderSide::merge(a.top, b.top),
818            start: BorderSide::merge(a.start, b.start),
819            end: BorderSide::merge(a.end, b.end),
820            bottom: BorderSide::merge(a.bottom, b.bottom),
821        }
822    }
823
824    /// Linearly interpolate between two borders.
825    pub fn lerp(
826        a: Option<BorderDirectional>,
827        b: Option<BorderDirectional>,
828        t: f64,
829    ) -> Option<BorderDirectional> {
830        if a == b {
831            return a;
832        }
833        match (a, b) {
834            (None, None) => None,
835            (None, Some(b)) => Some(b.scale(t)),
836            (Some(a), None) => Some(a.scale(1.0 - t)),
837            (Some(a), Some(b)) => Some(BorderDirectional {
838                top: BorderSide::lerp(a.top, b.top, t),
839                end: BorderSide::lerp(a.end, b.end, t),
840                bottom: BorderSide::lerp(a.bottom, b.bottom, t),
841                start: BorderSide::lerp(a.start, b.start, t),
842            }),
843        }
844    }
845
846    /// Creates a copy of this border, scaled by the factor `t`.
847    pub fn scale(self, t: f64) -> BorderDirectional {
848        BorderDirectional {
849            top: self.top.scale(t),
850            start: self.start.scale(t),
851            end: self.end.scale(t),
852            bottom: self.bottom.scale(t),
853        }
854    }
855
856    fn color_is_uniform(self) -> bool {
857        let top_color = self.top.color;
858        self.start.color == top_color
859            && self.bottom.color == top_color
860            && self.end.color == top_color
861    }
862
863    fn width_is_uniform(self) -> bool {
864        let top_width = self.top.width;
865        self.start.width == top_width
866            && self.bottom.width == top_width
867            && self.end.width == top_width
868    }
869
870    fn style_is_uniform(self) -> bool {
871        let top_style = self.top.style;
872        self.start.style == top_style
873            && self.bottom.style == top_style
874            && self.end.style == top_style
875    }
876
877    fn stroke_align_is_uniform(self) -> bool {
878        let top_stroke_align = self.top.stroke_align;
879        self.start.stroke_align == top_stroke_align
880            && self.bottom.stroke_align == top_stroke_align
881            && self.end.stroke_align == top_stroke_align
882    }
883
884    fn distinct_visible_colors(self) -> Vec<Color> {
885        let mut colors = Vec::new();
886        for side in [self.top, self.end, self.bottom, self.start] {
887            if side.style != BorderStyle::None && !colors.contains(&side.color) {
888                colors.push(side.color);
889            }
890        }
891        colors
892    }
893
894    fn has_hairline_border(self) -> bool {
895        (self.top.style == BorderStyle::Solid && self.top.width == 0.0)
896            || (self.end.style == BorderStyle::Solid && self.end.width == 0.0)
897            || (self.bottom.style == BorderStyle::Solid && self.bottom.width == 0.0)
898            || (self.start.style == BorderStyle::Solid && self.start.width == 0.0)
899    }
900}
901
902impl Default for BorderDirectional {
903    fn default() -> BorderDirectional {
904        BorderDirectional {
905            top: BorderSide::NONE,
906            start: BorderSide::NONE,
907            end: BorderSide::NONE,
908            bottom: BorderSide::NONE,
909        }
910    }
911}
912
913impl ShapeBorder for BorderDirectional {
914    fn dimensions(&self) -> EdgeInsetsGeometry {
915        EdgeInsetsDirectional::from_steb(
916            self.start.stroke_inset(),
917            self.top.stroke_inset(),
918            self.end.stroke_inset(),
919            self.bottom.stroke_inset(),
920        )
921        .into()
922    }
923
924    fn add(&self, other: &ShapeBorderRef, _reversed: bool) -> Option<ShapeBorderRef> {
925        if let Some(typed_other) = other.as_any().downcast_ref::<BorderDirectional>() {
926            if BorderSide::can_merge(self.top, typed_other.top)
927                && BorderSide::can_merge(self.start, typed_other.start)
928                && BorderSide::can_merge(self.end, typed_other.end)
929                && BorderSide::can_merge(self.bottom, typed_other.bottom)
930            {
931                return Some(ShapeBorderRef::new(BorderDirectional::merge(
932                    *self,
933                    *typed_other,
934                )));
935            }
936            return None;
937        }
938        if let Some(typed_other) = other.as_any().downcast_ref::<Border>() {
939            if !BorderSide::can_merge(typed_other.top, self.top)
940                || !BorderSide::can_merge(typed_other.bottom, self.bottom)
941            {
942                return None;
943            }
944            if self.start != BorderSide::NONE || self.end != BorderSide::NONE {
945                if typed_other.left != BorderSide::NONE || typed_other.right != BorderSide::NONE {
946                    return None;
947                }
948                debug_assert_eq!(typed_other.left, BorderSide::NONE);
949                debug_assert_eq!(typed_other.right, BorderSide::NONE);
950                return Some(ShapeBorderRef::new(BorderDirectional {
951                    top: BorderSide::merge(typed_other.top, self.top),
952                    start: self.start,
953                    end: self.end,
954                    bottom: BorderSide::merge(typed_other.bottom, self.bottom),
955                }) as _);
956            }
957            debug_assert_eq!(self.start, BorderSide::NONE);
958            debug_assert_eq!(self.end, BorderSide::NONE);
959            return Some(ShapeBorderRef::new(Border {
960                top: BorderSide::merge(typed_other.top, self.top),
961                right: typed_other.right,
962                bottom: BorderSide::merge(typed_other.bottom, self.bottom),
963                left: typed_other.left,
964            }) as _);
965        }
966        None
967    }
968
969    fn scale(&self, t: f64) -> ShapeBorderRef {
970        ShapeBorderRef::new(BorderDirectional::scale(*self, t))
971    }
972
973    fn lerp_from(&self, a: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
974        if let Some(a) = a.and_then(|a| a.as_any().downcast_ref::<BorderDirectional>()) {
975            BorderDirectional::lerp(Some(*a), Some(*self), t)
976                .map(|border| ShapeBorderRef::new(border) as _)
977        } else if a.is_none() {
978            Some(ShapeBorderRef::new(BorderDirectional::scale(*self, t)))
979        } else {
980            None
981        }
982    }
983
984    fn lerp_to(&self, b: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
985        if let Some(b) = b.and_then(|b| b.as_any().downcast_ref::<BorderDirectional>()) {
986            BorderDirectional::lerp(Some(*self), Some(*b), t)
987                .map(|border| ShapeBorderRef::new(border) as _)
988        } else if b.is_none() {
989            Some(ShapeBorderRef::new(BorderDirectional::scale(
990                *self,
991                1.0 - t,
992            )))
993        } else {
994            None
995        }
996    }
997
998    fn get_outer_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
999        box_get_outer_path(rect, text_direction)
1000    }
1001
1002    fn get_inner_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
1003        box_get_inner_path(self.dimensions(), rect, text_direction)
1004    }
1005
1006    fn hit_test(
1007        &self,
1008        rect: Rect,
1009        position: Offset,
1010        _text_direction: Option<TextDirection>,
1011    ) -> bool {
1012        rect.contains(position)
1013    }
1014
1015    fn paint_interior(
1016        &self,
1017        canvas: &mut Canvas,
1018        rect: Rect,
1019        paint: &Paint,
1020        _text_direction: Option<TextDirection>,
1021    ) {
1022        canvas.draw_rect(rect, paint);
1023    }
1024
1025    fn prefer_paint_interior(&self) -> bool {
1026        true
1027    }
1028
1029    fn paint(&self, canvas: &mut Canvas, rect: Rect, text_direction: Option<TextDirection>) {
1030        <Self as BoxBorder>::paint(
1031            self,
1032            canvas,
1033            rect,
1034            text_direction,
1035            BoxShape::Rectangle,
1036            None,
1037        );
1038    }
1039
1040    fn as_any(&self) -> &dyn Any {
1041        self
1042    }
1043
1044    fn as_box_border(&self) -> Option<&dyn BoxBorder> {
1045        Some(self)
1046    }
1047
1048    fn into_box_border(self: Rc<Self>) -> Option<Rc<dyn BoxBorder>> {
1049        Some(self)
1050    }
1051
1052    fn eq_shape(&self, other: &dyn ShapeBorder) -> bool {
1053        other
1054            .as_any()
1055            .downcast_ref::<BorderDirectional>()
1056            .is_some_and(|other| other == self)
1057    }
1058}
1059
1060impl BoxBorder for BorderDirectional {
1061    fn top(&self) -> BorderSide {
1062        self.top
1063    }
1064
1065    fn bottom(&self) -> BorderSide {
1066        self.bottom
1067    }
1068
1069    fn is_uniform(&self) -> bool {
1070        self.color_is_uniform()
1071            && self.width_is_uniform()
1072            && self.style_is_uniform()
1073            && self.stroke_align_is_uniform()
1074    }
1075
1076    fn paint(
1077        &self,
1078        canvas: &mut Canvas,
1079        rect: Rect,
1080        text_direction: Option<TextDirection>,
1081        shape: BoxShape,
1082        border_radius: Option<BorderRadius>,
1083    ) {
1084        if self.is_uniform() {
1085            match self.top.style {
1086                BorderStyle::None => return,
1087                BorderStyle::Solid => {
1088                    match shape {
1089                        BoxShape::Circle => {
1090                            debug_assert!(
1091                                border_radius.is_none(),
1092                                "A circle cannot have a border radius. Remove either the shape or the borderRadius argument."
1093                            );
1094                            paint_uniform_border_with_circle(canvas, rect, self.top);
1095                        }
1096                        BoxShape::Rectangle => {
1097                            if let Some(border_radius) = border_radius
1098                                && border_radius != BorderRadius::ZERO
1099                            {
1100                                paint_uniform_border_with_radius(
1101                                    canvas,
1102                                    rect,
1103                                    self.top,
1104                                    border_radius,
1105                                );
1106                                return;
1107                            }
1108                            paint_uniform_border_with_rectangle(canvas, rect, self.top);
1109                        }
1110                    }
1111                    return;
1112                }
1113            }
1114        }
1115
1116        if self.style_is_uniform() && self.top.style == BorderStyle::None {
1117            return;
1118        }
1119
1120        debug_assert!(
1121            text_direction.is_some(),
1122            "Non-uniform BorderDirectional objects require a TextDirection when painting."
1123        );
1124        let (left, right) = match text_direction.unwrap() {
1125            TextDirection::Rtl => (self.end, self.start),
1126            TextDirection::Ltr => (self.start, self.end),
1127        };
1128
1129        let visible_colors = self.distinct_visible_colors();
1130        let has_hairline_border = self.has_hairline_border();
1131        if visible_colors.len() == 1
1132            && !has_hairline_border
1133            && (shape == BoxShape::Circle
1134                || border_radius.is_some_and(|radius| radius != BorderRadius::ZERO))
1135        {
1136            <dyn BoxBorder>::paint_non_uniform_border(
1137                canvas,
1138                rect,
1139                border_radius,
1140                text_direction,
1141                shape,
1142                if self.top.style == BorderStyle::None {
1143                    BorderSide::NONE
1144                } else {
1145                    self.top
1146                },
1147                if right.style == BorderStyle::None {
1148                    BorderSide::NONE
1149                } else {
1150                    right
1151                },
1152                if self.bottom.style == BorderStyle::None {
1153                    BorderSide::NONE
1154                } else {
1155                    self.bottom
1156                },
1157                if left.style == BorderStyle::None {
1158                    BorderSide::NONE
1159                } else {
1160                    left
1161                },
1162                visible_colors[0],
1163            );
1164            return;
1165        }
1166
1167        if has_hairline_border {
1168            debug_assert!(
1169                border_radius.is_none() || border_radius == Some(BorderRadius::ZERO),
1170                "A side like `BorderSide(width: 0.0, style: BorderStyle.solid)` can only be drawn when BorderRadius is zero or null."
1171            );
1172        }
1173        debug_assert!(
1174            border_radius.is_none(),
1175            "A borderRadius can only be given for borders with uniform colors."
1176        );
1177        debug_assert!(
1178            shape == BoxShape::Rectangle,
1179            "A Border can only be drawn as a circle on borders with uniform colors."
1180        );
1181        debug_assert!(
1182            self.stroke_align_is_uniform()
1183                && self.top.stroke_align == BorderSide::STROKE_ALIGN_INSIDE,
1184            "A Border can only draw strokeAlign different than strokeAlignInside on borders with uniform colors."
1185        );
1186
1187        paint_border(canvas, rect, self.top, right, self.bottom, left);
1188    }
1189}
1190
1191impl Debug for BorderDirectional {
1192    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
1193        let mut arguments = Vec::new();
1194        if self.top != BorderSide::NONE {
1195            arguments.push(format!("top: {:?}", self.top));
1196        }
1197        if self.start != BorderSide::NONE {
1198            arguments.push(format!("start: {:?}", self.start));
1199        }
1200        if self.end != BorderSide::NONE {
1201            arguments.push(format!("end: {:?}", self.end));
1202        }
1203        if self.bottom != BorderSide::NONE {
1204            arguments.push(format!("bottom: {:?}", self.bottom));
1205        }
1206        write!(f, "BorderDirectional({})", arguments.join(", "))
1207    }
1208}
1209
1210/// Dart's `BoxShape.toString`: the enum's type and name.
1211impl std::fmt::Display for BoxShape {
1212    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1213        match self {
1214            BoxShape::Rectangle => f.write_str("BoxShape.rectangle"),
1215            BoxShape::Circle => f.write_str("BoxShape.circle"),
1216        }
1217    }
1218}
1219
1220#[cfg(test)]
1221mod tests {
1222    use super::*;
1223    use std::any::Any;
1224
1225    use waft_embedder::Color;
1226
1227    use crate::edge_insets::EdgeInsetsGeometry;
1228
1229    fn width(w: f64) -> BorderSide {
1230        BorderSide {
1231            width: w,
1232            ..BorderSide::default()
1233        }
1234    }
1235
1236    fn color_width(color: u32, w: f64) -> BorderSide {
1237        BorderSide {
1238            color: Color::new(color),
1239            width: w,
1240            ..BorderSide::default()
1241        }
1242    }
1243
1244    fn border_all(w: f64) -> Border {
1245        Border::all(
1246            Color::new(0xFF000000),
1247            w,
1248            BorderStyle::Solid,
1249            BorderSide::STROKE_ALIGN_INSIDE,
1250        )
1251    }
1252
1253    fn none_scaled() -> Border {
1254        Border::all(
1255            Color::new(0xFF000000),
1256            0.0,
1257            BorderStyle::None,
1258            BorderSide::STROKE_ALIGN_INSIDE,
1259        )
1260    }
1261
1262    fn plus(a: &(impl ShapeBorder + Copy), b: &(impl ShapeBorder + Copy)) -> ShapeBorderRef {
1263        ShapeBorderRef::new(*a).plus(&ShapeBorderRef::new(*b))
1264    }
1265
1266    fn expect_border(got: Option<BoxBorderRef>, expected: Border) {
1267        let got = got.expect("expected a border");
1268        let got = got
1269            .as_any()
1270            .downcast_ref::<Border>()
1271            .unwrap_or_else(|| panic!("expected Border, got {got:?}"));
1272        assert_eq!(*got, expected);
1273    }
1274
1275    fn expect_directional(got: Option<BoxBorderRef>, expected: BorderDirectional) {
1276        let got = got.expect("expected a border");
1277        let got = got
1278            .as_any()
1279            .downcast_ref::<BorderDirectional>()
1280            .unwrap_or_else(|| panic!("expected BorderDirectional, got {got:?}"));
1281        assert_eq!(*got, expected);
1282    }
1283
1284    fn contains(path: &Path, x: f64, y: f64) -> bool {
1285        path.contains(Offset::new(x, y))
1286    }
1287
1288    #[derive(Clone, Copy, Debug)]
1289    struct SillyBorder;
1290
1291    impl ShapeBorder for SillyBorder {
1292        fn dimensions(&self) -> EdgeInsetsGeometry {
1293            EdgeInsetsGeometry::ZERO
1294        }
1295
1296        fn scale(&self, _t: f64) -> ShapeBorderRef {
1297            ShapeBorderRef::new(*self)
1298        }
1299
1300        fn get_outer_path(&self, rect: Rect, _text_direction: Option<TextDirection>) -> Path {
1301            rect_path(rect)
1302        }
1303
1304        fn get_inner_path(&self, rect: Rect, _text_direction: Option<TextDirection>) -> Path {
1305            rect_path(rect)
1306        }
1307
1308        fn paint(&self, _canvas: &mut Canvas, _rect: Rect, _text_direction: Option<TextDirection>) {
1309        }
1310
1311        fn as_any(&self) -> &dyn Any {
1312            self
1313        }
1314
1315        fn as_box_border(&self) -> Option<&dyn BoxBorder> {
1316            Some(self)
1317        }
1318
1319        fn into_box_border(self: Rc<Self>) -> Option<Rc<dyn BoxBorder>> {
1320            Some(self)
1321        }
1322
1323        fn eq_shape(&self, other: &dyn ShapeBorder) -> bool {
1324            other.as_any().downcast_ref::<SillyBorder>().is_some()
1325        }
1326    }
1327
1328    impl BoxBorder for SillyBorder {
1329        fn top(&self) -> BorderSide {
1330            BorderSide::NONE
1331        }
1332
1333        fn bottom(&self) -> BorderSide {
1334            BorderSide::NONE
1335        }
1336
1337        fn is_uniform(&self) -> bool {
1338            true
1339        }
1340
1341        fn paint(
1342            &self,
1343            _canvas: &mut Canvas,
1344            _rect: Rect,
1345            _text_direction: Option<TextDirection>,
1346            _shape: BoxShape,
1347            _border_radius: Option<BorderRadius>,
1348        ) {
1349        }
1350    }
1351
1352    #[test]
1353    fn from_border_side_and_symmetric() {
1354        let side = BorderSide::default();
1355        let border = Border::from_border_side(side);
1356        assert_eq!(border.left, side);
1357        assert_eq!(border.top, side);
1358        assert_eq!(border.right, side);
1359        assert_eq!(border.bottom, side);
1360
1361        let side1 = BorderSide {
1362            color: Color::new(0xFFFFFFFF),
1363            ..BorderSide::default()
1364        };
1365        let side2 = BorderSide::default();
1366        let border = Border::symmetric(side1, side2);
1367        assert_eq!(border.left, side1);
1368        assert_eq!(border.top, side2);
1369        assert_eq!(border.right, side1);
1370        assert_eq!(border.bottom, side2);
1371    }
1372
1373    #[test]
1374    fn merge_add_scale() {
1375        let magenta3 = color_width(0xFFFF00FF, 3.0);
1376        let magenta6 = color_width(0xFFFF00FF, 6.0);
1377        let yellow2 = color_width(0xFFFFFF00, 2.0);
1378        let yellow_none0 = BorderSide {
1379            color: Color::new(0xFFFFFF00),
1380            width: 0.0,
1381            style: BorderStyle::None,
1382            ..BorderSide::default()
1383        };
1384        assert_eq!(
1385            Border::merge(
1386                Border {
1387                    top: yellow2,
1388                    ..Border::default()
1389                },
1390                Border {
1391                    right: magenta3,
1392                    ..Border::default()
1393                }
1394            ),
1395            Border {
1396                top: yellow2,
1397                right: magenta3,
1398                ..Border::default()
1399            }
1400        );
1401        assert_eq!(
1402            Border::merge(
1403                Border {
1404                    bottom: magenta3,
1405                    ..Border::default()
1406                },
1407                Border {
1408                    bottom: magenta3,
1409                    ..Border::default()
1410                }
1411            ),
1412            Border {
1413                bottom: magenta6,
1414                ..Border::default()
1415            }
1416        );
1417        assert_eq!(
1418            plus(
1419                &Border {
1420                    top: yellow2,
1421                    ..Border::default()
1422                },
1423                &Border {
1424                    right: magenta3,
1425                    ..Border::default()
1426                }
1427            )
1428            .as_any()
1429            .downcast_ref::<Border>()
1430            .copied()
1431            .unwrap(),
1432            Border {
1433                top: yellow2,
1434                right: magenta3,
1435                ..Border::default()
1436            }
1437        );
1438        assert!(
1439            plus(
1440                &Border {
1441                    left: magenta3,
1442                    ..Border::default()
1443                },
1444                &Border {
1445                    left: yellow2,
1446                    ..Border::default()
1447                }
1448            )
1449            .as_any()
1450            .downcast_ref::<Border>()
1451            .is_none()
1452        );
1453
1454        let b3 = Border {
1455            left: magenta3,
1456            ..Border::default()
1457        };
1458        let b6 = Border {
1459            left: magenta6,
1460            ..Border::default()
1461        };
1462        assert_eq!(b3.scale(2.0), b6);
1463        let b_y0 = Border {
1464            top: yellow_none0,
1465            ..Border::default()
1466        };
1467        assert_eq!(b_y0.scale(3.0), b_y0);
1468        let b_y2 = Border {
1469            top: yellow2,
1470            ..Border::default()
1471        };
1472        assert_eq!(b_y2.scale(0.0), b_y0);
1473    }
1474
1475    #[test]
1476    #[should_panic]
1477    fn merge_conflicting_colors_panics() {
1478        let magenta3 = color_width(0xFFFF00FF, 3.0);
1479        let yellow2 = color_width(0xFFFFFF00, 2.0);
1480        let _ = Border::merge(
1481            Border {
1482                left: magenta3,
1483                ..Border::default()
1484            },
1485            Border {
1486                left: yellow2,
1487                ..Border::default()
1488            },
1489        );
1490    }
1491
1492    #[test]
1493    fn dimensions_and_is_uniform() {
1494        assert_eq!(
1495            Border {
1496                left: width(2.0),
1497                top: width(3.0),
1498                bottom: width(5.0),
1499                right: width(7.0),
1500            }
1501            .dimensions(),
1502            EdgeInsets::from_ltrb(2.0, 3.0, 7.0, 5.0).into()
1503        );
1504        assert!(
1505            !Border {
1506                left: width(3.0),
1507                top: width(3.0),
1508                right: width(3.0),
1509                bottom: width(3.1),
1510            }
1511            .is_uniform()
1512        );
1513        assert!(
1514            Border {
1515                left: width(3.0),
1516                top: width(3.0),
1517                right: width(3.0),
1518                bottom: width(3.0),
1519            }
1520            .is_uniform()
1521        );
1522        assert!(Border::default().is_uniform());
1523
1524        let inside = border_all(10.0);
1525        assert_eq!(inside.dimensions(), EdgeInsets::all(10.0).into());
1526        let center = Border::all(
1527            Color::new(0xFF000000),
1528            10.0,
1529            BorderStyle::Solid,
1530            BorderSide::STROKE_ALIGN_CENTER,
1531        );
1532        assert_eq!(center.dimensions(), EdgeInsets::all(5.0).into());
1533        let outside = Border::all(
1534            Color::new(0xFF000000),
1535            10.0,
1536            BorderStyle::Solid,
1537            BorderSide::STROKE_ALIGN_OUTSIDE,
1538        );
1539        assert_eq!(outside.dimensions(), EdgeInsets::ZERO.into());
1540    }
1541
1542    #[test]
1543    fn lerp() {
1544        let visual_with_top10 = Border {
1545            top: width(10.0),
1546            ..Border::default()
1547        };
1548        let at_minus100 = Border {
1549            left: width(0.0),
1550            right: width(300.0),
1551            ..Border::default()
1552        };
1553        let at0 = Border {
1554            left: width(100.0),
1555            right: width(200.0),
1556            ..Border::default()
1557        };
1558        let at25 = Border {
1559            left: width(125.0),
1560            right: width(175.0),
1561            ..Border::default()
1562        };
1563        let at75 = Border {
1564            left: width(175.0),
1565            right: width(125.0),
1566            ..Border::default()
1567        };
1568        let at100 = Border {
1569            left: width(200.0),
1570            right: width(100.0),
1571            ..Border::default()
1572        };
1573        let at200 = Border {
1574            left: width(300.0),
1575            right: width(0.0),
1576            ..Border::default()
1577        };
1578
1579        assert!(Border::lerp(None, None, -1.0).is_none());
1580        assert_eq!(
1581            Border::lerp(Some(visual_with_top10), None, -1.0),
1582            Some(Border {
1583                top: width(20.0),
1584                ..Border::default()
1585            })
1586        );
1587        assert_eq!(
1588            Border::lerp(None, Some(visual_with_top10), -1.0),
1589            Some(Border::default())
1590        );
1591        assert_eq!(
1592            Border::lerp(Some(at0), Some(at100), -1.0),
1593            Some(at_minus100)
1594        );
1595        assert_eq!(Border::lerp(Some(at0), Some(at100), 0.25), Some(at25));
1596        assert_eq!(Border::lerp(Some(at0), Some(at100), 0.75), Some(at75));
1597        assert_eq!(Border::lerp(Some(at0), Some(at100), 2.0), Some(at200));
1598    }
1599
1600    #[test]
1601    #[should_panic(
1602        expected = "A Border can only draw strokeAlign different than BorderSide.strokeAlignInside on borders with uniform colors."
1603    )]
1604    fn paint_nonuniform_stroke_align_panics() {
1605        let mut canvas = Canvas::new();
1606        ShapeBorder::paint(
1607            &Border {
1608                left: BorderSide {
1609                    stroke_align: BorderSide::STROKE_ALIGN_CENTER,
1610                    color: Color::new(0xFF000001),
1611                    ..BorderSide::default()
1612                },
1613                right: BorderSide {
1614                    stroke_align: BorderSide::STROKE_ALIGN_OUTSIDE,
1615                    color: Color::new(0xFF000002),
1616                    ..BorderSide::default()
1617                },
1618                ..Border::default()
1619            },
1620            &mut canvas,
1621            Rect::from_ltwh(10.0, 20.0, 30.0, 40.0),
1622            None,
1623        );
1624    }
1625
1626    #[test]
1627    fn factories() {
1628        let side1 = BorderSide::default();
1629        let side2 = width(2.0);
1630        let side3 = width(3.0);
1631        let side4 = width(4.0);
1632        assert_eq!(
1633            <dyn BoxBorder>::from_ltrb(side2, side3, side4, side1),
1634            Border {
1635                left: side1,
1636                top: side2,
1637                right: side3,
1638                bottom: side4,
1639            }
1640        );
1641        assert_eq!(
1642            <dyn BoxBorder>::all(
1643                Color::new(0xFF000000),
1644                4.0,
1645                BorderStyle::Solid,
1646                BorderSide::STROKE_ALIGN_INSIDE,
1647            ),
1648            border_all(4.0)
1649        );
1650        assert_eq!(
1651            <dyn BoxBorder>::from_border_side(side3),
1652            Border::from_border_side(side3)
1653        );
1654        assert_eq!(
1655            <dyn BoxBorder>::symmetric(side3, side2),
1656            Border::symmetric(side3, side2)
1657        );
1658        assert_eq!(
1659            <dyn BoxBorder>::from_steb(side2, side1, side3, side4),
1660            BorderDirectional {
1661                start: side1,
1662                top: side2,
1663                end: side3,
1664                bottom: side4,
1665            }
1666        );
1667    }
1668
1669    #[test]
1670    fn box_border_lerp_null_and_mixed() {
1671        let directional_with_top10 = BorderDirectional {
1672            top: width(10.0),
1673            ..BorderDirectional::default()
1674        };
1675        let visual_with_top100 = Border {
1676            top: width(100.0),
1677            ..Border::default()
1678        };
1679        let visual_with_top10 = Border {
1680            top: width(10.0),
1681            ..Border::default()
1682        };
1683        assert!(BoxBorderRef::lerp(None, None, -1.0).is_none());
1684        expect_border(
1685            BoxBorderRef::lerp(Some(&BoxBorderRef::new(border_all(10.0))), None, -1.0),
1686            border_all(20.0),
1687        );
1688        expect_border(
1689            BoxBorderRef::lerp(None, Some(&BoxBorderRef::new(border_all(10.0))), -1.0),
1690            none_scaled(),
1691        );
1692        expect_directional(
1693            BoxBorderRef::lerp(Some(&BoxBorderRef::new(directional_with_top10)), None, -1.0),
1694            BorderDirectional {
1695                top: width(20.0),
1696                ..BorderDirectional::default()
1697            },
1698        );
1699        expect_border(
1700            BoxBorderRef::lerp(
1701                Some(&BoxBorderRef::new(directional_with_top10)),
1702                Some(&BoxBorderRef::new(visual_with_top100)),
1703                -1.0,
1704            ),
1705            Border::default(),
1706        );
1707        expect_border(
1708            BoxBorderRef::lerp(
1709                Some(&BoxBorderRef::new(directional_with_top10)),
1710                Some(&BoxBorderRef::new(visual_with_top100)),
1711                0.0,
1712            ),
1713            visual_with_top10,
1714        );
1715        expect_border(
1716            BoxBorderRef::lerp(
1717                Some(&BoxBorderRef::new(directional_with_top10)),
1718                Some(&BoxBorderRef::new(visual_with_top100)),
1719                0.25,
1720            ),
1721            Border {
1722                top: width(32.5),
1723                ..Border::default()
1724            },
1725        );
1726
1727        let silly = SillyBorder;
1728        let empty = Border::default();
1729        let at_neg = BoxBorderRef::lerp(
1730            Some(&BoxBorderRef::new(silly)),
1731            Some(&BoxBorderRef::new(empty)),
1732            -1.0,
1733        )
1734        .unwrap();
1735        assert!(at_neg.eq_shape(&silly));
1736        let at_075 = BoxBorderRef::lerp(
1737            Some(&BoxBorderRef::new(silly)),
1738            Some(&BoxBorderRef::new(empty)),
1739            0.75,
1740        )
1741        .unwrap();
1742        assert!(at_075.eq_shape(&none_scaled()));
1743    }
1744
1745    #[test]
1746    fn directional_merge_add_scale_lerp() {
1747        let magenta3 = color_width(0xFFFF00FF, 3.0);
1748        let magenta6 = color_width(0xFFFF00FF, 6.0);
1749        let yellow2 = color_width(0xFFFFFF00, 2.0);
1750        assert_eq!(
1751            BorderDirectional::merge(
1752                BorderDirectional {
1753                    top: yellow2,
1754                    ..BorderDirectional::default()
1755                },
1756                BorderDirectional {
1757                    end: magenta3,
1758                    ..BorderDirectional::default()
1759                }
1760            ),
1761            BorderDirectional {
1762                top: yellow2,
1763                end: magenta3,
1764                ..BorderDirectional::default()
1765            }
1766        );
1767        assert_eq!(
1768            plus(
1769                &Border {
1770                    left: color_width(0x11111111, 1.0),
1771                    ..Border::default()
1772                },
1773                &BorderDirectional {
1774                    top: color_width(0x22222222, 1.0),
1775                    ..BorderDirectional::default()
1776                }
1777            )
1778            .as_any()
1779            .downcast_ref::<Border>()
1780            .copied()
1781            .unwrap(),
1782            Border {
1783                left: color_width(0x11111111, 1.0),
1784                top: color_width(0x22222222, 1.0),
1785                ..Border::default()
1786            }
1787        );
1788
1789        let b3 = BorderDirectional {
1790            start: magenta3,
1791            ..BorderDirectional::default()
1792        };
1793        let b6 = BorderDirectional {
1794            start: magenta6,
1795            ..BorderDirectional::default()
1796        };
1797        assert_eq!(b3.scale(2.0), b6);
1798
1799        let at0 = BorderDirectional {
1800            start: width(100.0),
1801            end: width(200.0),
1802            ..BorderDirectional::default()
1803        };
1804        let at100 = BorderDirectional {
1805            start: width(200.0),
1806            end: width(100.0),
1807            ..BorderDirectional::default()
1808        };
1809        assert_eq!(
1810            BorderDirectional::lerp(Some(at0), Some(at100), 0.25),
1811            Some(BorderDirectional {
1812                start: width(125.0),
1813                end: width(175.0),
1814                ..BorderDirectional::default()
1815            })
1816        );
1817    }
1818
1819    #[test]
1820    fn inner_and_outer_paths() {
1821        let border = Border {
1822            top: width(10.0),
1823            right: width(20.0),
1824            ..Border::default()
1825        };
1826        let rect = Rect::from_ltrb(50.0, 60.0, 110.0, 190.0);
1827        let outer = border.get_outer_path(rect, Some(TextDirection::Rtl));
1828        assert!(contains(&outer, 50.0, 60.0));
1829        assert!(contains(&outer, 110.0, 190.0));
1830        assert!(!contains(&outer, 40.0, 60.0));
1831        let inner = border.get_inner_path(rect, Some(TextDirection::Rtl));
1832        assert!(contains(&inner, 50.0, 70.0));
1833        assert!(!contains(&inner, 50.0, 60.0));
1834
1835        let border_directional = BorderDirectional {
1836            top: width(10.0),
1837            end: width(20.0),
1838            ..BorderDirectional::default()
1839        };
1840        let inner_rtl = border_directional.get_inner_path(rect, Some(TextDirection::Rtl));
1841        assert!(contains(&inner_rtl, 70.0, 70.0));
1842        assert!(!contains(&inner_rtl, 50.0, 70.0));
1843        let inner_ltr = border_directional.get_inner_path(rect, Some(TextDirection::Ltr));
1844        assert!(contains(&inner_ltr, 50.0, 70.0));
1845        assert!(!contains(&inner_ltr, 110.0, 80.0));
1846    }
1847}