1use std::any::Any;
4use std::fmt::{self, Debug, Formatter, Result as FmtResult};
5use std::rc::Rc;
6
7use waft_embedder::{Canvas, FillRule, Paint, PaintStyle, Path, PathBuilder, Stroke};
8use waft_embedder::{Color, Offset, Rect, lerp_double};
9use waft_foundation::{DiagnosticPropertiesBuilder, Diagnosticable, DoubleProperty, EnumProperty};
10
11use crate::basic_types::TextDirection;
12use crate::colors::ColorProperty;
13use crate::edge_insets::EdgeInsetsGeometry;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum BorderStyle {
18 None,
20 Solid,
22}
23
24#[derive(Clone, Copy, PartialEq)]
31pub struct BorderSide {
32 pub color: Color,
34 pub width: f64,
45 pub style: BorderStyle,
51 pub stroke_align: f64,
64}
65
66impl BorderSide {
67 pub const STROKE_ALIGN_INSIDE: f64 = -1.0;
69 pub const STROKE_ALIGN_CENTER: f64 = 0.0;
71 pub const STROKE_ALIGN_OUTSIDE: f64 = 1.0;
73
74 pub const NONE: BorderSide = BorderSide {
76 color: Color::new(0xFF000000),
77 width: 0.0,
78 style: BorderStyle::None,
79 stroke_align: Self::STROKE_ALIGN_INSIDE,
80 };
81
82 pub fn new(color: Color, width: f64, style: BorderStyle, stroke_align: f64) -> BorderSide {
86 debug_assert!(width >= 0.0);
87 BorderSide {
88 color,
89 width,
90 style,
91 stroke_align,
92 }
93 }
94
95 pub fn merge(a: BorderSide, b: BorderSide) -> BorderSide {
105 debug_assert!(Self::can_merge(a, b));
106 let a_is_none = a.style == BorderStyle::None && a.width == 0.0;
107 let b_is_none = b.style == BorderStyle::None && b.width == 0.0;
108 if a_is_none && b_is_none {
109 return BorderSide::NONE;
110 }
111 if a_is_none {
112 return b;
113 }
114 if b_is_none {
115 return a;
116 }
117 debug_assert_eq!(a.color, b.color);
118 debug_assert_eq!(a.style, b.style);
119 BorderSide {
120 color: a.color, width: a.width + b.width,
122 stroke_align: a.stroke_align.max(b.stroke_align),
123 style: a.style, }
125 }
126
127 pub fn copy_with(
129 &self,
130 color: Option<Color>,
131 width: Option<f64>,
132 style: Option<BorderStyle>,
133 stroke_align: Option<f64>,
134 ) -> BorderSide {
135 BorderSide {
136 color: color.unwrap_or(self.color),
137 width: width.unwrap_or(self.width),
138 style: style.unwrap_or(self.style),
139 stroke_align: stroke_align.unwrap_or(self.stroke_align),
140 }
141 }
142
143 pub fn scale(&self, t: f64) -> BorderSide {
152 BorderSide {
153 color: self.color,
154 width: (self.width * t).max(0.0),
155 style: if t <= 0.0 {
156 BorderStyle::None
157 } else {
158 self.style
159 },
160 stroke_align: Self::STROKE_ALIGN_INSIDE,
161 }
162 }
163
164 pub fn to_paint(&self) -> Paint {
171 match self.style {
172 BorderStyle::Solid => Paint {
173 color: self.color.into(),
174 style: PaintStyle::Stroke(Stroke::new(self.width as f32)),
175 ..Paint::default()
176 },
177 BorderStyle::None => Paint {
178 color: Color::new(0x00000000).into(),
179 style: PaintStyle::Stroke(Stroke::new(0.0)),
180 ..Paint::default()
181 },
182 }
183 }
184
185 pub fn can_merge(a: BorderSide, b: BorderSide) -> bool {
190 if (a.style == BorderStyle::None && a.width == 0.0)
191 || (b.style == BorderStyle::None && b.width == 0.0)
192 {
193 return true;
194 }
195 a.style == b.style && a.color == b.color
196 }
197
198 pub fn lerp(a: BorderSide, b: BorderSide, t: f64) -> BorderSide {
200 if a == b {
201 return a;
202 }
203 if t == 0.0 {
204 return a;
205 }
206 if t == 1.0 {
207 return b;
208 }
209 let width = lerp_double(Some(a.width), Some(b.width), t).unwrap();
210 if width < 0.0 {
211 return BorderSide::NONE;
212 }
213 if a.style == b.style && a.stroke_align == b.stroke_align {
214 return BorderSide {
215 color: Color::lerp(Some(a.color), Some(b.color), t).unwrap(),
216 width,
217 style: a.style, stroke_align: a.stroke_align, };
220 }
221 let color_a = match a.style {
222 BorderStyle::Solid => a.color,
223 BorderStyle::None => a.color.with_alpha(0x00),
224 };
225 let color_b = match b.style {
226 BorderStyle::Solid => b.color,
227 BorderStyle::None => b.color.with_alpha(0x00),
228 };
229 if a.stroke_align != b.stroke_align {
230 return BorderSide {
231 color: Color::lerp(Some(color_a), Some(color_b), t).unwrap(),
232 width,
233 stroke_align: lerp_double(Some(a.stroke_align), Some(b.stroke_align), t).unwrap(),
234 style: BorderStyle::Solid,
235 };
236 }
237 BorderSide {
238 color: Color::lerp(Some(color_a), Some(color_b), t).unwrap(),
239 width,
240 stroke_align: a.stroke_align, style: BorderStyle::Solid,
242 }
243 }
244
245 pub fn stroke_inset(&self) -> f64 {
247 self.width * (1.0 - (1.0 + self.stroke_align) / 2.0)
248 }
249
250 pub fn stroke_outset(&self) -> f64 {
252 self.width * (1.0 + self.stroke_align) / 2.0
253 }
254
255 pub fn stroke_offset(&self) -> f64 {
257 self.width * self.stroke_align
258 }
259}
260
261impl Default for BorderSide {
262 fn default() -> BorderSide {
263 BorderSide::new(
264 Color::new(0xFF000000),
265 1.0,
266 BorderStyle::Solid,
267 Self::STROKE_ALIGN_INSIDE,
268 )
269 }
270}
271
272impl Diagnosticable for BorderSide {
273 fn to_string_short(&self) -> String {
274 "BorderSide".to_string()
275 }
276
277 fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
278 properties.add(
279 ColorProperty::new("color", Some(self.color))
280 .default_value(Some(Color::new(0xFF000000))),
281 );
282 properties.add(DoubleProperty::new("width", Some(self.width)).default_value(Some(1.0)));
283 properties.add(
284 DoubleProperty::new("strokeAlign", Some(self.stroke_align))
285 .default_value(Some(Self::STROKE_ALIGN_INSIDE)),
286 );
287 properties.add(
288 EnumProperty::<BorderStyle>::new("style", Some(self.style))
289 .default_value(Some(BorderStyle::Solid)),
290 );
291 }
292}
293
294impl Debug for BorderSide {
295 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
296 f.write_str(&Diagnosticable::to_string(self))
297 }
298}
299
300impl fmt::Display for BorderSide {
302 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
303 Debug::fmt(self, f)
304 }
305}
306
307pub trait ShapeBorder: Any + Debug {
315 fn dimensions(&self) -> EdgeInsetsGeometry;
317
318 fn add(&self, other: &ShapeBorderRef, reversed: bool) -> Option<ShapeBorderRef> {
327 let _ = (other, reversed);
328 None
329 }
330
331 fn scale(&self, t: f64) -> ShapeBorderRef;
333
334 fn lerp_from(&self, a: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
340 if a.is_none() {
341 Some(self.scale(t))
342 } else {
343 None
344 }
345 }
346
347 fn lerp_to(&self, b: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
353 if b.is_none() {
354 Some(self.scale(1.0 - t))
355 } else {
356 None
357 }
358 }
359
360 fn get_outer_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path;
362
363 fn get_inner_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path;
365
366 fn hit_test(
368 &self,
369 rect: Rect,
370 position: Offset,
371 text_direction: Option<TextDirection>,
372 ) -> bool {
373 self.get_outer_path(rect, text_direction).contains(position)
374 }
375
376 fn paint_interior(
382 &self,
383 canvas: &mut Canvas,
384 rect: Rect,
385 paint: &Paint,
386 text_direction: Option<TextDirection>,
387 ) {
388 let _ = (canvas, rect, paint, text_direction);
389 debug_assert!(
390 !self.prefer_paint_interior(),
391 "prefer_paint_interior returns true but paint_interior is not implemented."
392 );
393 debug_assert!(
394 false,
395 "prefer_paint_interior returns false, so it is an error to call its paint_interior method."
396 );
397 }
398
399 fn prefer_paint_interior(&self) -> bool {
401 false
402 }
403
404 fn paint(&self, canvas: &mut Canvas, rect: Rect, text_direction: Option<TextDirection>);
406
407 fn as_any(&self) -> &dyn Any;
409
410 fn as_outlined_border(&self) -> Option<&dyn OutlinedBorder> {
412 None
413 }
414
415 fn into_outlined_border(self: Rc<Self>) -> Option<Rc<dyn OutlinedBorder>> {
419 None
420 }
421
422 fn as_box_border(&self) -> Option<&dyn crate::box_border::BoxBorder> {
424 None
425 }
426
427 fn into_box_border(self: Rc<Self>) -> Option<Rc<dyn crate::box_border::BoxBorder>> {
431 None
432 }
433
434 fn eq_shape(&self, other: &dyn ShapeBorder) -> bool {
437 std::ptr::addr_eq(self.as_any(), other.as_any())
438 }
439}
440
441#[derive(Clone)]
448pub struct ShapeBorderRef(Rc<dyn ShapeBorder>);
449
450impl ShapeBorderRef {
451 pub fn new(border: impl ShapeBorder) -> ShapeBorderRef {
453 ShapeBorderRef(Rc::new(border))
454 }
455
456 pub fn from_shared(border: Rc<dyn ShapeBorder>) -> ShapeBorderRef {
458 ShapeBorderRef(border)
459 }
460
461 pub fn as_box_border_ref(&self) -> Option<crate::box_border::BoxBorderRef> {
464 Rc::clone(&self.0)
465 .into_box_border()
466 .map(crate::box_border::BoxBorderRef::from_rc)
467 }
468
469 pub fn as_outlined_border_ref(&self) -> Option<OutlinedBorderRef> {
471 Rc::clone(&self.0)
472 .into_outlined_border()
473 .map(OutlinedBorderRef)
474 }
475
476 pub fn plus(&self, other: &ShapeBorderRef) -> ShapeBorderRef {
485 self.add(other, false)
486 .or_else(|| other.add(self, true))
487 .unwrap_or_else(|| {
488 ShapeBorderRef::new(CompoundBorder::new(vec![other.clone(), self.clone()]))
489 })
490 }
491
492 pub fn lerp(
494 a: Option<&ShapeBorderRef>,
495 b: Option<&ShapeBorderRef>,
496 t: f64,
497 ) -> Option<ShapeBorderRef> {
498 match (a, b) {
499 (None, None) => return None,
500 (Some(a), Some(b)) if Rc::ptr_eq(&a.0, &b.0) => return Some(a.clone()),
501 _ => {}
502 }
503 let (a_border, b_border) = (a.map(|a| &*a.0), b.map(|b| &*b.0));
504 b_border
505 .and_then(|b| b.lerp_from(a_border, t))
506 .or_else(|| a_border.and_then(|a| a.lerp_to(b_border, t)))
507 .or_else(|| b_border.and_then(|b| b.lerp_to(a_border, 1.0 - t)))
508 .or_else(|| a_border.and_then(|a| a.lerp_from(b_border, 1.0 - t)))
509 .or_else(|| if t < 0.5 { a.cloned() } else { b.cloned() })
510 }
511}
512
513impl<T: ShapeBorder> From<T> for ShapeBorderRef {
514 fn from(border: T) -> ShapeBorderRef {
515 ShapeBorderRef::new(border)
516 }
517}
518
519impl From<Box<dyn ShapeBorder>> for ShapeBorderRef {
520 fn from(border: Box<dyn ShapeBorder>) -> ShapeBorderRef {
521 ShapeBorderRef(Rc::from(border))
522 }
523}
524
525impl From<OutlinedBorderRef> for ShapeBorderRef {
526 fn from(border: OutlinedBorderRef) -> ShapeBorderRef {
527 ShapeBorderRef(border.0)
528 }
529}
530
531impl std::ops::Deref for ShapeBorderRef {
532 type Target = dyn ShapeBorder;
533
534 fn deref(&self) -> &dyn ShapeBorder {
535 &*self.0
536 }
537}
538
539impl PartialEq for ShapeBorderRef {
540 fn eq(&self, other: &ShapeBorderRef) -> bool {
541 Rc::ptr_eq(&self.0, &other.0) || self.0.eq_shape(&*other.0)
542 }
543}
544
545impl Debug for ShapeBorderRef {
546 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
547 Debug::fmt(&*self.0, f)
548 }
549}
550
551impl fmt::Display for ShapeBorderRef {
553 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
554 Debug::fmt(self, f)
555 }
556}
557
558impl PartialEq for dyn ShapeBorder {
559 fn eq(&self, other: &dyn ShapeBorder) -> bool {
560 self.eq_shape(other)
561 }
562}
563
564pub trait OutlinedBorder: ShapeBorder {
567 fn side(&self) -> BorderSide;
569
570 fn copy_with(&self, side: Option<BorderSide>) -> OutlinedBorderRef;
573}
574
575#[derive(Clone)]
578pub struct OutlinedBorderRef(Rc<dyn OutlinedBorder>);
579
580impl OutlinedBorderRef {
581 pub fn new(border: impl OutlinedBorder) -> OutlinedBorderRef {
583 OutlinedBorderRef(Rc::new(border))
584 }
585
586 pub fn lerp(
588 a: Option<&OutlinedBorderRef>,
589 b: Option<&OutlinedBorderRef>,
590 t: f64,
591 ) -> Option<OutlinedBorderRef> {
592 if let (Some(a), Some(b)) = (a, b)
593 && Rc::ptr_eq(&a.0, &b.0)
594 {
595 return Some(a.clone());
596 }
597 let result = ShapeBorderRef::lerp(
598 a.cloned().map(ShapeBorderRef::from).as_ref(),
599 b.cloned().map(ShapeBorderRef::from).as_ref(),
600 t,
601 )?;
602 Some(
605 result
606 .as_outlined_border_ref()
607 .expect("the lerp of two outlined borders is an OutlinedBorder"),
608 )
609 }
610}
611
612impl<T: OutlinedBorder> From<T> for OutlinedBorderRef {
613 fn from(border: T) -> OutlinedBorderRef {
614 OutlinedBorderRef::new(border)
615 }
616}
617
618impl std::ops::Deref for OutlinedBorderRef {
619 type Target = dyn OutlinedBorder;
620
621 fn deref(&self) -> &dyn OutlinedBorder {
622 &*self.0
623 }
624}
625
626impl PartialEq for OutlinedBorderRef {
627 fn eq(&self, other: &OutlinedBorderRef) -> bool {
628 Rc::ptr_eq(&self.0, &other.0) || self.0.eq_shape(&*other.0)
629 }
630}
631
632impl Debug for OutlinedBorderRef {
633 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
634 Debug::fmt(&*self.0, f)
635 }
636}
637
638impl std::fmt::Display for OutlinedBorderRef {
639 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
641 Debug::fmt(self, f)
642 }
643}
644
645impl PartialEq for dyn OutlinedBorder {
647 fn eq(&self, other: &dyn OutlinedBorder) -> bool {
648 self.eq_shape(other)
649 }
650}
651
652pub fn outlined_border_dimensions(side: BorderSide) -> EdgeInsetsGeometry {
654 EdgeInsetsGeometry::all(side.stroke_inset().max(0.0))
655}
656
657struct CompoundBorder {
661 borders: Vec<ShapeBorderRef>,
662}
663
664impl CompoundBorder {
665 fn new(borders: Vec<ShapeBorderRef>) -> CompoundBorder {
666 debug_assert!(borders.len() >= 2);
667 debug_assert!(
668 borders
669 .iter()
670 .all(|border| border.as_any().downcast_ref::<CompoundBorder>().is_none())
671 );
672 CompoundBorder { borders }
673 }
674
675 fn lerp(a: Option<&dyn ShapeBorder>, b: Option<&dyn ShapeBorder>, t: f64) -> CompoundBorder {
676 debug_assert!(
677 a.is_some_and(|border| border.as_any().downcast_ref::<CompoundBorder>().is_some())
678 || b.is_some_and(|border| border
679 .as_any()
680 .downcast_ref::<CompoundBorder>()
681 .is_some())
682 );
683 let a_list = compound_or_single(a);
684 let b_list = compound_or_single(b);
685 let mut results = Vec::new();
686 let length = a_list.len().max(b_list.len());
687 for index in 0..length {
688 let local_a = a_list.get(index).copied().flatten();
689 let local_b = b_list.get(index).copied().flatten();
690 if let (Some(local_a), Some(local_b)) = (local_a, local_b)
691 && let Some(local_result) = local_a
692 .lerp_to(Some(local_b), t)
693 .or_else(|| local_b.lerp_from(Some(local_a), t))
694 {
695 results.push(local_result);
696 continue;
697 }
698 if let Some(local_b) = local_b {
699 results.push(local_b.scale(t));
700 }
701 if let Some(local_a) = local_a {
702 results.push(local_a.scale(1.0 - t));
703 }
704 }
705 CompoundBorder::new(results)
706 }
707}
708
709fn compound_or_single(border: Option<&dyn ShapeBorder>) -> Vec<Option<&dyn ShapeBorder>> {
710 match border.and_then(|border| border.as_any().downcast_ref::<CompoundBorder>()) {
711 Some(compound) => compound.borders.iter().map(|b| Some(&**b)).collect(),
712 None => vec![border],
713 }
714}
715
716impl ShapeBorder for CompoundBorder {
717 fn dimensions(&self) -> EdgeInsetsGeometry {
718 self.borders
719 .iter()
720 .fold(EdgeInsetsGeometry::ZERO, |previous, border| {
721 previous.add(border.dimensions())
722 })
723 }
724
725 fn add(&self, other: &ShapeBorderRef, reversed: bool) -> Option<ShapeBorderRef> {
726 if other.as_any().downcast_ref::<CompoundBorder>().is_none() {
727 let ours = if reversed {
728 &self.borders[self.borders.len() - 1]
729 } else {
730 &self.borders[0]
731 };
732 let merged = ours
733 .add(other, reversed)
734 .or_else(|| other.add(ours, !reversed));
735 if let Some(merged) = merged {
736 let mut result = self.borders.clone();
737 let index = if reversed { result.len() - 1 } else { 0 };
738 result[index] = merged;
739 return Some(ShapeBorderRef::new(CompoundBorder::new(result)));
740 }
741 }
742 let mut merged_borders = Vec::new();
743 if reversed {
744 merged_borders.extend(self.borders.iter().cloned());
745 }
746 if let Some(other_compound) = other.as_any().downcast_ref::<CompoundBorder>() {
747 merged_borders.extend(other_compound.borders.iter().cloned());
748 } else {
749 merged_borders.push(other.clone());
750 }
751 if !reversed {
752 merged_borders.extend(self.borders.iter().cloned());
753 }
754 Some(ShapeBorderRef::new(CompoundBorder::new(merged_borders)))
755 }
756
757 fn scale(&self, t: f64) -> ShapeBorderRef {
758 ShapeBorderRef::new(CompoundBorder::new(
759 self.borders.iter().map(|border| border.scale(t)).collect(),
760 ))
761 }
762
763 fn lerp_from(&self, a: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
764 Some(ShapeBorderRef::new(CompoundBorder::lerp(a, Some(self), t)))
765 }
766
767 fn lerp_to(&self, b: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
768 Some(ShapeBorderRef::new(CompoundBorder::lerp(Some(self), b, t)))
769 }
770
771 fn get_inner_path(&self, mut rect: Rect, text_direction: Option<TextDirection>) -> Path {
772 for border in &self.borders[..self.borders.len() - 1] {
773 rect = border
774 .dimensions()
775 .resolve(text_direction)
776 .deflate_rect(rect);
777 }
778 self.borders[self.borders.len() - 1].get_inner_path(rect, text_direction)
779 }
780
781 fn get_outer_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
782 self.borders[0].get_outer_path(rect, text_direction)
783 }
784
785 fn hit_test(
786 &self,
787 rect: Rect,
788 position: Offset,
789 text_direction: Option<TextDirection>,
790 ) -> bool {
791 self.borders[0].hit_test(rect, position, text_direction)
792 }
793
794 fn paint_interior(
795 &self,
796 canvas: &mut Canvas,
797 rect: Rect,
798 paint: &Paint,
799 text_direction: Option<TextDirection>,
800 ) {
801 self.borders[0].paint_interior(canvas, rect, paint, text_direction);
802 }
803
804 fn prefer_paint_interior(&self) -> bool {
805 self.borders
806 .iter()
807 .all(|border| border.prefer_paint_interior())
808 }
809
810 fn paint(&self, canvas: &mut Canvas, mut rect: Rect, text_direction: Option<TextDirection>) {
811 for border in &self.borders {
812 border.paint(canvas, rect, text_direction);
813 rect = border
814 .dimensions()
815 .resolve(text_direction)
816 .deflate_rect(rect);
817 }
818 }
819
820 fn as_any(&self) -> &dyn Any {
821 self
822 }
823
824 fn eq_shape(&self, other: &dyn ShapeBorder) -> bool {
825 other
826 .as_any()
827 .downcast_ref::<CompoundBorder>()
828 .is_some_and(|other| {
829 self.borders.len() == other.borders.len()
830 && self
831 .borders
832 .iter()
833 .zip(other.borders.iter())
834 .all(|(a, b)| a.eq_shape(&**b))
835 })
836 }
837}
838
839impl Debug for CompoundBorder {
840 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
841 let mut first = true;
842 for border in self.borders.iter().rev() {
843 if !first {
844 write!(f, " + ")?;
845 }
846 first = false;
847 write!(f, "{border:?}")?;
848 }
849 Ok(())
850 }
851}
852
853pub fn paint_border(
862 canvas: &mut Canvas,
863 rect: Rect,
864 top: BorderSide,
865 right: BorderSide,
866 bottom: BorderSide,
867 left: BorderSide,
868) {
869 let mut paint = Paint {
873 style: PaintStyle::Stroke(Stroke::new(0.0)),
874 ..Paint::default()
875 };
876
877 match top.style {
878 BorderStyle::Solid => {
879 paint.color = top.color.into();
880 let mut path = PathBuilder::new();
881 path.move_to(Offset::new(rect.left, rect.top));
882 path.line_to(Offset::new(rect.right, rect.top));
883 if top.width == 0.0 {
884 paint.style = PaintStyle::Stroke(Stroke::new(0.0));
885 } else {
886 paint.style = PaintStyle::Fill;
887 path.line_to(Offset::new(rect.right - right.width, rect.top + top.width));
888 path.line_to(Offset::new(rect.left + left.width, rect.top + top.width));
889 }
890 canvas.draw_path(&path.build(), FillRule::NonZero, &paint);
891 }
892 BorderStyle::None => {}
893 }
894
895 match right.style {
896 BorderStyle::Solid => {
897 paint.color = right.color.into();
898 let mut path = PathBuilder::new();
899 path.move_to(Offset::new(rect.right, rect.top));
900 path.line_to(Offset::new(rect.right, rect.bottom));
901 if right.width == 0.0 {
902 paint.style = PaintStyle::Stroke(Stroke::new(0.0));
903 } else {
904 paint.style = PaintStyle::Fill;
905 path.line_to(Offset::new(
906 rect.right - right.width,
907 rect.bottom - bottom.width,
908 ));
909 path.line_to(Offset::new(rect.right - right.width, rect.top + top.width));
910 }
911 canvas.draw_path(&path.build(), FillRule::NonZero, &paint);
912 }
913 BorderStyle::None => {}
914 }
915
916 match bottom.style {
917 BorderStyle::Solid => {
918 paint.color = bottom.color.into();
919 let mut path = PathBuilder::new();
920 path.move_to(Offset::new(rect.right, rect.bottom));
921 path.line_to(Offset::new(rect.left, rect.bottom));
922 if bottom.width == 0.0 {
923 paint.style = PaintStyle::Stroke(Stroke::new(0.0));
924 } else {
925 paint.style = PaintStyle::Fill;
926 path.line_to(Offset::new(
927 rect.left + left.width,
928 rect.bottom - bottom.width,
929 ));
930 path.line_to(Offset::new(
931 rect.right - right.width,
932 rect.bottom - bottom.width,
933 ));
934 }
935 canvas.draw_path(&path.build(), FillRule::NonZero, &paint);
936 }
937 BorderStyle::None => {}
938 }
939
940 match left.style {
941 BorderStyle::Solid => {
942 paint.color = left.color.into();
943 let mut path = PathBuilder::new();
944 path.move_to(Offset::new(rect.left, rect.bottom));
945 path.line_to(Offset::new(rect.left, rect.top));
946 if left.width == 0.0 {
947 paint.style = PaintStyle::Stroke(Stroke::new(0.0));
948 } else {
949 paint.style = PaintStyle::Fill;
950 path.line_to(Offset::new(rect.left + left.width, rect.top + top.width));
951 path.line_to(Offset::new(
952 rect.left + left.width,
953 rect.bottom - bottom.width,
954 ));
955 }
956 canvas.draw_path(&path.build(), FillRule::NonZero, &paint);
957 }
958 BorderStyle::None => {}
959 }
960}
961
962pub trait BorderSideExtension: Any + Debug {
964 fn as_any(&self) -> &dyn Any;
966
967 fn eq_extension(&self, other: &dyn BorderSideExtension) -> bool;
971}
972
973#[derive(Clone)]
984pub struct AnyBorderSide {
985 value: BorderSide,
986 extension: Option<Rc<dyn BorderSideExtension>>,
987}
988
989impl AnyBorderSide {
990 pub fn new(value: BorderSide) -> AnyBorderSide {
992 AnyBorderSide {
993 value,
994 extension: None,
995 }
996 }
997
998 pub fn with_shared(value: BorderSide, extension: Rc<dyn BorderSideExtension>) -> AnyBorderSide {
1000 AnyBorderSide {
1001 value,
1002 extension: Some(extension),
1003 }
1004 }
1005
1006 pub fn value(&self) -> &BorderSide {
1008 &self.value
1009 }
1010
1011 pub fn extension<E: BorderSideExtension>(&self) -> Option<&E> {
1013 self.extension
1014 .as_ref()
1015 .and_then(|extension| extension.as_any().downcast_ref::<E>())
1016 }
1017
1018 pub fn has_extension(&self) -> bool {
1020 self.extension.is_some()
1021 }
1022}
1023
1024impl std::ops::Deref for AnyBorderSide {
1025 type Target = BorderSide;
1026
1027 fn deref(&self) -> &BorderSide {
1028 &self.value
1029 }
1030}
1031
1032impl From<BorderSide> for AnyBorderSide {
1033 fn from(value: BorderSide) -> AnyBorderSide {
1034 AnyBorderSide::new(value)
1035 }
1036}
1037
1038impl PartialEq for AnyBorderSide {
1039 fn eq(&self, other: &AnyBorderSide) -> bool {
1040 if self.value != other.value {
1041 return false;
1042 }
1043 match (&self.extension, &other.extension) {
1044 (None, None) => true,
1045 (Some(mine), Some(theirs)) => mine.eq_extension(&**theirs),
1046 _ => false,
1047 }
1048 }
1049}
1050
1051impl Debug for AnyBorderSide {
1052 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1053 match &self.extension {
1054 Some(extension) => extension.fmt(f),
1055 None => self.value.fmt(f),
1056 }
1057 }
1058}
1059
1060impl std::fmt::Display for AnyBorderSide {
1061 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1063 std::fmt::Debug::fmt(self, f)
1064 }
1065}
1066
1067#[cfg(test)]
1068mod tests {
1069 use super::*;
1070 use crate::box_border::Border;
1071
1072 fn side(color: Color, width: f64) -> BorderSide {
1073 BorderSide {
1074 color,
1075 width,
1076 ..BorderSide::default()
1077 }
1078 }
1079
1080 #[test]
1082 fn border_side_to_string() {
1083 let side = BorderSide::new(
1084 Color::new(0xFFAABBCC),
1085 1.2345,
1086 BorderStyle::Solid,
1087 BorderSide::STROKE_ALIGN_INSIDE,
1088 );
1089 assert_eq!(
1090 format!("{side}"),
1091 format!("BorderSide(color: {}, width: 1.2)", Color::new(0xFFAABBCC))
1092 );
1093 }
1094
1095 #[test]
1097 fn compound_borders_to_string() {
1098 let b1 = Border::all(Color::new(0xFF00FF00), 1.0, BorderStyle::Solid, -1.0);
1099 let b2 = Border::all(Color::new(0xFF0000FF), 1.0, BorderStyle::Solid, -1.0);
1100 let b1 = ShapeBorderRef::new(b1);
1101 let b2 = ShapeBorderRef::new(b2);
1102 assert_eq!(
1103 b1.plus(&b2).to_string(),
1104 format!(
1105 "Border.all(BorderSide(color: {})) + Border.all(BorderSide(color: {}))",
1106 Color::new(0xFF00FF00),
1107 Color::new(0xFF0000FF)
1108 )
1109 );
1110 let two_b2 = b2.plus(&b2);
1111 assert_eq!(
1112 b1.plus(&two_b2).to_string(),
1113 format!(
1114 "Border.all(BorderSide(color: {})) + Border.all(BorderSide(color: {}, width: 2.0))",
1115 Color::new(0xFF00FF00),
1116 Color::new(0xFF0000FF)
1117 )
1118 );
1119 let scaled = b1.plus(&b2).scale(3.0);
1120 assert_eq!(
1121 scaled.to_string(),
1122 format!(
1123 "Border.all(BorderSide(color: {}, width: 3.0)) + Border.all(BorderSide(color: {}, width: 3.0))",
1124 Color::new(0xFF00FF00),
1125 Color::new(0xFF0000FF)
1126 )
1127 );
1128 assert_eq!(
1129 b1.plus(&b2).scale(0.0).to_string(),
1130 format!(
1131 "Border.all(BorderSide(color: {}, width: 0.0, style: none)) + Border.all(BorderSide(color: {}, width: 0.0, style: none))",
1132 Color::new(0xFF00FF00),
1133 Color::new(0xFF0000FF)
1134 )
1135 );
1136 }
1137
1138 #[test]
1139 fn merging() {
1140 let blue = BorderSide {
1141 color: Color::new(0xFF0000FF),
1142 ..BorderSide::default()
1143 };
1144 let blue2 = BorderSide {
1145 color: Color::new(0xFF0000FF),
1146 width: 2.0,
1147 ..BorderSide::default()
1148 };
1149 let green = BorderSide {
1150 color: Color::new(0xFF00FF00),
1151 ..BorderSide::default()
1152 };
1153 let green2 = BorderSide {
1154 color: Color::new(0xFF00FF00),
1155 width: 2.0,
1156 ..BorderSide::default()
1157 };
1158 let green3 = BorderSide {
1159 color: Color::new(0xFF00FF00),
1160 width: 3.0,
1161 ..BorderSide::default()
1162 };
1163 let green5 = BorderSide {
1164 color: Color::new(0xFF00FF00),
1165 width: 5.0,
1166 ..BorderSide::default()
1167 };
1168 let none = BorderSide {
1169 style: BorderStyle::None,
1170 ..BorderSide::default()
1171 };
1172 let none2 = BorderSide {
1173 color: Color::new(0xFF0000FF),
1174 width: 2.0,
1175 style: BorderStyle::None,
1176 ..BorderSide::default()
1177 };
1178 let none3 = BorderSide {
1179 style: BorderStyle::None,
1180 width: 3.0,
1181 ..BorderSide::default()
1182 };
1183 let side2 = BorderSide {
1184 width: 2.0,
1185 ..BorderSide::default()
1186 };
1187 let side3 = BorderSide {
1188 width: 3.0,
1189 ..BorderSide::default()
1190 };
1191 let side5 = BorderSide {
1192 width: 5.0,
1193 ..BorderSide::default()
1194 };
1195 let solid = BorderSide::default();
1196 let yellow_none = BorderSide {
1197 style: BorderStyle::None,
1198 color: Color::new(0xFFFFFF00),
1199 width: 0.0,
1200 ..BorderSide::default()
1201 };
1202
1203 assert!(BorderSide::can_merge(BorderSide::NONE, BorderSide::NONE));
1204 assert!(BorderSide::can_merge(BorderSide::NONE, side2));
1205 assert!(BorderSide::can_merge(BorderSide::NONE, yellow_none));
1206 assert!(!BorderSide::can_merge(green, blue));
1207 assert!(!BorderSide::can_merge(green2, blue2));
1208 assert!(BorderSide::can_merge(green2, green3));
1209 assert!(!BorderSide::can_merge(green2, none2));
1210 assert!(BorderSide::can_merge(none3, BorderSide::NONE));
1211 assert!(!BorderSide::can_merge(none3, side2));
1212 assert!(BorderSide::can_merge(none3, yellow_none));
1213 assert!(BorderSide::can_merge(side2, BorderSide::NONE));
1214 assert!(!BorderSide::can_merge(side2, none3));
1215 assert!(BorderSide::can_merge(side2, side3));
1216 assert!(BorderSide::can_merge(side2, yellow_none));
1217 assert!(BorderSide::can_merge(side3, side2));
1218 assert!(!BorderSide::can_merge(solid, none));
1219 assert!(BorderSide::can_merge(yellow_none, side2));
1220 assert!(BorderSide::can_merge(yellow_none, yellow_none));
1221
1222 assert_eq!(
1223 BorderSide::merge(BorderSide::NONE, BorderSide::NONE),
1224 BorderSide::NONE
1225 );
1226 assert_eq!(BorderSide::merge(BorderSide::NONE, side2), side2);
1227 assert_eq!(
1228 BorderSide::merge(BorderSide::NONE, yellow_none),
1229 BorderSide::NONE
1230 );
1231 assert_eq!(BorderSide::merge(green2, green3), green5);
1232 assert_eq!(BorderSide::merge(none3, BorderSide::NONE), none3);
1233 assert_eq!(BorderSide::merge(none3, yellow_none), none3);
1234 assert_eq!(BorderSide::merge(side2, BorderSide::NONE), side2);
1235 assert_eq!(BorderSide::merge(side2, side3), side5);
1236 assert_eq!(BorderSide::merge(side2, yellow_none), side2);
1237 assert_eq!(BorderSide::merge(side3, side2), side5);
1238 assert_eq!(BorderSide::merge(yellow_none, side2), side2);
1239 assert_eq!(
1240 BorderSide::merge(yellow_none, yellow_none),
1241 BorderSide::NONE
1242 );
1243 }
1244
1245 #[test]
1246 fn copy_with_and_scale() {
1247 let green2 = BorderSide {
1248 color: Color::new(0xFF00FF00),
1249 width: 2.0,
1250 ..BorderSide::default()
1251 };
1252 let blue3 = BorderSide {
1253 color: Color::new(0xFF0000FF),
1254 width: 3.0,
1255 ..BorderSide::default()
1256 };
1257 let blue2 = BorderSide {
1258 color: Color::new(0xFF0000FF),
1259 width: 2.0,
1260 ..BorderSide::default()
1261 };
1262 let green3 = BorderSide {
1263 color: Color::new(0xFF00FF00),
1264 width: 3.0,
1265 ..BorderSide::default()
1266 };
1267 let none2 = BorderSide {
1268 color: Color::new(0xFF00FF00),
1269 width: 2.0,
1270 style: BorderStyle::None,
1271 ..BorderSide::default()
1272 };
1273 assert_eq!(
1274 green2.copy_with(Some(Color::new(0xFF0000FF)), Some(3.0), None, None),
1275 blue3
1276 );
1277 assert_eq!(green2.copy_with(None, Some(3.0), None, None), green3);
1278 assert_eq!(
1279 green2.copy_with(Some(Color::new(0xFF0000FF)), None, None, None),
1280 blue2
1281 );
1282 assert_eq!(
1283 green2.copy_with(None, None, Some(BorderStyle::None), None),
1284 none2
1285 );
1286
1287 let side3 = BorderSide {
1288 width: 3.0,
1289 color: Color::new(0xFF0000FF),
1290 ..BorderSide::default()
1291 };
1292 let side6 = BorderSide {
1293 width: 6.0,
1294 color: Color::new(0xFF0000FF),
1295 ..BorderSide::default()
1296 };
1297 let none = BorderSide {
1298 style: BorderStyle::None,
1299 width: 0.0,
1300 color: Color::new(0xFF0000FF),
1301 ..BorderSide::default()
1302 };
1303 assert_eq!(side3.scale(2.0), side6);
1304 assert_eq!(side6.scale(0.5), side3);
1305 assert_eq!(side6.scale(0.0), none);
1306 assert_eq!(side6.scale(-1.0), none);
1307 assert_eq!(none.scale(2.0), none);
1308 }
1309
1310 #[test]
1311 fn to_paint_stroke_and_none() {
1312 let paint1 = BorderSide {
1313 width: 2.5,
1314 color: Color::new(0xFFFFFF00),
1315 ..BorderSide::default()
1316 }
1317 .to_paint();
1318 assert_eq!(paint1.style, PaintStyle::Stroke(Stroke::new(2.5)));
1319 assert_eq!(paint1.color, Color::new(0xFFFFFF00).into());
1320 assert_eq!(paint1.blend_mode, waft_embedder::BlendMode::SrcOver);
1321
1322 let paint2 = BorderSide {
1323 width: 2.5,
1324 color: Color::new(0xFFFFFF00),
1325 style: BorderStyle::None,
1326 ..BorderSide::default()
1327 }
1328 .to_paint();
1329 assert_eq!(paint2.style, PaintStyle::Stroke(Stroke::new(0.0)));
1330 assert_eq!(paint2.color, Color::new(0x00000000).into());
1331 assert_eq!(paint2.blend_mode, waft_embedder::BlendMode::SrcOver);
1332 }
1333
1334 #[test]
1335 fn lerp_identical_and_negative_width() {
1336 let border = BorderSide::default();
1337 assert_eq!(BorderSide::lerp(border, border, 0.5), border);
1338
1339 let side0 = BorderSide {
1340 width: 0.0,
1341 ..BorderSide::default()
1342 };
1343 let side1 = BorderSide::default();
1344 let side2 = BorderSide {
1345 width: 2.0,
1346 ..BorderSide::default()
1347 };
1348 assert_eq!(BorderSide::lerp(side2, side1, 10.0), BorderSide::NONE);
1349 assert_eq!(BorderSide::lerp(side1, side2, -10.0), BorderSide::NONE);
1350 assert_eq!(BorderSide::lerp(side0, side1, 2.0), side2);
1351 assert_eq!(BorderSide::lerp(side1, side0, 2.0), BorderSide::NONE);
1352 assert_eq!(BorderSide::lerp(side2, side1, 2.0), side0);
1353 }
1354
1355 #[test]
1356 fn lerp_stroke_align() {
1357 let side0 = BorderSide {
1358 width: 2.0,
1359 ..BorderSide::default()
1360 };
1361 let side1 = BorderSide {
1362 width: 2.0,
1363 stroke_align: BorderSide::STROKE_ALIGN_OUTSIDE,
1364 ..BorderSide::default()
1365 };
1366 assert_eq!(
1367 BorderSide::lerp(side0, side1, 0.0),
1368 BorderSide {
1369 width: 2.0,
1370 ..BorderSide::default()
1371 }
1372 );
1373 assert_eq!(
1374 BorderSide::lerp(side0, side1, 0.5),
1375 BorderSide {
1376 width: 2.0,
1377 stroke_align: BorderSide::STROKE_ALIGN_CENTER,
1378 ..BorderSide::default()
1379 }
1380 );
1381 assert_eq!(
1382 BorderSide::lerp(side0, side1, 1.0),
1383 BorderSide {
1384 width: 2.0,
1385 stroke_align: BorderSide::STROKE_ALIGN_OUTSIDE,
1386 ..BorderSide::default()
1387 }
1388 );
1389
1390 let side2 = BorderSide {
1391 width: 2.0,
1392 ..BorderSide::default()
1393 };
1394 let side3 = BorderSide {
1395 width: 2.0,
1396 stroke_align: BorderSide::STROKE_ALIGN_CENTER,
1397 ..BorderSide::default()
1398 };
1399 assert_eq!(
1400 BorderSide::lerp(side2, side3, 0.5),
1401 BorderSide {
1402 width: 2.0,
1403 stroke_align: -0.5,
1404 ..BorderSide::default()
1405 }
1406 );
1407 }
1408
1409 #[test]
1410 fn paint_border_records_one_path_per_solid_side() {
1411 let mut canvas = Canvas::new();
1412 paint_border(
1413 &mut canvas,
1414 Rect::from_ltrb(0.0, 0.0, 10.0, 10.0),
1415 side(Color::new(0xFFFF0000), 1.0),
1416 side(Color::new(0xFF00FF00), 1.0),
1417 side(Color::new(0xFF0000FF), 1.0),
1418 side(Color::new(0xFFFFFF00), 1.0),
1419 );
1420 assert_eq!(canvas.build().draw_count(), 4);
1421 }
1422
1423 fn rect_path(rect: Rect) -> Path {
1424 let mut path = PathBuilder::new();
1425 path.rect(rect.into());
1426 path.build().into()
1427 }
1428
1429 #[derive(Clone, Copy, Debug)]
1431 struct LerpBorder {
1432 t: Option<f64>,
1433 side: BorderSide,
1434 }
1435
1436 impl LerpBorder {
1437 fn new(t: Option<f64>, side: BorderSide) -> LerpBorder {
1438 LerpBorder { t, side }
1439 }
1440 }
1441
1442 impl ShapeBorder for LerpBorder {
1443 fn dimensions(&self) -> EdgeInsetsGeometry {
1444 outlined_border_dimensions(self.side)
1445 }
1446
1447 fn scale(&self, t: f64) -> ShapeBorderRef {
1448 ShapeBorderRef::new(LerpBorder::new(Some(t), self.side.scale(t)))
1449 }
1450
1451 fn get_outer_path(&self, rect: Rect, _text_direction: Option<TextDirection>) -> Path {
1452 rect_path(rect)
1453 }
1454
1455 fn get_inner_path(&self, rect: Rect, _text_direction: Option<TextDirection>) -> Path {
1456 rect_path(rect)
1457 }
1458
1459 fn paint(&self, _canvas: &mut Canvas, _rect: Rect, _text_direction: Option<TextDirection>) {
1460 }
1461
1462 fn as_any(&self) -> &dyn Any {
1463 self
1464 }
1465
1466 fn as_outlined_border(&self) -> Option<&dyn OutlinedBorder> {
1467 Some(self)
1468 }
1469
1470 fn into_outlined_border(self: Rc<Self>) -> Option<Rc<dyn OutlinedBorder>> {
1471 Some(self)
1472 }
1473
1474 fn eq_shape(&self, other: &dyn ShapeBorder) -> bool {
1475 other
1476 .as_any()
1477 .downcast_ref::<LerpBorder>()
1478 .is_some_and(|other| other.t == self.t && other.side == self.side)
1479 }
1480 }
1481
1482 impl OutlinedBorder for LerpBorder {
1483 fn side(&self) -> BorderSide {
1484 self.side
1485 }
1486
1487 fn copy_with(&self, side: Option<BorderSide>) -> OutlinedBorderRef {
1488 OutlinedBorderRef::new(LerpBorder::new(self.t, side.unwrap_or(self.side)))
1489 }
1490 }
1491
1492 #[derive(Clone, Copy, Debug)]
1493 struct ReverseLerpToBorder;
1494
1495 impl ShapeBorder for ReverseLerpToBorder {
1496 fn dimensions(&self) -> EdgeInsetsGeometry {
1497 outlined_border_dimensions(BorderSide::NONE)
1498 }
1499
1500 fn lerp_to(&self, b: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
1501 if b.is_some_and(|b| b.as_any().downcast_ref::<LerpBorder>().is_some()) {
1502 Some(ShapeBorderRef::new(LerpBorder::new(
1503 Some(t),
1504 BorderSide::NONE,
1505 )))
1506 } else if b.is_none() {
1507 Some(self.scale(1.0 - t))
1508 } else {
1509 None
1510 }
1511 }
1512
1513 fn scale(&self, t: f64) -> ShapeBorderRef {
1514 ShapeBorderRef::new(LerpBorder::new(Some(t), BorderSide::NONE.scale(t)))
1515 }
1516
1517 fn get_outer_path(&self, rect: Rect, _text_direction: Option<TextDirection>) -> Path {
1518 rect_path(rect)
1519 }
1520
1521 fn get_inner_path(&self, rect: Rect, _text_direction: Option<TextDirection>) -> Path {
1522 rect_path(rect)
1523 }
1524
1525 fn paint(&self, _canvas: &mut Canvas, _rect: Rect, _text_direction: Option<TextDirection>) {
1526 }
1527
1528 fn as_any(&self) -> &dyn Any {
1529 self
1530 }
1531
1532 fn as_outlined_border(&self) -> Option<&dyn OutlinedBorder> {
1533 Some(self)
1534 }
1535
1536 fn into_outlined_border(self: Rc<Self>) -> Option<Rc<dyn OutlinedBorder>> {
1537 Some(self)
1538 }
1539 }
1540
1541 impl OutlinedBorder for ReverseLerpToBorder {
1542 fn side(&self) -> BorderSide {
1543 BorderSide::NONE
1544 }
1545
1546 fn copy_with(&self, _side: Option<BorderSide>) -> OutlinedBorderRef {
1547 OutlinedBorderRef::new(*self)
1548 }
1549 }
1550
1551 #[derive(Clone, Copy, Debug)]
1552 struct ReverseLerpFromBorder;
1553
1554 impl ShapeBorder for ReverseLerpFromBorder {
1555 fn dimensions(&self) -> EdgeInsetsGeometry {
1556 outlined_border_dimensions(BorderSide::NONE)
1557 }
1558
1559 fn lerp_from(&self, a: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
1560 if a.is_some_and(|a| a.as_any().downcast_ref::<LerpBorder>().is_some()) {
1561 Some(ShapeBorderRef::new(LerpBorder::new(
1562 Some(t),
1563 BorderSide::NONE,
1564 )))
1565 } else if a.is_none() {
1566 Some(self.scale(t))
1567 } else {
1568 None
1569 }
1570 }
1571
1572 fn scale(&self, t: f64) -> ShapeBorderRef {
1573 ShapeBorderRef::new(LerpBorder::new(Some(t), BorderSide::NONE.scale(t)))
1574 }
1575
1576 fn get_outer_path(&self, rect: Rect, _text_direction: Option<TextDirection>) -> Path {
1577 rect_path(rect)
1578 }
1579
1580 fn get_inner_path(&self, rect: Rect, _text_direction: Option<TextDirection>) -> Path {
1581 rect_path(rect)
1582 }
1583
1584 fn paint(&self, _canvas: &mut Canvas, _rect: Rect, _text_direction: Option<TextDirection>) {
1585 }
1586
1587 fn as_any(&self) -> &dyn Any {
1588 self
1589 }
1590
1591 fn as_outlined_border(&self) -> Option<&dyn OutlinedBorder> {
1592 Some(self)
1593 }
1594
1595 fn into_outlined_border(self: Rc<Self>) -> Option<Rc<dyn OutlinedBorder>> {
1596 Some(self)
1597 }
1598 }
1599
1600 impl OutlinedBorder for ReverseLerpFromBorder {
1601 fn side(&self) -> BorderSide {
1602 BorderSide::NONE
1603 }
1604
1605 fn copy_with(&self, _side: Option<BorderSide>) -> OutlinedBorderRef {
1606 OutlinedBorderRef::new(*self)
1607 }
1608 }
1609
1610 #[derive(Clone, Copy)]
1613 struct NamedWidthBorder {
1614 name: &'static str,
1615 width: f64,
1616 }
1617
1618 impl Debug for NamedWidthBorder {
1619 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
1620 write!(f, "NamedWidthBorder({}, {:.1})", self.name, self.width)
1621 }
1622 }
1623
1624 impl ShapeBorder for NamedWidthBorder {
1625 fn dimensions(&self) -> EdgeInsetsGeometry {
1626 EdgeInsetsGeometry::all(self.width)
1627 }
1628
1629 fn scale(&self, t: f64) -> ShapeBorderRef {
1630 ShapeBorderRef::new(NamedWidthBorder {
1631 name: self.name,
1632 width: (self.width * t).max(0.0),
1633 })
1634 }
1635
1636 fn get_outer_path(&self, rect: Rect, _text_direction: Option<TextDirection>) -> Path {
1637 rect_path(rect)
1638 }
1639
1640 fn get_inner_path(&self, rect: Rect, _text_direction: Option<TextDirection>) -> Path {
1641 rect_path(rect)
1642 }
1643
1644 fn paint(&self, _canvas: &mut Canvas, _rect: Rect, _text_direction: Option<TextDirection>) {
1645 }
1646
1647 fn as_any(&self) -> &dyn Any {
1648 self
1649 }
1650
1651 fn eq_shape(&self, other: &dyn ShapeBorder) -> bool {
1652 other
1653 .as_any()
1654 .downcast_ref::<NamedWidthBorder>()
1655 .is_some_and(|other| other.name == self.name && other.width == self.width)
1656 }
1657 }
1658
1659 #[test]
1660 fn a_shape_border_ref_equals_its_clones_and_compares_others_by_eq_shape() {
1661 let named = || {
1663 ShapeBorderRef::new(NamedWidthBorder {
1664 name: "green",
1665 width: 1.0,
1666 })
1667 };
1668 assert_eq!(named(), named());
1669 let shared = ShapeBorderRef::new(ShapeWithInterior);
1670 assert_eq!(shared.clone(), shared);
1671 assert_ne!(ShapeBorderRef::new(ShapeWithInterior), shared);
1672 }
1673
1674 #[test]
1675 fn an_outlined_border_ref_shares_its_border_with_the_shape_border_ref_made_of_it() {
1676 let outlined = OutlinedBorderRef::new(LerpBorder::new(None, BorderSide::NONE));
1677 let shape = ShapeBorderRef::from(outlined.clone());
1678 assert_eq!(shape.as_outlined_border_ref(), Some(outlined));
1679 assert!(
1680 ShapeBorderRef::new(ShapeWithInterior)
1681 .as_outlined_border_ref()
1682 .is_none()
1683 );
1684 }
1685
1686 #[test]
1687 fn shape_border_lerp_identical_a_b() {
1688 assert!(ShapeBorderRef::lerp(None, None, 0.0).is_none());
1689 let border = LerpBorder::new(None, BorderSide::NONE);
1690 let as_shape = ShapeBorderRef::new(border);
1691 let lerped = ShapeBorderRef::lerp(Some(&as_shape), Some(&as_shape), 0.5).unwrap();
1692 assert!(Rc::ptr_eq(&lerped.0, &as_shape.0), "Dart's `identical`");
1693 }
1694
1695 #[test]
1696 fn outlined_border_lerp_identical_a_b() {
1697 assert!(OutlinedBorderRef::lerp(None, None, 0.0).is_none());
1698 let border = LerpBorder::new(None, BorderSide::NONE);
1699 let as_outlined = OutlinedBorderRef::new(border);
1700 let lerped = OutlinedBorderRef::lerp(Some(&as_outlined), Some(&as_outlined), 0.5).unwrap();
1701 assert!(Rc::ptr_eq(&lerped.0, &as_outlined.0), "Dart's `identical`");
1702 }
1703
1704 #[test]
1705 fn shape_border_lerp_tries_equivalent_reverse_interpolation() {
1706 let a = ShapeBorderRef::new(LerpBorder::new(None, BorderSide::NONE));
1707 let b = ShapeBorderRef::new(ReverseLerpToBorder);
1708 let got = ShapeBorderRef::lerp(Some(&a), Some(&b), 0.25).unwrap();
1709 assert!(got.eq_shape(&LerpBorder::new(Some(0.75), BorderSide::NONE)));
1710
1711 let a = ShapeBorderRef::new(ReverseLerpFromBorder);
1712 let b = ShapeBorderRef::new(LerpBorder::new(None, BorderSide::NONE));
1713 let got = ShapeBorderRef::lerp(Some(&a), Some(&b), 0.25).unwrap();
1714 assert!(got.eq_shape(&LerpBorder::new(Some(0.75), BorderSide::NONE)));
1715 }
1716
1717 #[test]
1718 fn outlined_border_lerp_tries_equivalent_reverse_interpolation() {
1719 let a = OutlinedBorderRef::new(LerpBorder::new(None, BorderSide::NONE));
1720 let b = OutlinedBorderRef::new(ReverseLerpToBorder);
1721 let got = OutlinedBorderRef::lerp(Some(&a), Some(&b), 0.25).unwrap();
1722 assert!(got.eq_shape(&LerpBorder::new(Some(0.75), BorderSide::NONE)));
1723
1724 let a = OutlinedBorderRef::new(ReverseLerpFromBorder);
1725 let b = OutlinedBorderRef::new(LerpBorder::new(None, BorderSide::NONE));
1726 let got = OutlinedBorderRef::lerp(Some(&a), Some(&b), 0.25).unwrap();
1727 assert!(got.eq_shape(&LerpBorder::new(Some(0.75), BorderSide::NONE)));
1728 }
1729
1730 #[test]
1731 fn compound_borders() {
1732 let b1 = NamedWidthBorder {
1733 name: "green",
1734 width: 1.0,
1735 };
1736 let b2 = NamedWidthBorder {
1737 name: "blue",
1738 width: 1.0,
1739 };
1740 let (b1, b2) = (ShapeBorderRef::new(b1), ShapeBorderRef::new(b2));
1741 let compound = b1.plus(&b2);
1742 assert_eq!(
1743 format!("{compound:?}"),
1744 "NamedWidthBorder(green, 1.0) + NamedWidthBorder(blue, 1.0)"
1745 );
1746 assert_eq!(compound.dimensions(), EdgeInsetsGeometry::all(2.0));
1747
1748 let scaled = compound.scale(3.0);
1749 assert_eq!(
1750 format!("{scaled:?}"),
1751 "NamedWidthBorder(green, 3.0) + NamedWidthBorder(blue, 3.0)"
1752 );
1753
1754 let left = b1.plus(&b2);
1755 let right = b1.plus(&b2);
1756 assert!(left.eq_shape(&*right));
1757
1758 let b2b2 = b2.plus(&b2);
1759 let inner = b1.plus(&b2b2);
1760 let outer = b1.plus(&b2).plus(&b2);
1761 assert!(inner.eq_shape(&*outer));
1762 assert_eq!(inner.dimensions(), EdgeInsetsGeometry::all(3.0));
1763 }
1764
1765 #[test]
1766 fn shape_border_hit_test_uses_the_outer_path() {
1767 let border = NamedWidthBorder {
1768 name: "hit",
1769 width: 1.0,
1770 };
1771 let rect = Rect::from_ltrb(0.0, 0.0, 10.0, 10.0);
1772 assert!(border.hit_test(rect, Offset::new(5.0, 5.0), None));
1773 assert!(!border.hit_test(rect, Offset::new(-1.0, 5.0), None));
1774 }
1775
1776 #[derive(Clone, Copy, Debug)]
1777 struct ShapeWithInterior;
1778
1779 impl ShapeBorder for ShapeWithInterior {
1780 fn dimensions(&self) -> EdgeInsetsGeometry {
1781 EdgeInsetsGeometry::ZERO
1782 }
1783
1784 fn scale(&self, _t: f64) -> ShapeBorderRef {
1785 ShapeBorderRef::new(*self)
1786 }
1787
1788 fn get_outer_path(&self, rect: Rect, _text_direction: Option<TextDirection>) -> Path {
1789 rect_path(rect)
1790 }
1791
1792 fn get_inner_path(&self, rect: Rect, _text_direction: Option<TextDirection>) -> Path {
1793 rect_path(rect)
1794 }
1795
1796 fn paint_interior(
1797 &self,
1798 _canvas: &mut Canvas,
1799 _rect: Rect,
1800 _paint: &Paint,
1801 _text_direction: Option<TextDirection>,
1802 ) {
1803 }
1804
1805 fn prefer_paint_interior(&self) -> bool {
1806 true
1807 }
1808
1809 fn paint(&self, _canvas: &mut Canvas, _rect: Rect, _text_direction: Option<TextDirection>) {
1810 }
1811
1812 fn as_any(&self) -> &dyn Any {
1813 self
1814 }
1815 }
1816
1817 #[derive(Clone, Copy, Debug)]
1818 struct ShapeWithoutInterior;
1819
1820 impl ShapeBorder for ShapeWithoutInterior {
1821 fn dimensions(&self) -> EdgeInsetsGeometry {
1822 EdgeInsetsGeometry::ZERO
1823 }
1824
1825 fn scale(&self, _t: f64) -> ShapeBorderRef {
1826 ShapeBorderRef::new(*self)
1827 }
1828
1829 fn get_outer_path(&self, rect: Rect, _text_direction: Option<TextDirection>) -> Path {
1830 rect_path(rect)
1831 }
1832
1833 fn get_inner_path(&self, rect: Rect, _text_direction: Option<TextDirection>) -> Path {
1834 rect_path(rect)
1835 }
1836
1837 fn paint(&self, _canvas: &mut Canvas, _rect: Rect, _text_direction: Option<TextDirection>) {
1838 }
1839
1840 fn as_any(&self) -> &dyn Any {
1841 self
1842 }
1843 }
1844
1845 #[test]
1846 fn compound_borders_with_differing_prefer_paint_interiors() {
1847 assert!(ShapeWithInterior.prefer_paint_interior());
1848 assert!(!ShapeWithoutInterior.prefer_paint_interior());
1849 assert!(
1850 ShapeBorderRef::new(ShapeWithInterior)
1851 .plus(&ShapeBorderRef::new(ShapeWithInterior))
1852 .prefer_paint_interior()
1853 );
1854 assert!(
1855 !ShapeBorderRef::new(ShapeWithInterior)
1856 .plus(&ShapeBorderRef::new(ShapeWithoutInterior))
1857 .prefer_paint_interior()
1858 );
1859 assert!(
1860 !ShapeBorderRef::new(ShapeWithoutInterior)
1861 .plus(&ShapeBorderRef::new(ShapeWithInterior))
1862 .prefer_paint_interior()
1863 );
1864 assert!(
1865 !ShapeBorderRef::new(ShapeWithoutInterior)
1866 .plus(&ShapeBorderRef::new(ShapeWithoutInterior))
1867 .prefer_paint_interior()
1868 );
1869 }
1870}