Skip to main content

waft_painting/
linear_border.rs

1//! Flutter counterpart: `painting/linear_border.dart`.
2
3use std::any::Any;
4use std::fmt::{Debug, Formatter, Result as FmtResult};
5use std::rc::Rc;
6
7use waft_embedder::{
8    Canvas, Color, FillRule, Offset, Paint, PaintStyle, Path, PathBuilder, Rect, Stroke,
9    lerp_double,
10};
11
12use crate::basic_types::TextDirection;
13use crate::borders::{
14    BorderSide, BorderStyle, OutlinedBorder, OutlinedBorderRef, ShapeBorder, ShapeBorderRef,
15};
16use crate::edge_insets::{EdgeInsetsDirectional, EdgeInsetsGeometry};
17
18/// Defines the relative size and alignment of one [`LinearBorder`] edge.
19///
20/// A [`LinearBorder`] defines a box outline as zero to four edges, each of
21/// which is rendered as a single line. The width and color of the lines is
22/// defined by [`LinearBorder::side`].
23///
24/// Each line's length is defined by [`size`](Self::size), a value between 0.0
25/// and 1.0 (the default) which defines the length as a percentage of the
26/// length of a box edge.
27///
28/// When [`size`](Self::size) is less than 1.0, the line is aligned within the
29/// available space according to [`alignment`](Self::alignment), a value
30/// between -1.0 and 1.0. The default is 0.0, which means centered, -1.0 means
31/// align on the "start" side, and 1.0 means align on the "end" side.
32#[derive(Clone, Copy, PartialEq)]
33pub struct LinearBorderEdge {
34    /// A value between 0.0 and 1.0 that defines the length of the edge as a
35    /// percentage of the length of the corresponding box edge. Default is 1.0.
36    pub size: f64,
37    /// A value between -1.0 and 1.0 that defines how edges for which
38    /// [`size`](Self::size) is less than 1.0 are aligned relative to the
39    /// corresponding box edge.
40    pub alignment: f64,
41}
42
43impl LinearBorderEdge {
44    /// Defines one side of a [`LinearBorder`].
45    ///
46    /// The values of [`size`](Self::size) and [`alignment`](Self::alignment)
47    /// must be between 0.0 and 1.0, and -1.0 and 1.0 respectively.
48    pub fn new(size: f64, alignment: f64) -> LinearBorderEdge {
49        debug_assert!(
50            (0.0..=1.0).contains(&size),
51            "size must be between 0.0 and 1.0"
52        );
53        LinearBorderEdge { size, alignment }
54    }
55
56    /// Linearly interpolates between two [`LinearBorderEdge`]s.
57    ///
58    /// If both `a` and `b` are None then None is returned. If `a` is None then
59    /// we interpolate to `b` varying [`size`](Self::size) from 0.0 to `b.size`.
60    /// If `b` is None then we interpolate from `a` varying size from `a.size`
61    /// to zero. Otherwise both values are interpolated.
62    pub fn lerp(
63        a: Option<LinearBorderEdge>,
64        b: Option<LinearBorderEdge>,
65        t: f64,
66    ) -> Option<LinearBorderEdge> {
67        if a == b {
68            return a;
69        }
70        let a = match a {
71            Some(a) => a,
72            None => LinearBorderEdge::new(0.0, b.unwrap().alignment),
73        };
74        let b = match b {
75            Some(b) => b,
76            None => LinearBorderEdge::new(0.0, a.alignment),
77        };
78        Some(LinearBorderEdge::new(
79            lerp_double(Some(a.size), Some(b.size), t).unwrap(),
80            lerp_double(Some(a.alignment), Some(b.alignment), t).unwrap(),
81        ))
82    }
83}
84
85impl Default for LinearBorderEdge {
86    fn default() -> LinearBorderEdge {
87        LinearBorderEdge::new(1.0, 0.0)
88    }
89}
90
91impl Debug for LinearBorderEdge {
92    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
93        let mut s = String::from("LinearBorderEdge(");
94        if self.size != 1.0 {
95            s.push_str(&format!("size: {}", self.size));
96        }
97        if self.alignment != 0.0 {
98            let comma = if self.size != 1.0 { ", " } else { "" };
99            s.push_str(&format!("{comma}alignment: {}", self.alignment));
100        }
101        s.push(')');
102        write!(f, "{s}")
103    }
104}
105
106/// An [`OutlinedBorder`] like `BoxBorder` that allows one to define a
107/// rectangular (box) border in terms of zero to four [`LinearBorderEdge`]s,
108/// each of which is rendered as a single line.
109///
110/// This class resolves itself against the current [`TextDirection`]. Start and
111/// end values resolve to left and right for [`TextDirection::Ltr`] and to
112/// right and left for [`TextDirection::Rtl`].
113#[derive(Clone, Copy, PartialEq)]
114pub struct LinearBorder {
115    /// The border outline's color and weight.
116    pub side: BorderSide,
117    /// Defines the left edge for [`TextDirection::Ltr`] or the right for
118    /// [`TextDirection::Rtl`].
119    pub start: Option<LinearBorderEdge>,
120    /// Defines the right edge for [`TextDirection::Ltr`] or the left for
121    /// [`TextDirection::Rtl`].
122    pub end: Option<LinearBorderEdge>,
123    /// Defines the top edge.
124    pub top: Option<LinearBorderEdge>,
125    /// Defines the bottom edge.
126    pub bottom: Option<LinearBorderEdge>,
127}
128
129impl LinearBorder {
130    /// No border.
131    pub const NONE: LinearBorder = LinearBorder {
132        side: BorderSide::NONE,
133        start: None,
134        end: None,
135        top: None,
136        bottom: None,
137    };
138
139    /// Creates a rectangular box border that's rendered as zero to four lines.
140    pub fn new() -> LinearBorder {
141        LinearBorder::NONE
142    }
143
144    /// The color and width of each line.
145    pub fn side(mut self, side: BorderSide) -> LinearBorder {
146        self.side = side;
147        self
148    }
149
150    /// Defines the left edge for [`TextDirection::Ltr`] or the right for
151    /// [`TextDirection::Rtl`].
152    pub fn start(mut self, start: LinearBorderEdge) -> LinearBorder {
153        self.start = Some(start);
154        self
155    }
156
157    /// Defines the right edge for [`TextDirection::Ltr`] or the left for
158    /// [`TextDirection::Rtl`].
159    pub fn end(mut self, end: LinearBorderEdge) -> LinearBorder {
160        self.end = Some(end);
161        self
162    }
163
164    /// Defines the top edge.
165    pub fn top(mut self, top: LinearBorderEdge) -> LinearBorder {
166        self.top = Some(top);
167        self
168    }
169
170    /// Defines the bottom edge.
171    pub fn bottom(mut self, bottom: LinearBorderEdge) -> LinearBorder {
172        self.bottom = Some(bottom);
173        self
174    }
175
176    /// Creates a rectangular box border with an edge on the left for
177    /// [`TextDirection::Ltr`] or on the right for [`TextDirection::Rtl`].
178    pub fn start_side(side: BorderSide, alignment: f64, size: f64) -> LinearBorder {
179        LinearBorder::new()
180            .side(side)
181            .start(LinearBorderEdge::new(size, alignment))
182    }
183
184    /// Creates a rectangular box border with an edge on the right for
185    /// [`TextDirection::Ltr`] or on the left for [`TextDirection::Rtl`].
186    pub fn end_side(side: BorderSide, alignment: f64, size: f64) -> LinearBorder {
187        LinearBorder::new()
188            .side(side)
189            .end(LinearBorderEdge::new(size, alignment))
190    }
191
192    /// Creates a rectangular box border with an edge on the top.
193    pub fn top_side(side: BorderSide, alignment: f64, size: f64) -> LinearBorder {
194        LinearBorder::new()
195            .side(side)
196            .top(LinearBorderEdge::new(size, alignment))
197    }
198
199    /// Creates a rectangular box border with an edge on the bottom.
200    pub fn bottom_side(side: BorderSide, alignment: f64, size: f64) -> LinearBorder {
201        LinearBorder::new()
202            .side(side)
203            .bottom(LinearBorderEdge::new(size, alignment))
204    }
205
206    /// Creates a copy of this border, scaled by the factor `t`.
207    pub fn scale(&self, t: f64) -> LinearBorder {
208        LinearBorder::new().side(self.side.scale(t))
209    }
210
211    /// Creates a copy of this object. Chain setters to replace fields
212    /// (`border.copy_with().side(s).start(e)`).
213    pub fn copy_with(&self) -> LinearBorder {
214        *self
215    }
216
217    fn from_fields(
218        side: BorderSide,
219        start: Option<LinearBorderEdge>,
220        end: Option<LinearBorderEdge>,
221        top: Option<LinearBorderEdge>,
222        bottom: Option<LinearBorderEdge>,
223    ) -> LinearBorder {
224        LinearBorder {
225            side,
226            start,
227            end,
228            top,
229            bottom,
230        }
231    }
232}
233
234impl Default for LinearBorder {
235    fn default() -> LinearBorder {
236        LinearBorder::NONE
237    }
238}
239
240impl ShapeBorder for LinearBorder {
241    fn dimensions(&self) -> EdgeInsetsGeometry {
242        let width = self.side.width;
243        EdgeInsetsDirectional::from_steb(
244            if self.start.is_none() { 0.0 } else { width },
245            if self.top.is_none() { 0.0 } else { width },
246            if self.end.is_none() { 0.0 } else { width },
247            if self.bottom.is_none() { 0.0 } else { width },
248        )
249        .into()
250    }
251
252    fn scale(&self, t: f64) -> ShapeBorderRef {
253        ShapeBorderRef::new(LinearBorder::scale(self, t))
254    }
255
256    fn lerp_from(&self, a: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
257        if let Some(a) = a.and_then(|a| a.as_any().downcast_ref::<LinearBorder>()) {
258            Some(ShapeBorderRef::new(LinearBorder::from_fields(
259                BorderSide::lerp(a.side, self.side, t),
260                LinearBorderEdge::lerp(a.start, self.start, t),
261                LinearBorderEdge::lerp(a.end, self.end, t),
262                LinearBorderEdge::lerp(a.top, self.top, t),
263                LinearBorderEdge::lerp(a.bottom, self.bottom, t),
264            )))
265        } else if a.is_none() {
266            Some(ShapeBorder::scale(self, t))
267        } else {
268            None
269        }
270    }
271
272    fn lerp_to(&self, b: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
273        if let Some(b) = b.and_then(|b| b.as_any().downcast_ref::<LinearBorder>()) {
274            Some(ShapeBorderRef::new(LinearBorder::from_fields(
275                BorderSide::lerp(self.side, b.side, t),
276                LinearBorderEdge::lerp(self.start, b.start, t),
277                LinearBorderEdge::lerp(self.end, b.end, t),
278                LinearBorderEdge::lerp(self.top, b.top, t),
279                LinearBorderEdge::lerp(self.bottom, b.bottom, t),
280            )))
281        } else if b.is_none() {
282            Some(ShapeBorder::scale(self, 1.0 - t))
283        } else {
284            None
285        }
286    }
287
288    fn get_inner_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
289        let adjusted_rect = self.dimensions().resolve(text_direction).deflate_rect(rect);
290        let mut path = PathBuilder::new();
291        path.rect(adjusted_rect.into());
292        path.build().into()
293    }
294
295    fn get_outer_path(&self, rect: Rect, _text_direction: Option<TextDirection>) -> Path {
296        let mut path = PathBuilder::new();
297        path.rect(rect.into());
298        path.build().into()
299    }
300
301    fn paint(&self, canvas: &mut Canvas, rect: Rect, text_direction: Option<TextDirection>) {
302        let insets = self.dimensions().resolve(text_direction);
303        let rtl = text_direction == Some(TextDirection::Rtl);
304
305        fn draw_edge(canvas: &mut Canvas, rect: Rect, color: Color) {
306            let mut paint = Paint {
307                color: color.into(),
308                ..Paint::default()
309            };
310            let mut path = PathBuilder::new();
311            path.move_to(Offset::new(rect.left, rect.top));
312            if rect.width() == 0.0 {
313                paint.style = PaintStyle::Stroke(Stroke::new(0.0));
314                path.line_to(Offset::new(rect.left, rect.bottom));
315            } else if rect.height() == 0.0 {
316                paint.style = PaintStyle::Stroke(Stroke::new(0.0));
317                path.line_to(Offset::new(rect.right, rect.top));
318            } else {
319                paint.style = PaintStyle::Fill;
320                path.line_to(Offset::new(rect.right, rect.top));
321                path.line_to(Offset::new(rect.right, rect.bottom));
322                path.line_to(Offset::new(rect.left, rect.bottom));
323            }
324            canvas.draw_path(&path.build(), FillRule::NonZero, &paint);
325        }
326
327        if let Some(start) = self.start
328            && start.size != 0.0
329            && self.side.style != BorderStyle::None
330        {
331            let inset_rect = Rect::from_ltwh(
332                rect.left,
333                rect.top + insets.top,
334                rect.width(),
335                rect.height() - insets.vertical(),
336            );
337            let x = if rtl {
338                rect.right - insets.right
339            } else {
340                rect.left
341            };
342            let width = if rtl { insets.right } else { insets.left };
343            let height = inset_rect.height() * start.size;
344            let y = (inset_rect.height() - height) * ((start.alignment + 1.0) / 2.0);
345            draw_edge(
346                canvas,
347                Rect::from_ltwh(x, y, width, height),
348                self.side.color,
349            );
350        }
351
352        if let Some(end) = self.end
353            && end.size != 0.0
354            && self.side.style != BorderStyle::None
355        {
356            let inset_rect = Rect::from_ltwh(
357                rect.left,
358                rect.top + insets.top,
359                rect.width(),
360                rect.height() - insets.vertical(),
361            );
362            let x = if rtl {
363                rect.left
364            } else {
365                rect.right - insets.right
366            };
367            let width = if rtl { insets.left } else { insets.right };
368            let height = inset_rect.height() * end.size;
369            let y = (inset_rect.height() - height) * ((end.alignment + 1.0) / 2.0);
370            draw_edge(
371                canvas,
372                Rect::from_ltwh(x, y, width, height),
373                self.side.color,
374            );
375        }
376
377        if let Some(top) = self.top
378            && top.size != 0.0
379            && self.side.style != BorderStyle::None
380        {
381            let width = rect.width() * top.size;
382            let start_x = (rect.width() - width) * ((top.alignment + 1.0) / 2.0);
383            let x = if rtl {
384                rect.width() - start_x - width
385            } else {
386                start_x
387            };
388            draw_edge(
389                canvas,
390                Rect::from_ltwh(x, rect.top, width, insets.top),
391                self.side.color,
392            );
393        }
394
395        if let Some(bottom) = self.bottom
396            && bottom.size != 0.0
397            && self.side.style != BorderStyle::None
398        {
399            let width = rect.width() * bottom.size;
400            let start_x = (rect.width() - width) * ((bottom.alignment + 1.0) / 2.0);
401            let x = if rtl {
402                rect.width() - start_x - width
403            } else {
404                start_x
405            };
406            draw_edge(
407                canvas,
408                Rect::from_ltwh(x, rect.bottom - insets.bottom, width, self.side.width),
409                self.side.color,
410            );
411        }
412    }
413
414    fn as_any(&self) -> &dyn Any {
415        self
416    }
417
418    fn as_outlined_border(&self) -> Option<&dyn OutlinedBorder> {
419        Some(self)
420    }
421
422    fn into_outlined_border(self: Rc<Self>) -> Option<Rc<dyn OutlinedBorder>> {
423        Some(self)
424    }
425
426    fn eq_shape(&self, other: &dyn ShapeBorder) -> bool {
427        other
428            .as_any()
429            .downcast_ref::<LinearBorder>()
430            .is_some_and(|other| other == self)
431    }
432}
433
434impl OutlinedBorder for LinearBorder {
435    fn side(&self) -> BorderSide {
436        self.side
437    }
438
439    fn copy_with(&self, side: Option<BorderSide>) -> OutlinedBorderRef {
440        OutlinedBorderRef::new(self.copy_with().side(side.unwrap_or(self.side)))
441    }
442}
443
444impl Debug for LinearBorder {
445    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
446        if self == &LinearBorder::NONE {
447            return write!(f, "LinearBorder.none");
448        }
449        write!(f, "LinearBorder(side: {:?}", self.side)?;
450        if let Some(start) = self.start {
451            write!(f, ", start: {start:?}")?;
452        }
453        if let Some(end) = self.end {
454            write!(f, ", end: {end:?}")?;
455        }
456        if let Some(top) = self.top {
457            write!(f, ", top: {top:?}")?;
458        }
459        if let Some(bottom) = self.bottom {
460            write!(f, ", bottom: {bottom:?}")?;
461        }
462        write!(f, ")")
463    }
464}
465
466#[cfg(test)]
467mod tests {
468    use super::*;
469    use crate::edge_insets::EdgeInsets;
470
471    #[test]
472    fn edge_defaults() {
473        let edge = LinearBorderEdge::default();
474        assert_eq!(edge.size, 1.0);
475        assert_eq!(edge.alignment, 0.0);
476    }
477
478    #[test]
479    fn defaults() {
480        fn expect_empty(border: LinearBorder) {
481            assert_eq!(border.side, BorderSide::NONE);
482            assert_eq!(border.dimensions(), EdgeInsets::ZERO.into());
483            assert!(!border.prefer_paint_interior());
484            assert!(border.start.is_none());
485            assert!(border.end.is_none());
486            assert!(border.top.is_none());
487            assert!(border.bottom.is_none());
488        }
489        expect_empty(LinearBorder::NONE);
490        let start = LinearBorder::start_side(BorderSide::NONE, 0.0, 1.0);
491        assert_eq!(start.side, BorderSide::NONE);
492        assert_eq!(start.start, Some(LinearBorderEdge::default()));
493        assert!(start.end.is_none());
494        let end = LinearBorder::end_side(BorderSide::NONE, 0.0, 1.0);
495        assert_eq!(end.end, Some(LinearBorderEdge::default()));
496        let top = LinearBorder::top_side(BorderSide::NONE, 0.0, 1.0);
497        assert_eq!(top.top, Some(LinearBorderEdge::default()));
498        let bottom = LinearBorder::bottom_side(BorderSide::NONE, 0.0, 1.0);
499        assert_eq!(bottom.bottom, Some(LinearBorderEdge::default()));
500    }
501
502    #[test]
503    fn copy_with_eq() {
504        assert_eq!(LinearBorder::NONE, LinearBorder::NONE.copy_with());
505        let side = BorderSide {
506            width: 10.0,
507            color: Color::new(0xFF123456),
508            ..BorderSide::default()
509        };
510        assert_eq!(
511            LinearBorder::NONE.copy_with().side(side),
512            LinearBorder::new().side(side)
513        );
514    }
515
516    #[test]
517    fn lerp_identical() {
518        assert!(OutlinedBorderRef::lerp(None, None, 0.0).is_none());
519        let border = LinearBorder::NONE;
520        assert!(
521            OutlinedBorderRef::lerp(
522                Some(&OutlinedBorderRef::new(border)),
523                Some(&OutlinedBorderRef::new(border)),
524                0.5
525            )
526            .unwrap()
527            .eq_shape(&border)
528        );
529        assert!(LinearBorderEdge::lerp(None, None, 0.0).is_none());
530        let edge = LinearBorderEdge::default();
531        assert_eq!(
532            LinearBorderEdge::lerp(Some(edge), Some(edge), 0.5),
533            Some(edge)
534        );
535    }
536}