Skip to main content

waft_rendering/
table_border.rs

1//! Flutter counterpart: `rendering/table_border.dart`.
2
3use std::fmt;
4
5use waft_embedder::{
6    Canvas, Color, FillRule, Offset, Paint, PaintStyle, PathBuilder, Rect, Stroke,
7};
8use waft_painting::{BorderRadius, BorderSide, BorderStyle, EdgeInsets, draw_drrect, paint_border};
9
10/// Border specification for `Table` widgets.
11///
12/// This is like `Border`, with the addition of two sides: the inner horizontal borders between
13/// rows and the inner vertical borders between columns.
14///
15/// The sides are represented by [`BorderSide`] objects.
16#[derive(Clone, Copy, PartialEq)]
17pub struct TableBorder {
18    /// The top side of this border.
19    pub top: BorderSide,
20    /// The right side of this border.
21    pub right: BorderSide,
22    /// The bottom side of this border.
23    pub bottom: BorderSide,
24    /// The left side of this border.
25    pub left: BorderSide,
26    /// The horizontal interior sides of this border.
27    pub horizontal_inside: BorderSide,
28    /// The vertical interior sides of this border.
29    pub vertical_inside: BorderSide,
30    /// The [`BorderRadius`] to use when painting the corners of this border.
31    ///
32    /// It is also applied to `DataTable`'s `Material`.
33    pub border_radius: BorderRadius,
34}
35
36impl Default for TableBorder {
37    fn default() -> TableBorder {
38        TableBorder::new()
39    }
40}
41
42impl TableBorder {
43    /// Creates a border for a table.
44    ///
45    /// All the sides of the border default to [`BorderSide::NONE`]; Dart's named arguments are
46    /// the setters.
47    pub const fn new() -> TableBorder {
48        TableBorder {
49            top: BorderSide::NONE,
50            right: BorderSide::NONE,
51            bottom: BorderSide::NONE,
52            left: BorderSide::NONE,
53            horizontal_inside: BorderSide::NONE,
54            vertical_inside: BorderSide::NONE,
55            border_radius: BorderRadius::ZERO,
56        }
57    }
58
59    /// Dart `TableBorder(top:)`.
60    pub fn top(mut self, top: BorderSide) -> TableBorder {
61        self.top = top;
62        self
63    }
64
65    /// Dart `TableBorder(right:)`.
66    pub fn right(mut self, right: BorderSide) -> TableBorder {
67        self.right = right;
68        self
69    }
70
71    /// Dart `TableBorder(bottom:)`.
72    pub fn bottom(mut self, bottom: BorderSide) -> TableBorder {
73        self.bottom = bottom;
74        self
75    }
76
77    /// Dart `TableBorder(left:)`.
78    pub fn left(mut self, left: BorderSide) -> TableBorder {
79        self.left = left;
80        self
81    }
82
83    /// Dart `TableBorder(horizontalInside:)`.
84    pub fn horizontal_inside(mut self, horizontal_inside: BorderSide) -> TableBorder {
85        self.horizontal_inside = horizontal_inside;
86        self
87    }
88
89    /// Dart `TableBorder(verticalInside:)`.
90    pub fn vertical_inside(mut self, vertical_inside: BorderSide) -> TableBorder {
91        self.vertical_inside = vertical_inside;
92        self
93    }
94
95    /// Dart `TableBorder(borderRadius:)`.
96    pub fn border_radius(mut self, border_radius: BorderRadius) -> TableBorder {
97        self.border_radius = border_radius;
98        self
99    }
100
101    /// A uniform border with all sides the same color and width.
102    ///
103    /// Dart's `TableBorder.all` defaults the sides to black solid borders, one logical pixel
104    /// wide, with no radius.
105    pub fn all(
106        color: Color,
107        width: f64,
108        style: BorderStyle,
109        border_radius: BorderRadius,
110    ) -> TableBorder {
111        let side = BorderSide::new(color, width, style, BorderSide::STROKE_ALIGN_INSIDE);
112        TableBorder {
113            top: side,
114            right: side,
115            bottom: side,
116            left: side,
117            horizontal_inside: side,
118            vertical_inside: side,
119            border_radius,
120        }
121    }
122
123    /// Creates a border for a table where all the interior sides use the same styling and all
124    /// the exterior sides use the same styling.
125    pub fn symmetric(
126        inside: BorderSide,
127        outside: BorderSide,
128        border_radius: BorderRadius,
129    ) -> TableBorder {
130        TableBorder {
131            top: outside,
132            right: outside,
133            bottom: outside,
134            left: outside,
135            horizontal_inside: inside,
136            vertical_inside: inside,
137            border_radius,
138        }
139    }
140
141    /// The widths of the sides of this border represented as an [`EdgeInsets`].
142    ///
143    /// This can be used, for example, with a `Padding` widget to inset a box by the size of
144    /// these borders.
145    pub fn dimensions(&self) -> EdgeInsets {
146        EdgeInsets::from_ltrb(
147            self.left.width,
148            self.top.width,
149            self.right.width,
150            self.bottom.width,
151        )
152    }
153
154    /// Whether all the sides of the border (outside and inside) are identical. Uniform borders
155    /// are typically more efficient to paint.
156    pub fn is_uniform(&self) -> bool {
157        self.all_sides_match(|side| side.color)
158            && self.all_sides_match(|side| side.width)
159            && self.all_sides_match(|side| side.style)
160    }
161
162    /// Whether all the outer sides of the border are identical.
163    fn outer_border_is_uniform(&self) -> bool {
164        self.outer_sides_match(|side| side.color)
165            && self.outer_sides_match(|side| side.width)
166            && self.outer_sides_match(|side| side.style)
167    }
168
169    fn all_sides_match<T: PartialEq>(&self, selector: impl Fn(&BorderSide) -> T) -> bool {
170        let top_value = selector(&self.top);
171
172        selector(&self.right) == top_value
173            && selector(&self.bottom) == top_value
174            && selector(&self.left) == top_value
175            && selector(&self.horizontal_inside) == top_value
176            && selector(&self.vertical_inside) == top_value
177    }
178
179    fn outer_sides_match<T: PartialEq>(&self, selector: impl Fn(&BorderSide) -> T) -> bool {
180        let top_value = selector(&self.top);
181
182        selector(&self.right) == top_value
183            && selector(&self.bottom) == top_value
184            && selector(&self.left) == top_value
185    }
186
187    /// Returns the set of distinct visible colors from the outer border sides.
188    ///
189    /// Only includes colors from border sides that are not [`BorderStyle::None`].
190    fn distinct_visible_outer_colors(&self) -> Vec<Color> {
191        let mut colors: Vec<Color> = Vec::new();
192        for side in [self.top, self.right, self.bottom, self.left] {
193            if side.style != BorderStyle::None && !colors.contains(&side.color) {
194                colors.push(side.color);
195            }
196        }
197        colors
198    }
199
200    fn paint_table_border(&self, canvas: &mut Canvas, rect: Rect) {
201        if self.outer_border_is_uniform() && self.border_radius != BorderRadius::ZERO {
202            let outer = self.border_radius.to_rrect(rect);
203            let inner = outer.deflate(self.top.width);
204            let paint = Paint {
205                color: self.top.color.into(),
206                ..Paint::default()
207            };
208            draw_drrect(canvas, outer, inner, &paint);
209            return;
210        }
211
212        let visible_colors = self.distinct_visible_outer_colors();
213        if visible_colors.len() == 1 && self.border_radius != BorderRadius::ZERO {
214            let visible = |side: BorderSide| match side.style {
215                BorderStyle::None => BorderSide::NONE,
216                BorderStyle::Solid => side,
217            };
218            TableBorder::paint_non_uniform_border_with_radius(
219                canvas,
220                rect,
221                self.border_radius,
222                visible_colors[0],
223                visible(self.top),
224                visible(self.right),
225                visible(self.bottom),
226                visible(self.left),
227            );
228            return;
229        }
230
231        paint_border(canvas, rect, self.top, self.right, self.bottom, self.left);
232    }
233
234    /// Paints a non-uniform border with border radius support.
235    ///
236    /// This is similar to `BoxBorder.paintNonUniformBorder` but adapted for table borders.
237    #[allow(clippy::too_many_arguments)]
238    fn paint_non_uniform_border_with_radius(
239        canvas: &mut Canvas,
240        rect: Rect,
241        border_radius: BorderRadius,
242        color: Color,
243        top: BorderSide,
244        right: BorderSide,
245        bottom: BorderSide,
246        left: BorderSide,
247    ) {
248        let border_rect = border_radius.to_rrect(rect);
249        let paint = Paint {
250            color: color.into(),
251            ..Paint::default()
252        };
253
254        let inner = EdgeInsets::from_ltrb(
255            left.stroke_inset(),
256            top.stroke_inset(),
257            right.stroke_inset(),
258            bottom.stroke_inset(),
259        )
260        .deflate_rrect(border_rect);
261
262        let outer = EdgeInsets::from_ltrb(
263            left.stroke_outset(),
264            top.stroke_outset(),
265            right.stroke_outset(),
266            bottom.stroke_outset(),
267        )
268        .inflate_rrect(border_rect);
269
270        draw_drrect(canvas, outer, inner, &paint);
271    }
272
273    /// Creates a copy of this border but with the widths scaled by the factor `t`.
274    ///
275    /// The `t` argument represents the multiplicand, or the position on the timeline for an
276    /// interpolation from nothing to `self`, with 0.0 meaning that the object returned should
277    /// be the nil variant of this object, 1.0 meaning that no change should be applied,
278    /// returning `self` (or something equivalent to `self`), and other values meaning that the
279    /// object should be multiplied by `t`. Negative values are treated like zero.
280    ///
281    /// Values for `t` are usually obtained from an `Animation<f64>`, such as an
282    /// `AnimationController`.
283    ///
284    /// See also:
285    ///
286    ///  * [`BorderSide::scale`], which is used to implement this method.
287    pub fn scale(&self, t: f64) -> TableBorder {
288        TableBorder::new()
289            .top(self.top.scale(t))
290            .right(self.right.scale(t))
291            .bottom(self.bottom.scale(t))
292            .left(self.left.scale(t))
293            .horizontal_inside(self.horizontal_inside.scale(t))
294            .vertical_inside(self.vertical_inside.scale(t))
295    }
296
297    /// Linearly interpolate between two table borders.
298    ///
299    /// If a border is `None`, it is treated as having only [`BorderSide::NONE`] borders.
300    ///
301    /// The `t` argument represents position on the timeline, with 0.0 meaning that the
302    /// interpolation has not started, returning `a` (or something equivalent to `a`), 1.0
303    /// meaning that the interpolation has finished, returning `b` (or something equivalent to
304    /// `b`), and values in between meaning that the interpolation is at the relevant point on
305    /// the timeline between `a` and `b`.
306    pub fn lerp(a: Option<TableBorder>, b: Option<TableBorder>, t: f64) -> Option<TableBorder> {
307        if a == b {
308            return a;
309        }
310        match (a, b) {
311            (None, None) => None,
312            (None, Some(b)) => Some(b.scale(t)),
313            (Some(a), None) => Some(a.scale(1.0 - t)),
314            (Some(a), Some(b)) => Some(
315                TableBorder::new()
316                    .top(BorderSide::lerp(a.top, b.top, t))
317                    .right(BorderSide::lerp(a.right, b.right, t))
318                    .bottom(BorderSide::lerp(a.bottom, b.bottom, t))
319                    .left(BorderSide::lerp(a.left, b.left, t))
320                    .horizontal_inside(BorderSide::lerp(
321                        a.horizontal_inside,
322                        b.horizontal_inside,
323                        t,
324                    ))
325                    .vertical_inside(BorderSide::lerp(a.vertical_inside, b.vertical_inside, t)),
326            ),
327        }
328    }
329
330    /// Paints the border around the given [`Rect`] on the given [`Canvas`], with the given
331    /// rows and columns.
332    ///
333    /// Uniform borders are more efficient to paint than more complex borders.
334    ///
335    /// The `rows` argument specifies the vertical positions between the rows, relative to the
336    /// given rectangle. For example, if the table contained two rows of height 100.0 each,
337    /// then `rows` would contain a single value, 100.0, which is the vertical position between
338    /// the two rows (relative to the top edge of `rect`).
339    ///
340    /// The `columns` argument specifies the horizontal positions between the columns, relative
341    /// to the given rectangle. For example, if the table contained two columns of height 100.0
342    /// each, then `columns` would contain a single value, 100.0, which is the vertical position
343    /// between the two columns (relative to the left edge of `rect`).
344    ///
345    /// The [`vertical_inside`](Self::vertical_inside) border is only drawn if there are at
346    /// least two columns. The [`horizontal_inside`](Self::horizontal_inside) border is only
347    /// drawn if there are at least two rows. The horizontal borders are drawn after the
348    /// vertical borders.
349    ///
350    /// The outer borders (in the order [`top`](Self::top), [`right`](Self::right),
351    /// [`bottom`](Self::bottom), [`left`](Self::left), with [`left`](Self::left) above the
352    /// others) are painted after the inner borders.
353    ///
354    /// The paint order is particularly notable in the case of partially-transparent borders.
355    pub fn paint(&self, canvas: &mut Canvas, rect: Rect, rows: &[f64], columns: &[f64]) {
356        // properties can't be null
357
358        // arguments can't be null
359        debug_assert!(rows.is_empty() || (rows[0] >= 0.0 && rows[rows.len() - 1] <= rect.height()));
360        debug_assert!(
361            columns.is_empty() || (columns[0] >= 0.0 && columns[columns.len() - 1] <= rect.width())
362        );
363
364        if !columns.is_empty() || !rows.is_empty() {
365            let mut paint = Paint::default();
366
367            if !columns.is_empty() {
368                match self.vertical_inside.style {
369                    BorderStyle::Solid => {
370                        paint.color = self.vertical_inside.color.into();
371                        paint.style =
372                            PaintStyle::Stroke(Stroke::new(self.vertical_inside.width as f32));
373                        let mut path = PathBuilder::new();
374                        for &x in columns {
375                            path.move_to(Offset::new(rect.left + x, rect.top));
376                            path.line_to(Offset::new(rect.left + x, rect.bottom));
377                        }
378                        canvas.draw_path(&path.build(), FillRule::NonZero, &paint);
379                    }
380                    BorderStyle::None => {}
381                }
382            }
383
384            if !rows.is_empty() {
385                match self.horizontal_inside.style {
386                    BorderStyle::Solid => {
387                        paint.color = self.horizontal_inside.color.into();
388                        paint.style =
389                            PaintStyle::Stroke(Stroke::new(self.horizontal_inside.width as f32));
390                        let mut path = PathBuilder::new();
391                        for &y in rows {
392                            path.move_to(Offset::new(rect.left, rect.top + y));
393                            path.line_to(Offset::new(rect.right, rect.top + y));
394                        }
395                        canvas.draw_path(&path.build(), FillRule::NonZero, &paint);
396                    }
397                    BorderStyle::None => {}
398                }
399            }
400        }
401
402        self.paint_table_border(canvas, rect);
403    }
404}
405
406impl fmt::Debug for TableBorder {
407    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
408        write!(
409            f,
410            "TableBorder({:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?})",
411            self.top,
412            self.right,
413            self.bottom,
414            self.left,
415            self.horizontal_inside,
416            self.vertical_inside,
417            self.border_radius
418        )
419    }
420}
421
422#[cfg(test)]
423mod tests {
424    use waft_embedder::Radius;
425
426    use super::*;
427
428    fn side(width: f64, color: u32) -> BorderSide {
429        BorderSide::new(
430            Color::new(color),
431            width,
432            BorderStyle::Solid,
433            BorderSide::STROKE_ALIGN_INSIDE,
434        )
435    }
436
437    /// `table_border_test.dart`: "TableBorder constructor".
438    #[test]
439    fn the_sides_not_given_are_none() {
440        let border = TableBorder::new()
441            .left(BorderSide::default())
442            .right(side(1.0, 0xFF00FF00))
443            .vertical_inside(BorderSide::default());
444        assert!(border.top == BorderSide::NONE);
445        assert!(border.right == side(1.0, 0xFF00FF00));
446        assert!(border.bottom == BorderSide::NONE);
447        assert!(border.left == BorderSide::default());
448        assert!(border.horizontal_inside == BorderSide::NONE);
449        assert!(border.vertical_inside == BorderSide::default());
450        assert!(border.dimensions() == EdgeInsets::symmetric(0.0, 1.0));
451        assert!(!border.is_uniform());
452        assert!(
453            border.scale(2.0)
454                == TableBorder::new()
455                    .left(side(2.0, 0xFF000000))
456                    .right(side(2.0, 0xFF00FF00))
457                    .vertical_inside(side(2.0, 0xFF000000))
458        );
459    }
460
461    /// `table_border_test.dart`: "TableBorder.all constructor" and "TableBorder.symmetric
462    /// constructor".
463    #[test]
464    fn all_and_symmetric_fill_the_sides() {
465        let all = TableBorder::all(
466            Color::new(0xFF00FFFF),
467            2.0,
468            BorderStyle::Solid,
469            BorderRadius::ZERO,
470        );
471        for each in [
472            all.top,
473            all.right,
474            all.bottom,
475            all.left,
476            all.horizontal_inside,
477            all.vertical_inside,
478        ] {
479            assert!(each == side(2.0, 0xFF00FFFF));
480        }
481        assert!(all.dimensions() == EdgeInsets::symmetric(2.0, 2.0));
482        assert!(all.is_uniform());
483        assert!(
484            all.scale(0.5)
485                == TableBorder::all(
486                    Color::new(0xFF00FFFF),
487                    1.0,
488                    BorderStyle::Solid,
489                    BorderRadius::ZERO
490                )
491        );
492
493        let symmetric = TableBorder::symmetric(
494            side(3.0, 0xFF000000),
495            side(1.0, 0xFFFF0000),
496            BorderRadius::ZERO,
497        );
498        assert!(symmetric.top == side(1.0, 0xFFFF0000));
499        assert!(symmetric.horizontal_inside == side(3.0, 0xFF000000));
500        assert!(symmetric.dimensions() == EdgeInsets::symmetric(1.0, 1.0));
501        assert!(!symmetric.is_uniform());
502        let gone = BorderSide::new(
503            Color::new(0xFFFF0000),
504            0.0,
505            BorderStyle::None,
506            BorderSide::STROKE_ALIGN_INSIDE,
507        );
508        assert!(
509            symmetric.scale(0.0)
510                == TableBorder::symmetric(BorderSide::NONE.scale(0.0), gone, BorderRadius::ZERO)
511        );
512    }
513
514    /// `table_border_test.dart`: "TableBorder.lerp" and "TableBorder.lerp with nulls".
515    #[test]
516    fn lerp_scales_every_side() {
517        let sides = [
518            side(1.0, 0x00000001),
519            side(2.0, 0x00000002),
520            side(3.0, 0x00000003),
521            side(4.0, 0x00000004),
522            side(5.0, 0x00000005),
523            side(6.0, 0x00000006),
524        ];
525        let scaled = |t: f64| {
526            TableBorder::new()
527                .top(sides[0].scale(t))
528                .right(sides[1].scale(t))
529                .bottom(sides[2].scale(t))
530                .left(sides[3].scale(t))
531                .horizontal_inside(sides[4].scale(t))
532                .vertical_inside(sides[5].scale(t))
533        };
534        let (a, b, c) = (scaled(1.0), scaled(2.0), scaled(3.0));
535        assert!(a.dimensions() == EdgeInsets::from_ltrb(4.0, 1.0, 2.0, 3.0));
536        assert!(TableBorder::lerp(Some(a), Some(c), 0.5) == Some(b));
537        assert!(TableBorder::lerp(Some(a), Some(b), 2.0) == Some(c));
538        assert!(TableBorder::lerp(Some(b), Some(c), -1.0) == Some(a));
539
540        let two = TableBorder::all(
541            Color::new(0xFF000000),
542            2.0,
543            BorderStyle::Solid,
544            BorderRadius::ZERO,
545        );
546        let one = TableBorder::all(
547            Color::new(0xFF000000),
548            1.0,
549            BorderStyle::Solid,
550            BorderRadius::ZERO,
551        );
552        assert!(TableBorder::lerp(Some(two), None, 0.5) == Some(one));
553        assert!(TableBorder::lerp(None, Some(two), 0.5) == Some(one));
554        assert!(TableBorder::lerp(None, None, 0.5).is_none());
555    }
556
557    /// `table_border_test.dart`: "TableBorder.all with a borderRadius".
558    #[test]
559    fn all_keeps_its_radius() {
560        let radius = BorderRadius::all(Radius::circular(8.0));
561        let border = TableBorder::all(Color::new(0xFF000000), 1.0, BorderStyle::Solid, radius);
562        assert!(border.border_radius == radius);
563    }
564}