Skip to main content

waft_painting/
border_radius.rs

1//! Flutter counterpart: `painting/border_radius.dart`.
2
3use std::fmt::{self, Debug};
4use std::ops::{Add, Div, Mul, Neg, Rem, Sub};
5
6use waft_embedder::{RRect, RSuperellipse, Radius, Rect};
7
8use crate::basic_types::TextDirection;
9
10/// Base class for [`BorderRadius`] that allows for text-direction aware
11/// resolution.
12///
13/// A property or argument of this type accepts classes created either with
14/// [`BorderRadius::only`] and its variants, or
15/// [`BorderRadiusDirectional::only`] and its variants.
16///
17/// To convert a [`BorderRadiusGeometry`] object of indeterminate type into a
18/// [`BorderRadius`] object, call the [`resolve`](BorderRadiusGeometry::resolve)
19/// method.
20///
21/// Non-exhaustive: `_MixedBorderRadius` (cross-kind `add`/`subtract`) is a
22/// later arm.
23#[non_exhaustive]
24#[derive(Clone, Copy, PartialEq)]
25pub enum BorderRadiusGeometry {
26    /// Visual corners — Dart's `BorderRadius`.
27    BorderRadius(BorderRadius),
28    /// Writing-direction corners — Dart's `BorderRadiusDirectional`.
29    Directional(BorderRadiusDirectional),
30}
31
32impl BorderRadiusGeometry {
33    /// Creates a [`BorderRadius`] where all radii are `radius`.
34    pub const fn all(radius: Radius) -> BorderRadiusGeometry {
35        BorderRadiusGeometry::BorderRadius(BorderRadius::all(radius))
36    }
37
38    /// Creates a [`BorderRadius`] where all radii are
39    /// [`Radius::circular(radius)`](Radius::circular).
40    pub fn circular(radius: f64) -> BorderRadiusGeometry {
41        BorderRadiusGeometry::BorderRadius(BorderRadius::circular(radius))
42    }
43
44    /// Creates a horizontally symmetrical border radius.
45    ///
46    /// Utilizing the `left` and `right` properties will return a
47    /// [`BorderRadius`], while `start` and `end` will yield a
48    /// [`BorderRadiusDirectional`]. These properties cannot be used
49    /// interchangeably.
50    pub fn horizontal(
51        left: Option<Radius>,
52        right: Option<Radius>,
53        start: Option<Radius>,
54        end: Option<Radius>,
55    ) -> BorderRadiusGeometry {
56        debug_assert!(
57            (left.is_none() && right.is_none()) || (start.is_none() && end.is_none()),
58            "The left and right values cannot be used in conjunction with start and end."
59        );
60        if start.is_some() || end.is_some() {
61            BorderRadiusGeometry::Directional(BorderRadiusDirectional::horizontal(
62                start.unwrap_or(Radius::ZERO),
63                end.unwrap_or(Radius::ZERO),
64            ))
65        } else {
66            BorderRadiusGeometry::BorderRadius(BorderRadius::horizontal(
67                left.unwrap_or(Radius::ZERO),
68                right.unwrap_or(Radius::ZERO),
69            ))
70        }
71    }
72
73    /// Creates a [`BorderRadius`] with only the given non-zero values.
74    ///
75    /// The other corners will be right angles.
76    pub const fn only(
77        top_left: Radius,
78        top_right: Radius,
79        bottom_left: Radius,
80        bottom_right: Radius,
81    ) -> BorderRadiusGeometry {
82        BorderRadiusGeometry::BorderRadius(BorderRadius::only(
83            top_left,
84            top_right,
85            bottom_left,
86            bottom_right,
87        ))
88    }
89
90    /// Creates a [`BorderRadiusDirectional`] with only the given non-zero
91    /// values.
92    ///
93    /// The other corners will be right angles.
94    pub const fn directional(
95        top_start: Radius,
96        top_end: Radius,
97        bottom_start: Radius,
98        bottom_end: Radius,
99    ) -> BorderRadiusGeometry {
100        BorderRadiusGeometry::Directional(BorderRadiusDirectional::only(
101            top_start,
102            top_end,
103            bottom_start,
104            bottom_end,
105        ))
106    }
107
108    /// Creates a vertically symmetric [`BorderRadius`] where the top and bottom
109    /// sides of the rectangle have the same radii.
110    pub const fn vertical(top: Radius, bottom: Radius) -> BorderRadiusGeometry {
111        BorderRadiusGeometry::BorderRadius(BorderRadius::vertical(top, bottom))
112    }
113
114    /// A [`BorderRadius`] with all zero radii.
115    pub const ZERO: BorderRadiusGeometry = BorderRadiusGeometry::BorderRadius(BorderRadius::ZERO);
116
117    fn top_left(&self) -> Radius {
118        match self {
119            BorderRadiusGeometry::BorderRadius(radius) => radius.top_left,
120            BorderRadiusGeometry::Directional(_) => Radius::ZERO,
121        }
122    }
123
124    fn top_right(&self) -> Radius {
125        match self {
126            BorderRadiusGeometry::BorderRadius(radius) => radius.top_right,
127            BorderRadiusGeometry::Directional(_) => Radius::ZERO,
128        }
129    }
130
131    fn bottom_left(&self) -> Radius {
132        match self {
133            BorderRadiusGeometry::BorderRadius(radius) => radius.bottom_left,
134            BorderRadiusGeometry::Directional(_) => Radius::ZERO,
135        }
136    }
137
138    fn bottom_right(&self) -> Radius {
139        match self {
140            BorderRadiusGeometry::BorderRadius(radius) => radius.bottom_right,
141            BorderRadiusGeometry::Directional(_) => Radius::ZERO,
142        }
143    }
144
145    fn top_start(&self) -> Radius {
146        match self {
147            BorderRadiusGeometry::BorderRadius(_) => Radius::ZERO,
148            BorderRadiusGeometry::Directional(radius) => radius.top_start,
149        }
150    }
151
152    fn top_end(&self) -> Radius {
153        match self {
154            BorderRadiusGeometry::BorderRadius(_) => Radius::ZERO,
155            BorderRadiusGeometry::Directional(radius) => radius.top_end,
156        }
157    }
158
159    fn bottom_start(&self) -> Radius {
160        match self {
161            BorderRadiusGeometry::BorderRadius(_) => Radius::ZERO,
162            BorderRadiusGeometry::Directional(radius) => radius.bottom_start,
163        }
164    }
165
166    fn bottom_end(&self) -> Radius {
167        match self {
168            BorderRadiusGeometry::BorderRadius(_) => Radius::ZERO,
169            BorderRadiusGeometry::Directional(radius) => radius.bottom_end,
170        }
171    }
172
173    /// Integer divides the [`BorderRadiusGeometry`] object's corners by the
174    /// given factor.
175    pub fn truncating_div(&self, other: f64) -> BorderRadiusGeometry {
176        match self {
177            BorderRadiusGeometry::BorderRadius(radius) => {
178                BorderRadiusGeometry::BorderRadius(radius.truncating_div(other))
179            }
180            BorderRadiusGeometry::Directional(radius) => {
181                BorderRadiusGeometry::Directional(radius.truncating_div(other))
182            }
183        }
184    }
185
186    /// Convert this instance into a [`BorderRadius`], so that the radii are
187    /// expressed for specific physical corners (top-left, top-right, etc)
188    /// rather than in a direction-dependent manner.
189    ///
190    /// See also:
191    ///
192    ///  * [`BorderRadius`], for which this is a no-op (returns itself).
193    ///  * [`BorderRadiusDirectional`], which flips the horizontal direction
194    ///    based on the `direction` argument.
195    pub fn resolve(&self, direction: Option<TextDirection>) -> BorderRadius {
196        match self {
197            BorderRadiusGeometry::BorderRadius(radius) => radius.resolve(direction),
198            BorderRadiusGeometry::Directional(radius) => radius.resolve(direction),
199        }
200    }
201
202    /// Returns the sum of two [`BorderRadiusGeometry`] objects.
203    ///
204    /// Same-kind add returns that kind. Cross-kind add (`_MixedBorderRadius`) is
205    /// deferred.
206    #[allow(clippy::should_implement_trait)]
207    pub fn add(self, other: BorderRadiusGeometry) -> BorderRadiusGeometry {
208        match (self, other) {
209            (BorderRadiusGeometry::BorderRadius(a), BorderRadiusGeometry::BorderRadius(b)) => {
210                BorderRadiusGeometry::BorderRadius(a + b)
211            }
212            (BorderRadiusGeometry::Directional(a), BorderRadiusGeometry::Directional(b)) => {
213                BorderRadiusGeometry::Directional(a + b)
214            }
215            _ => panic!("cross-kind BorderRadiusGeometry::add (_MixedBorderRadius) is deferred"),
216        }
217    }
218
219    /// Returns the difference between two [`BorderRadiusGeometry`] objects.
220    ///
221    /// Same-kind subtract returns that kind. Cross-kind subtract
222    /// (`_MixedBorderRadius`) is deferred.
223    pub fn subtract(self, other: BorderRadiusGeometry) -> BorderRadiusGeometry {
224        match (self, other) {
225            (BorderRadiusGeometry::BorderRadius(a), BorderRadiusGeometry::BorderRadius(b)) => {
226                BorderRadiusGeometry::BorderRadius(a - b)
227            }
228            (BorderRadiusGeometry::Directional(a), BorderRadiusGeometry::Directional(b)) => {
229                BorderRadiusGeometry::Directional(a - b)
230            }
231            _ => {
232                panic!("cross-kind BorderRadiusGeometry::subtract (_MixedBorderRadius) is deferred")
233            }
234        }
235    }
236
237    /// Linearly interpolate between two [`BorderRadiusGeometry`] objects.
238    ///
239    /// Same-kind lerp uses [`add`](Self::add) / [`subtract`](Self::subtract).
240    /// Cross-kind lerp (`_MixedBorderRadius`) is deferred.
241    pub fn lerp(
242        a: Option<BorderRadiusGeometry>,
243        b: Option<BorderRadiusGeometry>,
244        t: f64,
245    ) -> Option<BorderRadiusGeometry> {
246        match (a, b) {
247            (None, None) => return None,
248            (Some(a), Some(b)) if a == b => return Some(a),
249            _ => {}
250        }
251        let a = a.unwrap_or(BorderRadiusGeometry::ZERO);
252        let b = b.unwrap_or(BorderRadiusGeometry::ZERO);
253        Some(a.add(b.subtract(a) * t))
254    }
255}
256
257impl From<BorderRadius> for BorderRadiusGeometry {
258    fn from(radius: BorderRadius) -> BorderRadiusGeometry {
259        BorderRadiusGeometry::BorderRadius(radius)
260    }
261}
262
263impl From<BorderRadiusDirectional> for BorderRadiusGeometry {
264    fn from(radius: BorderRadiusDirectional) -> BorderRadiusGeometry {
265        BorderRadiusGeometry::Directional(radius)
266    }
267}
268
269impl Neg for BorderRadiusGeometry {
270    type Output = BorderRadiusGeometry;
271
272    fn neg(self) -> BorderRadiusGeometry {
273        match self {
274            BorderRadiusGeometry::BorderRadius(radius) => {
275                BorderRadiusGeometry::BorderRadius(-radius)
276            }
277            BorderRadiusGeometry::Directional(radius) => BorderRadiusGeometry::Directional(-radius),
278        }
279    }
280}
281
282impl Mul<f64> for BorderRadiusGeometry {
283    type Output = BorderRadiusGeometry;
284
285    fn mul(self, other: f64) -> BorderRadiusGeometry {
286        match self {
287            BorderRadiusGeometry::BorderRadius(radius) => {
288                BorderRadiusGeometry::BorderRadius(radius * other)
289            }
290            BorderRadiusGeometry::Directional(radius) => {
291                BorderRadiusGeometry::Directional(radius * other)
292            }
293        }
294    }
295}
296
297impl Div<f64> for BorderRadiusGeometry {
298    type Output = BorderRadiusGeometry;
299
300    fn div(self, other: f64) -> BorderRadiusGeometry {
301        match self {
302            BorderRadiusGeometry::BorderRadius(radius) => {
303                BorderRadiusGeometry::BorderRadius(radius / other)
304            }
305            BorderRadiusGeometry::Directional(radius) => {
306                BorderRadiusGeometry::Directional(radius / other)
307            }
308        }
309    }
310}
311
312impl Rem<f64> for BorderRadiusGeometry {
313    type Output = BorderRadiusGeometry;
314
315    fn rem(self, other: f64) -> BorderRadiusGeometry {
316        match self {
317            BorderRadiusGeometry::BorderRadius(radius) => {
318                BorderRadiusGeometry::BorderRadius(radius % other)
319            }
320            BorderRadiusGeometry::Directional(radius) => {
321                BorderRadiusGeometry::Directional(radius % other)
322            }
323        }
324    }
325}
326
327impl Debug for BorderRadiusGeometry {
328    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
329        let visual = visual_debug(self);
330        let logical = logical_debug(self);
331        match (visual, logical) {
332            (Some(visual), Some(logical)) => write!(f, "{visual} + {logical}"),
333            (Some(visual), None) => write!(f, "{visual}"),
334            (None, Some(logical)) => write!(f, "{logical}"),
335            (None, None) => write!(f, "BorderRadius.zero"),
336        }
337    }
338}
339
340/// Dart's `BorderRadiusGeometry.toString`, which [`Debug`] already renders.
341impl std::fmt::Display for BorderRadiusGeometry {
342    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
343        std::fmt::Debug::fmt(self, f)
344    }
345}
346
347fn visual_debug(geometry: &BorderRadiusGeometry) -> Option<String> {
348    let top_left = geometry.top_left();
349    let top_right = geometry.top_right();
350    let bottom_left = geometry.bottom_left();
351    let bottom_right = geometry.bottom_right();
352    if top_left == top_right && top_right == bottom_left && bottom_left == bottom_right {
353        if top_left != Radius::ZERO {
354            if top_left.x == top_left.y {
355                Some(format!("BorderRadius.circular({:.1})", top_left.x))
356            } else {
357                Some(format!("BorderRadius.all({top_left:?})"))
358            }
359        } else {
360            None
361        }
362    } else {
363        let mut result = String::from("BorderRadius.only(");
364        let mut comma = false;
365        if top_left != Radius::ZERO {
366            result.push_str(&format!("topLeft: {top_left:?}"));
367            comma = true;
368        }
369        if top_right != Radius::ZERO {
370            if comma {
371                result.push_str(", ");
372            }
373            result.push_str(&format!("topRight: {top_right:?}"));
374            comma = true;
375        }
376        if bottom_left != Radius::ZERO {
377            if comma {
378                result.push_str(", ");
379            }
380            result.push_str(&format!("bottomLeft: {bottom_left:?}"));
381            comma = true;
382        }
383        if bottom_right != Radius::ZERO {
384            if comma {
385                result.push_str(", ");
386            }
387            result.push_str(&format!("bottomRight: {bottom_right:?}"));
388        }
389        result.push(')');
390        Some(result)
391    }
392}
393
394fn logical_debug(geometry: &BorderRadiusGeometry) -> Option<String> {
395    let top_start = geometry.top_start();
396    let top_end = geometry.top_end();
397    let bottom_start = geometry.bottom_start();
398    let bottom_end = geometry.bottom_end();
399    if top_start == top_end && top_end == bottom_end && bottom_end == bottom_start {
400        if top_start != Radius::ZERO {
401            if top_start.x == top_start.y {
402                Some(format!(
403                    "BorderRadiusDirectional.circular({:.1})",
404                    top_start.x
405                ))
406            } else {
407                Some(format!("BorderRadiusDirectional.all({top_start:?})"))
408            }
409        } else {
410            None
411        }
412    } else {
413        let mut result = String::from("BorderRadiusDirectional.only(");
414        let mut comma = false;
415        if top_start != Radius::ZERO {
416            result.push_str(&format!("topStart: {top_start:?}"));
417            comma = true;
418        }
419        if top_end != Radius::ZERO {
420            if comma {
421                result.push_str(", ");
422            }
423            result.push_str(&format!("topEnd: {top_end:?}"));
424            comma = true;
425        }
426        if bottom_start != Radius::ZERO {
427            if comma {
428                result.push_str(", ");
429            }
430            result.push_str(&format!("bottomStart: {bottom_start:?}"));
431            comma = true;
432        }
433        if bottom_end != Radius::ZERO {
434            if comma {
435                result.push_str(", ");
436            }
437            result.push_str(&format!("bottomEnd: {bottom_end:?}"));
438        }
439        result.push(')');
440        Some(result)
441    }
442}
443
444/// An immutable set of radii for each corner of a rectangle.
445///
446/// Used by `BoxDecoration` when the shape is a `BoxShape.rectangle`.
447///
448/// The [`BorderRadius`] class specifies offsets in terms of visual corners,
449/// e.g. [`top_left`](BorderRadius::top_left). These values are not affected by
450/// the [`TextDirection`]. To support both left-to-right and right-to-left
451/// layouts, consider using [`BorderRadiusDirectional`], which is expressed in
452/// terms that are relative to a [`TextDirection`] (typically obtained from the
453/// ambient `Directionality`).
454#[derive(Clone, Copy, PartialEq)]
455pub struct BorderRadius {
456    /// The top-left [`Radius`].
457    pub top_left: Radius,
458    /// The top-right [`Radius`].
459    pub top_right: Radius,
460    /// The bottom-left [`Radius`].
461    pub bottom_left: Radius,
462    /// The bottom-right [`Radius`].
463    pub bottom_right: Radius,
464}
465
466impl BorderRadius {
467    /// Creates a border radius where all radii are `radius`.
468    pub const fn all(radius: Radius) -> BorderRadius {
469        BorderRadius::only(radius, radius, radius, radius)
470    }
471
472    /// Creates a border radius where all radii are
473    /// [`Radius::circular(radius)`](Radius::circular).
474    pub fn circular(radius: f64) -> BorderRadius {
475        BorderRadius::all(Radius::circular(radius))
476    }
477
478    /// Creates a vertically symmetric border radius where the top and bottom
479    /// sides of the rectangle have the same radii.
480    pub const fn vertical(top: Radius, bottom: Radius) -> BorderRadius {
481        BorderRadius::only(top, top, bottom, bottom)
482    }
483
484    /// Creates a horizontally symmetrical border radius where the left and
485    /// right sides of the rectangle have the same radii.
486    pub const fn horizontal(left: Radius, right: Radius) -> BorderRadius {
487        BorderRadius::only(left, right, left, right)
488    }
489
490    /// Creates a border radius with only the given non-zero values. The other
491    /// corners will be right angles.
492    pub const fn only(
493        top_left: Radius,
494        top_right: Radius,
495        bottom_left: Radius,
496        bottom_right: Radius,
497    ) -> BorderRadius {
498        BorderRadius {
499            top_left,
500            top_right,
501            bottom_left,
502            bottom_right,
503        }
504    }
505
506    /// Returns a copy of this BorderRadius with the given fields replaced with
507    /// the new values.
508    pub fn copy_with(
509        &self,
510        top_left: Option<Radius>,
511        top_right: Option<Radius>,
512        bottom_left: Option<Radius>,
513        bottom_right: Option<Radius>,
514    ) -> BorderRadius {
515        BorderRadius::only(
516            top_left.unwrap_or(self.top_left),
517            top_right.unwrap_or(self.top_right),
518            bottom_left.unwrap_or(self.bottom_left),
519            bottom_right.unwrap_or(self.bottom_right),
520        )
521    }
522
523    /// Creates an [`RRect`] from the current border radius and a [`Rect`].
524    ///
525    /// If any of the radii have negative values in x or y, those values will be
526    /// clamped to zero in order to produce a valid [`RRect`].
527    pub fn to_rrect(&self, rect: Rect) -> RRect {
528        RRect::from_rect_and_corners(
529            rect,
530            self.top_left.clamp(Some(Radius::ZERO), None),
531            self.top_right.clamp(Some(Radius::ZERO), None),
532            self.bottom_right.clamp(Some(Radius::ZERO), None),
533            self.bottom_left.clamp(Some(Radius::ZERO), None),
534        )
535    }
536
537    /// Creates an [`RSuperellipse`] from the current border radius and a [`Rect`].
538    ///
539    /// If any of the radii have negative values in x or y, those values will be
540    /// clamped to zero in order to produce a valid [`RRect`].
541    pub fn to_r_superellipse(&self, rect: Rect) -> RSuperellipse {
542        RSuperellipse::from_rect_and_corners(
543            rect,
544            self.top_left.clamp(Some(Radius::ZERO), None),
545            self.top_right.clamp(Some(Radius::ZERO), None),
546            self.bottom_right.clamp(Some(Radius::ZERO), None),
547            self.bottom_left.clamp(Some(Radius::ZERO), None),
548        )
549    }
550
551    /// A border radius with all zero radii.
552    pub const ZERO: BorderRadius = BorderRadius::all(Radius::ZERO);
553
554    /// Integer divides each corner of the [`BorderRadius`] by the given factor.
555    pub fn truncating_div(&self, other: f64) -> BorderRadius {
556        BorderRadius::only(
557            self.top_left.truncating_div(other),
558            self.top_right.truncating_div(other),
559            self.bottom_left.truncating_div(other),
560            self.bottom_right.truncating_div(other),
561        )
562    }
563
564    /// Linearly interpolate between two [`BorderRadius`] objects.
565    ///
566    /// If either is null, this function interpolates from [`BorderRadius::ZERO`].
567    pub fn lerp(a: Option<BorderRadius>, b: Option<BorderRadius>, t: f64) -> Option<BorderRadius> {
568        if a == b {
569            return a;
570        }
571        match (a, b) {
572            (None, None) => None,
573            (None, Some(b)) => Some(b * t),
574            (Some(a), None) => Some(a * (1.0 - t)),
575            (Some(a), Some(b)) => Some(BorderRadius::only(
576                Radius::lerp(Some(a.top_left), Some(b.top_left), t).unwrap(),
577                Radius::lerp(Some(a.top_right), Some(b.top_right), t).unwrap(),
578                Radius::lerp(Some(a.bottom_left), Some(b.bottom_left), t).unwrap(),
579                Radius::lerp(Some(a.bottom_right), Some(b.bottom_right), t).unwrap(),
580            )),
581        }
582    }
583
584    /// Convert this instance into a [`BorderRadius`].
585    pub fn resolve(&self, _direction: Option<TextDirection>) -> BorderRadius {
586        *self
587    }
588}
589
590impl Sub for BorderRadius {
591    type Output = BorderRadius;
592
593    fn sub(self, other: BorderRadius) -> BorderRadius {
594        BorderRadius::only(
595            self.top_left - other.top_left,
596            self.top_right - other.top_right,
597            self.bottom_left - other.bottom_left,
598            self.bottom_right - other.bottom_right,
599        )
600    }
601}
602
603impl Add for BorderRadius {
604    type Output = BorderRadius;
605
606    fn add(self, other: BorderRadius) -> BorderRadius {
607        BorderRadius::only(
608            self.top_left + other.top_left,
609            self.top_right + other.top_right,
610            self.bottom_left + other.bottom_left,
611            self.bottom_right + other.bottom_right,
612        )
613    }
614}
615
616impl Neg for BorderRadius {
617    type Output = BorderRadius;
618
619    fn neg(self) -> BorderRadius {
620        BorderRadius::only(
621            -self.top_left,
622            -self.top_right,
623            -self.bottom_left,
624            -self.bottom_right,
625        )
626    }
627}
628
629impl Mul<f64> for BorderRadius {
630    type Output = BorderRadius;
631
632    fn mul(self, other: f64) -> BorderRadius {
633        BorderRadius::only(
634            self.top_left * other,
635            self.top_right * other,
636            self.bottom_left * other,
637            self.bottom_right * other,
638        )
639    }
640}
641
642impl Div<f64> for BorderRadius {
643    type Output = BorderRadius;
644
645    fn div(self, other: f64) -> BorderRadius {
646        BorderRadius::only(
647            self.top_left / other,
648            self.top_right / other,
649            self.bottom_left / other,
650            self.bottom_right / other,
651        )
652    }
653}
654
655impl Rem<f64> for BorderRadius {
656    type Output = BorderRadius;
657
658    fn rem(self, other: f64) -> BorderRadius {
659        BorderRadius::only(
660            self.top_left % other,
661            self.top_right % other,
662            self.bottom_left % other,
663            self.bottom_right % other,
664        )
665    }
666}
667
668impl Debug for BorderRadius {
669    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
670        Debug::fmt(&BorderRadiusGeometry::from(*self), f)
671    }
672}
673
674/// An immutable set of radii for each corner of a rectangle, but with the
675/// corners specified in a manner dependent on the writing direction.
676///
677/// This can be used to specify a corner radius on the leading or trailing edge
678/// of a box, so that it flips to the other side when the text alignment flips
679/// (e.g. being on the top right in English text but the top left in Arabic
680/// text).
681///
682/// See also:
683///
684///  * [`BorderRadius`], a variant that uses physical labels (`topLeft` and
685///    `topRight` instead of `topStart` and `topEnd`).
686#[derive(Clone, Copy, PartialEq)]
687pub struct BorderRadiusDirectional {
688    /// The top-start [`Radius`].
689    pub top_start: Radius,
690    /// The top-end [`Radius`].
691    pub top_end: Radius,
692    /// The bottom-start [`Radius`].
693    pub bottom_start: Radius,
694    /// The bottom-end [`Radius`].
695    pub bottom_end: Radius,
696}
697
698impl BorderRadiusDirectional {
699    /// Creates a border radius where all radii are `radius`.
700    pub const fn all(radius: Radius) -> BorderRadiusDirectional {
701        BorderRadiusDirectional::only(radius, radius, radius, radius)
702    }
703
704    /// Creates a border radius where all radii are
705    /// [`Radius::circular(radius)`](Radius::circular).
706    pub fn circular(radius: f64) -> BorderRadiusDirectional {
707        BorderRadiusDirectional::all(Radius::circular(radius))
708    }
709
710    /// Creates a vertically symmetric border radius where the top and bottom
711    /// sides of the rectangle have the same radii.
712    pub const fn vertical(top: Radius, bottom: Radius) -> BorderRadiusDirectional {
713        BorderRadiusDirectional::only(top, top, bottom, bottom)
714    }
715
716    /// Creates a horizontally symmetrical border radius where the start and end
717    /// sides of the rectangle have the same radii.
718    pub const fn horizontal(start: Radius, end: Radius) -> BorderRadiusDirectional {
719        BorderRadiusDirectional::only(start, end, start, end)
720    }
721
722    /// Creates a border radius with only the given non-zero values. The other
723    /// corners will be right angles.
724    pub const fn only(
725        top_start: Radius,
726        top_end: Radius,
727        bottom_start: Radius,
728        bottom_end: Radius,
729    ) -> BorderRadiusDirectional {
730        BorderRadiusDirectional {
731            top_start,
732            top_end,
733            bottom_start,
734            bottom_end,
735        }
736    }
737
738    /// A border radius with all zero radii.
739    ///
740    /// Consider using [`BorderRadius::ZERO`] instead, since that object has the
741    /// same effect, but will be cheaper to [`resolve`](Self::resolve).
742    pub const ZERO: BorderRadiusDirectional = BorderRadiusDirectional::all(Radius::ZERO);
743
744    /// Integer divides each corner of the [`BorderRadiusDirectional`] by the
745    /// given factor.
746    pub fn truncating_div(&self, other: f64) -> BorderRadiusDirectional {
747        BorderRadiusDirectional::only(
748            self.top_start.truncating_div(other),
749            self.top_end.truncating_div(other),
750            self.bottom_start.truncating_div(other),
751            self.bottom_end.truncating_div(other),
752        )
753    }
754
755    /// Linearly interpolate between two [`BorderRadiusDirectional`] objects.
756    ///
757    /// If either is null, this function interpolates from
758    /// [`BorderRadiusDirectional::ZERO`].
759    pub fn lerp(
760        a: Option<BorderRadiusDirectional>,
761        b: Option<BorderRadiusDirectional>,
762        t: f64,
763    ) -> Option<BorderRadiusDirectional> {
764        if a == b {
765            return a;
766        }
767        match (a, b) {
768            (None, None) => None,
769            (None, Some(b)) => Some(b * t),
770            (Some(a), None) => Some(a * (1.0 - t)),
771            (Some(a), Some(b)) => Some(BorderRadiusDirectional::only(
772                Radius::lerp(Some(a.top_start), Some(b.top_start), t).unwrap(),
773                Radius::lerp(Some(a.top_end), Some(b.top_end), t).unwrap(),
774                Radius::lerp(Some(a.bottom_start), Some(b.bottom_start), t).unwrap(),
775                Radius::lerp(Some(a.bottom_end), Some(b.bottom_end), t).unwrap(),
776            )),
777        }
778    }
779
780    /// Convert this instance into a [`BorderRadius`], so that the radii are
781    /// expressed for specific physical corners.
782    pub fn resolve(&self, direction: Option<TextDirection>) -> BorderRadius {
783        match direction.expect("No TextDirection found.") {
784            TextDirection::Rtl => BorderRadius::only(
785                self.top_end,
786                self.top_start,
787                self.bottom_end,
788                self.bottom_start,
789            ),
790            TextDirection::Ltr => BorderRadius::only(
791                self.top_start,
792                self.top_end,
793                self.bottom_start,
794                self.bottom_end,
795            ),
796        }
797    }
798}
799
800impl Sub for BorderRadiusDirectional {
801    type Output = BorderRadiusDirectional;
802
803    fn sub(self, other: BorderRadiusDirectional) -> BorderRadiusDirectional {
804        BorderRadiusDirectional::only(
805            self.top_start - other.top_start,
806            self.top_end - other.top_end,
807            self.bottom_start - other.bottom_start,
808            self.bottom_end - other.bottom_end,
809        )
810    }
811}
812
813impl Add for BorderRadiusDirectional {
814    type Output = BorderRadiusDirectional;
815
816    fn add(self, other: BorderRadiusDirectional) -> BorderRadiusDirectional {
817        BorderRadiusDirectional::only(
818            self.top_start + other.top_start,
819            self.top_end + other.top_end,
820            self.bottom_start + other.bottom_start,
821            self.bottom_end + other.bottom_end,
822        )
823    }
824}
825
826impl Neg for BorderRadiusDirectional {
827    type Output = BorderRadiusDirectional;
828
829    fn neg(self) -> BorderRadiusDirectional {
830        BorderRadiusDirectional::only(
831            -self.top_start,
832            -self.top_end,
833            -self.bottom_start,
834            -self.bottom_end,
835        )
836    }
837}
838
839impl Mul<f64> for BorderRadiusDirectional {
840    type Output = BorderRadiusDirectional;
841
842    fn mul(self, other: f64) -> BorderRadiusDirectional {
843        BorderRadiusDirectional::only(
844            self.top_start * other,
845            self.top_end * other,
846            self.bottom_start * other,
847            self.bottom_end * other,
848        )
849    }
850}
851
852impl Div<f64> for BorderRadiusDirectional {
853    type Output = BorderRadiusDirectional;
854
855    fn div(self, other: f64) -> BorderRadiusDirectional {
856        BorderRadiusDirectional::only(
857            self.top_start / other,
858            self.top_end / other,
859            self.bottom_start / other,
860            self.bottom_end / other,
861        )
862    }
863}
864
865impl Rem<f64> for BorderRadiusDirectional {
866    type Output = BorderRadiusDirectional;
867
868    fn rem(self, other: f64) -> BorderRadiusDirectional {
869        BorderRadiusDirectional::only(
870            self.top_start % other,
871            self.top_end % other,
872            self.bottom_start % other,
873            self.bottom_end % other,
874        )
875    }
876}
877
878impl Debug for BorderRadiusDirectional {
879    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
880        Debug::fmt(&BorderRadiusGeometry::from(*self), f)
881    }
882}
883
884/// Dart's `BorderRadius.toString`, which [`Debug`] already renders.
885impl std::fmt::Display for BorderRadius {
886    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
887        std::fmt::Debug::fmt(self, f)
888    }
889}
890
891#[cfg(test)]
892mod tests {
893    use super::*;
894
895    #[test]
896    fn border_radius_constructors() {
897        let radius = Radius::elliptical(5.0, 7.0);
898        let all = BorderRadius::all(radius);
899        assert_eq!(all.top_left, radius);
900        assert_eq!(all.top_right, radius);
901        assert_eq!(all.bottom_left, radius);
902        assert_eq!(all.bottom_right, radius);
903
904        let circular = BorderRadius::circular(3.0);
905        assert_eq!(circular.top_left, Radius::elliptical(3.0, 3.0));
906
907        let radius1 = Radius::elliptical(89.0, 87.0);
908        let radius2 = Radius::elliptical(103.0, 107.0);
909        let vertical = BorderRadius::vertical(radius1, radius2);
910        assert_eq!(vertical.top_left, radius1);
911        assert_eq!(vertical.top_right, radius1);
912        assert_eq!(vertical.bottom_left, radius2);
913        assert_eq!(vertical.bottom_right, radius2);
914
915        let horizontal = BorderRadius::horizontal(radius1, radius2);
916        assert_eq!(horizontal.top_left, radius1);
917        assert_eq!(horizontal.top_right, radius2);
918        assert_eq!(horizontal.bottom_left, radius1);
919        assert_eq!(horizontal.bottom_right, radius2);
920
921        assert_eq!(BorderRadius::ZERO.top_left, Radius::ZERO);
922
923        let only = BorderRadius::only(Radius::ZERO, radius1, Radius::ZERO, radius2);
924        assert_eq!(only.top_left, Radius::ZERO);
925        assert_eq!(only.top_right, radius1);
926        assert_eq!(only.bottom_left, Radius::ZERO);
927        assert_eq!(only.bottom_right, radius2);
928    }
929
930    #[test]
931    fn same_kind_operators() {
932        assert_eq!(
933            BorderRadius::only(
934                Radius::elliptical(1.0, 2.0),
935                Radius::ZERO,
936                Radius::ZERO,
937                Radius::ZERO
938            ) - BorderRadius::only(
939                Radius::elliptical(3.0, 5.0),
940                Radius::ZERO,
941                Radius::ZERO,
942                Radius::ZERO
943            ),
944            BorderRadius::only(
945                Radius::elliptical(-2.0, -3.0),
946                Radius::ZERO,
947                Radius::ZERO,
948                Radius::ZERO
949            )
950        );
951        assert_eq!(
952            -BorderRadius::only(
953                Radius::elliptical(1.0, 2.0),
954                Radius::ZERO,
955                Radius::ZERO,
956                Radius::ZERO
957            ),
958            BorderRadius::only(
959                Radius::elliptical(-1.0, -2.0),
960                Radius::ZERO,
961                Radius::ZERO,
962                Radius::ZERO
963            )
964        );
965        assert_eq!(
966            BorderRadius::all(Radius::circular(15.0)) / 10.0,
967            BorderRadius::all(Radius::circular(1.5))
968        );
969        assert_eq!(
970            BorderRadius::all(Radius::circular(15.0)).truncating_div(10.0),
971            BorderRadius::all(Radius::circular(1.0))
972        );
973        assert_eq!(
974            BorderRadius::all(Radius::circular(15.0)) % 10.0,
975            BorderRadius::all(Radius::circular(5.0))
976        );
977    }
978
979    #[test]
980    fn lerp_invariants() {
981        let a = BorderRadius::all(Radius::circular(10.0));
982        let b = BorderRadius::all(Radius::circular(20.0));
983        assert_eq!(BorderRadius::lerp(Some(a), Some(b), 0.25), Some(a * 1.25));
984        assert_eq!(BorderRadius::lerp(None, None, 0.25), None);
985        assert_eq!(BorderRadius::lerp(None, Some(b), 0.25), Some(b * 0.25));
986        assert_eq!(BorderRadius::lerp(Some(a), None, 0.25), Some(a * 0.75));
987    }
988
989    #[test]
990    fn lerp_crazy() {
991        let a = BorderRadius::only(
992            Radius::elliptical(10.0, 20.0),
993            Radius::elliptical(30.0, 40.0),
994            Radius::elliptical(50.0, 60.0),
995            Radius::ZERO,
996        );
997        let b = BorderRadius::only(
998            Radius::ZERO,
999            Radius::elliptical(100.0, 110.0),
1000            Radius::elliptical(120.0, 130.0),
1001            Radius::elliptical(140.0, 150.0),
1002        );
1003        let c = BorderRadius::only(
1004            Radius::elliptical(5.0, 10.0),
1005            Radius::elliptical(65.0, 75.0),
1006            Radius::elliptical(85.0, 95.0),
1007            Radius::elliptical(70.0, 75.0),
1008        );
1009        assert_eq!(BorderRadius::lerp(Some(a), Some(b), 0.5), Some(c));
1010    }
1011
1012    #[test]
1013    fn directional_resolve_ltr_rtl() {
1014        let radius1 = Radius::elliptical(89.0, 87.0);
1015        let radius2 = Radius::elliptical(103.0, 107.0);
1016        let horizontal = BorderRadiusDirectional::horizontal(radius1, radius2);
1017        assert_eq!(
1018            horizontal.resolve(Some(TextDirection::Ltr)),
1019            BorderRadius::only(radius1, radius2, radius1, radius2)
1020        );
1021        assert_eq!(
1022            horizontal.resolve(Some(TextDirection::Rtl)),
1023            BorderRadius::only(radius2, radius1, radius2, radius1)
1024        );
1025
1026        let only = BorderRadiusDirectional::only(Radius::ZERO, radius1, Radius::ZERO, radius2);
1027        assert_eq!(
1028            only.resolve(Some(TextDirection::Ltr)),
1029            BorderRadius::only(Radius::ZERO, radius1, Radius::ZERO, radius2)
1030        );
1031        assert_eq!(
1032            only.resolve(Some(TextDirection::Rtl)),
1033            BorderRadius::only(radius1, Radius::ZERO, radius2, Radius::ZERO)
1034        );
1035    }
1036
1037    #[test]
1038    fn dart_runtime_type_keeps_zero_kinds_unequal() {
1039        assert_ne!(
1040            BorderRadiusGeometry::from(BorderRadius::ZERO),
1041            BorderRadiusGeometry::from(BorderRadiusDirectional::ZERO)
1042        );
1043    }
1044
1045    #[test]
1046    fn copy_with_replaces_given_fields() {
1047        let radius = Radius::circular(10.0);
1048        let border_radius = BorderRadius::all(radius);
1049        assert_eq!(
1050            border_radius
1051                .copy_with(Some(Radius::ZERO), None, None, None)
1052                .top_left,
1053            Radius::ZERO
1054        );
1055        assert_eq!(
1056            border_radius
1057                .copy_with(Some(Radius::ZERO), None, None, None)
1058                .copy_with(Some(radius), None, None, None),
1059            border_radius
1060        );
1061    }
1062
1063    #[test]
1064    fn geometry_factories() {
1065        let radius5 = Radius::circular(5.0);
1066        let radius10 = Radius::circular(10.0);
1067        assert_eq!(
1068            BorderRadiusGeometry::all(radius10),
1069            BorderRadiusGeometry::from(BorderRadius::all(radius10))
1070        );
1071        assert_eq!(
1072            BorderRadiusGeometry::circular(10.0),
1073            BorderRadiusGeometry::from(BorderRadius::circular(10.0))
1074        );
1075        assert_eq!(
1076            BorderRadiusGeometry::horizontal(Some(radius5), Some(radius10), None, None),
1077            BorderRadiusGeometry::from(BorderRadius::horizontal(radius5, radius10))
1078        );
1079        assert_eq!(
1080            BorderRadiusGeometry::horizontal(None, None, Some(radius5), Some(radius10)),
1081            BorderRadiusGeometry::from(BorderRadiusDirectional::horizontal(radius5, radius10))
1082        );
1083        assert_eq!(
1084            BorderRadiusGeometry::ZERO,
1085            BorderRadiusGeometry::from(BorderRadius::ZERO)
1086        );
1087    }
1088}