waft-widgets 0.11.0

Widget framework and 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
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
//! Flutter counterpart: `widgets/magnifier.dart`.

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

use waft_animation::AnimationController;
use waft_embedder::{
    Clip, FilterQuality, ImageFilter, Matrix4, Offset, Path, PathBuilder, PathFillType, Rect, Size,
    TextBaseline,
};
use waft_foundation::{App, Handle, Listener, OptionRetained, ValueNotifier};
use waft_painting::{
    Alignment, AlignmentGeometry, BoxShadow, RoundedRectangleBorder, ShapeBorderRef,
    ShapeDecoration,
};
use waft_rendering::{
    AnyRenderBox, AnyRenderObject, BackdropFilterLayer, BoxConstraints, BoxHitTestResult,
    ContainerLayer, CustomClipper, PaintingContext, RenderBox, RenderBoxData, RenderHandle,
    RenderObject, RenderObjectData, RenderObjectWithChildData, RenderObjectWithChildMixin,
    RenderProxyBoxMixin,
};
use waft_scheduler::TickerFuture;

use crate::framework::{
    BuildContext, IntoWidget, KeyRef, RenderObjectWidget, SingleChildRenderObjectWidget, State,
    StatelessWidget, WidgetRef,
};
use crate::widgets::basic::{ClipPath, IgnorePointer, Opacity, SizedBox, Stack, WidgetBuilder};
use crate::widgets::container::DecoratedBox;
use crate::widgets::inherited_theme::InheritedTheme;
use crate::widgets::navigator::Navigator;
use crate::widgets::overlay::{Overlay, OverlayEntry};
use waft_foundation::Ref;

/// Signature for a builder that builds a [`WidgetRef`] with a [`MagnifierController`].
///
/// The builder is called exactly once per magnifier.
///
/// If the `controller` parameter's [`MagnifierController::animation_controller`]
/// field is set (by the builder) to an [`AnimationController`], the
/// [`MagnifierController`] will drive the animation during entry and exit.
///
/// The `magnifier_info` parameter is updated with new [`MagnifierInfo`] instances
/// during the lifetime of the built magnifier, e.g. as the user moves their
/// finger around the text field.
pub type MagnifierBuilder = Rc<
    dyn Fn(
        &mut App,
        BuildContext,
        Ref<MagnifierController>,
        Ref<ValueNotifier<MagnifierInfo>>,
    ) -> Option<WidgetRef>,
>;

/// A data class that contains the geometry information of text layouts
/// and selection gestures, used to position magnifiers.
#[derive(Clone, Copy, PartialEq)]
pub struct MagnifierInfo {
    /// The offset of the gesture position that the magnifier should be shown at.
    pub global_gesture_position: Offset,
    /// The rect of the current line the magnifier should be shown at, without
    /// taking into account any padding of the field; only the position of the
    /// first and last character.
    pub current_line_boundaries: Rect,
    /// The rect of the handle that the magnifier should follow.
    pub caret_rect: Rect,
    /// The bounds of the entire text field that the magnifier is bound to.
    pub field_bounds: Rect,
}

impl MagnifierInfo {
    /// Constructs a [`MagnifierInfo`] from provided geometry values.
    pub const fn new(
        global_gesture_position: Offset,
        caret_rect: Rect,
        field_bounds: Rect,
        current_line_boundaries: Rect,
    ) -> MagnifierInfo {
        MagnifierInfo {
            global_gesture_position,
            caret_rect,
            field_bounds,
            current_line_boundaries,
        }
    }

    /// Const [`MagnifierInfo`] with all values set to 0.
    pub const EMPTY: MagnifierInfo = MagnifierInfo {
        global_gesture_position: Offset::ZERO,
        caret_rect: Rect::ZERO,
        current_line_boundaries: Rect::ZERO,
        field_bounds: Rect::ZERO,
    };
}

impl Debug for MagnifierInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "MagnifierInfo(position: {:?}, line: {:?}, caret: {:?}, field: {:?})",
            self.global_gesture_position,
            self.current_line_boundaries,
            self.caret_rect,
            self.field_bounds
        )
    }
}

/// A configuration object for a magnifier (e.g. in a text field).
///
/// In general, most features of the magnifier can be configured by controlling
/// the widgets built by the [`magnifier_builder`](Self::magnifier_builder).
#[derive(Clone)]
pub struct TextMagnifierConfiguration {
    magnifier_builder: Option<MagnifierBuilder>,
    /// Whether a magnifier should show the text editing handles or not.
    ///
    /// This flag is used by `SelectionOverlay.showMagnifier` to control the order
    /// of layers in the rendering; specifically, whether to place the layer
    /// containing the handles above or below the layer containing the magnifier
    /// in the [`Overlay`].
    pub should_display_handles_in_magnifier: bool,
}

impl TextMagnifierConfiguration {
    /// Constructs a [`TextMagnifierConfiguration`] from parts.
    ///
    /// If [`magnifier_builder`](Self::magnifier_builder) is not set, a default
    /// [`MagnifierBuilder`] will be used that does not build a magnifier.
    pub const fn new() -> TextMagnifierConfiguration {
        TextMagnifierConfiguration {
            magnifier_builder: None,
            should_display_handles_in_magnifier: true,
        }
    }

    /// The builder callback that creates the widget that renders the magnifier.
    pub fn magnifier_builder(&self) -> MagnifierBuilder {
        self.magnifier_builder
            .clone()
            .unwrap_or_else(|| Rc::new(none))
    }

    /// Dart `TextMagnifierConfiguration(magnifierBuilder:)`.
    pub fn with_magnifier_builder(
        mut self,
        magnifier_builder: MagnifierBuilder,
    ) -> TextMagnifierConfiguration {
        self.magnifier_builder = Some(magnifier_builder);
        self
    }

    /// Dart `TextMagnifierConfiguration(shouldDisplayHandlesInMagnifier:)`.
    pub fn should_display_handles_in_magnifier(
        mut self,
        should_display_handles_in_magnifier: bool,
    ) -> TextMagnifierConfiguration {
        self.should_display_handles_in_magnifier = should_display_handles_in_magnifier;
        self
    }

    pub(crate) fn same_configuration(&self, other: &TextMagnifierConfiguration) -> bool {
        self.should_display_handles_in_magnifier == other.should_display_handles_in_magnifier
            && match (&self.magnifier_builder, &other.magnifier_builder) {
                (None, None) => true,
                (Some(a), Some(b)) => Rc::ptr_eq(a, b),
                _ => false,
            }
    }

    /// A constant for a [`TextMagnifierConfiguration`] that is disabled, meaning it
    /// never builds anything, regardless of platform.
    pub const DISABLED: TextMagnifierConfiguration = TextMagnifierConfiguration::new();
}

impl Default for TextMagnifierConfiguration {
    fn default() -> TextMagnifierConfiguration {
        TextMagnifierConfiguration::new()
    }
}

fn none(
    _app: &mut App,
    _context: BuildContext,
    _controller: Ref<MagnifierController>,
    _magnifier_info: Ref<ValueNotifier<MagnifierInfo>>,
) -> Option<WidgetRef> {
    None
}

/// A controller for a magnifier.
///
/// [`MagnifierController`]'s main benefit over holding a raw [`OverlayEntry`] is that
/// [`MagnifierController`] will handle logic around waiting for a magnifier to animate in or out.
///
/// If a magnifier chooses to have an entry / exit animation, it should provide the animation
/// controller to [`MagnifierController::animation_controller`]. [`MagnifierController`] will then drive
/// the [`AnimationController`] and wait for it to be complete before removing it from the
/// [`Overlay`].
///
/// To check the status of the magnifier, see [`MagnifierController::shown`].
pub struct MagnifierController {
    /// The controller that will be driven in / out when show / hide is triggered,
    /// respectively.
    pub animation_controller: Option<Ref<AnimationController>>,
    overlay_entry: Option<Ref<OverlayEntry>>,
}

impl MagnifierController {
    /// If there is no in / out animation for the magnifier, [`animation_controller`](Self::animation_controller)
    /// should be left unset.
    pub fn new(app: &mut App) -> Ref<MagnifierController> {
        app.create(MagnifierController {
            animation_controller: None,
            overlay_entry: None,
        })
    }

    /// Dart `MagnifierController(animationController:)`.
    pub fn animation_controller(
        self: Ref<Self>,
        app: &mut App,
        animation_controller: Ref<AnimationController>,
    ) -> Ref<Self> {
        animation_controller.set_value(app, 0.0);
        app.get_mut(&self).animation_controller = Some(animation_controller);
        self
    }

    /// The magnifier's [`OverlayEntry`], if currently in the overlay.
    ///
    /// This is exposed so that other overlay entries can be positioned above or
    /// below this [`overlay_entry`](Self::overlay_entry). Anything in the paint order after the
    /// `RawMagnifier` in this [`OverlayEntry`] will not be displayed in the
    /// magnifier; if it is desired for an overlay entry to be displayed in the
    /// magnifier, it *must* be positioned below the magnifier.
    ///
    /// To check if a magnifier is in the overlay, use [`shown`](Self::shown). The
    /// [`overlay_entry`](Self::overlay_entry) field may be non-null even when the magnifier is
    /// not visible.
    pub fn overlay_entry(self: Handle<Self>, app: &App) -> Option<Handle<OverlayEntry>> {
        app.get(self).overlay_entry.handle()
    }

    /// Whether the magnifier is currently being shown.
    ///
    /// This is false when nothing is in the overlay, when the
    /// [`animation_controller`](Self::animation_controller) is in the
    /// [`waft_animation::AnimationStatus::Dismissed`] state, or when
    /// the [`animation_controller`](Self::animation_controller) is animating out (i.e. in the
    /// [`waft_animation::AnimationStatus::Reverse`] state).
    ///
    /// It is true in the opposite cases, i.e. when the overlay is not empty, and
    /// either the [`animation_controller`](Self::animation_controller) is `None`, in the
    /// [`waft_animation::AnimationStatus::Completed`] state, or in the
    /// [`waft_animation::AnimationStatus::Forward`]
    /// state.
    pub fn shown(self: Handle<Self>, app: &App) -> bool {
        app.get(self).overlay_entry.is_some()
            && app
                .get(self)
                .animation_controller
                .as_ref()
                .is_none_or(|controller| controller.status(app).is_forward_or_completed())
    }

    /// Displays the magnifier.
    ///
    /// Returns a future that completes when the magnifier is fully shown, i.e. done
    /// with its entry animation.
    ///
    /// To control what overlays are shown in the magnifier, use `below`. See
    /// [`overlay_entry`](Self::overlay_entry) for more details on how to utilize `below`.
    ///
    /// If the magnifier already exists (i.e. [`overlay_entry`](Self::overlay_entry) is `Some`),
    /// then [`show`](Self::show) will replace the old overlay without playing an exit
    /// animation. Consider awaiting [`hide`](Self::hide) first, to animate from the old
    /// magnifier to the new one.
    pub fn show(
        self: Handle<Self>,
        app: &mut App,
        context: BuildContext,
        builder: WidgetBuilder,
        below: Option<Handle<OverlayEntry>>,
    ) -> TickerFuture {
        if let Some(entry) = app.get(self).overlay_entry.handle() {
            entry.remove(app);
            entry.dispose(app);
        }

        let overlay_state = Overlay::of(app, context, true);

        let to = Navigator::maybe_of(app, context, false).map(|navigator| navigator.context(app));
        let captured_themes = <dyn InheritedTheme>::capture(app, context, to);

        let overlay_entry = OverlayEntry::new(
            app,
            Rc::new(move |app: &mut App, context: BuildContext| {
                captured_themes.wrap(builder(app, context))
            }),
            false,
            false,
            false,
        );
        app.get_mut(self).overlay_entry = Some(overlay_entry.clone());
        overlay_state.insert(app, overlay_entry, below, None);

        if let Some(controller) = app.get(self).animation_controller.handle() {
            controller.forward(app, None)
        } else {
            TickerFuture::complete()
        }
    }

    /// Schedules a hide of the magnifier.
    ///
    /// If this [`MagnifierController`] has an [`animation_controller`](Self::animation_controller),
    /// then [`hide`](Self::hide) reverses the animation controller and waits
    /// for the animation to complete. Then, if `remove_from_overlay`
    /// is true, remove the magnifier from the overlay.
    ///
    /// In general, `remove_from_overlay` should be true, unless
    /// the magnifier needs to preserve states between shows / hides.
    ///
    /// See also:
    ///
    ///  * [`remove_from_overlay`](Self::remove_from_overlay) which removes the [`OverlayEntry`] from the [`Overlay`]
    ///    synchronously.
    pub fn hide(self: Handle<Self>, app: &mut App, remove_from_overlay: bool) -> TickerFuture {
        if app.get(self).overlay_entry.is_none() {
            return TickerFuture::complete();
        }

        if let Some(controller) = app.get(self).animation_controller.handle() {
            let future = controller.reverse(app, None);
            if remove_from_overlay {
                future.when_complete(
                    app,
                    Listener::handle_method(self, MagnifierController::remove_from_overlay),
                );
            }
            return future;
        }

        if remove_from_overlay {
            self.remove_from_overlay(app);
        }
        TickerFuture::complete()
    }

    /// Remove the [`OverlayEntry`] from the [`Overlay`].
    ///
    /// This method removes the [`OverlayEntry`] synchronously,
    /// regardless of exit animation: this leads to abrupt removals
    /// of [`OverlayEntry`]s with animations.
    ///
    /// To allow the [`OverlayEntry`] to play its exit animation, consider calling
    /// [`hide`](Self::hide) instead, with `remove_from_overlay` set to true, and optionally await
    /// the returned future.
    pub fn remove_from_overlay(self: Handle<Self>, app: &mut App) {
        if let Some(entry) = app.get(self).overlay_entry.handle() {
            entry.remove(app);
            entry.dispose(app);
        }
        app.get_mut(self).overlay_entry = None;
    }

    /// A utility for calculating a new [`Rect`] from `rect` such that
    /// `rect` is fully constrained within `bounds`.
    ///
    /// Any point in the output rect is guaranteed to also be a point contained in `bounds`.
    ///
    /// It is a runtime error for `rect`.width to be greater than `bounds`.width,
    /// and it is also an error for `rect`.height to be greater than `bounds`.height.
    ///
    /// This algorithm translates `rect` the shortest distance such that it is entirely within
    /// `bounds`.
    ///
    /// If `rect` is already within `bounds`, no shift will be applied to `rect` and
    /// `rect` will be returned as-is.
    ///
    /// It is perfectly valid for the output rect to have a point along the edge of the
    /// `bounds`. If the desired output rect requires that no edges are parallel to edges
    /// of `bounds`, see [`Rect::deflate`] by 1 on `bounds` to achieve this effect.
    pub fn shift_within_bounds(rect: Rect, bounds: Rect) -> Rect {
        debug_assert!(
            rect.width() <= bounds.width(),
            "attempted to shift {rect:?} within {bounds:?}, but the rect has a greater width.",
        );
        debug_assert!(
            rect.height() <= bounds.height(),
            "attempted to shift {rect:?} within {bounds:?}, but the rect has a greater height.",
        );

        let mut rect_shift = Offset::ZERO;
        if rect.left < bounds.left {
            rect_shift = rect_shift + Offset::new(bounds.left - rect.left, 0.0);
        } else if rect.right > bounds.right {
            rect_shift = rect_shift + Offset::new(bounds.right - rect.right, 0.0);
        }

        if rect.top < bounds.top {
            rect_shift = rect_shift + Offset::new(0.0, bounds.top - rect.top);
        } else if rect.bottom > bounds.bottom {
            rect_shift = rect_shift + Offset::new(0.0, bounds.bottom - rect.bottom);
        }

        rect.shift(rect_shift)
    }
}

/// The decorations to put around the loupe in a [`RawMagnifier`].
///
/// See also:
///
///  * `Decoration`, a more general solution for [`DecoratedBox`].
#[derive(Clone, Debug)]
pub struct MagnifierDecoration {
    // TODO(ianh): deprecate [opacity] (moving it to [RawMagnifier]), and then
    // once [opacity] can be removed, replace [MagnifierDecoration] with a
    // `typedef` to [ShapeDecoration] and make anywhere that accepts a
    // [MagnifierDecoration] accept a [ShapeDecoration] instead. This would allow
    // magnifiers that don't offset the shadows to use the decoration to paint
    // over the loupe rather than having to have a Stack of widgets to do so.
    /// The opacity of the magnifier and decorations around the magnifier.
    ///
    /// When this is 1.0, the magnified image shows in the [`shape`](Self::shape) of the
    /// magnifier. When this is less than 1.0, the magnified image is transparent
    /// and shows through the unmagnified background.
    ///
    /// Generally this is only useful for animating the magnifier in and out, as a
    /// transparent magnifier looks quite confusing.
    pub opacity: f64,
    /// A list of shadows cast by the [`shape`](Self::shape).
    ///
    /// If the shadows are offset, consider setting [`RawMagnifier::clip_behavior`] to
    /// [`Clip::HardEdge`] (or similar) to ensure the shadow does not occlude the
    /// magnifier (the shadow is drawn above the magnifier).
    ///
    /// If the shadows are _not_ offset, consider using `BlurStyle::Outer` in the
    /// shadows instead, to avoid having to introduce a clip.
    ///
    /// In the event that [`shape`](Self::shape) consists of a stack of borders, the shadow
    /// is drawn using the bounds of the last one.
    ///
    /// See also:
    ///
    ///  * `kElevationToShadow`, which defines some shadows for Material design.
    ///    Those shadows use `BlurStyle::Normal` and may need to be converted to
    ///    `BlurStyle::Outer` for use with [`MagnifierDecoration`].
    pub shadows: Option<Vec<BoxShadow>>,
    /// The shape of the magnifier and the outline (border) around it.
    ///
    /// Shapes can be stacked (using `plus`). In that case, the magnifier and shadow are
    /// drawn according to the outside edge of the last shape, with the borders painted on
    /// top.
    pub shape: ShapeBorderRef,
}

impl MagnifierDecoration {
    /// Constructs a [`MagnifierDecoration`].
    ///
    /// By default, [`MagnifierDecoration`] is a rectangular magnifier with no
    /// shadows, and fully opaque.
    pub fn new() -> MagnifierDecoration {
        MagnifierDecoration::default()
    }

    /// Dart `MagnifierDecoration(opacity:)`.
    pub fn opacity(mut self, opacity: f64) -> MagnifierDecoration {
        self.opacity = opacity;
        self
    }

    /// Dart `MagnifierDecoration(shadows:)`.
    pub fn shadows(mut self, shadows: Vec<BoxShadow>) -> MagnifierDecoration {
        self.shadows = Some(shadows);
        self
    }

    /// Dart `MagnifierDecoration(shape:)`.
    pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> MagnifierDecoration {
        self.shape = shape.into();
        self
    }
}

impl Default for MagnifierDecoration {
    fn default() -> MagnifierDecoration {
        MagnifierDecoration {
            opacity: 1.0,
            shadows: None,
            shape: ShapeBorderRef::new(RoundedRectangleBorder::default()),
        }
    }
}

impl PartialEq for MagnifierDecoration {
    fn eq(&self, other: &MagnifierDecoration) -> bool {
        self.opacity == other.opacity && self.shadows == other.shadows && self.shape == other.shape
    }
}

/// A common base class for magnifiers.
///
/// This magnifying glass is useful for scenarios on mobile devices where
/// the user's finger may be covering part of the screen where a granular
/// action is being performed, such as navigating a small cursor with a drag
/// gesture, on an image or text.
///
/// A magnifier can be conveniently managed by [`MagnifierController`], which handles
/// showing and hiding the magnifier, with an optional entry / exit animation.
///
/// See:
/// * [`MagnifierController`], a controller to handle magnifiers in an overlay.
#[derive(Debug)]
pub struct RawMagnifier {
    pub key: Option<KeyRef>,
    /// An optional widget to position inside the len of the [`RawMagnifier`].
    ///
    /// This is positioned over the [`RawMagnifier`] - it may be useful for tinting the
    /// [`RawMagnifier`], or drawing a crosshair-like UI.
    pub child: Option<WidgetRef>,
    /// This magnifier's decoration.
    ///
    /// This sets the shape of the loupe, plus any borders and shadows that it
    /// casts. The default has no border and no shadow; combined with the default
    /// [`magnification_scale`](Self::magnification_scale) of 1.0, this results in the
    /// magnifier having no visible effect.
    ///
    /// If the [`decoration`](Self::decoration) has a [`MagnifierDecoration::shadows`] that
    /// uses offset shadows or uses a `BlurStyle` that would obscure the magnified image,
    /// consider setting [`clip_behavior`](Self::clip_behavior) to [`Clip::HardEdge`] (or
    /// similar) to ensure the magnified image is visible.
    pub decoration: MagnifierDecoration,
    /// Whether and how to clip the parts of [`decoration`](Self::decoration) that render
    /// inside the loupe.
    ///
    /// Defaults to [`Clip::None`].
    ///
    /// See the discussion at [`decoration`](Self::decoration).
    pub clip_behavior: Clip,
    /// The offset of the magnifier from [`RawMagnifier`]'s center.
    ///
    /// For example, if [`RawMagnifier`] is globally positioned at Offset(100, 100),
    /// and [`focal_point_offset`](Self::focal_point_offset) is Offset(-20, -20), then
    /// [`RawMagnifier`] will see the content at global offset (80, 80).
    ///
    /// If left as [`Offset::ZERO`], the [`RawMagnifier`] will show the content that
    /// is directly below it.
    pub focal_point_offset: Offset,
    /// How "zoomed in" the magnification subject is in the lens.
    ///
    /// The default is 1.0, which is no magnification.
    pub magnification_scale: f64,
    /// The size of the magnifier.
    ///
    /// This does not include the border from the [`decoration`](Self::decoration); it only
    /// includes the size of the magnifier.
    pub size: Size,
}

impl RawMagnifier {
    /// Constructs a [`RawMagnifier`].
    ///
    /// By default, this magnifier uses the default [`MagnifierDecoration`] (which
    /// draws nothing), the focal point is directly under the magnifier, and there
    /// is no magnification; this means that a default magnifier will be entirely
    /// invisible to the naked eye, painting exactly what is under it, exactly
    /// where it was painted originally.
    pub fn new(size: Size) -> RawMagnifier {
        RawMagnifier {
            key: None,
            child: None,
            decoration: MagnifierDecoration::new(),
            clip_behavior: Clip::None,
            focal_point_offset: Offset::ZERO,
            magnification_scale: 1.0,
            size,
        }
    }

    /// Dart `RawMagnifier(key:)`.
    pub fn key(mut self, key: KeyRef) -> RawMagnifier {
        self.key = Some(key);
        self
    }

    /// Dart `RawMagnifier(child:)`.
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> RawMagnifier {
        self.child = Some(child.into_widget());
        self
    }

    /// Dart `RawMagnifier(decoration:)`.
    pub fn decoration(mut self, decoration: MagnifierDecoration) -> RawMagnifier {
        self.decoration = decoration;
        self
    }

    /// Dart `RawMagnifier(clipBehavior:)`.
    pub fn clip_behavior(mut self, clip_behavior: Clip) -> RawMagnifier {
        self.clip_behavior = clip_behavior;
        self
    }

    /// Dart `RawMagnifier(focalPointOffset:)`.
    pub fn focal_point_offset(mut self, focal_point_offset: Offset) -> RawMagnifier {
        self.focal_point_offset = focal_point_offset;
        self
    }

    /// Dart `RawMagnifier(magnificationScale:)`.
    pub fn magnification_scale(mut self, magnification_scale: f64) -> RawMagnifier {
        debug_assert!(
            magnification_scale != 0.0,
            "Magnification scale of 0 results in undefined behavior."
        );
        self.magnification_scale = magnification_scale;
        self
    }
}

impl StatelessWidget for RawMagnifier {
    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
        let mut lens = SizedBox::from_size(Some(self.size));
        lens.child = self.child.clone();
        let mut decoration = ShapeDecoration::new(self.decoration.shape.clone());
        decoration.shadows = self.decoration.shadows.clone();
        Stack::new()
            .clip_behavior(Clip::None)
            .alignment(AlignmentGeometry::CENTER)
            .children([
                // The magnified image is clipped to the outer path of the shape.
                ClipPath::shape(self.decoration.shape.clone())
                    .child(
                        Opacity::new(self.decoration.opacity).child(
                            Magnifier::new()
                                .focal_point_offset(self.focal_point_offset)
                                .magnification_scale(self.magnification_scale)
                                .child(lens),
                        ),
                    )
                    .into_widget(),
                // Because `BackdropFilter` will filter any widgets before it, we apply
                // these styles after (i.e. in a younger sibling) to avoid the magnifier
                // from seeing its own styling.
                IgnorePointer::new()
                    .child(
                        Opacity::new(self.decoration.opacity).child(
                            ClipPath::new()
                                .clip_behavior(self.clip_behavior)
                                .clipper(Rc::new(NegativeClip::new(self.decoration.shape.clone())))
                                .child(
                                    DecoratedBox::new(decoration)
                                        .child(SizedBox::from_size(Some(self.size))),
                                ),
                        ),
                    )
                    .into_widget(),
            ])
            .into_widget()
    }
}

/// A clip that renders everything except the inside of a shape.
struct NegativeClip {
    shape: ShapeBorderRef,
}

impl NegativeClip {
    fn new(shape: ShapeBorderRef) -> NegativeClip {
        NegativeClip { shape }
    }
}

impl CustomClipper<Path> for NegativeClip {
    fn get_clip(&self, _app: &App, size: Size) -> Path {
        let mut path = PathBuilder::new();
        path.rect(Rect::LARGEST.into());
        path.append(
            self.shape
                .get_inner_path(Offset::ZERO & size, None)
                .as_valo(),
            &Matrix4::IDENTITY,
        );
        let mut path = Path::new(path.build());
        path.fill_type = PathFillType::EvenOdd;
        path
    }

    fn should_reclip(&self, _app: &App, old_clipper: &dyn CustomClipper<Path>) -> bool {
        let Some(old_clipper) = old_clipper.as_any().downcast_ref::<NegativeClip>() else {
            return true;
        };
        old_clipper.shape != self.shape
    }

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

/// Dart's `_Magnifier`: the render object widget of the lens.
#[derive(Debug)]
struct Magnifier {
    /// The Offset that the center of the [`Magnifier`] points to, relative
    /// to the center of the magnifier.
    focal_point_offset: Offset,
    /// The enlarge multiplier of the magnification.
    ///
    /// If equal to 1.0, the content in the magnifier is true to its real size.
    /// If greater than 1.0, the content appears bigger in the magnifier.
    magnification_scale: f64,
    child: Option<WidgetRef>,
}

impl Magnifier {
    fn new() -> Magnifier {
        Magnifier {
            focal_point_offset: Offset::ZERO,
            magnification_scale: 1.0,
            child: None,
        }
    }

    fn focal_point_offset(mut self, focal_point_offset: Offset) -> Magnifier {
        self.focal_point_offset = focal_point_offset;
        self
    }

    fn magnification_scale(mut self, magnification_scale: f64) -> Magnifier {
        self.magnification_scale = magnification_scale;
        self
    }

    #[cfg_attr(debug_assertions, track_caller)]
    fn child<K>(mut self, child: impl IntoWidget<K>) -> Magnifier {
        self.child = Some(child.into_widget());
        self
    }
}

impl RenderObjectWidget for Magnifier {
    type RenderObject = RenderMagnification;

    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
        RenderMagnification::new(app, self.focal_point_offset, self.magnification_scale, None)
            .as_object()
    }

    fn update_render_object(
        &self,
        app: &mut App,
        _context: BuildContext,
        render_object: RenderHandle<RenderMagnification>,
    ) {
        render_object.set_focal_point_offset(app, self.focal_point_offset);
        render_object.set_magnification_scale(app, self.magnification_scale);
    }
}

impl SingleChildRenderObjectWidget for Magnifier {
    fn child(&self) -> Option<&WidgetRef> {
        self.child.as_ref()
    }
}

/// Dart's `_RenderMagnification`: a proxy box that shows, under its child, what was painted
/// before it, moved and scaled by [`magnification_matrix`](Self::magnification_matrix).
struct RenderMagnification {
    render_object: RenderObjectData,
    render_box: RenderBoxData,
    child: RenderObjectWithChildData<AnyRenderBox>,
    focal_point_offset: Offset,
    magnification_scale: f64,
}

impl RenderMagnification {
    fn new(
        app: &mut App,
        focal_point_offset: Offset,
        magnification_scale: f64,
        child: Option<AnyRenderBox>,
    ) -> RenderHandle<RenderMagnification> {
        let this = RenderHandle::new_box(
            app,
            RenderMagnification {
                render_object: RenderObjectData::new(),
                render_box: RenderBoxData::new(),
                child: RenderObjectWithChildData::new(),
                focal_point_offset,
                magnification_scale,
            },
        );
        this.set_child(app, child);
        this
    }

    fn focal_point_offset(self: RenderHandle<Self>, app: &App) -> Offset {
        self.get(app).focal_point_offset
    }

    fn set_focal_point_offset(self: RenderHandle<Self>, app: &mut App, value: Offset) {
        if self.focal_point_offset(app) == value {
            return;
        }
        self.get_mut(app).focal_point_offset = value;
        self.mark_needs_paint(app);
    }

    fn magnification_scale(self: RenderHandle<Self>, app: &App) -> f64 {
        self.get(app).magnification_scale
    }

    fn set_magnification_scale(self: RenderHandle<Self>, app: &mut App, value: f64) {
        if self.magnification_scale(app) == value {
            return;
        }
        self.get_mut(app).magnification_scale = value;
        self.mark_needs_paint(app);
    }

    /// The transform Dart's `paint` hands `ImageFilter.matrix` for the backdrop painted at
    /// `offset`: a scale by [`magnification_scale`](Self::magnification_scale) about this
    /// box's center, which brings the focal point under the center.
    fn magnification_matrix(self: RenderHandle<Self>, app: &App, offset: Offset) -> Matrix4 {
        let this_center = Alignment::CENTER.along_size(self.size(app)) + offset;
        let magnification_scale = self.magnification_scale(app);
        let focal_point_offset = self.focal_point_offset(app);
        let scale = magnification_scale as f32;
        Matrix4::translation(
            (magnification_scale * (-focal_point_offset.dx() - this_center.dx()) + this_center.dx())
                as f32,
            (magnification_scale * (-focal_point_offset.dy() - this_center.dy()) + this_center.dy())
                as f32,
        )
        .then(&Matrix4::from_flutter_array(&[
            scale, 0.0, 0.0, 0.0, //
            0.0, scale, 0.0, 0.0, //
            0.0, 0.0, scale, 0.0, //
            0.0, 0.0, 0.0, 1.0,
        ]))
    }
}

impl RenderObjectWithChildMixin for RenderMagnification {
    type ChildType = AnyRenderBox;

    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
        &self.get(app).child
    }

    fn child_data_mut(
        self: RenderHandle<Self>,
        app: &mut App,
    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
        &mut self.get_mut(app).child
    }
}

impl RenderProxyBoxMixin for RenderMagnification {}

impl RenderObject for RenderMagnification {
    waft_rendering::render_object_accessors!();

    fn always_needs_compositing(self: RenderHandle<Self>, _app: &App) -> bool {
        true
    }

    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
        RenderProxyBoxMixin::perform_layout(self, app);
    }

    fn paint(
        self: RenderHandle<Self>,
        app: &mut App,
        context: &mut PaintingContext,
        offset: Offset,
    ) {
        let filter =
            ImageFilter::matrix(self.magnification_matrix(app, offset), FilterQuality::High);

        let layer = match self.as_object().layer_as::<BackdropFilterLayer>(app) {
            Some(layer) => layer,
            None => {
                let layer = BackdropFilterLayer::new(app);
                self.as_object()
                    .set_layer(app, Some(layer.as_container_layer()));
                layer
            }
        };
        layer.set_filter(app, Some(filter));

        context.push_layer(
            app,
            layer.as_container_layer(),
            |app, context, offset| RenderProxyBoxMixin::paint(self, app, context, offset),
            offset,
            None,
        );
    }

    fn visit_children(
        self: RenderHandle<Self>,
        app: &App,
        visitor: &mut dyn FnMut(AnyRenderObject),
    ) {
        if let Some(child) = self.child(app) {
            visitor(child.as_object());
        }
    }
}

impl RenderBox for RenderMagnification {
    waft_rendering::render_box_accessors!();

    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
        RenderProxyBoxMixin::setup_parent_data(self, app, child);
    }

    fn apply_paint_transform(
        self: RenderHandle<Self>,
        app: &App,
        child: AnyRenderObject,
        transform: &mut Matrix4,
    ) {
        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
    }

    fn hit_test_children(
        self: RenderHandle<Self>,
        app: &mut App,
        result: &mut BoxHitTestResult<'_>,
        position: Offset,
    ) -> bool {
        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
    }

    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
    }

    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
    }

    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
    }

    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
    }

    fn compute_distance_to_actual_baseline(
        self: RenderHandle<Self>,
        app: &mut App,
        baseline: TextBaseline,
    ) -> Option<f64> {
        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
    }

    fn compute_dry_baseline(
        self: RenderHandle<Self>,
        app: &mut App,
        constraints: BoxConstraints,
        baseline: TextBaseline,
    ) -> Option<f64> {
        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
    }

    fn compute_dry_layout(
        self: RenderHandle<Self>,
        app: &mut App,
        constraints: BoxConstraints,
    ) -> Size {
        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use waft_animation::{AnimationBehavior, AnimationStatus};
    use waft_embedder::{BlurStyle, Color, Radius, TextDirection};
    use waft_foundation::UniqueKey;
    use waft_painting::{BorderRadius, BorderSide, BorderStyle, CircleBorder};
    use waft_rendering::{
        RenderClipPath, RenderCustomClip, RenderDecoratedBox, RenderOpacity, RenderStack,
    };
    use waft_scheduler::{FrameTarget, SchedulerBinding};

    use super::*;
    use crate::binding::WidgetsBinding;
    use crate::framework::{AnyElement, GlobalKey};
    use crate::testing::{TestVSync, WidgetTester, test_widgets};
    use crate::widgets::basic::{Center, Directionality, Positioned};
    use crate::widgets::text::Text;

    fn elements(app: &mut App) -> Vec<AnyElement> {
        fn visit(app: &App, element: AnyElement, found: &mut Vec<AnyElement>) {
            found.push(element);
            for child in element.children(app) {
                visit(app, child, found);
            }
        }
        let mut found = Vec::new();
        let root = WidgetsBinding::instance(app)
            .root_element(app)
            .expect("a mounted tree");
        visit(app, root, &mut found);
        found
    }

    /// The render objects of the mounted tree that are an `R`, in tree order.
    fn render_objects<R: RenderObject>(app: &mut App) -> Vec<RenderHandle<R>> {
        fn visit<R: RenderObject>(
            app: &App,
            node: AnyRenderObject,
            found: &mut Vec<RenderHandle<R>>,
        ) {
            if let Some(handle) = node.downcast::<R>(app) {
                found.push(handle);
            }
            node.visit_children(app, &mut |child| visit(app, child, found));
        }
        let root = WidgetsBinding::instance(app)
            .root_element(app)
            .and_then(|root| root.find_render_object(app))
            .expect("a laid out tree");
        let mut found = Vec::new();
        visit(app, root, &mut found);
        found
    }

    /// The render box of the first element whose widget `matches`.
    fn render_box_where(app: &mut App, matches: impl Fn(&WidgetRef) -> bool) -> AnyRenderBox {
        elements(app)
            .into_iter()
            .find(|element| matches(element.widget(app)))
            .and_then(|element| element.find_render_object(app))
            .and_then(|render_object| render_object.as_box())
            .expect("a mounted render box")
    }

    fn has_key(widget: &WidgetRef, key: &KeyRef) -> bool {
        widget.key() == Some(key)
    }

    /// Dart's `TestWidgetsApp(home: Placeholder())`: an overlay around a box whose context the
    /// magnifier is shown from.
    fn app_with_overlay(tester: &mut WidgetTester, home: GlobalKey) {
        tester.pump_widget(Directionality::new(
            TextDirection::Ltr,
            Overlay::wrap(SizedBox::new().key(home.into())),
        ));
    }

    /// Dart's `WidgetsBinding.instance.scheduleFrame()`, then `tester.pump()`.
    fn schedule_frame_and_pump(tester: &mut WidgetTester) {
        tester.update(|app| SchedulerBinding::schedule_frame(app, FrameTarget::EveryView));
        tester.pump();
    }

    fn raw_magnifier_builder(magnifier_key: KeyRef) -> WidgetBuilder {
        Rc::new(move |_app: &mut App, _context: BuildContext| {
            RawMagnifier::new(Size::new(100.0, 100.0))
                .key(magnifier_key.clone())
                .into_widget()
        })
    }

    #[test]
    fn a_raw_magnifier_is_as_large_as_its_size() {
        test_widgets(|tester| {
            tester.pump_widget(
                Directionality::new(
                    TextDirection::Ltr,
                    Center::new().child(RawMagnifier::new(Size::new(100.0, 80.0))),
                )
                .into_widget(),
            );
            let mut app = tester.cell.borrow_mut();
            let magnifier =
                render_box_where(&mut app, |widget| widget.as_any().is::<RawMagnifier>());
            assert_eq!(magnifier.size(&app), Size::new(100.0, 80.0));
            let lens = render_objects::<RenderMagnification>(&mut app);
            assert_eq!(lens.len(), 1);
            assert_eq!(lens[0].size(&app), Size::new(100.0, 80.0));
        });
    }

    #[test]
    fn a_raw_magnifier_does_not_crash_at_zero_area() {
        test_widgets(|tester| {
            tester.pump_widget(
                Directionality::new(
                    TextDirection::Ltr,
                    Center::new().child(
                        SizedBox::shrink()
                            .child(RawMagnifier::new(Size::square(2.0)).child(Text::new("X"))),
                    ),
                )
                .into_widget(),
            );
            let mut app = tester.cell.borrow_mut();
            let magnifier =
                render_box_where(&mut app, |widget| widget.as_any().is::<RawMagnifier>());
            assert_eq!(magnifier.size(&app), Size::ZERO);
        });
    }

    #[test]
    fn the_lens_takes_the_focal_point_and_the_magnification_scale_of_the_magnifier() {
        test_widgets(|tester| {
            let magnifier = |focal_point_offset: Offset, magnification_scale: f64| {
                Directionality::new(
                    TextDirection::Ltr,
                    Center::new().child(
                        RawMagnifier::new(Size::new(100.0, 100.0))
                            .focal_point_offset(focal_point_offset)
                            .magnification_scale(magnification_scale),
                    ),
                )
                .into_widget()
            };
            tester.pump_widget(magnifier(Offset::new(50.0, 50.0), 2.0));
            let mut app = tester.cell.borrow_mut();
            let lens = render_objects::<RenderMagnification>(&mut app)[0];
            assert_eq!(lens.focal_point_offset(&app), Offset::new(50.0, 50.0));
            assert_eq!(lens.magnification_scale(&app), 2.0);
            assert!(lens.as_object().needs_compositing(&app));

            drop(app);
            tester.pump_widget(magnifier(Offset::new(-20.0, 10.0), 3.0));
            let app = tester.cell.borrow();
            assert_eq!(lens.focal_point_offset(&app), Offset::new(-20.0, 10.0));
            assert_eq!(lens.magnification_scale(&app), 3.0);
        });
    }

    #[test]
    fn the_magnification_matrix_scales_the_focal_point_into_the_center_of_the_lens() {
        test_widgets(|tester| {
            // Dart's 'should render with correct focal point and decoration' setup: a lens of
            // 100 x 100 at (200, 200) that looks 50 right and 50 down, at twice the size.
            tester.pump_widget(
                Directionality::new(
                    TextDirection::Ltr,
                    Center::new().child(
                        RawMagnifier::new(Size::new(100.0, 100.0))
                            .focal_point_offset(Offset::new(50.0, 50.0))
                            .magnification_scale(2.0),
                    ),
                )
                .into_widget(),
            );
            let mut app = tester.cell.borrow_mut();
            let lens = render_objects::<RenderMagnification>(&mut app)[0];
            let matrix = lens.magnification_matrix(&app, Offset::new(200.0, 200.0));

            let center = waft_embedder::valo::Point::new(250.0, 250.0);
            let focal_point = waft_embedder::valo::Point::new(300.0, 300.0);
            assert_eq!(matrix.map_point(focal_point), center);
            let one_right_of_focal_point = waft_embedder::valo::Point::new(301.0, 300.0);
            assert_eq!(
                matrix.map_point(one_right_of_focal_point),
                waft_embedder::valo::Point::new(252.0, 250.0)
            );
            assert_eq!(
                matrix.to_flutter_array(),
                [
                    2.0, 0.0, 0.0, 0.0, //
                    0.0, 2.0, 0.0, 0.0, //
                    0.0, 0.0, 2.0, 0.0, //
                    -350.0, -350.0, 0.0, 1.0,
                ]
            );
        });
    }

    #[test]
    fn the_lens_filters_the_backdrop_through_its_magnification_matrix() {
        test_widgets(|tester| {
            tester.pump_widget(
                Directionality::new(
                    TextDirection::Ltr,
                    Center::new().child(
                        RawMagnifier::new(Size::new(100.0, 100.0))
                            .focal_point_offset(Offset::new(50.0, 50.0))
                            .magnification_scale(2.0),
                    ),
                )
                .into_widget(),
            );
            let mut app = tester.cell.borrow_mut();
            let lens = render_objects::<RenderMagnification>(&mut app)[0];
            // The lens paints at the origin of the opacity layer `RawMagnifier` fades it in, as
            // `PaintingContext.pushOpacity` paints its child at `Offset.zero`.
            let offset = Offset::ZERO;
            let layer = lens
                .as_object()
                .layer_as::<BackdropFilterLayer>(&app)
                .expect("the lens pushes a backdrop filter layer");
            assert_eq!(
                layer.filter(&app),
                Some(&ImageFilter::matrix(
                    lens.magnification_matrix(&app, offset),
                    FilterQuality::High
                ))
            );
        });
    }

    #[test]
    fn the_decoration_is_painted_over_the_lens_through_a_negative_clip() {
        test_widgets(|tester| {
            let shadow = BoxShadow::new(
                Color::new(0xFFFFFF00),
                Offset::new(5.0, 5.0),
                10.0,
                10.0,
                BlurStyle::Normal,
            );
            let shape = RoundedRectangleBorder::new(
                BorderSide::new(Color::new(0xFF000000), 2.0, BorderStyle::Solid, -1.0),
                BorderRadius::all(Radius::circular(10.0)).into(),
            );
            tester.pump_widget(
                Directionality::new(
                    TextDirection::Ltr,
                    Center::new().child(
                        RawMagnifier::new(Size::new(100.0, 100.0))
                            .clip_behavior(Clip::HardEdge)
                            .decoration(
                                MagnifierDecoration::new()
                                    .shadows(vec![shadow])
                                    .opacity(0.5)
                                    .shape(shape),
                            ),
                    ),
                )
                .into_widget(),
            );
            let mut app = tester.cell.borrow_mut();

            let opacities = render_objects::<RenderOpacity>(&mut app);
            assert_eq!(opacities.len(), 2, "the lens and the decoration both fade");
            assert!(opacities.iter().all(|opacity| opacity.opacity(&app) == 0.5));

            let decorated = render_objects::<RenderDecoratedBox>(&mut app);
            assert_eq!(decorated.len(), 1);
            let decoration = decorated[0]
                .decoration(&app)
                .as_any()
                .downcast_ref::<ShapeDecoration>()
                .expect("a ShapeDecoration");
            assert_eq!(decoration.shadows, Some(vec![shadow]));
            assert!(decoration.shape.eq_shape(&shape));
            assert_eq!(decorated[0].size(&app), Size::new(100.0, 100.0));

            let clips = render_objects::<RenderClipPath>(&mut app);
            assert_eq!(clips.len(), 2);
            let (lens_clip, decoration_clip) = (clips[0], clips[1]);
            assert_eq!(lens_clip.clip_behavior(&app), Clip::AntiAlias);
            assert_eq!(decoration_clip.clip_behavior(&app), Clip::HardEdge);
            let negative = decoration_clip
                .clipper(&app)
                .expect("the negative clip")
                .get_clip(&app, Size::new(100.0, 100.0));
            assert!(negative.contains(Offset::new(-50.0, -50.0)));
            assert!(negative.contains(Offset::new(150.0, 50.0)));
            assert!(!negative.contains(Offset::new(50.0, 50.0)));

            let stack = render_objects::<RenderStack>(&mut app);
            assert_eq!(stack[0].size(&app), Size::new(100.0, 100.0));
        });
    }

    #[test]
    fn the_negative_clip_cuts_out_the_inside_of_a_shape() {
        let cell = waft_foundation::AppCell::new();
        let app = cell.borrow();
        let size = Size::new(100.0, 60.0);
        for shape in [
            ShapeBorderRef::new(RoundedRectangleBorder::default()),
            ShapeBorderRef::new(RoundedRectangleBorder::new(
                BorderSide::NONE,
                BorderRadius::all(Radius::elliptical(60.0, 50.0)).into(),
            )),
            ShapeBorderRef::new(CircleBorder::default()),
        ] {
            let clip = NegativeClip::new(shape.clone()).get_clip(&app, size);
            assert_eq!(clip.fill_type, PathFillType::EvenOdd);
            let hole = shape.get_inner_path(Offset::ZERO & size, None);
            for (x, y) in [(50.0, 30.0), (40.0, 25.0), (60.0, 35.0)] {
                let point = Offset::new(x, y);
                assert_eq!(
                    clip.contains(point),
                    !hole.contains(point),
                    "{shape:?} at {point:?}"
                );
            }
            for (x, y) in [(-1.0e6, -1.0e6), (1.0e6, 30.0), (50.0, 61.0)] {
                let point = Offset::new(x, y);
                assert!(clip.contains(point), "{shape:?} at {point:?}");
            }
        }
    }

    #[test]
    fn the_negative_clip_reclips_only_for_another_shape() {
        let cell = waft_foundation::AppCell::new();
        let app = cell.borrow();
        let square = NegativeClip::new(ShapeBorderRef::new(RoundedRectangleBorder::default()));
        let same = NegativeClip::new(ShapeBorderRef::new(RoundedRectangleBorder::default()));
        let round = NegativeClip::new(ShapeBorderRef::new(CircleBorder::default()));
        assert!(!same.should_reclip(&app, &square));
        assert!(round.should_reclip(&app, &square));
    }

    #[test]
    fn magnifier_decorations_with_the_same_fields_are_equal() {
        assert_eq!(MagnifierDecoration::new(), MagnifierDecoration::default());
        assert_eq!(MagnifierDecoration::new().opacity, 1.0);
        assert_eq!(MagnifierDecoration::new().shadows, None);
        assert_ne!(
            MagnifierDecoration::new(),
            MagnifierDecoration::new().opacity(0.5)
        );
        assert_ne!(
            MagnifierDecoration::new(),
            MagnifierDecoration::new().shape(CircleBorder::default())
        );
        assert_ne!(
            MagnifierDecoration::new(),
            MagnifierDecoration::new().shadows(Vec::new())
        );
    }

    #[test]
    fn should_immediately_remove_from_overlay_on_no_animation_controller() {
        test_widgets(|tester| {
            let home = GlobalKey::new();
            app_with_overlay(tester, home.clone());
            let mut app = tester.cell.borrow_mut();
            let context = home.current_context(&app).expect("mounted");
            let magnifier_controller = MagnifierController::new(&mut app);

            magnifier_controller.show(
                &mut app,
                context,
                raw_magnifier_builder(UniqueKey::new().into()),
                None,
            );
            drop(app);
            schedule_frame_and_pump(tester);
            let mut app = tester.cell.borrow_mut();
            assert!(magnifier_controller.overlay_entry(&app).is_some());

            magnifier_controller.hide(&mut app, true);
            drop(app);
            schedule_frame_and_pump(tester);
            let app = tester.cell.borrow();
            assert!(magnifier_controller.overlay_entry(&app).is_none());
        });
    }

    #[test]
    fn should_update_shown_based_on_animation_status() {
        test_widgets(|tester| {
            let home = GlobalKey::new();
            app_with_overlay(tester, home.clone());
            let mut app = tester.cell.borrow_mut();
            let context = home.current_context(&app).expect("mounted");
            let duration = Duration::from_secs(120);
            let animation_controller = AnimationController::new(
                &mut app,
                None,
                Some(duration),
                None,
                0.0,
                1.0,
                AnimationBehavior::Normal,
                TestVSync,
            );
            let magnifier_controller = MagnifierController::new(&mut app)
                .animation_controller(&mut app, animation_controller.clone());

            magnifier_controller.show(
                &mut app,
                context,
                raw_magnifier_builder(UniqueKey::new().into()),
                None,
            );
            drop(app);
            schedule_frame_and_pump(tester);
            let app = tester.cell.borrow();

            // No time has passed, so the animation controller has not completed.
            assert_eq!(animation_controller.status(&app), AnimationStatus::Forward);
            assert!(magnifier_controller.shown(&app));

            // Dart's `async.elapse(duration)` moves the case's own `FakeAsync`, which no frame
            // reads; the frames `pumpAndSettle` runs drive the controller.
            drop(app);
            tester.pump_and_settle();
            let mut app = tester.cell.borrow_mut();
            assert_eq!(
                animation_controller.status(&app),
                AnimationStatus::Completed
            );
            assert!(magnifier_controller.shown(&app));

            magnifier_controller.hide(&mut app, true);
            drop(app);
            schedule_frame_and_pump(tester);
            let app = tester.cell.borrow();
            assert_eq!(animation_controller.status(&app), AnimationStatus::Reverse);
            assert!(!magnifier_controller.shown(&app));

            drop(app);
            tester.pump_and_settle();
            let app = tester.cell.borrow();
            assert_eq!(
                animation_controller.status(&app),
                AnimationStatus::Dismissed
            );
            assert!(!magnifier_controller.shown(&app));
        });
    }

    #[test]
    fn should_insert_below_below_widget() {
        test_widgets(|tester| {
            let home = GlobalKey::new();
            app_with_overlay(tester, home.clone());
            let mut app = tester.cell.borrow_mut();
            let context = home.current_context(&app).expect("mounted");
            let magnifier_controller = MagnifierController::new(&mut app);
            let fake_magnifier: KeyRef = UniqueKey::new().into();
            let fake_before: KeyRef = UniqueKey::new().into();

            let before_key = fake_before.clone();
            let fake_before_overlay_entry = OverlayEntry::new(
                &mut app,
                Rc::new(move |_app: &mut App, _context: BuildContext| {
                    SizedBox::new().key(before_key.clone()).into_widget()
                }),
                false,
                false,
                false,
            );
            Overlay::of(&mut app, context, false).insert(
                &mut app,
                fake_before_overlay_entry.clone(),
                None,
                None,
            );
            let magnifier_key = fake_magnifier.clone();
            magnifier_controller.show(
                &mut app,
                context,
                Rc::new(move |_app: &mut App, _context: BuildContext| {
                    SizedBox::new().key(magnifier_key.clone()).into_widget()
                }),
                Some(fake_before_overlay_entry.handle()),
            );
            SchedulerBinding::schedule_frame(&mut app, FrameTarget::EveryView);
            drop(app);
            tester.pump_and_settle();
            let mut app = tester.cell.borrow_mut();

            let keyed: Vec<KeyRef> = elements(&mut app)
                .into_iter()
                .filter_map(|element| element.widget(&app).key().cloned())
                .filter(|key| key == &fake_magnifier || key == &fake_before)
                .collect();
            // Expect the magnifier to be the first child, even though it was inserted
            // after the fakeBefore.
            assert_eq!(keyed, vec![fake_magnifier, fake_before]);

            magnifier_controller.remove_from_overlay(&mut app);
            fake_before_overlay_entry.remove(&mut app);
            fake_before_overlay_entry.dispose(&mut app);
        });
    }

    #[test]
    fn should_insert_newly_built_widget_without_animating_out_if_overlay_is_not_none() {
        test_widgets(|tester| {
            let home = GlobalKey::new();
            app_with_overlay(tester, home.clone());
            let mut app = tester.cell.borrow_mut();
            let context = home.current_context(&app).expect("mounted");
            let magnifier_controller = MagnifierController::new(&mut app);
            let first: KeyRef = UniqueKey::new().into();
            let second: KeyRef = UniqueKey::new().into();

            magnifier_controller.show(
                &mut app,
                context,
                raw_magnifier_builder(first.clone()),
                None,
            );
            drop(app);
            schedule_frame_and_pump(tester);
            let app = tester.cell.borrow();
            drop(app);
            tester.pump_and_settle();
            let mut app = tester.cell.borrow_mut();

            magnifier_controller.show(
                &mut app,
                context,
                raw_magnifier_builder(second.clone()),
                None,
            );
            drop(app);
            schedule_frame_and_pump(tester);
            let mut app = tester.cell.borrow_mut();

            let count = |app: &mut App, key: &KeyRef| {
                elements(app)
                    .into_iter()
                    .filter(|element| has_key(element.widget(app), key))
                    .count()
            };
            assert_eq!(count(&mut app, &second), 1);
            assert_eq!(count(&mut app, &first), 0);
            magnifier_controller.remove_from_overlay(&mut app);
        });
    }

    #[test]
    fn shift_within_bounds_moves_a_rect_the_shortest_way_into_the_bounds() {
        let bounds = Rect::from_ltrb(0.0, 0.0, 100.0, 100.0);
        for (input, output) in [
            (
                Rect::from_ltrb(-100.0, -100.0, -80.0, -80.0),
                Rect::from_ltrb(0.0, 0.0, 20.0, 20.0),
            ),
            (
                Rect::from_ltrb(0.0, 0.0, 20.0, 20.0),
                Rect::from_ltrb(0.0, 0.0, 20.0, 20.0),
            ),
            (
                Rect::from_ltrb(110.0, 0.0, 120.0, 10.0),
                Rect::from_ltrb(90.0, 0.0, 100.0, 10.0),
            ),
            (
                Rect::from_ltrb(110.0, 110.0, 120.0, 120.0),
                Rect::from_ltrb(90.0, 90.0, 100.0, 100.0),
            ),
        ] {
            assert_eq!(
                MagnifierController::shift_within_bounds(input, bounds),
                output,
                "should shift {input:?} to {output:?} for bounds {bounds:?}"
            );
        }
    }

    #[test]
    fn raw_magnifier_sits_where_it_is_positioned() {
        test_widgets(|tester| {
            let key: KeyRef = UniqueKey::new().into();
            tester.pump_widget(
                Directionality::new(
                    TextDirection::Ltr,
                    Stack::new().children([Positioned::new(
                        RawMagnifier::new(Size::new(40.0, 40.0)).key(key.clone()),
                    )
                    .left(20.0)
                    .top(30.0)
                    .into_widget()]),
                )
                .into_widget(),
            );
            let mut app = tester.cell.borrow_mut();
            let magnifier = render_box_where(&mut app, |widget| has_key(widget, &key));
            assert_eq!(
                magnifier.local_to_global(&app, Offset::ZERO, None),
                Offset::new(20.0, 30.0)
            );
        });
    }
}