Skip to main content

waft_material/
input_border.rs

1//! Flutter counterpart: material_ui's `input_border.dart`.
2//!
3//! `InputBorder` is a trait over [`ShapeBorder`] whose `paint` takes the floating label's gap;
4//! each border's `ShapeBorder::paint` is that `paint` with Dart's default gap arguments, so a
5//! caller holding an [`InputBorderRef`] names the trait: `InputBorder::paint(&*border, ..)`.
6
7use std::any::Any;
8use std::f64::consts::PI;
9use std::fmt::{self, Debug};
10use std::rc::Rc;
11
12use waft_embedder::{
13    Canvas, FillRule, Offset, Paint, Path, PathBuilder, PathOperation, RRect, Radius, Rect,
14    clamp_double, lerp_double, path_combine, rrect_radii_elliptical,
15};
16use waft_painting::{
17    BorderRadius, BorderSide, BorderStyle, BoxBorder, BoxShape, EdgeInsetsGeometry, ShapeBorder,
18    ShapeBorderRef, TextDirection, draw_rrect,
19};
20use waft_widgets::{MaybeWidgetStateProperty, WidgetStateProperty};
21
22/// Defines the appearance of an `InputDecorator`'s border.
23///
24/// An input decorator's border is specified by `InputDecoration.border`.
25///
26/// The border is drawn relative to the input decorator's "container" which
27/// is the optionally filled area above the decorator's helper, error,
28/// and counter.
29///
30/// Input border's are decorated with a line whose weight and color are defined
31/// by [`border_side`](Self::border_side). The input decorator's renderer animates the input
32/// border's appearance in response to state changes, like gaining or losing the focus,
33/// by creating new copies of its input border with [`copy_with`](Self::copy_with).
34///
35/// See also:
36///
37///  * [`UnderlineInputBorder`], the default `InputDecorator` border which
38///    draws a horizontal line at the bottom of the input decorator's container.
39///  * [`OutlineInputBorder`], an `InputDecorator` border which draws a
40///    rounded rectangle around the input decorator's container.
41///  * `InputDecoration`, which is used to configure an `InputDecorator`.
42pub trait InputBorder: ShapeBorder {
43    /// Defines the border line's color and weight.
44    ///
45    /// The `InputDecorator` creates copies of its input border, using [`copy_with`](Self::copy_with),
46    /// based on the current theme and `InputDecorator.isFocused`.
47    fn border_side(&self) -> BorderSide;
48
49    /// Creates a copy of this input border with the specified `border_side`.
50    fn copy_with(&self, border_side: Option<BorderSide>) -> InputBorderRef;
51
52    /// True if this border will enclose the `InputDecorator`'s container.
53    ///
54    /// This property affects the alignment of container's contents. For example
55    /// when an input decorator is configured with an [`OutlineInputBorder`] its
56    /// label is centered with its container.
57    fn is_outline(&self) -> bool;
58
59    /// Paint this input border on `canvas`.
60    ///
61    /// The `rect` parameter bounds the `InputDecorator`'s container.
62    ///
63    /// The additional `gap` parameters reflect the state of the `InputDecorator`'s
64    /// floating label. When an input decorator gains the focus, its label
65    /// animates upwards, to make room for the input child. The `gap_start` and
66    /// `gap_extent` parameters define a floating label width interval, and
67    /// `gap_percentage` defines the animation's progress (0.0 to 1.0).
68    ///
69    /// Dart's defaults are `gap_extent: 0.0` and `gap_percentage: 0.0`, which the border's
70    /// `ShapeBorder::paint` passes.
71    fn paint(
72        &self,
73        canvas: &mut Canvas,
74        rect: Rect,
75        gap_start: Option<f64>,
76        gap_extent: f64,
77        gap_percentage: f64,
78        text_direction: Option<TextDirection>,
79    );
80
81    /// Dart's `border is WidgetStateProperty<InputBorder>`: this border as the property it
82    /// also is, for the borders that implement `WidgetStateProperty` (`WidgetStateInputBorder`
83    /// and the deprecated `MaterialState` input borders).
84    fn as_widget_state_property(&self) -> Option<&dyn WidgetStateProperty<InputBorderRef>> {
85        None
86    }
87}
88
89/// An [`InputBorder`] held by value: what a Dart field or parameter typed `InputBorder`
90/// becomes; [`ShapeBorderRef`]'s sharing and equality, for the narrower type.
91#[derive(Clone)]
92pub struct InputBorderRef(Rc<dyn InputBorder>);
93
94impl InputBorderRef {
95    /// Erases an [`InputBorder`].
96    pub fn new(border: impl InputBorder) -> InputBorderRef {
97        InputBorderRef(Rc::new(border))
98    }
99
100    /// No input border.
101    ///
102    /// Use this value with `InputDecoration.border` to specify that no border
103    /// should be drawn. The `InputDecoration.collapsed` constructor sets
104    /// its border to this value.
105    pub fn none() -> InputBorderRef {
106        InputBorderRef::new(NoInputBorder)
107    }
108}
109
110impl<T: InputBorder> From<T> for InputBorderRef {
111    fn from(border: T) -> InputBorderRef {
112        InputBorderRef::new(border)
113    }
114}
115
116/// Dart's `InputBorder extends ShapeBorder`: an input border is used wherever a shape is.
117impl From<InputBorderRef> for ShapeBorderRef {
118    fn from(border: InputBorderRef) -> ShapeBorderRef {
119        ShapeBorderRef::from_shared(border.0)
120    }
121}
122
123impl std::ops::Deref for InputBorderRef {
124    type Target = dyn InputBorder;
125
126    fn deref(&self) -> &dyn InputBorder {
127        &*self.0
128    }
129}
130
131impl PartialEq for InputBorderRef {
132    fn eq(&self, other: &InputBorderRef) -> bool {
133        Rc::ptr_eq(&self.0, &other.0) || self.0.eq_shape(&*other.0)
134    }
135}
136
137impl Debug for InputBorderRef {
138    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139        Debug::fmt(&*self.0, f)
140    }
141}
142
143impl PartialEq for dyn InputBorder {
144    fn eq(&self, other: &dyn InputBorder) -> bool {
145        self.eq_shape(other)
146    }
147}
148
149/// Dart's `T?` is `InputBorder?`: a `WidgetStateInputBorder` resolves to a border, which
150/// `resolve_as` wraps in `Some` for an `Option<InputBorderRef>`.
151impl MaybeWidgetStateProperty<InputBorderRef> for InputBorderRef {
152    fn as_widget_state_property(&self) -> Option<&dyn WidgetStateProperty<InputBorderRef>> {
153        InputBorder::as_widget_state_property(&**self)
154    }
155
156    fn from_resolved(value: InputBorderRef) -> InputBorderRef {
157        value
158    }
159}
160
161/// Dart's `Path()..addRect(rect)`.
162fn rect_path(rect: Rect) -> Path {
163    let mut path = PathBuilder::new();
164    path.rect(rect.into());
165    path.build().into()
166}
167
168/// Dart's `Path()..addRRect(rrect)`.
169fn rrect_path(rrect: RRect) -> Path {
170    let mut path = PathBuilder::new();
171    path.rrect_radii_elliptical(rrect.outer_rect(), rrect_radii_elliptical(rrect));
172    path.build().into()
173}
174
175/// Dart's `Path.addArc(oval, startAngle, sweepAngle)`: a new contour along the oval inscribed
176/// in `oval`, from `start_angle` clockwise through `sweep_angle` radians. An empty oval or a
177/// zero sweep adds nothing, as Skia's `addArc` does.
178fn add_arc(path: &mut PathBuilder, oval: Rect, start_angle: f64, sweep_angle: f64) {
179    if oval.is_empty() || sweep_angle == 0.0 {
180        return;
181    }
182    let center = oval.center();
183    let radius_x = oval.width() / 2.0;
184    let radius_y = oval.height() / 2.0;
185    path.move_to(Offset::new(
186        center.dx() + radius_x * start_angle.cos(),
187        center.dy() + radius_y * start_angle.sin(),
188    ));
189    path.ellipse(
190        center,
191        [radius_x as f32, radius_y as f32],
192        0.0,
193        start_angle as f32,
194        sweep_angle as f32,
195    );
196}
197
198/// Dart's `Canvas.drawLine`: a stroked two-point path.
199fn draw_line(canvas: &mut Canvas, p1: Offset, p2: Offset, paint: &Paint) {
200    let mut path = PathBuilder::new();
201    path.move_to(p1);
202    path.line_to(p2);
203    canvas.draw_path(&path.build(), FillRule::NonZero, paint);
204}
205
206// Used to create the InputBorder.none singleton.
207#[derive(Clone, Copy)]
208struct NoInputBorder;
209
210impl ShapeBorder for NoInputBorder {
211    fn dimensions(&self) -> EdgeInsetsGeometry {
212        EdgeInsetsGeometry::ZERO
213    }
214
215    fn scale(&self, _t: f64) -> ShapeBorderRef {
216        ShapeBorderRef::new(NoInputBorder)
217    }
218
219    fn get_outer_path(&self, rect: Rect, _text_direction: Option<TextDirection>) -> Path {
220        rect_path(rect)
221    }
222
223    fn get_inner_path(&self, rect: Rect, _text_direction: Option<TextDirection>) -> Path {
224        rect_path(rect)
225    }
226
227    fn paint_interior(
228        &self,
229        canvas: &mut Canvas,
230        rect: Rect,
231        paint: &Paint,
232        _text_direction: Option<TextDirection>,
233    ) {
234        canvas.draw_rect(rect, paint);
235    }
236
237    fn prefer_paint_interior(&self) -> bool {
238        true
239    }
240
241    fn paint(&self, canvas: &mut Canvas, rect: Rect, text_direction: Option<TextDirection>) {
242        InputBorder::paint(self, canvas, rect, None, 0.0, 0.0, text_direction);
243    }
244
245    fn as_any(&self) -> &dyn Any {
246        self
247    }
248
249    // Dart's `InputBorder.none` is the one `const _NoInputBorder()`, so every no-border is
250    // identical to every other.
251    fn eq_shape(&self, other: &dyn ShapeBorder) -> bool {
252        other.as_any().is::<NoInputBorder>()
253    }
254}
255
256impl InputBorder for NoInputBorder {
257    fn border_side(&self) -> BorderSide {
258        BorderSide::NONE
259    }
260
261    fn copy_with(&self, _border_side: Option<BorderSide>) -> InputBorderRef {
262        InputBorderRef::new(NoInputBorder)
263    }
264
265    fn is_outline(&self) -> bool {
266        false
267    }
268
269    fn paint(
270        &self,
271        _canvas: &mut Canvas,
272        _rect: Rect,
273        _gap_start: Option<f64>,
274        _gap_extent: f64,
275        _gap_percentage: f64,
276        _text_direction: Option<TextDirection>,
277    ) {
278        // Do not paint.
279    }
280}
281
282impl Debug for NoInputBorder {
283    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
284        f.write_str("_NoInputBorder()")
285    }
286}
287
288/// Draws a horizontal line at the bottom of an `InputDecorator`'s container and
289/// defines the container's shape.
290///
291/// The input decorator's "container" is the optionally filled area above the
292/// decorator's helper, error, and counter.
293///
294/// See also:
295///
296///  * [`OutlineInputBorder`], an `InputDecorator` border which draws a
297///    rounded rectangle around the input decorator's container.
298///  * `InputDecoration`, which is used to configure an `InputDecorator`.
299#[derive(Clone, Copy, PartialEq)]
300pub struct UnderlineInputBorder {
301    /// Defines the border line's color and weight.
302    pub border_side: BorderSide,
303
304    /// The radii of the border's rounded rectangle corners.
305    ///
306    /// When this border is used with a filled input decorator, see
307    /// `InputDecoration.filled`, the border radius defines the shape
308    /// of the background fill as well as the bottom left and right
309    /// edges of the underline itself.
310    ///
311    /// By default the top right and top left corners have a circular radius
312    /// of 4.0.
313    pub border_radius: BorderRadius,
314}
315
316impl Default for UnderlineInputBorder {
317    /// Creates an underline border for an `InputDecorator`.
318    ///
319    /// The [`border_side`](Self::border_side) parameter defaults to `BorderSide()`.
320    /// Applications typically do not specify a `border_side` parameter
321    /// because the input decorator substitutes its own, using `copy_with`, based
322    /// on the current theme and `InputDecorator.isFocused`.
323    ///
324    /// The [`border_radius`](Self::border_radius) parameter defaults to a value where the top
325    /// left and right corners have a circular radius of 4.0.
326    fn default() -> UnderlineInputBorder {
327        UnderlineInputBorder {
328            border_side: BorderSide::default(),
329            border_radius: BorderRadius::only(
330                Radius::circular(4.0),
331                Radius::circular(4.0),
332                Radius::ZERO,
333                Radius::ZERO,
334            ),
335        }
336    }
337}
338
339impl UnderlineInputBorder {
340    /// Creates an underline border for an `InputDecorator`, with Dart's defaults.
341    pub fn new() -> UnderlineInputBorder {
342        UnderlineInputBorder::default()
343    }
344
345    /// Dart `UnderlineInputBorder(borderSide:)`.
346    pub fn border_side(mut self, border_side: BorderSide) -> UnderlineInputBorder {
347        self.border_side = border_side;
348        self
349    }
350
351    /// Dart `UnderlineInputBorder(borderRadius:)`.
352    pub fn border_radius(mut self, border_radius: BorderRadius) -> UnderlineInputBorder {
353        self.border_radius = border_radius;
354        self
355    }
356
357    /// Creates a copy of this border with the given fields replaced.
358    pub fn copy_with(
359        &self,
360        border_side: Option<BorderSide>,
361        border_radius: Option<BorderRadius>,
362    ) -> UnderlineInputBorder {
363        UnderlineInputBorder {
364            border_side: border_side.unwrap_or(self.border_side),
365            border_radius: border_radius.unwrap_or(self.border_radius),
366        }
367    }
368
369    /// Creates a copy of this border, scaled by the factor `t`.
370    pub fn scale(&self, t: f64) -> UnderlineInputBorder {
371        UnderlineInputBorder::new().border_side(self.border_side.scale(t))
372    }
373}
374
375impl ShapeBorder for UnderlineInputBorder {
376    fn dimensions(&self) -> EdgeInsetsGeometry {
377        EdgeInsetsGeometry::only(0.0, 0.0, 0.0, self.border_side.width)
378    }
379
380    fn scale(&self, t: f64) -> ShapeBorderRef {
381        ShapeBorderRef::new(UnderlineInputBorder::scale(self, t))
382    }
383
384    fn lerp_from(&self, a: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
385        if let Some(a) = a.and_then(|a| a.as_any().downcast_ref::<UnderlineInputBorder>()) {
386            return Some(ShapeBorderRef::new(UnderlineInputBorder {
387                border_side: BorderSide::lerp(a.border_side, self.border_side, t),
388                border_radius: BorderRadius::lerp(
389                    Some(a.border_radius),
390                    Some(self.border_radius),
391                    t,
392                )
393                .expect("both radii are given"),
394            }));
395        }
396        if a.is_none() {
397            Some(ShapeBorder::scale(self, t))
398        } else {
399            None
400        }
401    }
402
403    fn lerp_to(&self, b: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
404        if let Some(b) = b.and_then(|b| b.as_any().downcast_ref::<UnderlineInputBorder>()) {
405            return Some(ShapeBorderRef::new(UnderlineInputBorder {
406                border_side: BorderSide::lerp(self.border_side, b.border_side, t),
407                border_radius: BorderRadius::lerp(
408                    Some(self.border_radius),
409                    Some(b.border_radius),
410                    t,
411                )
412                .expect("both radii are given"),
413            }));
414        }
415        if b.is_none() {
416            Some(ShapeBorder::scale(self, 1.0 - t))
417        } else {
418            None
419        }
420    }
421
422    fn get_inner_path(&self, rect: Rect, _text_direction: Option<TextDirection>) -> Path {
423        rect_path(Rect::from_ltwh(
424            rect.left,
425            rect.top,
426            rect.width(),
427            (rect.height() - self.border_side.width).max(0.0),
428        ))
429    }
430
431    fn get_outer_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
432        rrect_path(self.border_radius.resolve(text_direction).to_rrect(rect))
433    }
434
435    fn paint_interior(
436        &self,
437        canvas: &mut Canvas,
438        rect: Rect,
439        paint: &Paint,
440        text_direction: Option<TextDirection>,
441    ) {
442        draw_rrect(
443            canvas,
444            self.border_radius.resolve(text_direction).to_rrect(rect),
445            paint,
446        );
447    }
448
449    fn prefer_paint_interior(&self) -> bool {
450        true
451    }
452
453    fn paint(&self, canvas: &mut Canvas, rect: Rect, text_direction: Option<TextDirection>) {
454        InputBorder::paint(self, canvas, rect, None, 0.0, 0.0, text_direction);
455    }
456
457    fn as_any(&self) -> &dyn Any {
458        self
459    }
460
461    fn eq_shape(&self, other: &dyn ShapeBorder) -> bool {
462        other
463            .as_any()
464            .downcast_ref::<UnderlineInputBorder>()
465            .is_some_and(|other| other == self)
466    }
467}
468
469impl InputBorder for UnderlineInputBorder {
470    fn border_side(&self) -> BorderSide {
471        self.border_side
472    }
473
474    fn copy_with(&self, border_side: Option<BorderSide>) -> InputBorderRef {
475        InputBorderRef::new(UnderlineInputBorder::copy_with(self, border_side, None))
476    }
477
478    fn is_outline(&self) -> bool {
479        false
480    }
481
482    /// Draw a horizontal line at the bottom of `rect`.
483    ///
484    /// The [`border_side`](UnderlineInputBorder::border_side) defines the line's color and
485    /// weight. The `text_direction` `gap` and `text_direction` parameters are ignored.
486    fn paint(
487        &self,
488        canvas: &mut Canvas,
489        rect: Rect,
490        _gap_start: Option<f64>,
491        _gap_extent: f64,
492        _gap_percentage: f64,
493        text_direction: Option<TextDirection>,
494    ) {
495        if self.border_side.style == BorderStyle::None {
496            return;
497        }
498
499        if self.border_radius.bottom_left != Radius::ZERO
500            || self.border_radius.bottom_right != Radius::ZERO
501        {
502            // This prevents the border from leaking the color due to anti-aliasing rounding errors.
503            let updated_border_radius = BorderRadius::only(
504                Radius::ZERO,
505                Radius::ZERO,
506                self.border_radius
507                    .bottom_left
508                    .clamp(None, Some(Radius::circular(rect.height() / 2.0))),
509                self.border_radius
510                    .bottom_right
511                    .clamp(None, Some(Radius::circular(rect.height() / 2.0))),
512            );
513
514            <dyn BoxBorder>::paint_non_uniform_border(
515                canvas,
516                rect,
517                Some(updated_border_radius),
518                text_direction,
519                BoxShape::Rectangle,
520                BorderSide::NONE,
521                BorderSide::NONE,
522                self.border_side
523                    .copy_with(None, None, None, Some(BorderSide::STROKE_ALIGN_INSIDE)),
524                BorderSide::NONE,
525                self.border_side.color,
526            );
527        } else {
528            let align_inside_offset = Offset::new(0.0, self.border_side.width / 2.0);
529            draw_line(
530                canvas,
531                rect.bottom_left() - align_inside_offset,
532                rect.bottom_right() - align_inside_offset,
533                &self.border_side.to_paint(),
534            );
535        }
536    }
537}
538
539impl Debug for UnderlineInputBorder {
540    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
541        f.write_str("UnderlineInputBorder()")
542    }
543}
544
545/// Draws a rounded rectangle around an `InputDecorator`'s container.
546///
547/// When the input decorator's label is floating, for example because its
548/// input child has the focus, the label appears in a gap in the border outline.
549///
550/// The input decorator's "container" is the optionally filled area above the
551/// decorator's helper, error, and counter.
552///
553/// See also:
554///
555///  * [`UnderlineInputBorder`], the default `InputDecorator` border which
556///    draws a horizontal line at the bottom of the input decorator's container.
557///  * [`ShapedInputBorder`], an `InputDecorator` border which draws a custom
558///    [`ShapeBorder`] around the input decorator's container.
559///  * `InputDecoration`, which is used to configure an `InputDecorator`.
560#[derive(Clone, Copy, PartialEq)]
561pub struct OutlineInputBorder {
562    /// Defines the border line's color and weight.
563    pub border_side: BorderSide,
564
565    /// Horizontal padding on either side of the border's
566    /// `InputDecoration.labelText` width gap.
567    ///
568    /// This value is used by the [`paint`](InputBorder::paint) method to compute the actual
569    /// gap width.
570    pub gap_padding: f64,
571
572    /// The radii of the border's rounded rectangle corners.
573    ///
574    /// The corner radii must be circular, i.e. their [`Radius::x`] and [`Radius::y`]
575    /// values must be the same.
576    pub border_radius: BorderRadius,
577}
578
579impl Default for OutlineInputBorder {
580    /// Creates a rounded rectangle outline border for an `InputDecorator`.
581    ///
582    /// If the [`border_side`](Self::border_side) parameter is [`BorderSide::NONE`], it will not
583    /// draw a border. However, it will still define a shape (which you can see if
584    /// `InputDecoration.filled` is true).
585    ///
586    /// If an application does not specify a `border_side` parameter of
587    /// value [`BorderSide::NONE`], the input decorator substitutes its own, using
588    /// `copy_with`, based on the current theme and `InputDecorator.isFocused`.
589    ///
590    /// The [`border_radius`](Self::border_radius) parameter defaults to a value where all four
591    /// corners have a circular radius of 4.0. The corner radii must be circular, i.e.
592    /// their [`Radius::x`] and [`Radius::y`] values must be the same.
593    ///
594    /// See also:
595    ///
596    ///  * `InputDecoration.floatingLabelBehavior`, which should be set to
597    ///    `FloatingLabelBehavior.never` when the `border_side` is
598    ///    [`BorderSide::NONE`]. If left as `FloatingLabelBehavior.auto`, the label
599    ///    will extend beyond the container as if the border were still being
600    ///    drawn.
601    fn default() -> OutlineInputBorder {
602        OutlineInputBorder {
603            border_side: BorderSide::default(),
604            gap_padding: 4.0,
605            border_radius: BorderRadius::all(Radius::circular(4.0)),
606        }
607    }
608}
609
610impl OutlineInputBorder {
611    /// Creates a rounded rectangle outline border for an `InputDecorator`, with Dart's
612    /// defaults.
613    pub fn new() -> OutlineInputBorder {
614        OutlineInputBorder::default()
615    }
616
617    /// Dart `OutlineInputBorder(borderSide:)`.
618    pub fn border_side(mut self, border_side: BorderSide) -> OutlineInputBorder {
619        self.border_side = border_side;
620        self
621    }
622
623    /// Dart `OutlineInputBorder(borderRadius:)`.
624    pub fn border_radius(mut self, border_radius: BorderRadius) -> OutlineInputBorder {
625        self.border_radius = border_radius;
626        self
627    }
628
629    /// Dart `OutlineInputBorder(gapPadding:)`.
630    pub fn gap_padding(mut self, gap_padding: f64) -> OutlineInputBorder {
631        debug_assert!(gap_padding >= 0.0);
632        self.gap_padding = gap_padding;
633        self
634    }
635
636    // The label text's gap can extend into the corners (even both the top left
637    // and the top right corner). To avoid the more complicated problem of finding
638    // how far the gap penetrates into an elliptical corner, just require them
639    // to be circular.
640    //
641    // This can't be checked by the constructor because const constructor.
642    fn corners_are_circular(border_radius: BorderRadius) -> bool {
643        border_radius.top_left.x == border_radius.top_left.y
644            && border_radius.bottom_left.x == border_radius.bottom_left.y
645            && border_radius.top_right.x == border_radius.top_right.y
646            && border_radius.bottom_right.x == border_radius.bottom_right.y
647    }
648
649    /// Creates a copy of this border with the given fields replaced.
650    pub fn copy_with(
651        &self,
652        border_side: Option<BorderSide>,
653        border_radius: Option<BorderRadius>,
654        gap_padding: Option<f64>,
655    ) -> OutlineInputBorder {
656        OutlineInputBorder::new()
657            .border_side(border_side.unwrap_or(self.border_side))
658            .border_radius(border_radius.unwrap_or(self.border_radius))
659            .gap_padding(gap_padding.unwrap_or(self.gap_padding))
660    }
661
662    /// Creates a copy of this border, scaled by the factor `t`.
663    pub fn scale(&self, t: f64) -> OutlineInputBorder {
664        OutlineInputBorder::new()
665            .border_side(self.border_side.scale(t))
666            .border_radius(self.border_radius * t)
667            .gap_padding(self.gap_padding * t)
668    }
669
670    fn gap_border_path(&self, center: RRect, outer_width: f64, start: f64, extent: f64) -> Path {
671        // When the corner radii on any side add up to be greater than the
672        // given height, each radius has to be scaled to not exceed the
673        // size of the width/height of the RRect.
674        let scaled_rrect = center.scale_radii();
675
676        let tl_corner = Rect::from_ltwh(
677            scaled_rrect.left,
678            scaled_rrect.top,
679            scaled_rrect.tl_radius_x * 2.0,
680            scaled_rrect.tl_radius_y * 2.0,
681        );
682        let tr_corner = Rect::from_ltwh(
683            scaled_rrect.right - scaled_rrect.tr_radius_x * 2.0,
684            scaled_rrect.top,
685            scaled_rrect.tr_radius_x * 2.0,
686            scaled_rrect.tr_radius_y * 2.0,
687        );
688        let br_corner = Rect::from_ltwh(
689            scaled_rrect.right - scaled_rrect.br_radius_x * 2.0,
690            scaled_rrect.bottom - scaled_rrect.br_radius_y * 2.0,
691            scaled_rrect.br_radius_x * 2.0,
692            scaled_rrect.br_radius_y * 2.0,
693        );
694        let bl_corner = Rect::from_ltwh(
695            scaled_rrect.left,
696            scaled_rrect.bottom - scaled_rrect.bl_radius_y * 2.0,
697            scaled_rrect.bl_radius_x * 2.0,
698            scaled_rrect.bl_radius_y * 2.0,
699        );
700
701        // This assumes that the radius is circular (x and y radius are equal).
702        // Currently, BorderRadius only supports circular radii.
703        const CORNER_ARC_SWEEP: f64 = PI / 2.0;
704        let mut path = PathBuilder::new();
705
706        // Top left corner
707        if scaled_rrect.tl_radius() != Radius::ZERO {
708            let tl_corner_arc_sweep =
709                clamp_double(1.0 - start / scaled_rrect.tl_radius_x, 0.0, 1.0).acos();
710            add_arc(&mut path, tl_corner, PI, tl_corner_arc_sweep);
711        } else {
712            // Because the path is painted with Paint.strokeCap = StrokeCap.butt, horizontal coordinate is moved
713            // based on strokeOffset to respect strokeAlign.
714            path.move_to(Offset::new(
715                scaled_rrect.left + self.border_side.stroke_offset() / 2.0,
716                scaled_rrect.top,
717            ));
718        }
719
720        // Draw top border from top left corner to gap start.
721        if start > scaled_rrect.tl_radius_x {
722            path.line_to(Offset::new(start, scaled_rrect.top));
723        }
724
725        // Draw top border from gap end to top right corner and draw top right corner.
726        const TR_CORNER_ARC_START: f64 = (3.0 * PI) / 2.0;
727        const TR_CORNER_ARC_SWEEP: f64 = CORNER_ARC_SWEEP;
728        if start + extent < outer_width - scaled_rrect.tr_radius_x {
729            path.move_to(Offset::new(start + extent, scaled_rrect.top));
730            path.line_to(Offset::new(
731                scaled_rrect.right - scaled_rrect.tr_radius_x,
732                scaled_rrect.top,
733            ));
734            if scaled_rrect.tr_radius() != Radius::ZERO {
735                add_arc(
736                    &mut path,
737                    tr_corner,
738                    TR_CORNER_ARC_START,
739                    TR_CORNER_ARC_SWEEP,
740                );
741            }
742        } else if start + extent < outer_width {
743            let dx = outer_width - (start + extent);
744            let sweep = clamp_double(1.0 - dx / scaled_rrect.tr_radius_x, 0.0, 1.0).asin();
745            add_arc(
746                &mut path,
747                tr_corner,
748                TR_CORNER_ARC_START + sweep,
749                TR_CORNER_ARC_SWEEP - sweep,
750            );
751        }
752
753        // Draw right border and bottom right corner.
754        if scaled_rrect.br_radius() != Radius::ZERO {
755            path.move_to(Offset::new(
756                scaled_rrect.right,
757                scaled_rrect.top + scaled_rrect.tr_radius_y,
758            ));
759        }
760        path.line_to(Offset::new(
761            scaled_rrect.right,
762            scaled_rrect.bottom - scaled_rrect.br_radius_y,
763        ));
764        if scaled_rrect.br_radius() != Radius::ZERO {
765            add_arc(&mut path, br_corner, 0.0, CORNER_ARC_SWEEP);
766        }
767
768        // Draw bottom border and bottom left corner.
769        path.line_to(Offset::new(
770            scaled_rrect.left + scaled_rrect.bl_radius_x,
771            scaled_rrect.bottom,
772        ));
773        if scaled_rrect.bl_radius() != Radius::ZERO {
774            add_arc(&mut path, bl_corner, PI / 2.0, CORNER_ARC_SWEEP);
775        }
776
777        // Draw left border
778        path.line_to(Offset::new(
779            scaled_rrect.left,
780            scaled_rrect.top + scaled_rrect.tl_radius_y,
781        ));
782
783        path.build().into()
784    }
785}
786
787impl ShapeBorder for OutlineInputBorder {
788    fn dimensions(&self) -> EdgeInsetsGeometry {
789        EdgeInsetsGeometry::all(self.border_side.stroke_inset())
790    }
791
792    fn scale(&self, t: f64) -> ShapeBorderRef {
793        ShapeBorderRef::new(OutlineInputBorder::scale(self, t))
794    }
795
796    fn lerp_from(&self, a: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
797        if let Some(outline) = a.and_then(|a| a.as_any().downcast_ref::<OutlineInputBorder>()) {
798            return Some(ShapeBorderRef::new(
799                OutlineInputBorder::new()
800                    .border_radius(
801                        BorderRadius::lerp(
802                            Some(outline.border_radius),
803                            Some(self.border_radius),
804                            t,
805                        )
806                        .expect("both radii are given"),
807                    )
808                    .border_side(BorderSide::lerp(outline.border_side, self.border_side, t))
809                    .gap_padding(outline.gap_padding),
810            ));
811        }
812        if a.is_none() {
813            Some(ShapeBorder::scale(self, t))
814        } else {
815            None
816        }
817    }
818
819    fn lerp_to(&self, b: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
820        if let Some(outline) = b.and_then(|b| b.as_any().downcast_ref::<OutlineInputBorder>()) {
821            return Some(ShapeBorderRef::new(
822                OutlineInputBorder::new()
823                    .border_radius(
824                        BorderRadius::lerp(
825                            Some(self.border_radius),
826                            Some(outline.border_radius),
827                            t,
828                        )
829                        .expect("both radii are given"),
830                    )
831                    .border_side(BorderSide::lerp(self.border_side, outline.border_side, t))
832                    .gap_padding(outline.gap_padding),
833            ));
834        }
835        if b.is_none() {
836            Some(ShapeBorder::scale(self, 1.0 - t))
837        } else {
838            None
839        }
840    }
841
842    fn get_inner_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
843        rrect_path(
844            self.border_radius
845                .resolve(text_direction)
846                .to_rrect(rect)
847                .deflate(self.border_side.stroke_inset()),
848        )
849    }
850
851    fn get_outer_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
852        rrect_path(self.border_radius.resolve(text_direction).to_rrect(rect))
853    }
854
855    fn paint_interior(
856        &self,
857        canvas: &mut Canvas,
858        rect: Rect,
859        paint: &Paint,
860        text_direction: Option<TextDirection>,
861    ) {
862        draw_rrect(
863            canvas,
864            self.border_radius.resolve(text_direction).to_rrect(rect),
865            paint,
866        );
867    }
868
869    fn prefer_paint_interior(&self) -> bool {
870        true
871    }
872
873    fn paint(&self, canvas: &mut Canvas, rect: Rect, text_direction: Option<TextDirection>) {
874        InputBorder::paint(self, canvas, rect, None, 0.0, 0.0, text_direction);
875    }
876
877    fn as_any(&self) -> &dyn Any {
878        self
879    }
880
881    fn eq_shape(&self, other: &dyn ShapeBorder) -> bool {
882        other
883            .as_any()
884            .downcast_ref::<OutlineInputBorder>()
885            .is_some_and(|other| other == self)
886    }
887}
888
889impl InputBorder for OutlineInputBorder {
890    fn border_side(&self) -> BorderSide {
891        self.border_side
892    }
893
894    fn copy_with(&self, border_side: Option<BorderSide>) -> InputBorderRef {
895        InputBorderRef::new(OutlineInputBorder::copy_with(self, border_side, None, None))
896    }
897
898    fn is_outline(&self) -> bool {
899        true
900    }
901
902    /// Draw a rounded rectangle around `rect` using
903    /// [`border_radius`](OutlineInputBorder::border_radius).
904    ///
905    /// The [`border_side`](OutlineInputBorder::border_side) defines the line's color and
906    /// weight.
907    ///
908    /// The top side of the rounded rectangle may be interrupted by a single gap
909    /// if `gap_extent` is non-null. In that case the gap begins at
910    /// `gap_start - gap_padding` (assuming that the `text_direction` is [`TextDirection::Ltr`]).
911    /// The gap's width is `(gap_padding + gap_extent + gap_padding) * gap_percentage`.
912    fn paint(
913        &self,
914        canvas: &mut Canvas,
915        rect: Rect,
916        gap_start: Option<f64>,
917        gap_extent: f64,
918        gap_percentage: f64,
919        text_direction: Option<TextDirection>,
920    ) {
921        debug_assert!((0.0..=1.0).contains(&gap_percentage));
922        debug_assert!(OutlineInputBorder::corners_are_circular(self.border_radius));
923
924        let paint = self.border_side.to_paint();
925        let outer = self.border_radius.to_rrect(rect);
926        let center = outer.inflate(self.border_side.stroke_offset() / 2.0);
927        match gap_start {
928            Some(gap_start) if gap_extent > 0.0 && gap_percentage != 0.0 => {
929                let extent = lerp_double(
930                    Some(0.0),
931                    Some(gap_extent + self.gap_padding * 2.0),
932                    gap_percentage,
933                )
934                .expect("both ends are given");
935                let start = match text_direction.expect("a gap needs a text direction") {
936                    TextDirection::Rtl => gap_start + self.gap_padding - extent,
937                    TextDirection::Ltr => gap_start - self.gap_padding,
938                };
939                let path = self.gap_border_path(center, outer.width(), start.max(0.0), extent);
940                canvas.draw_path(path.as_valo(), path.fill_type, &paint);
941            }
942            _ => draw_rrect(canvas, center, &paint),
943        }
944    }
945}
946
947impl Debug for OutlineInputBorder {
948    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
949        f.write_str("OutlineInputBorder()")
950    }
951}
952
953/// Draws a custom shape around an `InputDecorator`'s container.
954///
955/// This border allows any [`ShapeBorder`] to be used as an input decorator border.
956/// This provides maximum flexibility for custom border shapes while maintaining
957/// the gap functionality for floating labels.
958///
959/// When the input decorator's label is floating, for example because its
960/// input child has the focus, the label appears in a gap in the border outline.
961///
962/// The input decorator's "container" is the optionally filled area above the
963/// decorator's helper, error, and counter.
964///
965/// See also:
966///
967///  * [`OutlineInputBorder`], a traditional rounded rectangle border.
968///  * [`UnderlineInputBorder`], the default `InputDecorator` border which
969///    draws a horizontal line at the bottom of the input decorator's container.
970///  * `RoundedSuperellipseBorder`, which can be used with this border for iOS-style shapes.
971///  * `InputDecoration`, which is used to configure an `InputDecorator`.
972#[derive(Clone)]
973pub struct ShapedInputBorder {
974    /// Defines the border line's color and weight.
975    pub border_side: BorderSide,
976
977    /// Horizontal padding on either side of the border's
978    /// `InputDecoration.labelText` width gap.
979    ///
980    /// This value is used by the [`paint`](InputBorder::paint) method to compute the actual
981    /// gap width.
982    pub gap_padding: f64,
983
984    /// The shape of the border.
985    pub shape: ShapeBorderRef,
986}
987
988impl ShapedInputBorder {
989    /// Creates a shaped outline border for an `InputDecorator`.
990    ///
991    /// The `shape` parameter defines the custom border shape. It can be any
992    /// [`ShapeBorder`] such as `RoundedSuperellipseBorder`, `StadiumBorder`,
993    /// `BeveledRectangleBorder`, or a custom shape.
994    ///
995    /// If the [`border_side`](Self::border_side) parameter is [`BorderSide::NONE`], it will
996    /// not draw a border. However, it will still define a shape (which you can see if
997    /// `InputDecoration.filled` is true).
998    ///
999    /// If an application does not specify a `border_side` parameter of
1000    /// value [`BorderSide::NONE`], the input decorator substitutes its own, using
1001    /// `copy_with`, based on the current theme and `InputDecorator.isFocused`.
1002    ///
1003    /// See also:
1004    ///
1005    ///  * `InputDecoration.floatingLabelBehavior`, which should be set to
1006    ///    `FloatingLabelBehavior.never` when the `border_side` is
1007    ///    [`BorderSide::NONE`]. If left as `FloatingLabelBehavior.auto`, the label
1008    ///    will extend beyond the container as if the border were still being
1009    ///    drawn.
1010    pub fn new(shape: impl Into<ShapeBorderRef>) -> ShapedInputBorder {
1011        ShapedInputBorder {
1012            border_side: BorderSide::default(),
1013            gap_padding: 4.0,
1014            shape: shape.into(),
1015        }
1016    }
1017
1018    /// Dart `ShapedInputBorder(borderSide:)`.
1019    pub fn border_side(mut self, border_side: BorderSide) -> ShapedInputBorder {
1020        self.border_side = border_side;
1021        self
1022    }
1023
1024    /// Dart `ShapedInputBorder(gapPadding:)`.
1025    pub fn gap_padding(mut self, gap_padding: f64) -> ShapedInputBorder {
1026        debug_assert!(gap_padding >= 0.0);
1027        self.gap_padding = gap_padding;
1028        self
1029    }
1030
1031    /// Creates a copy of this border with the given fields replaced.
1032    pub fn copy_with(
1033        &self,
1034        border_side: Option<BorderSide>,
1035        shape: Option<ShapeBorderRef>,
1036        gap_padding: Option<f64>,
1037    ) -> ShapedInputBorder {
1038        ShapedInputBorder::new(shape.unwrap_or_else(|| self.shape.clone()))
1039            .border_side(border_side.unwrap_or(self.border_side))
1040            .gap_padding(gap_padding.unwrap_or(self.gap_padding))
1041    }
1042
1043    /// Creates a copy of this border, scaled by the factor `t`.
1044    pub fn scale(&self, t: f64) -> ShapedInputBorder {
1045        ShapedInputBorder::new(self.shape.scale(t))
1046            .border_side(self.border_side.scale(t))
1047            .gap_padding(self.gap_padding * t)
1048    }
1049
1050    fn gap_border_path(
1051        &self,
1052        rect: Rect,
1053        start: f64,
1054        extent: f64,
1055        text_direction: Option<TextDirection>,
1056    ) -> Path {
1057        // Create a continuous path for the border with a gap in the top edge.
1058        let outer_path = self.shape.get_outer_path(rect, text_direction);
1059
1060        // If there's no meaningful gap, return the full outline.
1061        if start <= 0.0 && extent <= 0.0 {
1062            return outer_path;
1063        }
1064
1065        // Create a rectangle that represents the gap area.
1066        // The gap is on the top edge, so we create a rect that covers the gap region.
1067        let gap_left = start;
1068        let gap_right = start + extent;
1069
1070        // Create a path that excludes the gap area by combining with a difference operation.
1071        // We'll subtract a small rectangle at the top where the gap should be.
1072        let gap_rect = rect_path(Rect::from_ltrb(
1073            clamp_double(gap_left, rect.left, rect.right),
1074            rect.top - 1.0, // Extend slightly beyond to ensure clean cut.
1075            clamp_double(gap_right, rect.left, rect.right),
1076            rect.top + 1.0, // Small height to only affect top edge.
1077        ));
1078
1079        path_combine(PathOperation::Difference, &outer_path, &gap_rect)
1080    }
1081}
1082
1083impl PartialEq for ShapedInputBorder {
1084    fn eq(&self, other: &ShapedInputBorder) -> bool {
1085        other.border_side == self.border_side
1086            && other.shape == self.shape
1087            && other.gap_padding == self.gap_padding
1088    }
1089}
1090
1091impl ShapeBorder for ShapedInputBorder {
1092    fn dimensions(&self) -> EdgeInsetsGeometry {
1093        EdgeInsetsGeometry::all(self.border_side.width)
1094    }
1095
1096    fn scale(&self, t: f64) -> ShapeBorderRef {
1097        ShapeBorderRef::new(ShapedInputBorder::scale(self, t))
1098    }
1099
1100    fn lerp_from(&self, a: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
1101        if let Some(a) = a.and_then(|a| a.as_any().downcast_ref::<ShapedInputBorder>()) {
1102            return Some(ShapeBorderRef::new(
1103                ShapedInputBorder::new(
1104                    ShapeBorderRef::lerp(Some(&a.shape), Some(&self.shape), t)
1105                        .expect("two shapes lerp to a shape"),
1106                )
1107                .border_side(BorderSide::lerp(a.border_side, self.border_side, t))
1108                .gap_padding(a.gap_padding),
1109            ));
1110        }
1111        if a.is_none() {
1112            Some(ShapeBorder::scale(self, t))
1113        } else {
1114            None
1115        }
1116    }
1117
1118    fn lerp_to(&self, b: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
1119        if let Some(b) = b.and_then(|b| b.as_any().downcast_ref::<ShapedInputBorder>()) {
1120            return Some(ShapeBorderRef::new(
1121                ShapedInputBorder::new(
1122                    ShapeBorderRef::lerp(Some(&self.shape), Some(&b.shape), t)
1123                        .expect("two shapes lerp to a shape"),
1124                )
1125                .border_side(BorderSide::lerp(self.border_side, b.border_side, t))
1126                .gap_padding(b.gap_padding),
1127            ));
1128        }
1129        if b.is_none() {
1130            Some(ShapeBorder::scale(self, 1.0 - t))
1131        } else {
1132            None
1133        }
1134    }
1135
1136    fn get_inner_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
1137        self.shape
1138            .get_inner_path(rect.deflate(self.border_side.width), text_direction)
1139    }
1140
1141    fn get_outer_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
1142        self.shape.get_outer_path(rect, text_direction)
1143    }
1144
1145    fn paint_interior(
1146        &self,
1147        canvas: &mut Canvas,
1148        rect: Rect,
1149        paint: &Paint,
1150        text_direction: Option<TextDirection>,
1151    ) {
1152        if self.shape.prefer_paint_interior() {
1153            self.shape
1154                .paint_interior(canvas, rect, paint, text_direction);
1155        } else {
1156            // Fallback for shapes that don't support paintInterior.
1157            let path = self.shape.get_outer_path(rect, text_direction);
1158            canvas.draw_path(path.as_valo(), path.fill_type, paint);
1159        }
1160    }
1161
1162    fn prefer_paint_interior(&self) -> bool {
1163        self.shape.prefer_paint_interior()
1164    }
1165
1166    fn paint(&self, canvas: &mut Canvas, rect: Rect, text_direction: Option<TextDirection>) {
1167        InputBorder::paint(self, canvas, rect, None, 0.0, 0.0, text_direction);
1168    }
1169
1170    fn as_any(&self) -> &dyn Any {
1171        self
1172    }
1173
1174    fn eq_shape(&self, other: &dyn ShapeBorder) -> bool {
1175        other
1176            .as_any()
1177            .downcast_ref::<ShapedInputBorder>()
1178            .is_some_and(|other| other == self)
1179    }
1180}
1181
1182impl InputBorder for ShapedInputBorder {
1183    fn border_side(&self) -> BorderSide {
1184        self.border_side
1185    }
1186
1187    fn copy_with(&self, border_side: Option<BorderSide>) -> InputBorderRef {
1188        InputBorderRef::new(ShapedInputBorder::copy_with(self, border_side, None, None))
1189    }
1190
1191    fn is_outline(&self) -> bool {
1192        true
1193    }
1194
1195    /// Draw the custom shape around `rect`.
1196    ///
1197    /// The [`border_side`](ShapedInputBorder::border_side) defines the line's color and
1198    /// weight.
1199    ///
1200    /// The top side of the border may be interrupted by a single gap
1201    /// if `gap_extent` is non-null. In that case the gap begins at
1202    /// `gap_start - gap_padding` (assuming that the `text_direction` is [`TextDirection::Ltr`]).
1203    /// The gap's width is `(gap_padding + gap_extent + gap_padding) * gap_percentage`.
1204    fn paint(
1205        &self,
1206        canvas: &mut Canvas,
1207        rect: Rect,
1208        gap_start: Option<f64>,
1209        gap_extent: f64,
1210        gap_percentage: f64,
1211        text_direction: Option<TextDirection>,
1212    ) {
1213        debug_assert!((0.0..=1.0).contains(&gap_percentage));
1214
1215        let paint = self.border_side.to_paint();
1216        let deflated_rect = rect.deflate(self.border_side.width / 2.0);
1217
1218        match gap_start {
1219            Some(gap_start) if gap_extent > 0.0 && gap_percentage != 0.0 => {
1220                let extent = lerp_double(
1221                    Some(0.0),
1222                    Some(gap_extent + self.gap_padding * 2.0),
1223                    gap_percentage,
1224                )
1225                .expect("both ends are given");
1226                let start = match text_direction.expect("a gap needs a text direction") {
1227                    TextDirection::Rtl => gap_start + self.gap_padding - extent,
1228                    TextDirection::Ltr => gap_start - self.gap_padding,
1229                };
1230                let path =
1231                    self.gap_border_path(deflated_rect, start.max(0.0), extent, text_direction);
1232                canvas.draw_path(path.as_valo(), path.fill_type, &paint);
1233            }
1234            // Draw the shape without a gap.
1235            _ => match self.shape.as_outlined_border() {
1236                Some(outlined_shape) => {
1237                    // Create a copy with our border side.
1238                    let shaped_border = outlined_shape.copy_with(Some(self.border_side));
1239                    shaped_border.paint(canvas, deflated_rect, text_direction);
1240                }
1241                None => {
1242                    let path = self.shape.get_outer_path(deflated_rect, text_direction);
1243                    canvas.draw_path(path.as_valo(), path.fill_type, &paint);
1244                }
1245            },
1246        }
1247    }
1248}
1249
1250impl Debug for ShapedInputBorder {
1251    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1252        f.write_str("ShapedInputBorder()")
1253    }
1254}
1255
1256/// Dart's `shape as InputBorder` on a border that `ShapeBorder::lerp` gave back: the input
1257/// border it is, when it is one of this crate's input borders.
1258///
1259/// A `dyn ShapeBorder` cannot be asked for a supertrait it does not name, so a border of
1260/// another crate's `InputBorder` type answers `None`.
1261#[allow(deprecated)]
1262pub(crate) fn input_border_of(shape: &dyn ShapeBorder) -> Option<InputBorderRef> {
1263    let any = shape.as_any();
1264    if let Some(border) = any.downcast_ref::<NoInputBorder>() {
1265        return Some(InputBorderRef::new(*border));
1266    }
1267    if let Some(border) = any.downcast_ref::<UnderlineInputBorder>() {
1268        return Some(InputBorderRef::new(*border));
1269    }
1270    if let Some(border) = any.downcast_ref::<OutlineInputBorder>() {
1271        return Some(InputBorderRef::new(*border));
1272    }
1273    if let Some(border) = any.downcast_ref::<ShapedInputBorder>() {
1274        return Some(InputBorderRef::new(border.clone()));
1275    }
1276    if let Some(border) = any.downcast_ref::<crate::material_state::WidgetStateInputBorder>() {
1277        return Some(InputBorderRef::new(border.clone()));
1278    }
1279    if let Some(border) =
1280        any.downcast_ref::<crate::material_state::MaterialStateOutlineInputBorder>()
1281    {
1282        return Some(InputBorderRef::new(border.clone()));
1283    }
1284    if let Some(border) =
1285        any.downcast_ref::<crate::material_state::MaterialStateUnderlineInputBorder>()
1286    {
1287        return Some(InputBorderRef::new(border.clone()));
1288    }
1289    None
1290}
1291
1292#[cfg(test)]
1293mod tests {
1294    use waft_embedder::valo::{Op, Point};
1295    use waft_painting::{RoundedRectangleBorder, RoundedSuperellipseBorder, StadiumBorder};
1296    use waft_widgets::{Center, IntoWidget};
1297
1298    use waft_widgets::testing::test_widgets;
1299
1300    use super::*;
1301    use crate::colors::Colors;
1302    use crate::input_decorator::{FloatingLabelBehavior, InputDecoration};
1303    use crate::scaffold::Scaffold;
1304    use crate::test_support::material_app;
1305    use crate::text_field::TextField;
1306    use crate::theme_data::ThemeData;
1307
1308    fn superellipse(radius: f64) -> RoundedSuperellipseBorder {
1309        RoundedSuperellipseBorder::new(
1310            BorderSide::NONE,
1311            Some(BorderRadius::all(Radius::circular(radius)).into()),
1312        )
1313    }
1314
1315    fn width(width: f64) -> BorderSide {
1316        BorderSide {
1317            width,
1318            ..BorderSide::default()
1319        }
1320    }
1321
1322    fn blue(width: f64) -> BorderSide {
1323        BorderSide {
1324            color: Colors::BLUE.primary(),
1325            width,
1326            ..BorderSide::default()
1327        }
1328    }
1329
1330    #[test]
1331    fn shaped_input_border_constructor() {
1332        let input_border = ShapedInputBorder::new(RoundedRectangleBorder::default());
1333        assert_eq!(input_border.border_side, BorderSide::default());
1334        assert!(
1335            input_border
1336                .shape
1337                .eq_shape(&RoundedRectangleBorder::default())
1338        );
1339        assert_eq!(input_border.gap_padding, 4.0);
1340        assert!(input_border.is_outline());
1341    }
1342
1343    #[test]
1344    fn shaped_input_border_with_rounded_superellipse_border() {
1345        let input_border = ShapedInputBorder::new(superellipse(12.0));
1346        assert_eq!(input_border.border_side, BorderSide::default());
1347        assert!(input_border.shape.eq_shape(&superellipse(12.0)));
1348        assert_eq!(input_border.gap_padding, 4.0);
1349        assert!(input_border.is_outline());
1350    }
1351
1352    #[test]
1353    fn shaped_input_border_copy_with_and_equality() {
1354        let input_border = ShapedInputBorder::new(RoundedRectangleBorder::default());
1355        let copy = input_border.copy_with(None, None, None);
1356        assert!(input_border == copy);
1357
1358        let copy2 = input_border.copy_with(
1359            Some(blue(1.0)),
1360            Some(ShapeBorderRef::new(StadiumBorder::new(BorderSide::NONE))),
1361            Some(8.0),
1362        );
1363        assert_eq!(copy2.border_side, blue(1.0));
1364        assert!(copy2.shape.eq_shape(&StadiumBorder::new(BorderSide::NONE)));
1365        assert_eq!(copy2.gap_padding, 8.0);
1366        assert!(input_border != copy2);
1367    }
1368
1369    #[test]
1370    fn shaped_input_border_scale() {
1371        let input_border = ShapedInputBorder::new(superellipse(10.0)).border_side(width(2.0));
1372        let scaled = input_border.scale(2.0);
1373        assert_eq!(scaled.border_side.width, 4.0);
1374        assert!(scaled.shape.eq_shape(&superellipse(20.0)));
1375        assert_eq!(scaled.gap_padding, 8.0);
1376    }
1377
1378    #[test]
1379    fn shaped_input_border_lerp() {
1380        let input_border1 = ShapedInputBorder::new(superellipse(4.0)).gap_padding(2.0);
1381        let input_border2 = ShapedInputBorder::new(superellipse(12.0))
1382            .border_side(width(3.0))
1383            .gap_padding(6.0);
1384
1385        let lerped = ShapeBorderRef::lerp(
1386            Some(&ShapeBorderRef::new(input_border1)),
1387            Some(&ShapeBorderRef::new(input_border2)),
1388            0.5,
1389        )
1390        .expect("two shaped input borders lerp");
1391        let lerped = lerped
1392            .as_any()
1393            .downcast_ref::<ShapedInputBorder>()
1394            .expect("a shaped input border");
1395        assert_eq!(lerped.border_side.width, 2.0);
1396        assert!(lerped.shape.eq_shape(&superellipse(8.0)));
1397        // gapPadding is not interpolated, it takes the value from the source
1398        assert_eq!(lerped.gap_padding, 2.0);
1399    }
1400
1401    #[test]
1402    fn shaped_input_border_dimensions() {
1403        let input_border =
1404            ShapedInputBorder::new(RoundedRectangleBorder::default()).border_side(width(4.0));
1405        assert_eq!(input_border.dimensions(), EdgeInsetsGeometry::all(4.0));
1406    }
1407
1408    fn pump_text_field(
1409        border: fn() -> ShapedInputBorder,
1410        floating_label_behavior: FloatingLabelBehavior,
1411    ) {
1412        test_widgets(|tester| {
1413            let theme = ThemeData::new(&tester.cell.borrow());
1414            let app = material_app(
1415                theme,
1416                Scaffold::new()
1417                    .body(
1418                        Center::new().child(
1419                            TextField::new().decoration(Some(
1420                                InputDecoration::new()
1421                                    .border(border())
1422                                    .label_text("Test Label")
1423                                    .floating_label_behavior(floating_label_behavior),
1424                            )),
1425                        ),
1426                    )
1427                    .into_widget(),
1428            );
1429            tester.pump_widget(app);
1430            tester.pump_and_settle();
1431        });
1432    }
1433
1434    #[test]
1435    fn shaped_input_border_paint_with_rounded_superellipse_border() {
1436        pump_text_field(
1437            || ShapedInputBorder::new(superellipse(12.0)).border_side(blue(2.0)),
1438            FloatingLabelBehavior::Auto,
1439        );
1440    }
1441
1442    #[test]
1443    fn shaped_input_border_paint_with_gap() {
1444        pump_text_field(
1445            || ShapedInputBorder::new(superellipse(12.0)).border_side(blue(2.0)),
1446            FloatingLabelBehavior::Always,
1447        );
1448    }
1449
1450    #[test]
1451    fn shaped_input_border_paint_with_stadium_border() {
1452        pump_text_field(
1453            || ShapedInputBorder::new(StadiumBorder::new(BorderSide::NONE)).border_side(blue(2.0)),
1454            FloatingLabelBehavior::Auto,
1455        );
1456    }
1457
1458    #[test]
1459    fn shaped_input_border_paint_interior() {
1460        let input_border = ShapedInputBorder::new(superellipse(12.0));
1461        assert!(input_border.prefer_paint_interior());
1462
1463        let mut canvas = Canvas::new();
1464        input_border.paint_interior(
1465            &mut canvas,
1466            Rect::from_ltrb(10.0, 20.0, 30.0, 40.0),
1467            &Paint::default(),
1468            None,
1469        );
1470        canvas.build();
1471    }
1472
1473    /// The gap Dart's `paint` cuts for a floating label: the shape's area less a rectangle two
1474    /// pixels high over the gap's span of the top edge, whose outline the border strokes.
1475    #[test]
1476    fn a_shaped_input_border_cuts_its_gap_from_the_top_edge() {
1477        let input_border = ShapedInputBorder::new(RoundedRectangleBorder::default());
1478        let mut canvas = Canvas::new();
1479        InputBorder::paint(
1480            &input_border,
1481            &mut canvas,
1482            Rect::from_ltrb(0.0, 0.0, 200.0, 50.0),
1483            Some(40.0),
1484            60.0,
1485            1.0,
1486            Some(TextDirection::Ltr),
1487        );
1488        let list = canvas.build();
1489        let Some(Op::DrawPath {
1490            path, fill_rule, ..
1491        }) = list
1492            .ops()
1493            .iter()
1494            .find(|op| matches!(op, Op::DrawPath { .. }))
1495        else {
1496            panic!("the border is drawn as a path");
1497        };
1498        assert_eq!(
1499            *fill_rule,
1500            FillRule::EvenOdd,
1501            "the fill type `Path.combine` gives"
1502        );
1503        // The deflated rect's top is at 0.5; the gap runs from 40 - 4 to 36 + 60 + 2 * 4.
1504        let contains = |x, y| path.contains(Point::new(x, y), *fill_rule);
1505        assert!(contains(20.0, 1.0), "the top edge before the gap");
1506        assert!(!contains(70.0, 1.0), "the gap");
1507        assert!(contains(70.0, 10.0), "below the gap");
1508        assert!(contains(150.0, 1.0), "the top edge after the gap");
1509    }
1510}