waft-material 0.6.0

Material Design widgets for Waft
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
//! Flutter counterpart: material_ui's `input_border.dart`.
//!
//! `InputBorder` is a trait over [`ShapeBorder`] whose `paint` takes the floating label's gap;
//! each border's `ShapeBorder::paint` is that `paint` with Dart's default gap arguments, so a
//! caller holding an [`InputBorderRef`] names the trait: `InputBorder::paint(&*border, ..)`.

use std::any::Any;
use std::f64::consts::PI;
use std::fmt::{self, Debug};
use std::rc::Rc;

use waft_embedder::{
    Canvas, FillRule, Offset, Paint, Path, PathBuilder, PathOperation, RRect, Radius, Rect,
    clamp_double, lerp_double, path_combine, rrect_radii_elliptical,
};
use waft_painting::{
    BorderRadius, BorderSide, BorderStyle, BoxBorder, BoxShape, EdgeInsetsGeometry, ShapeBorder,
    ShapeBorderRef, TextDirection, draw_rrect,
};
use waft_widgets::{MaybeWidgetStateProperty, WidgetStateProperty};

/// Defines the appearance of an `InputDecorator`'s border.
///
/// An input decorator's border is specified by `InputDecoration.border`.
///
/// The border is drawn relative to the input decorator's "container" which
/// is the optionally filled area above the decorator's helper, error,
/// and counter.
///
/// Input border's are decorated with a line whose weight and color are defined
/// by [`border_side`](Self::border_side). The input decorator's renderer animates the input
/// border's appearance in response to state changes, like gaining or losing the focus,
/// by creating new copies of its input border with [`copy_with`](Self::copy_with).
///
/// See also:
///
///  * [`UnderlineInputBorder`], the default `InputDecorator` border which
///    draws a horizontal line at the bottom of the input decorator's container.
///  * [`OutlineInputBorder`], an `InputDecorator` border which draws a
///    rounded rectangle around the input decorator's container.
///  * `InputDecoration`, which is used to configure an `InputDecorator`.
pub trait InputBorder: ShapeBorder {
    /// Defines the border line's color and weight.
    ///
    /// The `InputDecorator` creates copies of its input border, using [`copy_with`](Self::copy_with),
    /// based on the current theme and `InputDecorator.isFocused`.
    fn border_side(&self) -> BorderSide;

    /// Creates a copy of this input border with the specified `border_side`.
    fn copy_with(&self, border_side: Option<BorderSide>) -> InputBorderRef;

    /// True if this border will enclose the `InputDecorator`'s container.
    ///
    /// This property affects the alignment of container's contents. For example
    /// when an input decorator is configured with an [`OutlineInputBorder`] its
    /// label is centered with its container.
    fn is_outline(&self) -> bool;

    /// Paint this input border on `canvas`.
    ///
    /// The `rect` parameter bounds the `InputDecorator`'s container.
    ///
    /// The additional `gap` parameters reflect the state of the `InputDecorator`'s
    /// floating label. When an input decorator gains the focus, its label
    /// animates upwards, to make room for the input child. The `gap_start` and
    /// `gap_extent` parameters define a floating label width interval, and
    /// `gap_percentage` defines the animation's progress (0.0 to 1.0).
    ///
    /// Dart's defaults are `gap_extent: 0.0` and `gap_percentage: 0.0`, which the border's
    /// `ShapeBorder::paint` passes.
    fn paint(
        &self,
        canvas: &mut Canvas,
        rect: Rect,
        gap_start: Option<f64>,
        gap_extent: f64,
        gap_percentage: f64,
        text_direction: Option<TextDirection>,
    );

    /// Dart's `border is WidgetStateProperty<InputBorder>`: this border as the property it
    /// also is, for the borders that implement `WidgetStateProperty` (`WidgetStateInputBorder`
    /// and the deprecated `MaterialState` input borders).
    fn as_widget_state_property(&self) -> Option<&dyn WidgetStateProperty<InputBorderRef>> {
        None
    }
}

/// An [`InputBorder`] held by value: what a Dart field or parameter typed `InputBorder`
/// becomes; [`ShapeBorderRef`]'s sharing and equality, for the narrower type.
#[derive(Clone)]
pub struct InputBorderRef(Rc<dyn InputBorder>);

impl InputBorderRef {
    /// Erases an [`InputBorder`].
    pub fn new(border: impl InputBorder) -> InputBorderRef {
        InputBorderRef(Rc::new(border))
    }

    /// No input border.
    ///
    /// Use this value with `InputDecoration.border` to specify that no border
    /// should be drawn. The `InputDecoration.collapsed` constructor sets
    /// its border to this value.
    pub fn none() -> InputBorderRef {
        InputBorderRef::new(NoInputBorder)
    }
}

impl<T: InputBorder> From<T> for InputBorderRef {
    fn from(border: T) -> InputBorderRef {
        InputBorderRef::new(border)
    }
}

/// Dart's `InputBorder extends ShapeBorder`: an input border is used wherever a shape is.
impl From<InputBorderRef> for ShapeBorderRef {
    fn from(border: InputBorderRef) -> ShapeBorderRef {
        ShapeBorderRef::from_shared(border.0)
    }
}

impl std::ops::Deref for InputBorderRef {
    type Target = dyn InputBorder;

    fn deref(&self) -> &dyn InputBorder {
        &*self.0
    }
}

impl PartialEq for InputBorderRef {
    fn eq(&self, other: &InputBorderRef) -> bool {
        Rc::ptr_eq(&self.0, &other.0) || self.0.eq_shape(&*other.0)
    }
}

impl Debug for InputBorderRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Debug::fmt(&*self.0, f)
    }
}

impl PartialEq for dyn InputBorder {
    fn eq(&self, other: &dyn InputBorder) -> bool {
        self.eq_shape(other)
    }
}

/// Dart's `T?` is `InputBorder?`: a `WidgetStateInputBorder` resolves to a border, which
/// `resolve_as` wraps in `Some` for an `Option<InputBorderRef>`.
impl MaybeWidgetStateProperty<InputBorderRef> for InputBorderRef {
    fn as_widget_state_property(&self) -> Option<&dyn WidgetStateProperty<InputBorderRef>> {
        InputBorder::as_widget_state_property(&**self)
    }

    fn from_resolved(value: InputBorderRef) -> InputBorderRef {
        value
    }
}

/// Dart's `Path()..addRect(rect)`.
fn rect_path(rect: Rect) -> Path {
    let mut path = PathBuilder::new();
    path.rect(rect.into());
    path.build().into()
}

/// Dart's `Path()..addRRect(rrect)`.
fn rrect_path(rrect: RRect) -> Path {
    let mut path = PathBuilder::new();
    path.rrect_radii_elliptical(rrect.outer_rect(), rrect_radii_elliptical(rrect));
    path.build().into()
}

/// Dart's `Path.addArc(oval, startAngle, sweepAngle)`: a new contour along the oval inscribed
/// in `oval`, from `start_angle` clockwise through `sweep_angle` radians. An empty oval or a
/// zero sweep adds nothing, as Skia's `addArc` does.
fn add_arc(path: &mut PathBuilder, oval: Rect, start_angle: f64, sweep_angle: f64) {
    if oval.is_empty() || sweep_angle == 0.0 {
        return;
    }
    let center = oval.center();
    let radius_x = oval.width() / 2.0;
    let radius_y = oval.height() / 2.0;
    path.move_to(Offset::new(
        center.dx() + radius_x * start_angle.cos(),
        center.dy() + radius_y * start_angle.sin(),
    ));
    path.ellipse(
        center,
        [radius_x as f32, radius_y as f32],
        0.0,
        start_angle as f32,
        sweep_angle as f32,
    );
}

/// Dart's `Canvas.drawLine`: a stroked two-point path.
fn draw_line(canvas: &mut Canvas, p1: Offset, p2: Offset, paint: &Paint) {
    let mut path = PathBuilder::new();
    path.move_to(p1);
    path.line_to(p2);
    canvas.draw_path(&path.build(), FillRule::NonZero, paint);
}

// Used to create the InputBorder.none singleton.
#[derive(Clone, Copy)]
struct NoInputBorder;

impl ShapeBorder for NoInputBorder {
    fn dimensions(&self) -> EdgeInsetsGeometry {
        EdgeInsetsGeometry::ZERO
    }

    fn scale(&self, _t: f64) -> ShapeBorderRef {
        ShapeBorderRef::new(NoInputBorder)
    }

    fn get_outer_path(&self, rect: Rect, _text_direction: Option<TextDirection>) -> Path {
        rect_path(rect)
    }

    fn get_inner_path(&self, rect: Rect, _text_direction: Option<TextDirection>) -> Path {
        rect_path(rect)
    }

    fn paint_interior(
        &self,
        canvas: &mut Canvas,
        rect: Rect,
        paint: &Paint,
        _text_direction: Option<TextDirection>,
    ) {
        canvas.draw_rect(rect, paint);
    }

    fn prefer_paint_interior(&self) -> bool {
        true
    }

    fn paint(&self, canvas: &mut Canvas, rect: Rect, text_direction: Option<TextDirection>) {
        InputBorder::paint(self, canvas, rect, None, 0.0, 0.0, text_direction);
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    // Dart's `InputBorder.none` is the one `const _NoInputBorder()`, so every no-border is
    // identical to every other.
    fn eq_shape(&self, other: &dyn ShapeBorder) -> bool {
        other.as_any().is::<NoInputBorder>()
    }
}

impl InputBorder for NoInputBorder {
    fn border_side(&self) -> BorderSide {
        BorderSide::NONE
    }

    fn copy_with(&self, _border_side: Option<BorderSide>) -> InputBorderRef {
        InputBorderRef::new(NoInputBorder)
    }

    fn is_outline(&self) -> bool {
        false
    }

    fn paint(
        &self,
        _canvas: &mut Canvas,
        _rect: Rect,
        _gap_start: Option<f64>,
        _gap_extent: f64,
        _gap_percentage: f64,
        _text_direction: Option<TextDirection>,
    ) {
        // Do not paint.
    }
}

impl Debug for NoInputBorder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("_NoInputBorder()")
    }
}

/// Draws a horizontal line at the bottom of an `InputDecorator`'s container and
/// defines the container's shape.
///
/// The input decorator's "container" is the optionally filled area above the
/// decorator's helper, error, and counter.
///
/// See also:
///
///  * [`OutlineInputBorder`], an `InputDecorator` border which draws a
///    rounded rectangle around the input decorator's container.
///  * `InputDecoration`, which is used to configure an `InputDecorator`.
#[derive(Clone, Copy, PartialEq)]
pub struct UnderlineInputBorder {
    /// Defines the border line's color and weight.
    pub border_side: BorderSide,

    /// The radii of the border's rounded rectangle corners.
    ///
    /// When this border is used with a filled input decorator, see
    /// `InputDecoration.filled`, the border radius defines the shape
    /// of the background fill as well as the bottom left and right
    /// edges of the underline itself.
    ///
    /// By default the top right and top left corners have a circular radius
    /// of 4.0.
    pub border_radius: BorderRadius,
}

impl Default for UnderlineInputBorder {
    /// Creates an underline border for an `InputDecorator`.
    ///
    /// The [`border_side`](Self::border_side) parameter defaults to `BorderSide()`.
    /// Applications typically do not specify a `border_side` parameter
    /// because the input decorator substitutes its own, using `copy_with`, based
    /// on the current theme and `InputDecorator.isFocused`.
    ///
    /// The [`border_radius`](Self::border_radius) parameter defaults to a value where the top
    /// left and right corners have a circular radius of 4.0.
    fn default() -> UnderlineInputBorder {
        UnderlineInputBorder {
            border_side: BorderSide::default(),
            border_radius: BorderRadius::only(
                Radius::circular(4.0),
                Radius::circular(4.0),
                Radius::ZERO,
                Radius::ZERO,
            ),
        }
    }
}

impl UnderlineInputBorder {
    /// Creates an underline border for an `InputDecorator`, with Dart's defaults.
    pub fn new() -> UnderlineInputBorder {
        UnderlineInputBorder::default()
    }

    /// Dart `UnderlineInputBorder(borderSide:)`.
    pub fn border_side(mut self, border_side: BorderSide) -> UnderlineInputBorder {
        self.border_side = border_side;
        self
    }

    /// Dart `UnderlineInputBorder(borderRadius:)`.
    pub fn border_radius(mut self, border_radius: BorderRadius) -> UnderlineInputBorder {
        self.border_radius = border_radius;
        self
    }

    /// Creates a copy of this border with the given fields replaced.
    pub fn copy_with(
        &self,
        border_side: Option<BorderSide>,
        border_radius: Option<BorderRadius>,
    ) -> UnderlineInputBorder {
        UnderlineInputBorder {
            border_side: border_side.unwrap_or(self.border_side),
            border_radius: border_radius.unwrap_or(self.border_radius),
        }
    }

    /// Creates a copy of this border, scaled by the factor `t`.
    pub fn scale(&self, t: f64) -> UnderlineInputBorder {
        UnderlineInputBorder::new().border_side(self.border_side.scale(t))
    }
}

impl ShapeBorder for UnderlineInputBorder {
    fn dimensions(&self) -> EdgeInsetsGeometry {
        EdgeInsetsGeometry::only(0.0, 0.0, 0.0, self.border_side.width)
    }

    fn scale(&self, t: f64) -> ShapeBorderRef {
        ShapeBorderRef::new(UnderlineInputBorder::scale(self, t))
    }

    fn lerp_from(&self, a: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
        if let Some(a) = a.and_then(|a| a.as_any().downcast_ref::<UnderlineInputBorder>()) {
            return Some(ShapeBorderRef::new(UnderlineInputBorder {
                border_side: BorderSide::lerp(a.border_side, self.border_side, t),
                border_radius: BorderRadius::lerp(
                    Some(a.border_radius),
                    Some(self.border_radius),
                    t,
                )
                .expect("both radii are given"),
            }));
        }
        if a.is_none() {
            Some(ShapeBorder::scale(self, t))
        } else {
            None
        }
    }

    fn lerp_to(&self, b: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
        if let Some(b) = b.and_then(|b| b.as_any().downcast_ref::<UnderlineInputBorder>()) {
            return Some(ShapeBorderRef::new(UnderlineInputBorder {
                border_side: BorderSide::lerp(self.border_side, b.border_side, t),
                border_radius: BorderRadius::lerp(
                    Some(self.border_radius),
                    Some(b.border_radius),
                    t,
                )
                .expect("both radii are given"),
            }));
        }
        if b.is_none() {
            Some(ShapeBorder::scale(self, 1.0 - t))
        } else {
            None
        }
    }

    fn get_inner_path(&self, rect: Rect, _text_direction: Option<TextDirection>) -> Path {
        rect_path(Rect::from_ltwh(
            rect.left,
            rect.top,
            rect.width(),
            (rect.height() - self.border_side.width).max(0.0),
        ))
    }

    fn get_outer_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
        rrect_path(self.border_radius.resolve(text_direction).to_rrect(rect))
    }

    fn paint_interior(
        &self,
        canvas: &mut Canvas,
        rect: Rect,
        paint: &Paint,
        text_direction: Option<TextDirection>,
    ) {
        draw_rrect(
            canvas,
            self.border_radius.resolve(text_direction).to_rrect(rect),
            paint,
        );
    }

    fn prefer_paint_interior(&self) -> bool {
        true
    }

    fn paint(&self, canvas: &mut Canvas, rect: Rect, text_direction: Option<TextDirection>) {
        InputBorder::paint(self, canvas, rect, None, 0.0, 0.0, text_direction);
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn eq_shape(&self, other: &dyn ShapeBorder) -> bool {
        other
            .as_any()
            .downcast_ref::<UnderlineInputBorder>()
            .is_some_and(|other| other == self)
    }
}

impl InputBorder for UnderlineInputBorder {
    fn border_side(&self) -> BorderSide {
        self.border_side
    }

    fn copy_with(&self, border_side: Option<BorderSide>) -> InputBorderRef {
        InputBorderRef::new(UnderlineInputBorder::copy_with(self, border_side, None))
    }

    fn is_outline(&self) -> bool {
        false
    }

    /// Draw a horizontal line at the bottom of `rect`.
    ///
    /// The [`border_side`](UnderlineInputBorder::border_side) defines the line's color and
    /// weight. The `text_direction` `gap` and `text_direction` parameters are ignored.
    fn paint(
        &self,
        canvas: &mut Canvas,
        rect: Rect,
        _gap_start: Option<f64>,
        _gap_extent: f64,
        _gap_percentage: f64,
        text_direction: Option<TextDirection>,
    ) {
        if self.border_side.style == BorderStyle::None {
            return;
        }

        if self.border_radius.bottom_left != Radius::ZERO
            || self.border_radius.bottom_right != Radius::ZERO
        {
            // This prevents the border from leaking the color due to anti-aliasing rounding errors.
            let updated_border_radius = BorderRadius::only(
                Radius::ZERO,
                Radius::ZERO,
                self.border_radius
                    .bottom_left
                    .clamp(None, Some(Radius::circular(rect.height() / 2.0))),
                self.border_radius
                    .bottom_right
                    .clamp(None, Some(Radius::circular(rect.height() / 2.0))),
            );

            <dyn BoxBorder>::paint_non_uniform_border(
                canvas,
                rect,
                Some(updated_border_radius),
                text_direction,
                BoxShape::Rectangle,
                BorderSide::NONE,
                BorderSide::NONE,
                self.border_side
                    .copy_with(None, None, None, Some(BorderSide::STROKE_ALIGN_INSIDE)),
                BorderSide::NONE,
                self.border_side.color,
            );
        } else {
            let align_inside_offset = Offset::new(0.0, self.border_side.width / 2.0);
            draw_line(
                canvas,
                rect.bottom_left() - align_inside_offset,
                rect.bottom_right() - align_inside_offset,
                &self.border_side.to_paint(),
            );
        }
    }
}

impl Debug for UnderlineInputBorder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("UnderlineInputBorder()")
    }
}

/// Draws a rounded rectangle around an `InputDecorator`'s container.
///
/// When the input decorator's label is floating, for example because its
/// input child has the focus, the label appears in a gap in the border outline.
///
/// The input decorator's "container" is the optionally filled area above the
/// decorator's helper, error, and counter.
///
/// See also:
///
///  * [`UnderlineInputBorder`], the default `InputDecorator` border which
///    draws a horizontal line at the bottom of the input decorator's container.
///  * [`ShapedInputBorder`], an `InputDecorator` border which draws a custom
///    [`ShapeBorder`] around the input decorator's container.
///  * `InputDecoration`, which is used to configure an `InputDecorator`.
#[derive(Clone, Copy, PartialEq)]
pub struct OutlineInputBorder {
    /// Defines the border line's color and weight.
    pub border_side: BorderSide,

    /// Horizontal padding on either side of the border's
    /// `InputDecoration.labelText` width gap.
    ///
    /// This value is used by the [`paint`](InputBorder::paint) method to compute the actual
    /// gap width.
    pub gap_padding: f64,

    /// The radii of the border's rounded rectangle corners.
    ///
    /// The corner radii must be circular, i.e. their [`Radius::x`] and [`Radius::y`]
    /// values must be the same.
    pub border_radius: BorderRadius,
}

impl Default for OutlineInputBorder {
    /// Creates a rounded rectangle outline border for an `InputDecorator`.
    ///
    /// If the [`border_side`](Self::border_side) parameter is [`BorderSide::NONE`], it will not
    /// draw a border. However, it will still define a shape (which you can see if
    /// `InputDecoration.filled` is true).
    ///
    /// If an application does not specify a `border_side` parameter of
    /// value [`BorderSide::NONE`], the input decorator substitutes its own, using
    /// `copy_with`, based on the current theme and `InputDecorator.isFocused`.
    ///
    /// The [`border_radius`](Self::border_radius) parameter defaults to a value where all four
    /// corners have a circular radius of 4.0. The corner radii must be circular, i.e.
    /// their [`Radius::x`] and [`Radius::y`] values must be the same.
    ///
    /// See also:
    ///
    ///  * `InputDecoration.floatingLabelBehavior`, which should be set to
    ///    `FloatingLabelBehavior.never` when the `border_side` is
    ///    [`BorderSide::NONE`]. If left as `FloatingLabelBehavior.auto`, the label
    ///    will extend beyond the container as if the border were still being
    ///    drawn.
    fn default() -> OutlineInputBorder {
        OutlineInputBorder {
            border_side: BorderSide::default(),
            gap_padding: 4.0,
            border_radius: BorderRadius::all(Radius::circular(4.0)),
        }
    }
}

impl OutlineInputBorder {
    /// Creates a rounded rectangle outline border for an `InputDecorator`, with Dart's
    /// defaults.
    pub fn new() -> OutlineInputBorder {
        OutlineInputBorder::default()
    }

    /// Dart `OutlineInputBorder(borderSide:)`.
    pub fn border_side(mut self, border_side: BorderSide) -> OutlineInputBorder {
        self.border_side = border_side;
        self
    }

    /// Dart `OutlineInputBorder(borderRadius:)`.
    pub fn border_radius(mut self, border_radius: BorderRadius) -> OutlineInputBorder {
        self.border_radius = border_radius;
        self
    }

    /// Dart `OutlineInputBorder(gapPadding:)`.
    pub fn gap_padding(mut self, gap_padding: f64) -> OutlineInputBorder {
        debug_assert!(gap_padding >= 0.0);
        self.gap_padding = gap_padding;
        self
    }

    // The label text's gap can extend into the corners (even both the top left
    // and the top right corner). To avoid the more complicated problem of finding
    // how far the gap penetrates into an elliptical corner, just require them
    // to be circular.
    //
    // This can't be checked by the constructor because const constructor.
    fn corners_are_circular(border_radius: BorderRadius) -> bool {
        border_radius.top_left.x == border_radius.top_left.y
            && border_radius.bottom_left.x == border_radius.bottom_left.y
            && border_radius.top_right.x == border_radius.top_right.y
            && border_radius.bottom_right.x == border_radius.bottom_right.y
    }

    /// Creates a copy of this border with the given fields replaced.
    pub fn copy_with(
        &self,
        border_side: Option<BorderSide>,
        border_radius: Option<BorderRadius>,
        gap_padding: Option<f64>,
    ) -> OutlineInputBorder {
        OutlineInputBorder::new()
            .border_side(border_side.unwrap_or(self.border_side))
            .border_radius(border_radius.unwrap_or(self.border_radius))
            .gap_padding(gap_padding.unwrap_or(self.gap_padding))
    }

    /// Creates a copy of this border, scaled by the factor `t`.
    pub fn scale(&self, t: f64) -> OutlineInputBorder {
        OutlineInputBorder::new()
            .border_side(self.border_side.scale(t))
            .border_radius(self.border_radius * t)
            .gap_padding(self.gap_padding * t)
    }

    fn gap_border_path(&self, center: RRect, outer_width: f64, start: f64, extent: f64) -> Path {
        // When the corner radii on any side add up to be greater than the
        // given height, each radius has to be scaled to not exceed the
        // size of the width/height of the RRect.
        let scaled_rrect = center.scale_radii();

        let tl_corner = Rect::from_ltwh(
            scaled_rrect.left,
            scaled_rrect.top,
            scaled_rrect.tl_radius_x * 2.0,
            scaled_rrect.tl_radius_y * 2.0,
        );
        let tr_corner = Rect::from_ltwh(
            scaled_rrect.right - scaled_rrect.tr_radius_x * 2.0,
            scaled_rrect.top,
            scaled_rrect.tr_radius_x * 2.0,
            scaled_rrect.tr_radius_y * 2.0,
        );
        let br_corner = Rect::from_ltwh(
            scaled_rrect.right - scaled_rrect.br_radius_x * 2.0,
            scaled_rrect.bottom - scaled_rrect.br_radius_y * 2.0,
            scaled_rrect.br_radius_x * 2.0,
            scaled_rrect.br_radius_y * 2.0,
        );
        let bl_corner = Rect::from_ltwh(
            scaled_rrect.left,
            scaled_rrect.bottom - scaled_rrect.bl_radius_y * 2.0,
            scaled_rrect.bl_radius_x * 2.0,
            scaled_rrect.bl_radius_y * 2.0,
        );

        // This assumes that the radius is circular (x and y radius are equal).
        // Currently, BorderRadius only supports circular radii.
        const CORNER_ARC_SWEEP: f64 = PI / 2.0;
        let mut path = PathBuilder::new();

        // Top left corner
        if scaled_rrect.tl_radius() != Radius::ZERO {
            let tl_corner_arc_sweep =
                clamp_double(1.0 - start / scaled_rrect.tl_radius_x, 0.0, 1.0).acos();
            add_arc(&mut path, tl_corner, PI, tl_corner_arc_sweep);
        } else {
            // Because the path is painted with Paint.strokeCap = StrokeCap.butt, horizontal coordinate is moved
            // based on strokeOffset to respect strokeAlign.
            path.move_to(Offset::new(
                scaled_rrect.left + self.border_side.stroke_offset() / 2.0,
                scaled_rrect.top,
            ));
        }

        // Draw top border from top left corner to gap start.
        if start > scaled_rrect.tl_radius_x {
            path.line_to(Offset::new(start, scaled_rrect.top));
        }

        // Draw top border from gap end to top right corner and draw top right corner.
        const TR_CORNER_ARC_START: f64 = (3.0 * PI) / 2.0;
        const TR_CORNER_ARC_SWEEP: f64 = CORNER_ARC_SWEEP;
        if start + extent < outer_width - scaled_rrect.tr_radius_x {
            path.move_to(Offset::new(start + extent, scaled_rrect.top));
            path.line_to(Offset::new(
                scaled_rrect.right - scaled_rrect.tr_radius_x,
                scaled_rrect.top,
            ));
            if scaled_rrect.tr_radius() != Radius::ZERO {
                add_arc(
                    &mut path,
                    tr_corner,
                    TR_CORNER_ARC_START,
                    TR_CORNER_ARC_SWEEP,
                );
            }
        } else if start + extent < outer_width {
            let dx = outer_width - (start + extent);
            let sweep = clamp_double(1.0 - dx / scaled_rrect.tr_radius_x, 0.0, 1.0).asin();
            add_arc(
                &mut path,
                tr_corner,
                TR_CORNER_ARC_START + sweep,
                TR_CORNER_ARC_SWEEP - sweep,
            );
        }

        // Draw right border and bottom right corner.
        if scaled_rrect.br_radius() != Radius::ZERO {
            path.move_to(Offset::new(
                scaled_rrect.right,
                scaled_rrect.top + scaled_rrect.tr_radius_y,
            ));
        }
        path.line_to(Offset::new(
            scaled_rrect.right,
            scaled_rrect.bottom - scaled_rrect.br_radius_y,
        ));
        if scaled_rrect.br_radius() != Radius::ZERO {
            add_arc(&mut path, br_corner, 0.0, CORNER_ARC_SWEEP);
        }

        // Draw bottom border and bottom left corner.
        path.line_to(Offset::new(
            scaled_rrect.left + scaled_rrect.bl_radius_x,
            scaled_rrect.bottom,
        ));
        if scaled_rrect.bl_radius() != Radius::ZERO {
            add_arc(&mut path, bl_corner, PI / 2.0, CORNER_ARC_SWEEP);
        }

        // Draw left border
        path.line_to(Offset::new(
            scaled_rrect.left,
            scaled_rrect.top + scaled_rrect.tl_radius_y,
        ));

        path.build().into()
    }
}

impl ShapeBorder for OutlineInputBorder {
    fn dimensions(&self) -> EdgeInsetsGeometry {
        EdgeInsetsGeometry::all(self.border_side.stroke_inset())
    }

    fn scale(&self, t: f64) -> ShapeBorderRef {
        ShapeBorderRef::new(OutlineInputBorder::scale(self, t))
    }

    fn lerp_from(&self, a: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
        if let Some(outline) = a.and_then(|a| a.as_any().downcast_ref::<OutlineInputBorder>()) {
            return Some(ShapeBorderRef::new(
                OutlineInputBorder::new()
                    .border_radius(
                        BorderRadius::lerp(
                            Some(outline.border_radius),
                            Some(self.border_radius),
                            t,
                        )
                        .expect("both radii are given"),
                    )
                    .border_side(BorderSide::lerp(outline.border_side, self.border_side, t))
                    .gap_padding(outline.gap_padding),
            ));
        }
        if a.is_none() {
            Some(ShapeBorder::scale(self, t))
        } else {
            None
        }
    }

    fn lerp_to(&self, b: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
        if let Some(outline) = b.and_then(|b| b.as_any().downcast_ref::<OutlineInputBorder>()) {
            return Some(ShapeBorderRef::new(
                OutlineInputBorder::new()
                    .border_radius(
                        BorderRadius::lerp(
                            Some(self.border_radius),
                            Some(outline.border_radius),
                            t,
                        )
                        .expect("both radii are given"),
                    )
                    .border_side(BorderSide::lerp(self.border_side, outline.border_side, t))
                    .gap_padding(outline.gap_padding),
            ));
        }
        if b.is_none() {
            Some(ShapeBorder::scale(self, 1.0 - t))
        } else {
            None
        }
    }

    fn get_inner_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
        rrect_path(
            self.border_radius
                .resolve(text_direction)
                .to_rrect(rect)
                .deflate(self.border_side.stroke_inset()),
        )
    }

    fn get_outer_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
        rrect_path(self.border_radius.resolve(text_direction).to_rrect(rect))
    }

    fn paint_interior(
        &self,
        canvas: &mut Canvas,
        rect: Rect,
        paint: &Paint,
        text_direction: Option<TextDirection>,
    ) {
        draw_rrect(
            canvas,
            self.border_radius.resolve(text_direction).to_rrect(rect),
            paint,
        );
    }

    fn prefer_paint_interior(&self) -> bool {
        true
    }

    fn paint(&self, canvas: &mut Canvas, rect: Rect, text_direction: Option<TextDirection>) {
        InputBorder::paint(self, canvas, rect, None, 0.0, 0.0, text_direction);
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn eq_shape(&self, other: &dyn ShapeBorder) -> bool {
        other
            .as_any()
            .downcast_ref::<OutlineInputBorder>()
            .is_some_and(|other| other == self)
    }
}

impl InputBorder for OutlineInputBorder {
    fn border_side(&self) -> BorderSide {
        self.border_side
    }

    fn copy_with(&self, border_side: Option<BorderSide>) -> InputBorderRef {
        InputBorderRef::new(OutlineInputBorder::copy_with(self, border_side, None, None))
    }

    fn is_outline(&self) -> bool {
        true
    }

    /// Draw a rounded rectangle around `rect` using
    /// [`border_radius`](OutlineInputBorder::border_radius).
    ///
    /// The [`border_side`](OutlineInputBorder::border_side) defines the line's color and
    /// weight.
    ///
    /// The top side of the rounded rectangle may be interrupted by a single gap
    /// if `gap_extent` is non-null. In that case the gap begins at
    /// `gap_start - gap_padding` (assuming that the `text_direction` is [`TextDirection::Ltr`]).
    /// The gap's width is `(gap_padding + gap_extent + gap_padding) * gap_percentage`.
    fn paint(
        &self,
        canvas: &mut Canvas,
        rect: Rect,
        gap_start: Option<f64>,
        gap_extent: f64,
        gap_percentage: f64,
        text_direction: Option<TextDirection>,
    ) {
        debug_assert!((0.0..=1.0).contains(&gap_percentage));
        debug_assert!(OutlineInputBorder::corners_are_circular(self.border_radius));

        let paint = self.border_side.to_paint();
        let outer = self.border_radius.to_rrect(rect);
        let center = outer.inflate(self.border_side.stroke_offset() / 2.0);
        match gap_start {
            Some(gap_start) if gap_extent > 0.0 && gap_percentage != 0.0 => {
                let extent = lerp_double(
                    Some(0.0),
                    Some(gap_extent + self.gap_padding * 2.0),
                    gap_percentage,
                )
                .expect("both ends are given");
                let start = match text_direction.expect("a gap needs a text direction") {
                    TextDirection::Rtl => gap_start + self.gap_padding - extent,
                    TextDirection::Ltr => gap_start - self.gap_padding,
                };
                let path = self.gap_border_path(center, outer.width(), start.max(0.0), extent);
                canvas.draw_path(path.as_valo(), path.fill_type, &paint);
            }
            _ => draw_rrect(canvas, center, &paint),
        }
    }
}

impl Debug for OutlineInputBorder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("OutlineInputBorder()")
    }
}

/// Draws a custom shape around an `InputDecorator`'s container.
///
/// This border allows any [`ShapeBorder`] to be used as an input decorator border.
/// This provides maximum flexibility for custom border shapes while maintaining
/// the gap functionality for floating labels.
///
/// When the input decorator's label is floating, for example because its
/// input child has the focus, the label appears in a gap in the border outline.
///
/// The input decorator's "container" is the optionally filled area above the
/// decorator's helper, error, and counter.
///
/// See also:
///
///  * [`OutlineInputBorder`], a traditional rounded rectangle border.
///  * [`UnderlineInputBorder`], the default `InputDecorator` border which
///    draws a horizontal line at the bottom of the input decorator's container.
///  * `RoundedSuperellipseBorder`, which can be used with this border for iOS-style shapes.
///  * `InputDecoration`, which is used to configure an `InputDecorator`.
#[derive(Clone)]
pub struct ShapedInputBorder {
    /// Defines the border line's color and weight.
    pub border_side: BorderSide,

    /// Horizontal padding on either side of the border's
    /// `InputDecoration.labelText` width gap.
    ///
    /// This value is used by the [`paint`](InputBorder::paint) method to compute the actual
    /// gap width.
    pub gap_padding: f64,

    /// The shape of the border.
    pub shape: ShapeBorderRef,
}

impl ShapedInputBorder {
    /// Creates a shaped outline border for an `InputDecorator`.
    ///
    /// The `shape` parameter defines the custom border shape. It can be any
    /// [`ShapeBorder`] such as `RoundedSuperellipseBorder`, `StadiumBorder`,
    /// `BeveledRectangleBorder`, or a custom shape.
    ///
    /// If the [`border_side`](Self::border_side) parameter is [`BorderSide::NONE`], it will
    /// not draw a border. However, it will still define a shape (which you can see if
    /// `InputDecoration.filled` is true).
    ///
    /// If an application does not specify a `border_side` parameter of
    /// value [`BorderSide::NONE`], the input decorator substitutes its own, using
    /// `copy_with`, based on the current theme and `InputDecorator.isFocused`.
    ///
    /// See also:
    ///
    ///  * `InputDecoration.floatingLabelBehavior`, which should be set to
    ///    `FloatingLabelBehavior.never` when the `border_side` is
    ///    [`BorderSide::NONE`]. If left as `FloatingLabelBehavior.auto`, the label
    ///    will extend beyond the container as if the border were still being
    ///    drawn.
    pub fn new(shape: impl Into<ShapeBorderRef>) -> ShapedInputBorder {
        ShapedInputBorder {
            border_side: BorderSide::default(),
            gap_padding: 4.0,
            shape: shape.into(),
        }
    }

    /// Dart `ShapedInputBorder(borderSide:)`.
    pub fn border_side(mut self, border_side: BorderSide) -> ShapedInputBorder {
        self.border_side = border_side;
        self
    }

    /// Dart `ShapedInputBorder(gapPadding:)`.
    pub fn gap_padding(mut self, gap_padding: f64) -> ShapedInputBorder {
        debug_assert!(gap_padding >= 0.0);
        self.gap_padding = gap_padding;
        self
    }

    /// Creates a copy of this border with the given fields replaced.
    pub fn copy_with(
        &self,
        border_side: Option<BorderSide>,
        shape: Option<ShapeBorderRef>,
        gap_padding: Option<f64>,
    ) -> ShapedInputBorder {
        ShapedInputBorder::new(shape.unwrap_or_else(|| self.shape.clone()))
            .border_side(border_side.unwrap_or(self.border_side))
            .gap_padding(gap_padding.unwrap_or(self.gap_padding))
    }

    /// Creates a copy of this border, scaled by the factor `t`.
    pub fn scale(&self, t: f64) -> ShapedInputBorder {
        ShapedInputBorder::new(self.shape.scale(t))
            .border_side(self.border_side.scale(t))
            .gap_padding(self.gap_padding * t)
    }

    fn gap_border_path(
        &self,
        rect: Rect,
        start: f64,
        extent: f64,
        text_direction: Option<TextDirection>,
    ) -> Path {
        // Create a continuous path for the border with a gap in the top edge.
        let outer_path = self.shape.get_outer_path(rect, text_direction);

        // If there's no meaningful gap, return the full outline.
        if start <= 0.0 && extent <= 0.0 {
            return outer_path;
        }

        // Create a rectangle that represents the gap area.
        // The gap is on the top edge, so we create a rect that covers the gap region.
        let gap_left = start;
        let gap_right = start + extent;

        // Create a path that excludes the gap area by combining with a difference operation.
        // We'll subtract a small rectangle at the top where the gap should be.
        let gap_rect = rect_path(Rect::from_ltrb(
            clamp_double(gap_left, rect.left, rect.right),
            rect.top - 1.0, // Extend slightly beyond to ensure clean cut.
            clamp_double(gap_right, rect.left, rect.right),
            rect.top + 1.0, // Small height to only affect top edge.
        ));

        path_combine(PathOperation::Difference, &outer_path, &gap_rect)
    }
}

impl PartialEq for ShapedInputBorder {
    fn eq(&self, other: &ShapedInputBorder) -> bool {
        other.border_side == self.border_side
            && other.shape == self.shape
            && other.gap_padding == self.gap_padding
    }
}

impl ShapeBorder for ShapedInputBorder {
    fn dimensions(&self) -> EdgeInsetsGeometry {
        EdgeInsetsGeometry::all(self.border_side.width)
    }

    fn scale(&self, t: f64) -> ShapeBorderRef {
        ShapeBorderRef::new(ShapedInputBorder::scale(self, t))
    }

    fn lerp_from(&self, a: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
        if let Some(a) = a.and_then(|a| a.as_any().downcast_ref::<ShapedInputBorder>()) {
            return Some(ShapeBorderRef::new(
                ShapedInputBorder::new(
                    ShapeBorderRef::lerp(Some(&a.shape), Some(&self.shape), t)
                        .expect("two shapes lerp to a shape"),
                )
                .border_side(BorderSide::lerp(a.border_side, self.border_side, t))
                .gap_padding(a.gap_padding),
            ));
        }
        if a.is_none() {
            Some(ShapeBorder::scale(self, t))
        } else {
            None
        }
    }

    fn lerp_to(&self, b: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
        if let Some(b) = b.and_then(|b| b.as_any().downcast_ref::<ShapedInputBorder>()) {
            return Some(ShapeBorderRef::new(
                ShapedInputBorder::new(
                    ShapeBorderRef::lerp(Some(&self.shape), Some(&b.shape), t)
                        .expect("two shapes lerp to a shape"),
                )
                .border_side(BorderSide::lerp(self.border_side, b.border_side, t))
                .gap_padding(b.gap_padding),
            ));
        }
        if b.is_none() {
            Some(ShapeBorder::scale(self, 1.0 - t))
        } else {
            None
        }
    }

    fn get_inner_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
        self.shape
            .get_inner_path(rect.deflate(self.border_side.width), text_direction)
    }

    fn get_outer_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
        self.shape.get_outer_path(rect, text_direction)
    }

    fn paint_interior(
        &self,
        canvas: &mut Canvas,
        rect: Rect,
        paint: &Paint,
        text_direction: Option<TextDirection>,
    ) {
        if self.shape.prefer_paint_interior() {
            self.shape
                .paint_interior(canvas, rect, paint, text_direction);
        } else {
            // Fallback for shapes that don't support paintInterior.
            let path = self.shape.get_outer_path(rect, text_direction);
            canvas.draw_path(path.as_valo(), path.fill_type, paint);
        }
    }

    fn prefer_paint_interior(&self) -> bool {
        self.shape.prefer_paint_interior()
    }

    fn paint(&self, canvas: &mut Canvas, rect: Rect, text_direction: Option<TextDirection>) {
        InputBorder::paint(self, canvas, rect, None, 0.0, 0.0, text_direction);
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn eq_shape(&self, other: &dyn ShapeBorder) -> bool {
        other
            .as_any()
            .downcast_ref::<ShapedInputBorder>()
            .is_some_and(|other| other == self)
    }
}

impl InputBorder for ShapedInputBorder {
    fn border_side(&self) -> BorderSide {
        self.border_side
    }

    fn copy_with(&self, border_side: Option<BorderSide>) -> InputBorderRef {
        InputBorderRef::new(ShapedInputBorder::copy_with(self, border_side, None, None))
    }

    fn is_outline(&self) -> bool {
        true
    }

    /// Draw the custom shape around `rect`.
    ///
    /// The [`border_side`](ShapedInputBorder::border_side) defines the line's color and
    /// weight.
    ///
    /// The top side of the border may be interrupted by a single gap
    /// if `gap_extent` is non-null. In that case the gap begins at
    /// `gap_start - gap_padding` (assuming that the `text_direction` is [`TextDirection::Ltr`]).
    /// The gap's width is `(gap_padding + gap_extent + gap_padding) * gap_percentage`.
    fn paint(
        &self,
        canvas: &mut Canvas,
        rect: Rect,
        gap_start: Option<f64>,
        gap_extent: f64,
        gap_percentage: f64,
        text_direction: Option<TextDirection>,
    ) {
        debug_assert!((0.0..=1.0).contains(&gap_percentage));

        let paint = self.border_side.to_paint();
        let deflated_rect = rect.deflate(self.border_side.width / 2.0);

        match gap_start {
            Some(gap_start) if gap_extent > 0.0 && gap_percentage != 0.0 => {
                let extent = lerp_double(
                    Some(0.0),
                    Some(gap_extent + self.gap_padding * 2.0),
                    gap_percentage,
                )
                .expect("both ends are given");
                let start = match text_direction.expect("a gap needs a text direction") {
                    TextDirection::Rtl => gap_start + self.gap_padding - extent,
                    TextDirection::Ltr => gap_start - self.gap_padding,
                };
                let path =
                    self.gap_border_path(deflated_rect, start.max(0.0), extent, text_direction);
                canvas.draw_path(path.as_valo(), path.fill_type, &paint);
            }
            // Draw the shape without a gap.
            _ => match self.shape.as_outlined_border() {
                Some(outlined_shape) => {
                    // Create a copy with our border side.
                    let shaped_border = outlined_shape.copy_with(Some(self.border_side));
                    shaped_border.paint(canvas, deflated_rect, text_direction);
                }
                None => {
                    let path = self.shape.get_outer_path(deflated_rect, text_direction);
                    canvas.draw_path(path.as_valo(), path.fill_type, &paint);
                }
            },
        }
    }
}

impl Debug for ShapedInputBorder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("ShapedInputBorder()")
    }
}

/// Dart's `shape as InputBorder` on a border that `ShapeBorder::lerp` gave back: the input
/// border it is, when it is one of this crate's input borders.
///
/// A `dyn ShapeBorder` cannot be asked for a supertrait it does not name, so a border of
/// another crate's `InputBorder` type answers `None`.
#[allow(deprecated)]
pub(crate) fn input_border_of(shape: &dyn ShapeBorder) -> Option<InputBorderRef> {
    let any = shape.as_any();
    if let Some(border) = any.downcast_ref::<NoInputBorder>() {
        return Some(InputBorderRef::new(*border));
    }
    if let Some(border) = any.downcast_ref::<UnderlineInputBorder>() {
        return Some(InputBorderRef::new(*border));
    }
    if let Some(border) = any.downcast_ref::<OutlineInputBorder>() {
        return Some(InputBorderRef::new(*border));
    }
    if let Some(border) = any.downcast_ref::<ShapedInputBorder>() {
        return Some(InputBorderRef::new(border.clone()));
    }
    if let Some(border) = any.downcast_ref::<crate::material_state::WidgetStateInputBorder>() {
        return Some(InputBorderRef::new(border.clone()));
    }
    if let Some(border) =
        any.downcast_ref::<crate::material_state::MaterialStateOutlineInputBorder>()
    {
        return Some(InputBorderRef::new(border.clone()));
    }
    if let Some(border) =
        any.downcast_ref::<crate::material_state::MaterialStateUnderlineInputBorder>()
    {
        return Some(InputBorderRef::new(border.clone()));
    }
    None
}

#[cfg(test)]
mod tests {
    use waft_embedder::valo::{Op, Point};
    use waft_painting::{RoundedRectangleBorder, RoundedSuperellipseBorder, StadiumBorder};
    use waft_widgets::{Center, IntoWidget};

    use waft_widgets::testing::test_widgets;

    use super::*;
    use crate::colors::Colors;
    use crate::input_decorator::{FloatingLabelBehavior, InputDecoration};
    use crate::scaffold::Scaffold;
    use crate::test_support::material_app;
    use crate::text_field::TextField;
    use crate::theme_data::ThemeData;

    fn superellipse(radius: f64) -> RoundedSuperellipseBorder {
        RoundedSuperellipseBorder::new(
            BorderSide::NONE,
            Some(BorderRadius::all(Radius::circular(radius)).into()),
        )
    }

    fn width(width: f64) -> BorderSide {
        BorderSide {
            width,
            ..BorderSide::default()
        }
    }

    fn blue(width: f64) -> BorderSide {
        BorderSide {
            color: Colors::BLUE.primary(),
            width,
            ..BorderSide::default()
        }
    }

    #[test]
    fn shaped_input_border_constructor() {
        let input_border = ShapedInputBorder::new(RoundedRectangleBorder::default());
        assert_eq!(input_border.border_side, BorderSide::default());
        assert!(
            input_border
                .shape
                .eq_shape(&RoundedRectangleBorder::default())
        );
        assert_eq!(input_border.gap_padding, 4.0);
        assert!(input_border.is_outline());
    }

    #[test]
    fn shaped_input_border_with_rounded_superellipse_border() {
        let input_border = ShapedInputBorder::new(superellipse(12.0));
        assert_eq!(input_border.border_side, BorderSide::default());
        assert!(input_border.shape.eq_shape(&superellipse(12.0)));
        assert_eq!(input_border.gap_padding, 4.0);
        assert!(input_border.is_outline());
    }

    #[test]
    fn shaped_input_border_copy_with_and_equality() {
        let input_border = ShapedInputBorder::new(RoundedRectangleBorder::default());
        let copy = input_border.copy_with(None, None, None);
        assert!(input_border == copy);

        let copy2 = input_border.copy_with(
            Some(blue(1.0)),
            Some(ShapeBorderRef::new(StadiumBorder::new(BorderSide::NONE))),
            Some(8.0),
        );
        assert_eq!(copy2.border_side, blue(1.0));
        assert!(copy2.shape.eq_shape(&StadiumBorder::new(BorderSide::NONE)));
        assert_eq!(copy2.gap_padding, 8.0);
        assert!(input_border != copy2);
    }

    #[test]
    fn shaped_input_border_scale() {
        let input_border = ShapedInputBorder::new(superellipse(10.0)).border_side(width(2.0));
        let scaled = input_border.scale(2.0);
        assert_eq!(scaled.border_side.width, 4.0);
        assert!(scaled.shape.eq_shape(&superellipse(20.0)));
        assert_eq!(scaled.gap_padding, 8.0);
    }

    #[test]
    fn shaped_input_border_lerp() {
        let input_border1 = ShapedInputBorder::new(superellipse(4.0)).gap_padding(2.0);
        let input_border2 = ShapedInputBorder::new(superellipse(12.0))
            .border_side(width(3.0))
            .gap_padding(6.0);

        let lerped = ShapeBorderRef::lerp(
            Some(&ShapeBorderRef::new(input_border1)),
            Some(&ShapeBorderRef::new(input_border2)),
            0.5,
        )
        .expect("two shaped input borders lerp");
        let lerped = lerped
            .as_any()
            .downcast_ref::<ShapedInputBorder>()
            .expect("a shaped input border");
        assert_eq!(lerped.border_side.width, 2.0);
        assert!(lerped.shape.eq_shape(&superellipse(8.0)));
        // gapPadding is not interpolated, it takes the value from the source
        assert_eq!(lerped.gap_padding, 2.0);
    }

    #[test]
    fn shaped_input_border_dimensions() {
        let input_border =
            ShapedInputBorder::new(RoundedRectangleBorder::default()).border_side(width(4.0));
        assert_eq!(input_border.dimensions(), EdgeInsetsGeometry::all(4.0));
    }

    fn pump_text_field(
        border: fn() -> ShapedInputBorder,
        floating_label_behavior: FloatingLabelBehavior,
    ) {
        test_widgets(|tester| {
            let theme = ThemeData::new(&tester.cell.borrow());
            let app = material_app(
                theme,
                Scaffold::new()
                    .body(
                        Center::new().child(
                            TextField::new().decoration(Some(
                                InputDecoration::new()
                                    .border(border())
                                    .label_text("Test Label")
                                    .floating_label_behavior(floating_label_behavior),
                            )),
                        ),
                    )
                    .into_widget(),
            );
            tester.pump_widget(app);
            tester.pump_and_settle();
        });
    }

    #[test]
    fn shaped_input_border_paint_with_rounded_superellipse_border() {
        pump_text_field(
            || ShapedInputBorder::new(superellipse(12.0)).border_side(blue(2.0)),
            FloatingLabelBehavior::Auto,
        );
    }

    #[test]
    fn shaped_input_border_paint_with_gap() {
        pump_text_field(
            || ShapedInputBorder::new(superellipse(12.0)).border_side(blue(2.0)),
            FloatingLabelBehavior::Always,
        );
    }

    #[test]
    fn shaped_input_border_paint_with_stadium_border() {
        pump_text_field(
            || ShapedInputBorder::new(StadiumBorder::new(BorderSide::NONE)).border_side(blue(2.0)),
            FloatingLabelBehavior::Auto,
        );
    }

    #[test]
    fn shaped_input_border_paint_interior() {
        let input_border = ShapedInputBorder::new(superellipse(12.0));
        assert!(input_border.prefer_paint_interior());

        let mut canvas = Canvas::new();
        input_border.paint_interior(
            &mut canvas,
            Rect::from_ltrb(10.0, 20.0, 30.0, 40.0),
            &Paint::default(),
            None,
        );
        canvas.build();
    }

    /// The gap Dart's `paint` cuts for a floating label: the shape's area less a rectangle two
    /// pixels high over the gap's span of the top edge, whose outline the border strokes.
    #[test]
    fn a_shaped_input_border_cuts_its_gap_from_the_top_edge() {
        let input_border = ShapedInputBorder::new(RoundedRectangleBorder::default());
        let mut canvas = Canvas::new();
        InputBorder::paint(
            &input_border,
            &mut canvas,
            Rect::from_ltrb(0.0, 0.0, 200.0, 50.0),
            Some(40.0),
            60.0,
            1.0,
            Some(TextDirection::Ltr),
        );
        let list = canvas.build();
        let Some(Op::DrawPath {
            path, fill_rule, ..
        }) = list
            .ops()
            .iter()
            .find(|op| matches!(op, Op::DrawPath { .. }))
        else {
            panic!("the border is drawn as a path");
        };
        assert_eq!(
            *fill_rule,
            FillRule::EvenOdd,
            "the fill type `Path.combine` gives"
        );
        // The deflated rect's top is at 0.5; the gap runs from 40 - 4 to 36 + 60 + 2 * 4.
        let contains = |x, y| path.contains(Point::new(x, y), *fill_rule);
        assert!(contains(20.0, 1.0), "the top edge before the gap");
        assert!(!contains(70.0, 1.0), "the gap");
        assert!(contains(70.0, 10.0), "below the gap");
        assert!(contains(150.0, 1.0), "the top edge after the gap");
    }
}