waft-material 0.11.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
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
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
//! Port of material_ui's `page_transitions_theme.dart`.
//!
//! Flutter rasterises the entering and exiting pages of the zoom and fade-forwards transitions
//! through `SnapshotWidget`; Waft's `SnapshotWidget` paints the child live (`OffsetLayer`
//! `.toImageSync` is deferred), so the zoom painters' `paint` is what draws, and their
//! `paint_snapshot` waits for the raster.

use std::fmt::{self, Debug};
use std::rc::Rc;
use std::time::Duration;
use waft_animation::{
    Animatable, AnimationRef, AnimationStatus, AnimationStatusListener, Cubic, Curve, Curves,
    Interval, ReverseAnimation, TweenSequence, TweenSequenceItem, ValueCurveTween, ValueTween,
    k_always_complete_animation,
};

use indexmap::IndexMap;
use waft_cupertino::CupertinoPageTransitionsBuilder;
use waft_embedder::valo::Sampling;
use waft_embedder::{Color, Image, Matrix4, Offset, Paint, Rect, Size, TargetPlatform};
use waft_foundation::{
    App, ChangeNotifier, ChangeNotifierData, DiagnosticPropertiesBuilder, Diagnosticable,
    DiagnosticsProperty, Handle, K_IS_WEB, Listener, OptionRetained, Ref,
};
use waft_painting::ClipContext;
use waft_rendering::{LayerHandle, OpacityLayer, PaintingContext, TransformLayer};
use waft_widgets::{
    AnyModalRoute, AnyPageRoute, AnySnapshotPainter, BuildContext, ColoredBox,
    DelegatedTransitionBuilder, DualTransitionBuilder, FadeTransition, IgnorePointer, IntoWidget,
    PageTransitionsBuilder, PageTransitionsBuilderRef, SlideTransition, SnapshotController,
    SnapshotMode, SnapshotPainter, SnapshotWidget, State, StateData, StatefulWidget,
    StatelessWidget, WidgetRef,
};

use crate::color_scheme::ColorScheme;
use crate::colors::Colors;
use crate::predictive_back_page_transitions_builder::PredictiveBackPageTransitionsBuilder;
use crate::theme::Theme;

// Zooms and fades a new page in, zooming out the previous page. This transition is designed to
// match the Android Q activity transition.
#[derive(Debug)]
pub(crate) struct ZoomPageTransition {
    /// The animation that drives the `child`'s entrance and exit.
    animation: AnimationRef<f64>,

    /// The animation that transitions `child` when new content is pushed on top of it.
    secondary_animation: AnimationRef<f64>,

    /// Whether the [`SnapshotWidget`] will be used.
    ///
    /// When this value is true, performance is improved by disabling animations on both the
    /// outgoing and incoming route. This also implies that ink-splashes or similar animations
    /// will not animate during the transition.
    allow_snapshotting: bool,

    /// The color of the scrim (background) that fades in and out during the transition.
    ///
    /// If not provided, defaults to current theme's `ColorScheme::surface` color.
    background_color: Option<Color>,

    /// The widget below this widget in the tree.
    child: Option<WidgetRef>,

    /// Whether to enable snapshotting on the entering route during the transition animation.
    ///
    /// If false, the route snapshotting will not be applied to the route being animating into,
    /// e.g. when transitioning from route A to route B, B will not be snapshotted.
    allow_enter_route_snapshotting: bool,
}

impl ZoomPageTransition {
    // A curve sequence that is similar to the 'fastOutExtraSlowIn' curve used in the native
    // transition.
    fn fast_out_extra_slow_in_tween_sequence_items() -> Vec<TweenSequenceItem<f64>> {
        vec![
            TweenSequenceItem::new(
                Rc::new(
                    ValueTween::new(0.0, 0.4).chain(ValueCurveTween::new(Rc::new(Cubic::new(
                        0.05, 0.0, 0.133333, 0.06,
                    )))),
                ),
                0.166666,
            ),
            TweenSequenceItem::new(
                Rc::new(
                    ValueTween::new(0.4, 1.0).chain(ValueCurveTween::new(Rc::new(Cubic::new(
                        0.208333, 0.82, 0.25, 1.0,
                    )))),
                ),
                1.0 - 0.166666,
            ),
        ]
    }

    fn scale_curve_sequence() -> TweenSequence<f64> {
        TweenSequence::new(ZoomPageTransition::fast_out_extra_slow_in_tween_sequence_items())
    }
}

impl StatelessWidget for ZoomPageTransition {
    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
        let enter_transition_background_color = self
            .background_color
            .unwrap_or_else(|| Theme::of(app, context).color_scheme.surface());
        let allow_snapshotting = self.allow_snapshotting;
        let allow_enter_route_snapshotting = self.allow_enter_route_snapshotting;
        let mut transition = DualTransitionBuilder::new(
            self.animation.clone(),
            move |_app, _context, animation, child| {
                ZoomEnterTransition {
                    animation,
                    reverse: false,
                    allow_snapshotting: allow_snapshotting && allow_enter_route_snapshotting,
                    background_color: enter_transition_background_color,
                    child: child.cloned(),
                }
                .into_widget()
            },
            move |_app, _context, animation, child| {
                ZoomExitTransition {
                    animation,
                    allow_snapshotting,
                    reverse: true,
                    child: child.cloned(),
                }
                .into_widget()
            },
        );
        transition.child = Some(
            ZoomPageTransitionsBuilder::snapshot_aware_delegated_transition(
                app,
                context,
                self.animation.clone(),
                self.secondary_animation.clone(),
                self.child.clone(),
                allow_snapshotting,
                allow_enter_route_snapshotting,
                Some(enter_transition_background_color),
            ),
        );
        transition.into_widget()
    }
}

#[derive(Debug)]
pub(crate) struct ZoomEnterTransition {
    pub(crate) animation: AnimationRef<f64>,
    child: Option<WidgetRef>,
    allow_snapshotting: bool,
    pub(crate) reverse: bool,
    background_color: Color,
}

impl StatefulWidget for ZoomEnterTransition {
    type State = ZoomEnterTransitionState;

    fn create_state(&self) -> ZoomEnterTransitionState {
        ZoomEnterTransitionState {
            state: StateData::new(),
            zoom_transition_base: ZoomTransitionBaseData::new(),
            delegate: None,
        }
    }
}

/// Dart's `_ZoomEnterTransitionState`.
pub(crate) struct ZoomEnterTransitionState {
    state: StateData<ZoomEnterTransition>,
    zoom_transition_base: ZoomTransitionBaseData,
    delegate: Option<Ref<ZoomEnterTransitionPainter>>,
}

impl ZoomEnterTransitionState {
    fn fade_in_transition() -> impl Animatable<f64> + Clone + 'static {
        ValueTween::new(0.0, 1.00).chain(ValueCurveTween::new(Rc::new(Interval::new(
            0.125,
            0.250,
            Curves::linear(),
        ))))
    }

    fn scale_down_transition() -> impl Animatable<f64> + Clone + 'static {
        ValueTween::new(1.10, 1.00).chain(ZoomPageTransition::scale_curve_sequence())
    }

    fn scale_up_transition() -> impl Animatable<f64> + Clone + 'static {
        ValueTween::new(0.85, 1.00).chain(ZoomPageTransition::scale_curve_sequence())
    }

    fn scrim_opacity_tween() -> impl Animatable<f64> + Clone + 'static {
        ValueTween::new(0.0, 0.60).chain(ValueCurveTween::new(Rc::new(Interval::new(
            0.2075,
            0.4175,
            Curves::linear(),
        ))))
    }

    fn update_animations(self: Handle<Self>, app: &mut App) {
        let widget = self.widget(app);
        let (reverse, animation) = (widget.reverse, widget.animation.clone());
        let fade_transition = if reverse {
            k_always_complete_animation(app)
        } else {
            ZoomEnterTransitionState::fade_in_transition().animate(app, animation.clone())
        };
        let scale_transition = if reverse {
            ZoomEnterTransitionState::scale_down_transition().animate(app, animation.clone())
        } else {
            ZoomEnterTransitionState::scale_up_transition().animate(app, animation.clone())
        };
        let base = self.zoom_transition_base_data_mut(app);
        base.fade_transition = Some(fade_transition);
        base.scale_transition = Some(scale_transition);

        animation.add_listener(
            app,
            Listener::handle_method(self, Self::on_animation_value_change),
        );
        animation.add_status_listener(
            app,
            AnimationStatusListener::handle_method(self, Self::on_animation_status_change),
        );
    }

    fn new_delegate(self: Handle<Self>, app: &mut App) -> Ref<ZoomEnterTransitionPainter> {
        let widget = self.widget(app);
        let (reverse, animation, background_color) = (
            widget.reverse,
            widget.animation.clone(),
            widget.background_color,
        );
        let fade = self.fade_transition(app);
        let scale = self.scale_transition(app);
        ZoomEnterTransitionPainter::new(app, reverse, scale, fade, animation, background_color)
    }

    fn delegate(self: Handle<Self>, app: &App) -> Ref<ZoomEnterTransitionPainter> {
        app.get(self)
            .delegate
            .clone()
            .expect("created in init_state")
    }

    /// Dart's `delegate.dispose()`.
    fn dispose_delegate(self: Handle<Self>, app: &mut App) {
        let delegate = self.delegate(app);
        delegate.dispose(app);
    }
}

impl ZoomTransitionBase for ZoomEnterTransitionState {
    fn zoom_transition_base_data(self: Handle<Self>, app: &App) -> &ZoomTransitionBaseData {
        &app.get(self).zoom_transition_base
    }

    fn zoom_transition_base_data_mut(
        self: Handle<Self>,
        app: &mut App,
    ) -> &mut ZoomTransitionBaseData {
        &mut app.get_mut(self).zoom_transition_base
    }

    // See SnapshotWidget doc comment, this is disabled on web because the canvaskit backend uses
    // a single thread for UI and raster work which diminishes the impact of this performance
    // improvement.
    fn use_snapshot(self: Handle<Self>, app: &App) -> bool {
        !K_IS_WEB && self.widget(app).allow_snapshotting
    }
}

impl State for ZoomEnterTransitionState {
    type Widget = ZoomEnterTransition;
    waft_widgets::state_accessors!();

    fn init_state(self: Handle<Self>, app: &mut App) {
        self.init_zoom_transition_base(app);
        self.update_animations(app);
        let delegate = self.new_delegate(app);
        app.get_mut(self).delegate = Some(delegate);
    }

    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &ZoomEnterTransition) {
        let widget = self.widget(app);
        if old_widget.reverse != widget.reverse || old_widget.animation != widget.animation {
            old_widget.animation.remove_listener(
                app,
                &Listener::handle_method(self, Self::on_animation_value_change),
            );
            old_widget.animation.remove_status_listener(
                app,
                &AnimationStatusListener::handle_method(self, Self::on_animation_status_change),
            );
            self.update_animations(app);
            self.dispose_delegate(app);
            let delegate = self.new_delegate(app);
            app.get_mut(self).delegate = Some(delegate);
        }
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        let animation = self.widget(app).animation.clone();
        animation.remove_listener(
            app,
            &Listener::handle_method(self, Self::on_animation_value_change),
        );
        animation.remove_status_listener(
            app,
            &AnimationStatusListener::handle_method(self, Self::on_animation_status_change),
        );
        self.dispose_delegate(app);
        ZoomTransitionBase::dispose(self, app);
    }

    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
        SnapshotWidget::new(self.controller(app), self.widget(app).child.clone())
            .painter(self.delegate(app).into_erased::<AnySnapshotPainter>())
            .mode(SnapshotMode::Permissive)
            .autoresize(true)
            .into_widget()
    }
}

#[derive(Debug)]
struct ZoomExitTransition {
    animation: AnimationRef<f64>,
    allow_snapshotting: bool,
    reverse: bool,
    child: Option<WidgetRef>,
}

impl StatefulWidget for ZoomExitTransition {
    type State = ZoomExitTransitionState;

    fn create_state(&self) -> ZoomExitTransitionState {
        ZoomExitTransitionState {
            state: StateData::new(),
            zoom_transition_base: ZoomTransitionBaseData::new(),
            delegate: None,
        }
    }
}

/// Dart's `_ZoomExitTransitionState`.
struct ZoomExitTransitionState {
    state: StateData<ZoomExitTransition>,
    zoom_transition_base: ZoomTransitionBaseData,
    delegate: Option<Ref<ZoomExitTransitionPainter>>,
}

impl ZoomExitTransitionState {
    fn fade_out_transition() -> impl Animatable<f64> + Clone + 'static {
        ValueTween::new(1.0, 0.0).chain(ValueCurveTween::new(Rc::new(Interval::new(
            0.0825,
            0.2075,
            Curves::linear(),
        ))))
    }

    fn scale_up_transition() -> impl Animatable<f64> + Clone + 'static {
        ValueTween::new(1.00, 1.05).chain(ZoomPageTransition::scale_curve_sequence())
    }

    fn scale_down_transition() -> impl Animatable<f64> + Clone + 'static {
        ValueTween::new(1.00, 0.90).chain(ZoomPageTransition::scale_curve_sequence())
    }

    fn update_animations(self: Handle<Self>, app: &mut App) {
        let widget = self.widget(app);
        let (reverse, animation) = (widget.reverse, widget.animation.clone());
        let fade_transition = if reverse {
            ZoomExitTransitionState::fade_out_transition().animate(app, animation.clone())
        } else {
            k_always_complete_animation(app)
        };
        let scale_transition = if reverse {
            ZoomExitTransitionState::scale_down_transition().animate(app, animation.clone())
        } else {
            ZoomExitTransitionState::scale_up_transition().animate(app, animation.clone())
        };
        let base = self.zoom_transition_base_data_mut(app);
        base.fade_transition = Some(fade_transition);
        base.scale_transition = Some(scale_transition);

        animation.add_listener(
            app,
            Listener::handle_method(self, Self::on_animation_value_change),
        );
        animation.add_status_listener(
            app,
            AnimationStatusListener::handle_method(self, Self::on_animation_status_change),
        );
    }

    fn new_delegate(self: Handle<Self>, app: &mut App) -> Ref<ZoomExitTransitionPainter> {
        let widget = self.widget(app);
        let (reverse, animation) = (widget.reverse, widget.animation.clone());
        let fade = self.fade_transition(app);
        let scale = self.scale_transition(app);
        ZoomExitTransitionPainter::new(app, reverse, scale, fade, animation)
    }

    fn delegate(self: Handle<Self>, app: &App) -> Ref<ZoomExitTransitionPainter> {
        app.get(self)
            .delegate
            .clone()
            .expect("created in init_state")
    }

    /// See [`ZoomEnterTransitionState::dispose_delegate`].
    fn dispose_delegate(self: Handle<Self>, app: &mut App) {
        let delegate = self.delegate(app);
        delegate.dispose(app);
    }
}

impl ZoomTransitionBase for ZoomExitTransitionState {
    fn zoom_transition_base_data(self: Handle<Self>, app: &App) -> &ZoomTransitionBaseData {
        &app.get(self).zoom_transition_base
    }

    fn zoom_transition_base_data_mut(
        self: Handle<Self>,
        app: &mut App,
    ) -> &mut ZoomTransitionBaseData {
        &mut app.get_mut(self).zoom_transition_base
    }

    // See SnapshotWidget doc comment, this is disabled on web because the canvaskit backend uses
    // a single thread for UI and raster work which diminishes the impact of this performance
    // improvement.
    fn use_snapshot(self: Handle<Self>, app: &App) -> bool {
        !K_IS_WEB && self.widget(app).allow_snapshotting
    }
}

impl State for ZoomExitTransitionState {
    type Widget = ZoomExitTransition;
    waft_widgets::state_accessors!();

    fn init_state(self: Handle<Self>, app: &mut App) {
        self.init_zoom_transition_base(app);
        self.update_animations(app);
        let delegate = self.new_delegate(app);
        app.get_mut(self).delegate = Some(delegate);
    }

    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &ZoomExitTransition) {
        let widget = self.widget(app);
        if old_widget.reverse != widget.reverse || old_widget.animation != widget.animation {
            old_widget.animation.remove_listener(
                app,
                &Listener::handle_method(self, Self::on_animation_value_change),
            );
            old_widget.animation.remove_status_listener(
                app,
                &AnimationStatusListener::handle_method(self, Self::on_animation_status_change),
            );
            self.update_animations(app);
            self.dispose_delegate(app);
            let delegate = self.new_delegate(app);
            app.get_mut(self).delegate = Some(delegate);
        }
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        let animation = self.widget(app).animation.clone();
        animation.remove_listener(
            app,
            &Listener::handle_method(self, Self::on_animation_value_change),
        );
        animation.remove_status_listener(
            app,
            &AnimationStatusListener::handle_method(self, Self::on_animation_status_change),
        );
        self.dispose_delegate(app);
        ZoomTransitionBase::dispose(self, app);
    }

    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
        SnapshotWidget::new(self.controller(app), self.widget(app).child.clone())
            .painter(self.delegate(app).into_erased::<AnySnapshotPainter>())
            .mode(SnapshotMode::Permissive)
            .autoresize(true)
            .into_widget()
    }
}

// This transition slides a new page in from right to left while fading it in, and simultaneously
// slides the previous page out to the left while fading it out. This transition is designed to
// match the Android U activity transition.
#[derive(Debug)]
pub(crate) struct FadeForwardsPageTransition {
    animation: AnimationRef<f64>,

    secondary_animation: AnimationRef<f64>,

    /// Whether the [`SnapshotWidget`] will be used.
    ///
    /// When this value is true, performance is improved by disabling animations on both the
    /// outgoing and incoming route. This also implies that ink-splashes or similar animations
    /// will not animate during the transition.
    allow_snapshotting: bool,

    background_color: Option<Color>,

    child: Option<WidgetRef>,
}

impl FadeForwardsPageTransition {
    // The new page slides in from right to left.
    fn forward_translation_tween() -> impl Animatable<Offset> + Clone + 'static {
        ValueTween::new(Offset::new(0.25, 0.0), Offset::ZERO).chain(ValueCurveTween::new(
            FadeForwardsPageTransitionsBuilder::transition_curve(),
        ))
    }

    // The old page slides back from left to right.
    fn backward_translation_tween() -> impl Animatable<Offset> + Clone + 'static {
        ValueTween::new(Offset::ZERO, Offset::new(0.25, 0.0)).chain(ValueCurveTween::new(
            FadeForwardsPageTransitionsBuilder::transition_curve(),
        ))
    }
}

impl StatelessWidget for FadeForwardsPageTransition {
    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
        let allow_snapshotting = self.allow_snapshotting;
        let mut transition = DualTransitionBuilder::new(
            self.animation.clone(),
            move |app, _context, animation, child| {
                let opacity = FadeForwardsPageTransitionsBuilder::fade_in_transition()
                    .animate(app, animation.clone());
                let position = FadeForwardsPageTransition::forward_translation_tween()
                    .animate(app, animation.clone());

                (FadeTransition::new(opacity)
                    .child(SlideTransition::new(position).child(FadeForwardsSnapshot {
                        animation,
                        allow_snapshotting,
                        child: child.cloned(),
                    }))
                    .into_widget()) as _
            },
            move |app, _context, animation, child| {
                let opacity = FadeForwardsPageTransitionsBuilder::fade_out_transition()
                    .animate(app, animation.clone());
                let position = FadeForwardsPageTransition::backward_translation_tween()
                    .animate(app, animation.clone());

                (IgnorePointer::new()
                    .ignoring(animation.status(app) == AnimationStatus::Forward)
                    .child(FadeTransition::new(opacity).child(
                        SlideTransition::new(position).child(FadeForwardsSnapshot {
                            animation,
                            allow_snapshotting,
                            child: child.cloned(),
                        }),
                    ))
                    .into_widget()) as _
            },
        );
        transition.child = Some(
            FadeForwardsPageTransitionsBuilder::snapshot_aware_delegated_transition(
                app,
                context,
                self.secondary_animation.clone(),
                self.background_color,
                allow_snapshotting,
                self.child.clone(),
            ),
        );
        transition.into_widget()
    }
}

// Paints a snapshot of its child instead of the live child while `animation` is running, for
// performance purposes.
//
// The child is rasterized once at the start of the animation. On each following frame, the
// enclosing FadeTransition and SlideTransition only have to composite a single image, and
// because a single image draw can absorb the opacity of the parent OpacityLayer, the engine can
// skip the offscreen saveLayer that a partially transparent live page would otherwise require.
//
// This means that animations inside of the child (e.g. ink splashes or progress indicators) are
// frozen for the duration of the transition, which is the same tradeoff made by
// [`ZoomPageTransitionsBuilder`]. If the child contains a platform view, the live child is
// painted instead (see [`SnapshotMode::Permissive`]).
#[derive(Debug)]
pub(crate) struct FadeForwardsSnapshot {
    animation: AnimationRef<f64>,

    allow_snapshotting: bool,

    child: Option<WidgetRef>,
}

impl StatefulWidget for FadeForwardsSnapshot {
    type State = FadeForwardsSnapshotState;

    fn create_state(&self) -> FadeForwardsSnapshotState {
        FadeForwardsSnapshotState {
            state: StateData::new(),
            controller: None,
        }
    }
}

/// Dart's `_FadeForwardsSnapshotState`. The controller is Dart's field initialiser; it needs the
/// `App`, so `init_state` makes it before anything reads it.
pub(crate) struct FadeForwardsSnapshotState {
    state: StateData<FadeForwardsSnapshot>,
    controller: Option<Ref<SnapshotController>>,
}

impl FadeForwardsSnapshotState {
    /// Dart's `_controller`.
    pub(crate) fn controller(self: Handle<Self>, app: &App) -> Handle<SnapshotController> {
        app.get(self)
            .controller
            .handle()
            .expect("created in init_state")
    }

    // See SnapshotWidget doc comment, this is disabled on web because the canvaskit backend uses
    // a single thread for UI and raster work which diminishes the impact of this performance
    // improvement.
    fn use_snapshot(self: Handle<Self>, app: &App) -> bool {
        !K_IS_WEB && self.widget(app).allow_snapshotting
    }

    // Listen to value changes as well as status changes. DualTransitionBuilder may replace its
    // proxy animation's parent without a status notification, so a status listener alone can
    // miss the start of an animation.
    fn add_listeners(self: Handle<Self>, app: &mut App, animation: AnimationRef<f64>) {
        animation.add_listener(
            app,
            Listener::handle_method(self, Self::update_snapshotting),
        );
        animation.add_status_listener(
            app,
            AnimationStatusListener::handle_method(self, Self::handle_status_change),
        );
    }

    fn remove_listeners(self: Handle<Self>, app: &mut App, animation: AnimationRef<f64>) {
        animation.remove_listener(
            app,
            &Listener::handle_method(self, Self::update_snapshotting),
        );
        animation.remove_status_listener(
            app,
            &AnimationStatusListener::handle_method(self, Self::handle_status_change),
        );
    }

    fn handle_status_change(self: Handle<Self>, app: &mut App, _status: AnimationStatus) {
        self.update_snapshotting(app);
    }

    fn update_snapshotting(self: Handle<Self>, app: &mut App) {
        let allow_snapshotting =
            self.use_snapshot(app) && self.widget(app).animation.is_animating(app);
        self.controller(app)
            .set_allow_snapshotting(app, allow_snapshotting);
    }
}

impl State for FadeForwardsSnapshotState {
    type Widget = FadeForwardsSnapshot;
    waft_widgets::state_accessors!();

    fn init_state(self: Handle<Self>, app: &mut App) {
        let controller = SnapshotController::new(app, false);
        app.get_mut(self).controller = Some(controller);
        let animation = self.widget(app).animation.clone();
        self.add_listeners(app, animation);
        self.update_snapshotting(app);
    }

    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &FadeForwardsSnapshot) {
        let animation = self.widget(app).animation.clone();
        if old_widget.animation != animation {
            self.remove_listeners(app, old_widget.animation.clone());
            self.add_listeners(app, animation);
        }
        self.update_snapshotting(app);
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        let animation = self.widget(app).animation.clone();
        self.remove_listeners(app, animation);
        self.controller(app).dispose(app);
    }

    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
        let controller = app
            .get(self)
            .controller
            .clone()
            .expect("created in init_state");
        SnapshotWidget::new(controller, self.widget(app).child.clone())
            .mode(SnapshotMode::Permissive)
            .autoresize(true)
            .into_widget()
    }
}

/// Used by [`PageTransitionsTheme`] to define a horizontal `MaterialPageRoute` page transition
/// animation that looks like the default page transition used on Android U.
///
/// Use `allow_snapshotting` to enable snapshotting via [`SnapshotWidget`] for all routes. When
/// enabled, the child will be rasterized once at the start of the animation so that the
/// transitions only have to composite a single image. This often improves performance at the
/// expense of freezing any animations that exist within the child for the duration of the
/// animation. If the child contains a platform view, the live child is painted instead (see
/// [`SnapshotMode::Permissive`]).
///
/// See also:
///
///  * `FadeUpwardsPageTransitionsBuilder`, which defines a page transition that's similar to
///    the one provided by Android O.
///  * `OpenUpwardsPageTransitionsBuilder`, which defines a page transition that's similar to
///    the one provided by Android P.
///  * [`ZoomPageTransitionsBuilder`], which defines the default page transition that's similar
///    to the one provided in Android Q.
///  * [`CupertinoPageTransitionsBuilder`], which defines a horizontal page transition that
///    matches native iOS page transitions.
///  * [`PredictiveBackPageTransitionsBuilder`], which defines a page transition that allows
///    peeking behind the current route on Android.
///  * `PageRoute::allow_snapshotting`, which enables or disables snapshotting on a per route
///    basis similar to the `allow_snapshotting` parameter.
///  * [`ZoomPageTransitionsBuilder::allow_snapshotting`], which is similar to the
///    `allow_snapshotting` parameter.
#[derive(Clone, Copy, Debug)]
pub struct FadeForwardsPageTransitionsBuilder {
    /// Whether FadeForwards page transitions will prefer to animate a snapshot of the entering
    /// and exiting routes.
    ///
    /// If not specified, defaults to true.
    ///
    /// When this value is true, FadeForwards page transitions will snapshot the entering and
    /// exiting routes. These snapshots are then animated in place of the underlying widgets to
    /// improve performance of the transition.
    ///
    /// Generally this means that animations that occur on the entering/exiting route while the
    /// route animation plays may appear frozen - unless they are a hero animation or something
    /// that is drawn in a separate overlay.
    pub allow_snapshotting: bool,

    /// The background color during transition between two routes.
    ///
    /// When a new page fades in and the old page fades out, this background color helps avoid a
    /// black background between two page.
    ///
    /// Defaults to `ColorScheme::surface`.
    pub background_color: Option<Color>,
}

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

impl FadeForwardsPageTransitionsBuilder {
    /// Constructs a page transition animation that matches the transition used on Android U.
    pub const fn new() -> FadeForwardsPageTransitionsBuilder {
        FadeForwardsPageTransitionsBuilder {
            allow_snapshotting: true,
            background_color: None,
        }
    }

    /// Dart `FadeForwardsPageTransitionsBuilder(allowSnapshotting:)`.
    pub const fn allow_snapshotting(
        mut self,
        allow_snapshotting: bool,
    ) -> FadeForwardsPageTransitionsBuilder {
        self.allow_snapshotting = allow_snapshotting;
        self
    }

    /// Dart `FadeForwardsPageTransitionsBuilder(backgroundColor:)`.
    pub const fn background_color(
        mut self,
        background_color: Color,
    ) -> FadeForwardsPageTransitionsBuilder {
        self.background_color = Some(background_color);
        self
    }

    /// The value of `transition_duration` in milliseconds.
    ///
    /// Eyeballed on a physical Pixel 9 running Android 16. This does not match the actual value
    /// used by native Android, which is 800ms, because native Android is using Material 3
    /// Expressive springs that are not currently supported by Flutter. So for now at least,
    /// this is an approximation.
    pub const K_TRANSITION_MILLISECONDS: u64 = 450;

    // Used by all of the sliding transition animations.
    fn transition_curve() -> Rc<dyn Curve> {
        Curves::ease_in_out_cubic_emphasized()
    }

    // The previous page slides from right to left as the current page appears.
    fn secondary_backward_translation_tween() -> impl Animatable<Offset> + Clone + 'static {
        ValueTween::new(Offset::ZERO, Offset::new(-0.25, 0.0)).chain(ValueCurveTween::new(
            FadeForwardsPageTransitionsBuilder::transition_curve(),
        ))
    }

    // The previous page slides from left to right as the current page disappears.
    fn secondary_forward_translation_tween() -> impl Animatable<Offset> + Clone + 'static {
        ValueTween::new(Offset::new(-0.25, 0.0), Offset::ZERO).chain(ValueCurveTween::new(
            FadeForwardsPageTransitionsBuilder::transition_curve(),
        ))
    }

    // The fade in transition when the new page appears.
    fn fade_in_transition() -> impl Animatable<f64> + Clone + 'static {
        ValueTween::new(0.0, 1.0).chain(ValueCurveTween::new(Rc::new(Interval::new(
            0.0,
            0.75,
            Curves::linear(),
        ))))
    }

    // The fade out transition of the old page when the new page appears.
    fn fade_out_transition() -> impl Animatable<f64> + Clone + 'static {
        ValueTween::new(1.0, 0.0).chain(ValueCurveTween::new(Rc::new(Interval::new(
            0.0,
            0.25,
            Curves::linear(),
        ))))
    }

    // A transition builder that takes into account the snapshotting properties of
    // FadeForwardsPageTransitionsBuilder.
    fn snapshot_aware_delegated_transition(
        app: &mut App,
        context: BuildContext,
        secondary_animation: AnimationRef<f64>,
        background_color: Option<Color>,
        allow_snapshotting: bool,
        child: Option<WidgetRef>,
    ) -> WidgetRef {
        let reversed = ReverseAnimation::new(app, secondary_animation.clone()).into_erased();
        let mut builder = DualTransitionBuilder::new(
            reversed,
            move |app, _context, animation, child| {
                let opacity = FadeForwardsPageTransitionsBuilder::fade_in_transition()
                    .animate(app, animation.clone());
                let position =
                    FadeForwardsPageTransitionsBuilder::secondary_forward_translation_tween()
                        .animate(app, animation.clone());

                (FadeTransition::new(opacity)
                    .child(SlideTransition::new(position).child(FadeForwardsSnapshot {
                        animation,
                        allow_snapshotting,
                        child: child.cloned(),
                    }))
                    .into_widget()) as _
            },
            move |app, _context, animation, child| {
                let opacity = FadeForwardsPageTransitionsBuilder::fade_out_transition()
                    .animate(app, animation.clone());
                let position =
                    FadeForwardsPageTransitionsBuilder::secondary_backward_translation_tween()
                        .animate(app, animation.clone());

                (FadeTransition::new(opacity)
                    .child(SlideTransition::new(position).child(FadeForwardsSnapshot {
                        animation,
                        allow_snapshotting,
                        child: child.cloned(),
                    }))
                    .into_widget()) as _
            },
        );
        builder.child = child;
        let builder = builder.into_widget();

        let is_opaque = AnyModalRoute::opaque_of(app, context).unwrap_or(true);

        if !is_opaque {
            return builder;
        }

        let color = if secondary_animation.is_animating(app) {
            background_color.unwrap_or_else(|| ColorScheme::of(app, context).surface())
        } else {
            Colors::TRANSPARENT
        };
        ColoredBox::new(color).child(builder).into_widget()
    }
}

impl PageTransitionsBuilder for FadeForwardsPageTransitionsBuilder {
    fn transition_duration(&self) -> Duration {
        Duration::from_millis(FadeForwardsPageTransitionsBuilder::K_TRANSITION_MILLISECONDS)
    }

    fn delegated_transition(&self) -> Option<DelegatedTransitionBuilder> {
        let this = *self;
        Some(DelegatedTransitionBuilder::new(
            move |app, context, _animation, secondary_animation, allow_snapshotting, child| {
                Some(
                    FadeForwardsPageTransitionsBuilder::snapshot_aware_delegated_transition(
                        app,
                        context,
                        secondary_animation,
                        this.background_color,
                        !ZoomPageTransitionsBuilder::K_PROFILE_FORCE_DISABLE_SNAPSHOTTING
                            && allow_snapshotting
                            && this.allow_snapshotting,
                        child.cloned(),
                    ),
                )
            },
        ))
    }

    fn build_transitions(
        &self,
        app: &mut App,
        route: AnyPageRoute,
        _context: BuildContext,
        animation: AnimationRef<f64>,
        secondary_animation: AnimationRef<f64>,
        child: WidgetRef,
    ) -> WidgetRef {
        FadeForwardsPageTransition {
            animation,
            secondary_animation,
            allow_snapshotting: !ZoomPageTransitionsBuilder::K_PROFILE_FORCE_DISABLE_SNAPSHOTTING
                && self.allow_snapshotting
                && route
                    .as_modal_route()
                    .as_transition_route()
                    .allow_snapshotting(app),
            background_color: self.background_color,
            child: Some(child),
        }
        .into_widget()
    }
}

/// Used by [`PageTransitionsTheme`] to define a zooming `MaterialPageRoute` page transition
/// animation that looks like the default page transition used on Android Q.
///
/// See also:
///
///  * `FadeUpwardsPageTransitionsBuilder`, which defines a page transition that's similar to
///    the one provided by Android O.
///  * `OpenUpwardsPageTransitionsBuilder`, which defines a page transition that's similar to
///    the one provided by Android P.
///  * [`CupertinoPageTransitionsBuilder`], which defines a horizontal page transition that
///    matches native iOS page transitions.
///  * [`PredictiveBackPageTransitionsBuilder`], which defines a page transition that allows
///    peeking behind the current route on Android.
///  * [`FadeForwardsPageTransitionsBuilder`], which defines a page transition that's similar to
///    the one provided by Android U.
#[derive(Clone, Copy, Debug)]
pub struct ZoomPageTransitionsBuilder {
    /// Whether zoom page transitions will prefer to animate a snapshot of the entering and
    /// exiting routes.
    ///
    /// If not specified, defaults to true.
    ///
    /// When this value is true, zoom page transitions will snapshot the entering and exiting
    /// routes. These snapshots are then animated in place of the underlying widgets to improve
    /// performance of the transition.
    ///
    /// Generally this means that animations that occur on the entering/exiting route while the
    /// route animation plays may appear frozen - unless they are a hero animation or something
    /// that is drawn in a separate overlay.
    ///
    /// See also:
    ///
    ///  * `PageRoute::allow_snapshotting`, which enables or disables snapshotting on a per route
    ///    basis.
    pub allow_snapshotting: bool,

    /// Whether to enable snapshotting on the entering route during the transition animation.
    ///
    /// If not specified, defaults to true. If false, the route snapshotting will not be applied
    /// to the route being animating into, e.g. when transitioning from route A to route B, B
    /// will not be snapshotted.
    pub allow_enter_route_snapshotting: bool,

    /// The color of the scrim (background) that fades in and out during the transition.
    ///
    /// If not provided, defaults to current theme's `ColorScheme::surface` color.
    pub background_color: Option<Color>,
}

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

impl ZoomPageTransitionsBuilder {
    /// Constructs a page transition animation that matches the transition used on Android Q.
    pub const fn new() -> ZoomPageTransitionsBuilder {
        ZoomPageTransitionsBuilder {
            allow_snapshotting: true,
            allow_enter_route_snapshotting: true,
            background_color: None,
        }
    }

    /// Dart `ZoomPageTransitionsBuilder(allowSnapshotting:)`.
    pub const fn allow_snapshotting(
        mut self,
        allow_snapshotting: bool,
    ) -> ZoomPageTransitionsBuilder {
        self.allow_snapshotting = allow_snapshotting;
        self
    }

    /// Dart `ZoomPageTransitionsBuilder(allowEnterRouteSnapshotting:)`.
    pub const fn allow_enter_route_snapshotting(
        mut self,
        allow_enter_route_snapshotting: bool,
    ) -> ZoomPageTransitionsBuilder {
        self.allow_enter_route_snapshotting = allow_enter_route_snapshotting;
        self
    }

    /// Dart `ZoomPageTransitionsBuilder(backgroundColor:)`.
    pub const fn background_color(mut self, background_color: Color) -> ZoomPageTransitionsBuilder {
        self.background_color = Some(background_color);
        self
    }

    // Allows devicelab benchmarks to force disable the snapshotting. This is intended to allow us
    // to profile and fix the underlying performance issues for the Impeller backend. Dart reads
    // it from the define `flutter.benchmarks.force_disable_snapshot`; a build of Waft has no
    // such define, so it is false, as in every Flutter build that does not pass it.
    const K_PROFILE_FORCE_DISABLE_SNAPSHOTTING: bool = false;

    // A transition builder that takes into account the snapshotting properties of
    // ZoomPageTransitionsBuilder.
    #[expect(
        clippy::too_many_arguments,
        reason = "Dart's positional arguments, in Dart's order"
    )]
    fn snapshot_aware_delegated_transition(
        app: &mut App,
        context: BuildContext,
        animation: AnimationRef<f64>,
        secondary_animation: AnimationRef<f64>,
        child: Option<WidgetRef>,
        allow_snapshotting: bool,
        allow_enter_route_snapshotting: bool,
        background_color: Option<Color>,
    ) -> WidgetRef {
        let _ = animation;
        let enter_transition_background_color =
            background_color.unwrap_or_else(|| Theme::of(app, context).color_scheme.surface());
        let reversed = ReverseAnimation::new(app, secondary_animation.clone()).into_erased();
        let mut builder = DualTransitionBuilder::new(
            reversed,
            move |_app, _context, animation, child| {
                ZoomEnterTransition {
                    animation,
                    allow_snapshotting: allow_snapshotting && allow_enter_route_snapshotting,
                    reverse: true,
                    background_color: enter_transition_background_color,
                    child: child.cloned(),
                }
                .into_widget()
            },
            move |_app, _context, animation, child| {
                ZoomExitTransition {
                    animation,
                    allow_snapshotting,
                    reverse: false,
                    child: child.cloned(),
                }
                .into_widget()
            },
        );
        builder.child = child;
        builder.into_widget()
    }
}

impl PageTransitionsBuilder for ZoomPageTransitionsBuilder {
    fn delegated_transition(&self) -> Option<DelegatedTransitionBuilder> {
        let this = *self;
        Some(DelegatedTransitionBuilder::new(
            move |app, context, animation, secondary_animation, allow_snapshotting, child| {
                Some(
                    ZoomPageTransitionsBuilder::snapshot_aware_delegated_transition(
                        app,
                        context,
                        animation,
                        secondary_animation,
                        child.cloned(),
                        allow_snapshotting && this.allow_snapshotting,
                        this.allow_enter_route_snapshotting,
                        this.background_color,
                    ),
                )
            },
        ))
    }

    fn build_transitions(
        &self,
        app: &mut App,
        route: AnyPageRoute,
        _context: BuildContext,
        animation: AnimationRef<f64>,
        secondary_animation: AnimationRef<f64>,
        child: WidgetRef,
    ) -> WidgetRef {
        ZoomPageTransition {
            animation,
            secondary_animation,
            allow_snapshotting: self.allow_snapshotting
                && route
                    .as_modal_route()
                    .as_transition_route()
                    .allow_snapshotting(app),
            allow_enter_route_snapshotting: self.allow_enter_route_snapshotting,
            background_color: self.background_color,
            child: Some(child),
        }
        .into_widget()
    }
}

/// Dart's `TargetPlatform.values`, in Dart's order.
const TARGET_PLATFORM_VALUES: [TargetPlatform; 6] = [
    TargetPlatform::Android,
    TargetPlatform::Fuchsia,
    TargetPlatform::IOS,
    TargetPlatform::Linux,
    TargetPlatform::MacOS,
    TargetPlatform::Windows,
];

/// Defines the page transition animations used by `MaterialPageRoute` for different
/// [`TargetPlatform`]s.
///
/// The `MaterialPageRoute::build_transitions` method looks up the current
/// [`PageTransitionsTheme`] with `Theme::of(app, context).page_transitions_theme` and delegates
/// to [`build_transitions`](Self::build_transitions).
///
/// If a builder with a matching platform is not found, then the [`ZoomPageTransitionsBuilder`]
/// is used.
///
/// The builders are shared: a theme and its copies hold one map, and the default theme's map is
/// one per thread, as Dart's `const` map is one object, so two default themes compare equal.
///
/// See also:
///
///  * `ThemeData::page_transitions_theme`, which defines the default page transitions for the
///    overall theme.
///  * `FadeUpwardsPageTransitionsBuilder`, which defines a page transition that's similar to
///    the one provided by Android O.
///  * `OpenUpwardsPageTransitionsBuilder`, which defines a page transition that's similar to
///    the one provided by Android P.
///  * [`ZoomPageTransitionsBuilder`], which defines the default page transition that's similar
///    to the one provided by Android Q.
///  * [`FadeForwardsPageTransitionsBuilder`], which defines the default page transition that's
///    similar to the one provided by Android U.
///  * [`CupertinoPageTransitionsBuilder`], which defines a horizontal page transition that
///    matches native iOS page transitions.
#[derive(Clone)]
pub struct PageTransitionsTheme {
    builders: Rc<IndexMap<TargetPlatform, PageTransitionsBuilderRef>>,
}

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

impl PageTransitionsTheme {
    /// Constructs an object that selects a transition based on the platform.
    ///
    /// By default the list of builders is: [`PredictiveBackPageTransitionsBuilder`] for
    /// [`TargetPlatform::Android`], [`ZoomPageTransitionsBuilder`] for
    /// [`TargetPlatform::Windows`] and [`TargetPlatform::Linux`], and
    /// [`CupertinoPageTransitionsBuilder`] for [`TargetPlatform::IOS`] and
    /// [`TargetPlatform::MacOS`].
    pub fn new() -> PageTransitionsTheme {
        PageTransitionsTheme {
            builders: PageTransitionsTheme::default_builders(),
        }
    }

    /// Dart `PageTransitionsTheme(builders:)`.
    pub fn with_builders(
        mut self,
        builders: IndexMap<TargetPlatform, PageTransitionsBuilderRef>,
    ) -> PageTransitionsTheme {
        self.builders = Rc::new(builders);
        self
    }

    /// Dart's `_defaultBuilders`: one map per thread, whose builders are one per thread too,
    /// as each of Dart's `const` builders is one object.
    fn default_builders() -> Rc<IndexMap<TargetPlatform, PageTransitionsBuilderRef>> {
        thread_local! {
            static DEFAULT_BUILDERS: Rc<IndexMap<TargetPlatform, PageTransitionsBuilderRef>> = {
                let predictive_back =
                    PageTransitionsBuilderRef::new(PredictiveBackPageTransitionsBuilder::new());
                let cupertino =
                    PageTransitionsBuilderRef::new(CupertinoPageTransitionsBuilder::new());
                let zoom = PageTransitionsBuilderRef::new(ZoomPageTransitionsBuilder::new());
                Rc::new(IndexMap::from([
                    (TargetPlatform::Android, predictive_back),
                    (TargetPlatform::IOS, cupertino.clone()),
                    (TargetPlatform::MacOS, cupertino),
                    (TargetPlatform::Windows, zoom.clone()),
                    (TargetPlatform::Linux, zoom),
                ]))
            };
        }
        DEFAULT_BUILDERS.with(Rc::clone)
    }

    /// The [`PageTransitionsBuilder`]s supported by this theme.
    pub fn builders(&self) -> &IndexMap<TargetPlatform, PageTransitionsBuilderRef> {
        &self.builders
    }

    /// Delegates to the builder for the current `ThemeData::platform`. If a builder for the
    /// current platform is not found, then the [`ZoomPageTransitionsBuilder`] is used.
    ///
    /// `MaterialPageRoute::build_transitions` delegates to this method.
    pub fn build_transitions(
        &self,
        app: &mut App,
        route: AnyPageRoute,
        context: BuildContext,
        animation: AnimationRef<f64>,
        secondary_animation: AnimationRef<f64>,
        child: WidgetRef,
    ) -> WidgetRef {
        let _ = (app, context);
        PageTransitionsThemeTransitions {
            builders: Rc::clone(&self.builders),
            route,
            animation,
            secondary_animation,
            child,
        }
        .into_widget()
    }

    /// Provides the delegate transition for the target platform.
    ///
    /// See `ModalRoute::delegated_transition`.
    pub fn delegated_transition(
        &self,
        platform: TargetPlatform,
    ) -> Option<DelegatedTransitionBuilder> {
        match self.builders.get(&platform) {
            Some(matching_builder) => matching_builder.delegated_transition(),
            None => ZoomPageTransitionsBuilder::new().delegated_transition(),
        }
    }

    // Map the builders to a list with one PageTransitionsBuilder per platform for the operator
    // == overload.
    fn all(
        builders: &IndexMap<TargetPlatform, PageTransitionsBuilderRef>,
    ) -> Vec<Option<PageTransitionsBuilderRef>> {
        TARGET_PLATFORM_VALUES
            .iter()
            .map(|platform| builders.get(platform).cloned())
            .collect()
    }
}

impl PartialEq for PageTransitionsTheme {
    fn eq(&self, other: &PageTransitionsTheme) -> bool {
        if Rc::ptr_eq(&self.builders, &other.builders) {
            return true;
        }
        PageTransitionsTheme::all(&other.builders) == PageTransitionsTheme::all(&self.builders)
    }
}

impl Debug for PageTransitionsTheme {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PageTransitionsTheme")
            .field("builders", &*self.builders)
            .finish()
    }
}

pub(crate) struct PageTransitionsThemeTransitions {
    builders: Rc<IndexMap<TargetPlatform, PageTransitionsBuilderRef>>,
    route: AnyPageRoute,
    animation: AnimationRef<f64>,
    secondary_animation: AnimationRef<f64>,
    child: WidgetRef,
}

impl Debug for PageTransitionsThemeTransitions {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("_PageTransitionsThemeTransitions")
            .field("route", &self.route)
            .field("child", &self.child)
            .finish_non_exhaustive()
    }
}

impl StatefulWidget for PageTransitionsThemeTransitions {
    type State = PageTransitionsThemeTransitionsState;

    fn create_state(&self) -> PageTransitionsThemeTransitionsState {
        PageTransitionsThemeTransitionsState {
            state: StateData::new(),
            transition_platform: None,
        }
    }
}

/// Dart's `_PageTransitionsThemeTransitionsState`.
pub(crate) struct PageTransitionsThemeTransitionsState {
    state: StateData<PageTransitionsThemeTransitions>,
    transition_platform: Option<TargetPlatform>,
}

impl State for PageTransitionsThemeTransitionsState {
    type Widget = PageTransitionsThemeTransitions;
    waft_widgets::state_accessors!();

    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
        let mut platform = Theme::of(app, context).platform;

        // If the theme platform is changed in the middle of a pop gesture, keep the transition
        // that the gesture began with until the gesture is finished.
        let route = self.widget(app).route;
        if route.as_modal_route().pop_gesture_in_progress(app) {
            let transition_platform = *app
                .get_mut(self)
                .transition_platform
                .get_or_insert(platform);
            platform = transition_platform;
        } else {
            app.get_mut(self).transition_platform = None;
        }

        let widget = self.widget(app);
        let (animation, secondary_animation, child) = (
            widget.animation.clone(),
            widget.secondary_animation.clone(),
            widget.child.clone(),
        );
        match widget.builders.get(&platform).cloned() {
            Some(matching_builder) => matching_builder.build_transitions(
                app,
                route,
                context,
                animation,
                secondary_animation,
                child,
            ),
            None => match platform {
                TargetPlatform::IOS => CupertinoPageTransitionsBuilder::new().build_transitions(
                    app,
                    route,
                    context,
                    animation,
                    secondary_animation,
                    child,
                ),
                TargetPlatform::Android
                | TargetPlatform::Fuchsia
                | TargetPlatform::Windows
                | TargetPlatform::MacOS
                | TargetPlatform::Linux => ZoomPageTransitionsBuilder::new().build_transitions(
                    app,
                    route,
                    context,
                    animation,
                    secondary_animation,
                    child,
                ),
            },
        }
    }
}

// Take an image and draw it centered and scaled. The image is already scaled by the
// `pixel_ratio`.
fn draw_image_scaled_and_centered(
    context: &mut PaintingContext,
    image: &Image,
    scale: f64,
    opacity: f64,
    pixel_ratio: f64,
) {
    if scale <= 0.0 || opacity <= 0.0 {
        return;
    }
    // Valo's default sampling, linear with linear mipmaps, is Dart's `FilterQuality.medium`.
    let sampling = Sampling::default();
    let paint = Paint::from_color(Color::from_rgbo(0, 0, 0, opacity).into());
    let logical_width = f64::from(image.width()) / pixel_ratio;
    let logical_height = f64::from(image.height()) / pixel_ratio;
    let scaled_logical_width = logical_width * scale;
    let scaled_logical_height = logical_height * scale;
    let left = (logical_width - scaled_logical_width) / 2.0;
    let top = (logical_height - scaled_logical_height) / 2.0;
    let dst = Rect::from_ltwh(left, top, scaled_logical_width, scaled_logical_height);
    context.canvas().draw_image_rect(
        image,
        Rect::from_ltwh(
            0.0,
            0.0,
            f64::from(image.width()),
            f64::from(image.height()),
        )
        .into(),
        dst.into(),
        sampling,
        &paint,
    );
}

fn update_scaled_transform(transform: &mut Matrix4, scale: f64, size: Size) {
    *transform = Matrix4::IDENTITY;
    if scale == 1.0 {
        return;
    }
    let s = scale as f32;
    *transform = transform.then(&Matrix4::from_flutter_array(&[
        s, 0.0, 0.0, 0.0, //
        0.0, s, 0.0, 0.0, //
        0.0, 0.0, s, 0.0, //
        0.0, 0.0, 0.0, 1.0,
    ]));
    let dx = ((size.width() * scale) - size.width()) / 2.0;
    let dy = ((size.height() * scale) - size.height()) / 2.0;
    *transform = transform.then(&Matrix4::translation(-dx as f32, -dy as f32));
}

/// The fields Dart's `_ZoomTransitionBase` mixin declares; both zoom transition states carry
/// this bag under the field `zoom_transition_base`.
struct ZoomTransitionBaseData {
    // Don't rasterize if:
    // 1. Rasterization is disabled by the platform.
    // 2. The animation is paused/stopped.
    // 3. The values of the scale/fade transition do not
    //    benefit from rasterization.
    controller: Option<Ref<SnapshotController>>,

    fade_transition: Option<AnimationRef<f64>>,
    scale_transition: Option<AnimationRef<f64>>,
}

impl ZoomTransitionBaseData {
    fn new() -> ZoomTransitionBaseData {
        ZoomTransitionBaseData {
            controller: None,
            fade_transition: None,
            scale_transition: None,
        }
    }
}

/// Dart's `_ZoomTransitionBase` mixin on `State`.
trait ZoomTransitionBase: State {
    /// The mixin's fields, held under the field `zoom_transition_base`.
    fn zoom_transition_base_data(self: Handle<Self>, app: &App) -> &ZoomTransitionBaseData;

    /// See [`zoom_transition_base_data`](Self::zoom_transition_base_data).
    fn zoom_transition_base_data_mut(
        self: Handle<Self>,
        app: &mut App,
    ) -> &mut ZoomTransitionBaseData;

    fn use_snapshot(self: Handle<Self>, app: &App) -> bool;

    /// Dart's field initialiser of `controller`; it needs the `App`, so the state's
    /// `init_state` runs it first.
    fn init_zoom_transition_base(self: Handle<Self>, app: &mut App) {
        let controller = SnapshotController::new(app, false);
        self.zoom_transition_base_data_mut(app).controller = Some(controller);
    }

    fn controller(self: Handle<Self>, app: &App) -> Ref<SnapshotController> {
        self.zoom_transition_base_data(app)
            .controller
            .clone()
            .expect("created in init_state")
    }

    fn fade_transition(self: Handle<Self>, app: &App) -> AnimationRef<f64> {
        self.zoom_transition_base_data(app)
            .fade_transition
            .clone()
            .expect("set in init_state")
    }

    fn scale_transition(self: Handle<Self>, app: &App) -> AnimationRef<f64> {
        self.zoom_transition_base_data(app)
            .scale_transition
            .clone()
            .expect("set in init_state")
    }

    fn on_animation_value_change(self: Handle<Self>, app: &mut App) {
        let scale = self.scale_transition(app).value(app);
        let fade = self.fade_transition(app).value(app);
        let controller = self.controller(app);
        if scale == 1.0 && (fade == 0.0 || fade == 1.0) {
            controller.set_allow_snapshotting(app, false);
        } else {
            let use_snapshot = self.use_snapshot(app);
            controller.set_allow_snapshotting(app, use_snapshot);
        }
    }

    fn on_animation_status_change(self: Handle<Self>, app: &mut App, status: AnimationStatus) {
        let allow_snapshotting = status.is_animating() && self.use_snapshot(app);
        self.controller(app)
            .set_allow_snapshotting(app, allow_snapshotting);
    }

    /// Dart's `_ZoomTransitionBase.dispose`, which the state's `dispose` runs last.
    fn dispose(self: Handle<Self>, app: &mut App) {
        self.controller(app).dispose(app);
    }
}

struct ZoomEnterTransitionPainter {
    change_notifier: ChangeNotifierData,
    reverse: bool,
    animation: AnimationRef<f64>,
    scale: AnimationRef<f64>,
    fade: AnimationRef<f64>,
    background_color: Color,
    transform: Matrix4,
    opacity_handle: LayerHandle<Handle<OpacityLayer>>,
    transform_handler: LayerHandle<Handle<TransformLayer>>,
}

impl ZoomEnterTransitionPainter {
    fn new(
        app: &mut App,
        reverse: bool,
        scale: AnimationRef<f64>,
        fade: AnimationRef<f64>,
        animation: AnimationRef<f64>,
        background_color: Color,
    ) -> Ref<ZoomEnterTransitionPainter> {
        let this = app.create(ZoomEnterTransitionPainter {
            change_notifier: ChangeNotifierData::new(),
            reverse,
            animation: animation.clone(),
            scale: scale.clone(),
            fade: fade.clone(),
            background_color,
            transform: Matrix4::IDENTITY,
            opacity_handle: LayerHandle::new(),
            transform_handler: LayerHandle::new(),
        });
        let handle = this.handle();
        animation.add_listener(
            app,
            Listener::handle_method(handle, Handle::notify_listeners),
        );
        animation.add_status_listener(
            app,
            AnimationStatusListener::handle_method(handle, Self::on_status_change),
        );
        scale.add_listener(
            app,
            Listener::handle_method(handle, Handle::notify_listeners),
        );
        fade.add_listener(
            app,
            Listener::handle_method(handle, Handle::notify_listeners),
        );
        this
    }

    fn on_status_change(self: Handle<Self>, app: &mut App, _status: AnimationStatus) {
        self.notify_listeners(app);
    }

    fn draw_scrim(
        self: Handle<Self>,
        app: &mut App,
        context: &mut PaintingContext,
        offset: Offset,
        size: Size,
    ) {
        let mut scrim_opacity = 0.0;
        // The transition's scrim opacity only increases on the forward transition. In the
        // reverse transition, the opacity should always be 0.0.
        //
        // Therefore, we need to only apply the scrim opacity animation when the transition is
        // running forwards.
        //
        // The reason that we check that the animation's status is not `completed` instead of
        // checking that it is `forward` is that this allows the interrupted reversal of the
        // forward transition to smoothly fade the scrim away. This prevents a disjointed removal
        // of the scrim.
        let this = app.get(self);
        let (reverse, animation, background_color) =
            (this.reverse, this.animation.handle(), this.background_color);
        if !reverse && !animation.is_completed(app) {
            scrim_opacity =
                ZoomEnterTransitionState::scrim_opacity_tween().evaluate(app, animation);
        }
        debug_assert!(!reverse || scrim_opacity == 0.0);
        if scrim_opacity > 0.0 {
            // Dart's `withOpacity`, deprecated there too: its rounding to an 8-bit alpha is part
            // of the behaviour being ported.
            #[allow(deprecated)]
            let color = background_color.with_opacity(scrim_opacity);
            context
                .canvas()
                .draw_rect(offset & size, &Paint::from_color(color.into()));
        }
    }

    /// Dart's `dispose`: lets go of the animations and the layers, then `ChangeNotifier`'s.
    fn dispose(self: Handle<Self>, app: &mut App) {
        let this = app.get(self);
        let (animation, scale, fade) = (
            this.animation.clone(),
            this.scale.clone(),
            this.fade.clone(),
        );
        animation.remove_listener(
            app,
            &Listener::handle_method(self, Handle::notify_listeners),
        );
        animation.remove_status_listener(
            app,
            &AnimationStatusListener::handle_method(self, Self::on_status_change),
        );
        scale.remove_listener(
            app,
            &Listener::handle_method(self, Handle::notify_listeners),
        );
        fade.remove_listener(
            app,
            &Listener::handle_method(self, Handle::notify_listeners),
        );
        LayerHandle::set_layer(app, |app| &mut app.get_mut(self).opacity_handle, None);
        LayerHandle::set_layer(app, |app| &mut app.get_mut(self).transform_handler, None);
        ChangeNotifierData::dispose(app, self);
    }
}

impl ChangeNotifier for ZoomEnterTransitionPainter {
    fn change_notifier_data(&self) -> &ChangeNotifierData {
        &self.change_notifier
    }

    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
        &mut self.change_notifier
    }
}

impl SnapshotPainter for ZoomEnterTransitionPainter {
    fn paint(
        self: Handle<Self>,
        app: &mut App,
        context: &mut PaintingContext,
        offset: Offset,
        size: Size,
        painter: &mut dyn FnMut(&mut App, &mut PaintingContext, Offset),
    ) {
        if !app.get(self).animation.is_animating(app) {
            return painter(app, context, offset);
        }

        self.draw_scrim(app, context, offset, size);
        let scale = app.get(self).scale.value(app);
        update_scaled_transform(&mut app.get_mut(self).transform, scale, size);
        let transform = app.get(self).transform;
        let old_transform = app.get(self).transform_handler.layer();
        let layer = context.push_transform(
            app,
            true,
            offset,
            transform,
            |app, context, offset| {
                let alpha = (app.get(self).fade.value(app) * 255.0).round() as i32;
                let old_opacity = app.get(self).opacity_handle.layer();
                let opacity = context.push_opacity(app, offset, alpha, painter, old_opacity);
                LayerHandle::set_layer(
                    app,
                    |app| &mut app.get_mut(self).opacity_handle,
                    Some(opacity),
                );
            },
            old_transform,
        );
        LayerHandle::set_layer(app, |app| &mut app.get_mut(self).transform_handler, layer);
    }

    fn paint_snapshot(
        self: Handle<Self>,
        app: &mut App,
        context: &mut PaintingContext,
        offset: Offset,
        size: Size,
        image: &Image,
        _source_size: Size,
        pixel_ratio: f64,
    ) {
        self.draw_scrim(app, context, offset, size);
        let this = app.get(self);
        let (scale, fade) = (this.scale.value(app), this.fade.value(app));
        draw_image_scaled_and_centered(context, image, scale, fade, pixel_ratio);
    }

    fn should_repaint(self: Handle<Self>, app: &App, old_painter: AnySnapshotPainter) -> bool {
        let old_delegate = app.get(
            old_painter
                .downcast::<ZoomEnterTransitionPainter>(app)
                .expect("the painter it replaces is a zoom enter painter"),
        );
        let this = app.get(self);
        old_delegate.reverse != this.reverse
            || old_delegate.animation.value(app) != this.animation.value(app)
            || old_delegate.scale.value(app) != this.scale.value(app)
            || old_delegate.fade.value(app) != this.fade.value(app)
    }
}

struct ZoomExitTransitionPainter {
    change_notifier: ChangeNotifierData,
    reverse: bool,
    scale: AnimationRef<f64>,
    fade: AnimationRef<f64>,
    animation: AnimationRef<f64>,
    transform: Matrix4,
    opacity_handle: LayerHandle<Handle<OpacityLayer>>,
    transform_handler: LayerHandle<Handle<TransformLayer>>,
}

impl ZoomExitTransitionPainter {
    fn new(
        app: &mut App,
        reverse: bool,
        scale: AnimationRef<f64>,
        fade: AnimationRef<f64>,
        animation: AnimationRef<f64>,
    ) -> Ref<ZoomExitTransitionPainter> {
        let this = app.create(ZoomExitTransitionPainter {
            change_notifier: ChangeNotifierData::new(),
            reverse,
            scale: scale.clone(),
            fade: fade.clone(),
            animation: animation.clone(),
            transform: Matrix4::IDENTITY,
            opacity_handle: LayerHandle::new(),
            transform_handler: LayerHandle::new(),
        });
        let handle = this.handle();
        scale.add_listener(
            app,
            Listener::handle_method(handle, Handle::notify_listeners),
        );
        fade.add_listener(
            app,
            Listener::handle_method(handle, Handle::notify_listeners),
        );
        animation.add_status_listener(
            app,
            AnimationStatusListener::handle_method(handle, Self::on_status_change),
        );
        this
    }

    fn on_status_change(self: Handle<Self>, app: &mut App, _status: AnimationStatus) {
        self.notify_listeners(app);
    }

    /// Dart's `dispose`: lets go of the layers and the animations, then `ChangeNotifier`'s.
    fn dispose(self: Handle<Self>, app: &mut App) {
        LayerHandle::set_layer(app, |app| &mut app.get_mut(self).opacity_handle, None);
        LayerHandle::set_layer(app, |app| &mut app.get_mut(self).transform_handler, None);
        let this = app.get(self);
        let (scale, fade, animation) = (
            this.scale.clone(),
            this.fade.clone(),
            this.animation.clone(),
        );
        scale.remove_listener(
            app,
            &Listener::handle_method(self, Handle::notify_listeners),
        );
        fade.remove_listener(
            app,
            &Listener::handle_method(self, Handle::notify_listeners),
        );
        animation.remove_status_listener(
            app,
            &AnimationStatusListener::handle_method(self, Self::on_status_change),
        );
        ChangeNotifierData::dispose(app, self);
    }
}

impl ChangeNotifier for ZoomExitTransitionPainter {
    fn change_notifier_data(&self) -> &ChangeNotifierData {
        &self.change_notifier
    }

    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
        &mut self.change_notifier
    }
}

impl SnapshotPainter for ZoomExitTransitionPainter {
    fn paint_snapshot(
        self: Handle<Self>,
        app: &mut App,
        context: &mut PaintingContext,
        _offset: Offset,
        _size: Size,
        image: &Image,
        _source_size: Size,
        pixel_ratio: f64,
    ) {
        let this = app.get(self);
        let (scale, fade) = (this.scale.value(app), this.fade.value(app));
        draw_image_scaled_and_centered(context, image, scale, fade, pixel_ratio);
    }

    fn paint(
        self: Handle<Self>,
        app: &mut App,
        context: &mut PaintingContext,
        offset: Offset,
        size: Size,
        painter: &mut dyn FnMut(&mut App, &mut PaintingContext, Offset),
    ) {
        if !app.get(self).animation.is_animating(app) {
            return painter(app, context, offset);
        }

        let scale = app.get(self).scale.value(app);
        update_scaled_transform(&mut app.get_mut(self).transform, scale, size);
        let transform = app.get(self).transform;
        let old_transform = app.get(self).transform_handler.layer();
        let layer = context.push_transform(
            app,
            true,
            offset,
            transform,
            |app, context, offset| {
                let alpha = (app.get(self).fade.value(app) * 255.0).round() as i32;
                let old_opacity = app.get(self).opacity_handle.layer();
                let opacity = context.push_opacity(app, offset, alpha, painter, old_opacity);
                LayerHandle::set_layer(
                    app,
                    |app| &mut app.get_mut(self).opacity_handle,
                    Some(opacity),
                );
            },
            old_transform,
        );
        LayerHandle::set_layer(app, |app| &mut app.get_mut(self).transform_handler, layer);
    }

    fn should_repaint(self: Handle<Self>, app: &App, old_painter: AnySnapshotPainter) -> bool {
        let old_delegate = app.get(
            old_painter
                .downcast::<ZoomExitTransitionPainter>(app)
                .expect("the painter it replaces is a zoom exit painter"),
        );
        let this = app.get(self);
        old_delegate.reverse != this.reverse
            || old_delegate.fade.value(app) != this.fade.value(app)
            || old_delegate.scale.value(app) != this.scale.value(app)
    }
}

/// Dart's `Map<TargetPlatform, PageTransitionsBuilder>.toString`.
fn builders_description(builders: &IndexMap<TargetPlatform, PageTransitionsBuilderRef>) -> String {
    let entries: Vec<String> = builders
        .iter()
        .map(|(platform, builder)| {
            format!(
                "{}: {}",
                waft_foundation::DartEnum(*platform),
                waft_foundation::InstanceOf(&**builder)
            )
        })
        .collect();
    format!("{{{}}}", entries.join(", "))
}

impl Diagnosticable for PageTransitionsTheme {
    fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
        let default_builders = PageTransitionsTheme::new().builders;
        properties.add(
            DiagnosticsProperty::<String>::new(
                "builders",
                Some(builders_description(&self.builders)),
            )
            .default_value(Some(builders_description(&default_builders))),
        );
    }
}

impl fmt::Display for PageTransitionsTheme {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&Diagnosticable::to_string(self))
    }
}

#[cfg(test)]
mod tests {
    use waft_animation::{AnimationBehavior, AnimationController};
    use waft_cupertino::CupertinoPageTransition;
    use waft_foundation::Listener;
    use waft_rendering::AnyLayer;
    use waft_widgets::{
        AnyElement, Builder, Navigator, NavigatorState, PageRouteBuilder, SizedBox,
        StatefulBuilder, Text, WidgetBuilder,
    };

    use waft_rendering::testing::{PaintCall, assert_paints};
    use waft_widgets::testing::{
        TargetPlatformVariant, TestPointer, TestVSync, WidgetTester, find, test_widgets,
        test_widgets_variant,
    };

    use super::*;
    use crate::app::MaterialApp;
    use crate::material::Material;
    use crate::page::MaterialPageRoute;
    use crate::test_support::{PaintInspection, material_page_app};
    use crate::text_button::TextButton;
    use crate::theme_data::ThemeData;
    use waft_animation::AnyAnimation;
    use waft_test::{assert_no_new_objects, object_snapshot};

    /// `tester.pumpWidget(MaterialApp(theme: theme(app), ..))` with the pages `configure` gives.
    fn pump_app(
        tester: &mut WidgetTester,
        theme: impl FnOnce(&App) -> ThemeData,
        configure: impl FnOnce(MaterialApp) -> MaterialApp,
    ) {
        let root = {
            let theme = theme(&tester.cell.borrow());
            material_page_app(theme, configure)
        };
        tester.pump_widget(root);
    }

    /// A page with a `TextButton` showing `label` that runs `on_pressed` with the page's context.
    fn button_page(
        label: &'static str,
        on_pressed: impl Fn(&mut App, BuildContext) + 'static,
    ) -> WidgetBuilder {
        let on_pressed = Rc::new(on_pressed);
        Rc::new(move |_app, context| {
            let on_pressed = Rc::clone(&on_pressed);
            Material::new()
                .child(TextButton::new(
                    Some(Listener::new(move |app| on_pressed(app, context))),
                    Some(Text::new(label)),
                ))
                .into_widget()
        })
    }

    fn text_page(text: &'static str) -> WidgetBuilder {
        Rc::new(move |_app, _context| Text::new(text).into_widget())
    }

    /// The cases' `routes`: `/` a button 'push' that pushes `/b`, and `/b` the text 'page b'.
    fn push_routes() -> Vec<(String, WidgetBuilder)> {
        vec![
            (
                "/".to_string(),
                button_page("push", |app, context| {
                    Navigator::push_named(app, context, "/b", None);
                }),
            ),
            ("/b".to_string(), text_page("page b")),
        ]
    }

    /// `ThemeData(pageTransitionsTheme: PageTransitionsTheme(builders: {platform: builder}))`.
    fn theme_with(
        platform: TargetPlatform,
        builder: impl PageTransitionsBuilder,
    ) -> impl FnOnce(&App) -> ThemeData {
        move |app| {
            ThemeData::builder()
                .page_transitions_theme(PageTransitionsTheme::new().with_builders(IndexMap::from(
                    [(platform, PageTransitionsBuilderRef::new(builder))],
                )))
                .build(app)
        }
    }

    fn count_onstage_text(tester: &WidgetTester, text: &str) -> usize {
        find::text(text).evaluate(tester).len()
    }

    fn count_of<W: 'static>(tester: &WidgetTester) -> usize {
        find::by_type::<W>().evaluate(tester).len()
    }

    fn navigator(tester: &WidgetTester) -> Handle<NavigatorState> {
        let element = *find::by_type::<Navigator>()
            .evaluate(tester)
            .first()
            .expect("a navigator");
        let app = tester.cell.borrow();
        element
            .state_handle::<NavigatorState>(&app)
            .expect("a navigator's state")
    }

    fn last_colored_box_color(tester: &WidgetTester) -> Color {
        let element = *find::by_type::<ColoredBox>()
            .evaluate(tester)
            .last()
            .expect("a ColoredBox");
        tester.widget::<ColoredBox, _>(element, |colored_box| colored_box.color.color())
    }

    #[test]
    fn the_default_page_transitions_theme_has_a_builder_for_every_platform_but_fuchsia() {
        let theme = PageTransitionsTheme::new();
        for platform in TARGET_PLATFORM_VALUES {
            match platform {
                TargetPlatform::Android
                | TargetPlatform::IOS
                | TargetPlatform::MacOS
                | TargetPlatform::Linux
                | TargetPlatform::Windows => {
                    assert!(theme.builders().get(&platform).is_some(), "{platform:?}")
                }
                TargetPlatform::Fuchsia => {
                    assert!(theme.builders().get(&platform).is_none(), "{platform:?}")
                }
            }
        }
    }

    #[test]
    fn two_default_themes_are_equal_and_a_theme_with_other_builders_is_not() {
        assert_eq!(PageTransitionsTheme::new(), PageTransitionsTheme::default());
        let default_builders = PageTransitionsTheme::new().builders().clone();
        assert_eq!(
            PageTransitionsTheme::new().with_builders(default_builders.clone()),
            PageTransitionsTheme::new()
        );
        let mut other_builders = default_builders;
        other_builders.insert(
            TargetPlatform::Android,
            PageTransitionsBuilderRef::new(ZoomPageTransitionsBuilder::new()),
        );
        assert_ne!(
            PageTransitionsTheme::new().with_builders(other_builders),
            PageTransitionsTheme::new()
        );
    }

    #[test]
    fn the_default_theme_builds_a_cupertino_page_transition_on_ios_and_macos() {
        for platform in [TargetPlatform::IOS, TargetPlatform::MacOS] {
            test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
                pump_app(tester, ThemeData::new, |app| app.routes(push_routes()));
                assert_eq!(count_of::<CupertinoPageTransition>(tester), 1);

                tester.tap(find::text("push"));
                tester.pump_and_settle();
                assert_eq!(count_onstage_text(tester, "page b"), 1);
                assert_eq!(count_of::<CupertinoPageTransition>(tester), 1);
            });
        }
    }

    #[test]
    fn the_default_theme_builds_a_fade_forwards_page_transition_on_android() {
        test_widgets(|tester| {
            pump_app(tester, ThemeData::new, |app| app.routes(push_routes()));
            assert_eq!(count_of::<FadeForwardsPageTransition>(tester), 1);

            tester.tap(find::text("push"));
            tester.pump_and_settle();
            assert_eq!(count_onstage_text(tester, "page b"), 1);
            assert_eq!(count_of::<FadeForwardsPageTransition>(tester), 1);
        });
    }

    /// The fade-forwards cases on the background: the last `ColoredBox` 400ms into the push.
    fn fade_forwards_background(builder: FadeForwardsPageTransitionsBuilder) -> Color {
        let mut color = Colors::TRANSPARENT;
        test_widgets(|tester| {
            pump_app(
                tester,
                move |app| {
                    let color_scheme = ThemeData::new(app)
                        .color_scheme
                        .with_surface(Colors::PINK.primary());
                    ThemeData::builder()
                        .page_transitions_theme(PageTransitionsTheme::new().with_builders(
                            IndexMap::from([(
                                TargetPlatform::Android,
                                PageTransitionsBuilderRef::new(builder),
                            )]),
                        ))
                        .color_scheme(color_scheme)
                        .build(app)
                },
                |app| app.routes(push_routes()),
            );
            assert_eq!(count_of::<FadeForwardsPageTransition>(tester), 1);

            tester.tap(find::text("push"));
            tester.pump_by(Duration::from_millis(400));
            color = last_colored_box_color(tester);

            tester.pump_and_settle();
            assert_eq!(count_onstage_text(tester, "page b"), 1);
            assert_eq!(count_of::<FadeForwardsPageTransition>(tester), 1);
        });
        color
    }

    #[test]
    fn fade_forwards_paints_the_color_scheme_surface_behind_the_pages_by_default() {
        let color = fade_forwards_background(FadeForwardsPageTransitionsBuilder::new());
        assert_eq!(color, Colors::PINK.primary());
    }

    #[test]
    fn fade_forwards_paints_its_background_color_behind_the_pages() {
        let color = fade_forwards_background(
            FadeForwardsPageTransitionsBuilder::new()
                .background_color(Colors::LIGHT_GREEN.primary()),
        );
        assert_eq!(color, Colors::LIGHT_GREEN.primary());
    }

    /// The fade-forwards delegated transition over `animation` and `secondary_animation` of a
    /// 100ms controller, around a `SizedBox`; answers the controller.
    fn delegated_fade_forwards(
        tester: &mut WidgetTester,
        animation: ValueTween<f64>,
        secondary_animation: ValueTween<f64>,
    ) -> Ref<AnimationController> {
        let controller = AnimationController::new(
            &mut tester.cell.borrow_mut(),
            None,
            Some(Duration::from_millis(100)),
            None,
            0.0,
            1.0,
            AnimationBehavior::Normal,
            TestVSync,
        );
        let (animation, secondary_animation) = {
            let mut app = tester.cell.borrow_mut();
            let parent = controller.erase::<AnyAnimation<f64>>();
            (
                animation.animate(&mut app, parent.clone()),
                secondary_animation.animate(&mut app, parent),
            )
        };
        tester.pump_widget(
            Builder::new(move |app, context| {
                FadeForwardsPageTransitionsBuilder::new()
                    .delegated_transition()
                    .expect("a delegated transition")
                    .call(
                        app,
                        context,
                        animation.clone(),
                        secondary_animation.clone(),
                        false,
                        Some(&SizedBox::new().into_widget()),
                    )
                    .expect("a widget")
            })
            .into_widget(),
        );
        controller
    }

    /// The opacity of the `FadeTransition` nearest above the `SizedBox`: Dart's
    /// `findAncestorRenderObjectOfType<RenderAnimatedOpacity>()?.opacity.value`.
    fn opacity(tester: &WidgetTester) -> f64 {
        let sized_box = *find::by_type::<SizedBox>()
            .evaluate(tester)
            .first()
            .expect("the SizedBox");
        let fade = tester.ancestor_of_type::<FadeTransition>(sized_box);
        let app = tester.cell.borrow();
        tester.widget::<FadeTransition, _>(fade, |fade| fade.opacity.value(&app))
    }

    #[test]
    fn the_fade_forwards_delegated_transition_fades_out_during_a_forward_secondary_animation() {
        test_widgets(|tester| {
            let controller = delegated_fade_forwards(
                tester,
                ValueTween::new(1.0, 0.0),
                ValueTween::new(0.0, 1.0),
            );

            // Since secondary animation is forward, transition will be reverse between duration
            // 0 to 0.25.
            controller.set_value(&mut tester.cell.borrow_mut(), 0.0);
            tester.pump();
            assert_eq!(opacity(tester), 1.0);

            controller.set_value(&mut tester.cell.borrow_mut(), 0.25);
            tester.pump();
            assert_eq!(opacity(tester), 0.0);
        });
    }

    #[test]
    fn the_fade_forwards_delegated_transition_fades_in_during_a_reverse_secondary_animation() {
        test_widgets(|tester| {
            let controller = delegated_fade_forwards(
                tester,
                ValueTween::new(0.0, 1.0),
                ValueTween::new(1.0, 0.0),
            );

            // Since secondary animation is reverse, transition will be forward between duration
            // 0.75 to 1.0.
            controller.set_value(&mut tester.cell.borrow_mut(), 0.75);
            tester.pump();
            assert_eq!(opacity(tester), 0.0);

            controller.set_value(&mut tester.cell.borrow_mut(), 1.0);
            tester.pump();
            assert_eq!(opacity(tester), 1.0);
        });
    }

    #[test]
    fn fade_forwards_paints_no_background_under_a_route_that_is_not_opaque() {
        test_widgets(|tester| {
            let light_green = Colors::LIGHT_GREEN.primary();
            let push_b = Rc::new(|app: &mut App, context: BuildContext| {
                let route = MaterialPageRoute::new(app, text_page("page b"));
                Navigator::of(app, context, false).push(app, route.erase());
            });
            let home = button_page("push a", move |app, context| {
                let push_b = Rc::clone(&push_b);
                let page = button_page("push b", move |app, _page_context| push_b(app, context));
                let route = PageRouteBuilder::new(
                    app,
                    Rc::new(move |app, page_context, _animation, _secondary| {
                        page(app, page_context)
                    }),
                )
                .opaque(app, false);
                Navigator::of(app, context, false).push(app, route.erase());
            });
            pump_app(
                tester,
                theme_with(
                    TargetPlatform::Android,
                    FadeForwardsPageTransitionsBuilder::new().background_color(light_green),
                ),
                move |app| app.routes([("/".to_string(), home)]),
            );
            let no_light_green_box = |tester: &WidgetTester| {
                find::by_type::<ColoredBox>()
                    .evaluate(tester)
                    .into_iter()
                    .all(|element| {
                        tester.widget::<ColoredBox, _>(element, |colored_box| {
                            colored_box.color.color() != light_green
                        })
                    })
            };

            tester.tap(find::text("push a"));
            tester.pump_and_settle();

            tester.tap(find::text("push b"));
            tester.pump_by(Duration::from_millis(400));

            // Check that ColoredBox is not used for non-opaque route.
            assert!(no_light_green_box(tester));

            tester.pump_and_settle();

            let page_b = *find::text("page b")
                .evaluate(tester)
                .first()
                .expect("page b");
            Navigator::pop(&mut tester.cell.borrow_mut(), page_b, None);

            tester.pump_and_settle_by(Duration::from_millis(400));

            // Check that ColoredBox is not used for non-opaque route
            assert!(no_light_green_box(tester));
        });
    }

    /// Not a Dart case: Dart's collector frees the transitions and the painter a zoom state's
    /// `_updateAnimations` replaces; here they are freed with their last reference.
    #[test]
    fn a_zoom_transition_given_a_new_animation_leaves_no_new_arena_objects() {
        test_widgets(|tester| {
            let [first, second] = [0.25, 0.5].map(|value| {
                tester
                    .cell
                    .borrow_mut()
                    .create(waft_animation::AlwaysStoppedAnimation::new(value))
                    .into_erased::<AnyAnimation<f64>>()
            });
            let zoom = |animation: AnimationRef<f64>, reverse: bool| -> WidgetRef {
                waft_widgets::Directionality::new(
                    waft_embedder::TextDirection::Ltr,
                    waft_widgets::Column::new().children([
                        ZoomEnterTransition {
                            animation: animation.clone(),
                            child: Some(SizedBox::new().into_widget()),
                            allow_snapshotting: true,
                            reverse,
                            background_color: Colors::BLACK,
                        }
                        .into_widget(),
                        ZoomExitTransition {
                            animation: animation.clone(),
                            allow_snapshotting: true,
                            reverse,
                            child: Some(SizedBox::new().into_widget()),
                        }
                        .into_widget(),
                    ]),
                )
                .into_widget()
            };
            for reverse in [false, true] {
                tester.pump_widget(zoom(first.clone(), reverse));
                tester.pump_widget(zoom(second.clone(), reverse));
                let snapshot = object_snapshot(&tester.cell.borrow());
                tester.pump_widget(zoom(first.clone(), reverse));
                tester.pump_widget(zoom(second.clone(), reverse));
                tester.cell.checkpoint();
                assert_no_new_objects(&tester.cell.borrow(), &snapshot);
            }
        });
    }

    /// Checks that the frame `at` into a push, and the one `at` into the pop that follows, leave
    /// no new arena objects with `builder`: Dart's collector frees what each frame's build
    /// replaces. `at` lies between the bounds of the intervals the transitions fade over, so the
    /// frame adds and drops no layer.
    fn assert_mid_transition_frames_leave_nothing(
        platform: TargetPlatform,
        builder: impl PageTransitionsBuilder,
        at: Duration,
    ) {
        let mut tester = WidgetTester::on(platform);
        pump_app(&mut tester, theme_with(platform, builder), |app| {
            app.routes(push_routes())
        });
        let assert_a_frame_leaves_nothing = |tester: &mut WidgetTester| {
            tester.pump();
            tester.pump_by(at);
            let snapshot = object_snapshot(&tester.cell.borrow());
            tester.pump_by(Duration::from_millis(16));
            tester.cell.checkpoint();
            assert_no_new_objects(&tester.cell.borrow(), &snapshot);
        };
        tester.tap(find::text("push"));
        assert_a_frame_leaves_nothing(&mut tester);
        tester.pump_and_settle();
        let page_b = *find::text("page b")
            .evaluate(&tester)
            .first()
            .expect("page b");
        Navigator::pop(&mut tester.cell.borrow_mut(), page_b, None);
        assert_a_frame_leaves_nothing(&mut tester);
    }

    /// Not a Dart case: see [`assert_mid_transition_frames_leave_nothing`].
    #[test]
    fn a_frame_of_a_zoom_push_or_pop_leaves_no_new_arena_objects() {
        test_widgets(|_tester| {
            assert_mid_transition_frames_leave_nothing(
                TargetPlatform::Android,
                ZoomPageTransitionsBuilder::new(),
                Duration::from_millis(100),
            );
        });
    }

    /// Not a Dart case: see [`assert_mid_transition_frames_leave_nothing`].
    #[test]
    fn a_frame_of_a_fade_forwards_push_or_pop_leaves_no_new_arena_objects() {
        test_widgets(|_tester| {
            assert_mid_transition_frames_leave_nothing(
                TargetPlatform::Android,
                FadeForwardsPageTransitionsBuilder::new(),
                Duration::from_millis(200),
            );
        });
    }

    #[test]
    fn the_fade_forwards_transition_lasts_450_ms() {
        test_widgets(|tester| {
            pump_app(
                tester,
                theme_with(
                    TargetPlatform::Android,
                    FadeForwardsPageTransitionsBuilder::new(),
                ),
                |app| app.routes(push_routes()),
            );
            assert_eq!(count_of::<FadeForwardsPageTransition>(tester), 1);

            tester.tap(find::text("push"));
            tester.pump_by(Duration::from_millis(799));
            assert_eq!(count_onstage_text(tester, "page b"), 0);
            // Color is not transparent during animation.
            assert_ne!(last_colored_box_color(tester), Colors::TRANSPARENT);

            tester.pump_by(Duration::from_millis(801));
            assert_eq!(count_onstage_text(tester, "page b"), 1);
            // Color is transparent after the animation.
            assert_eq!(last_colored_box_color(tester), Colors::TRANSPARENT);
        });
    }

    #[test]
    fn the_cupertino_page_transitions_builder_lasts_500_ms() {
        test_widgets_variant(TargetPlatformVariant::only(TargetPlatform::IOS), |tester| {
            pump_app(
                tester,
                theme_with(TargetPlatform::IOS, CupertinoPageTransitionsBuilder::new()),
                |app| app.routes(push_routes()),
            );
            assert_eq!(count_of::<CupertinoPageTransition>(tester), 1);

            tester.tap(find::text("push"));
            tester.pump();
            tester.pump_by(Duration::from_millis(499));
            let running = |tester: &WidgetTester| {
                waft_scheduler::SchedulerBinding::transient_callback_count(
                    &mut tester.cell.borrow_mut(),
                ) > 0
            };
            assert!(running(tester));

            tester.pump_by(Duration::from_millis(10));
            assert!(!running(tester));
        });
    }

    #[test]
    fn the_route_durations_follow_a_change_of_the_page_transitions_builder() {
        test_widgets(|tester| {
            let routes = || {
                vec![
                    (
                        "/".to_string(),
                        button_page("push", |app, context| {
                            Navigator::push_named(app, context, "/b", None);
                        }),
                    ),
                    (
                        "/b".to_string(),
                        Rc::new(|_app: &mut App, context: BuildContext| {
                            Material::new()
                                .child(
                                    waft_widgets::Column::new().children([
                                        TextButton::new(
                                            Some(Listener::new(move |app| {
                                                Navigator::pop(app, context, None)
                                            })),
                                            Some(Text::new("pop")),
                                        )
                                        .into_widget(),
                                        Text::new("page b").into_widget(),
                                    ]),
                                )
                                .into_widget()
                        }) as WidgetBuilder,
                    ),
                ]
            };
            pump_app(
                tester,
                theme_with(
                    TargetPlatform::Android,
                    FadeForwardsPageTransitionsBuilder::new(),
                ),
                move |app| app.routes(routes()),
            );
            assert_eq!(count_of::<FadeForwardsPageTransition>(tester), 1);

            tester.tap(find::text("push"));
            tester.pump_by(Duration::from_millis(799));
            assert_eq!(count_onstage_text(tester, "page b"), 0);
            // The color is not transparent during animation.
            assert_ne!(last_colored_box_color(tester), Colors::TRANSPARENT);

            tester.pump_by(Duration::from_millis(801));
            assert_eq!(count_onstage_text(tester, "page b"), 1);
            // The color is transparent after the animation.
            assert_eq!(last_colored_box_color(tester), Colors::TRANSPARENT);

            pump_app(
                tester,
                theme_with(
                    TargetPlatform::Android,
                    waft_widgets::FadeUpwardsPageTransitionsBuilder::new(),
                ),
                move |app| app.routes(routes()),
            );
            tester.pump_and_settle();
            assert_eq!(
                tester
                    .elements()
                    .into_iter()
                    .filter(|element| tester.is_onstage(*element))
                    .filter(
                        |element| format!("{:?}", element.widget(&tester.cell.borrow()))
                            .starts_with("_FadeUpwardsPageTransition")
                    )
                    .count(),
                1
            );
            tester.tap(find::text("pop"));
            tester.pump_by(Duration::from_millis(299));
            assert_eq!(count_onstage_text(tester, "page b"), 1);
            // ColoredBox doesn't exist in FadeUpwardsPageTransition.
            assert_eq!(count_of::<ColoredBox>(tester), 0);

            tester.pump_by(Duration::from_millis(301));
            assert_eq!(count_onstage_text(tester, "page b"), 0);
            // The first page.
            assert_eq!(count_onstage_text(tester, "push"), 1);
            assert_eq!(count_of::<ColoredBox>(tester), 0);
        });
    }

    #[test]
    fn a_page_transitions_theme_override_builds_a_cupertino_page_transition_on_android() {
        test_widgets(|tester| {
            pump_app(
                tester,
                theme_with(
                    TargetPlatform::Android,
                    CupertinoPageTransitionsBuilder::new(),
                ),
                |app| app.routes(push_routes()),
            );
            assert_eq!(count_of::<CupertinoPageTransition>(tester), 1);

            tester.tap(find::text("push"));
            tester.pump_and_settle();
            assert_eq!(count_onstage_text(tester, "page b"), 1);
            assert_eq!(count_of::<CupertinoPageTransition>(tester), 1);
        });
    }

    #[test]
    fn a_cupertino_page_transition_on_android_does_not_block_gestures_after_a_back_swipe() {
        test_widgets(|tester| {
            pump_app(
                tester,
                theme_with(
                    TargetPlatform::Android,
                    CupertinoPageTransitionsBuilder::new(),
                ),
                |app| app.routes(push_routes()),
            );
            assert_eq!(count_of::<CupertinoPageTransition>(tester), 1);

            tester.tap(find::text("push"));
            tester.pump_and_settle();
            assert_eq!(count_onstage_text(tester, "page b"), 1);
            assert_eq!(count_of::<CupertinoPageTransition>(tester), 1);

            tester.pump_and_settle_by(Duration::from_secs(60));

            let mut gesture = TestPointer::touch(1);
            tester.down(&mut gesture, Offset::new(5.0, 100.0));
            tester.move_to(&mut gesture, Offset::new(405.0, 100.0), true);
            tester.up(&gesture);
            tester.pump();

            tester.pump_and_settle_by(Duration::from_secs(60));

            assert_eq!(count_onstage_text(tester, "push"), 1);
            tester.tap(find::text("push"));
            tester.pump_and_settle();
            assert_eq!(count_onstage_text(tester, "page b"), 1);
        });
    }

    /// The zoom snapshotting cases' app: page 1 and page 2, the second route with
    /// `second_route_allow_snapshotting`, under a zoom builder with `theme_allow_snapshotting`.
    fn zoom_snapshotting_app(
        tester: &mut WidgetTester,
        theme_allow_snapshotting: bool,
        second_route_allow_snapshotting: bool,
    ) {
        pump_app(
            tester,
            theme_with(
                TargetPlatform::Android,
                ZoomPageTransitionsBuilder::new().allow_snapshotting(theme_allow_snapshotting),
            ),
            move |app| {
                app.on_generate_route(move |app, settings| {
                    if settings.name.as_deref() == Some("/") {
                        return Some(
                            (MaterialPageRoute::new(
                                app,
                                Rc::new(|_app, _context| {
                                    Material::new().child(Text::new("Page 1")).into_widget()
                                }),
                            ))
                            .into_erased(),
                        );
                    }
                    Some(
                        (MaterialPageRoute::new(
                            app,
                            Rc::new(|_app, _context| {
                                Material::new().child(Text::new("Page 2")).into_widget()
                            }),
                        )
                        .allow_snapshotting(app, second_route_allow_snapshotting))
                        .into_erased(),
                    )
                })
            },
        );
    }

    /// Whether a `SnapshotWidget` above `text` is set to take a snapshot: Dart's
    /// `isTransitioningWithSnapshotting` reads that from the layers a snapshot leaves out of the
    /// route's layer tree, and Waft's `SnapshotWidget` paints the child live, so the case reads
    /// the controllers.
    fn is_transitioning_with_snapshotting(tester: &WidgetTester, text: &str) -> bool {
        is_snapshotting(tester, text)
    }

    #[test]
    fn zoom_page_transitions_snapshot_both_routes_by_default() {
        test_widgets(|tester| {
            zoom_snapshotting_app(tester, true, true);

            // Transitioning from page 1 to page 2.
            let navigator = navigator(tester);
            navigator.push_named(&mut tester.cell.borrow_mut(), "/2", None);
            tester.pump();
            tester.pump_by(Duration::from_millis(50));

            // Exiting route should be snapshotted.
            assert!(is_transitioning_with_snapshotting(tester, "Page 1"));

            // Entering route should be snapshotted.
            assert!(is_transitioning_with_snapshotting(tester, "Page 2"));

            tester.pump_and_settle();

            // Transitioning back from page 2 to page 1.
            navigator.pop(&mut tester.cell.borrow_mut(), None);
            tester.pump();
            tester.pump_by(Duration::from_millis(50));

            // Exiting route should be snapshotted.
            assert!(is_transitioning_with_snapshotting(tester, "Page 2"));

            // Entering route should be snapshotted.
            assert!(is_transitioning_with_snapshotting(tester, "Page 1"));
        });
    }

    #[test]
    fn zoom_page_transitions_allow_snapshotting_false_snapshots_neither_route() {
        test_widgets(|tester| {
            zoom_snapshotting_app(tester, false, true);

            let navigator = navigator(tester);
            navigator.push_named(&mut tester.cell.borrow_mut(), "/2", None);
            tester.pump();
            tester.pump_by(Duration::from_millis(50));

            assert!(!is_transitioning_with_snapshotting(tester, "Page 1"));
            assert!(!is_transitioning_with_snapshotting(tester, "Page 2"));

            tester.pump_and_settle();

            navigator.pop(&mut tester.cell.borrow_mut(), None);
            tester.pump();
            tester.pump_by(Duration::from_millis(50));

            assert!(!is_transitioning_with_snapshotting(tester, "Page 2"));
            assert!(!is_transitioning_with_snapshotting(tester, "Page 1"));
        });
    }

    #[test]
    fn a_route_allow_snapshotting_false_overrides_the_zoom_builders_true() {
        test_widgets(|tester| {
            zoom_snapshotting_app(tester, true, false);

            let navigator = navigator(tester);
            navigator.push_named(&mut tester.cell.borrow_mut(), "/2", None);
            tester.pump();
            tester.pump_by(Duration::from_millis(50));

            // First route should be snapshotted.
            assert!(is_transitioning_with_snapshotting(tester, "Page 1"));

            // Second route should not be snapshotted.
            assert!(!is_transitioning_with_snapshotting(tester, "Page 2"));

            tester.pump_and_settle();
        });
    }

    #[test]
    fn the_zoom_page_transition_builds_the_page_once() {
        test_widgets(|tester| {
            let built_count = Rc::new(std::cell::Cell::new(0));
            let routes = {
                let built_count = Rc::clone(&built_count);
                vec![
                    (
                        "/".to_string(),
                        button_page("push", |app, context| {
                            Navigator::push_named(app, context, "/b", None);
                        }),
                    ),
                    (
                        "/b".to_string(),
                        Rc::new(move |_app: &mut App, _context: BuildContext| {
                            let built_count = Rc::clone(&built_count);
                            StatefulBuilder::new(move |_app, context, _set_state| {
                                // Increase the count each time the widget builds.
                                built_count.set(built_count.get() + 1);
                                TextButton::new(
                                    Some(Listener::new(move |app| {
                                        Navigator::pop(app, context, None)
                                    })),
                                    Some(Text::new("pop")),
                                )
                                .into_widget()
                            })
                            .into_widget()
                        }) as WidgetBuilder,
                    ),
                ]
            };
            pump_app(
                tester,
                theme_with(TargetPlatform::Android, ZoomPageTransitionsBuilder::new()),
                move |app| app.routes(routes),
            );

            // No matter push or pop was called, the child widget should built only once.
            tester.tap(find::text("push"));
            tester.pump_and_settle();
            assert_eq!(built_count.get(), 1);

            tester.tap(find::text("pop"));
            tester.pump_and_settle();
            assert_eq!(built_count.get(), 1);
        });
    }

    /// The layers under the `SnapshotWidget` nearest above `text`: Dart's
    /// `tester.layerListOf(find.ancestor(of: text, matching: find.byType(SnapshotWidget)).first)`.
    fn layers_above(tester: &WidgetTester, text: &str) -> Vec<AnyLayer> {
        let text = *find::text(text).evaluate(tester).first().expect("the text");
        let snapshot: AnyElement = tester.ancestor_of_type::<SnapshotWidget>(text);
        tester.layer_list_of(snapshot)
    }

    /// The scale of the first `TransformLayer` in `layers`.
    fn first_scale(tester: &WidgetTester, layers: &[AnyLayer]) -> f32 {
        let app = tester.cell.borrow();
        let transform = layers
            .iter()
            .find_map(|layer| app.handle::<TransformLayer>(layer.id()))
            .expect("a transform layer")
            .transform(&app)
            .expect("a transform");
        transform.to_flutter_array()[0]
    }

    /// The alpha of the first `OpacityLayer` in `layers`.
    fn first_alpha(tester: &WidgetTester, layers: &[AnyLayer]) -> i32 {
        let app = tester.cell.borrow();
        layers
            .iter()
            .find_map(|layer| app.handle::<OpacityLayer>(layer.id()))
            .expect("an opacity layer")
            .alpha(&app)
            .expect("an alpha")
    }

    // page_test 'test page transition (_ZoomPageTransition) without rasterization'.
    #[test]
    fn the_zoom_page_transition_scales_and_fades_the_pages_mid_animation() {
        test_widgets(|tester| {
            pump_app(
                tester,
                theme_with(TargetPlatform::Android, ZoomPageTransitionsBuilder::new()),
                |app| {
                    app.on_generate_route(|app, settings| {
                        let first = settings.name.as_deref() == Some("/");
                        Some(
                            (MaterialPageRoute::new(
                                app,
                                Rc::new(move |_app, _context| {
                                    Material::new()
                                        .child(Text::new(if first { "Page 1" } else { "Page 2" }))
                                        .into_widget()
                                }),
                            )
                            .allow_snapshotting(app, false))
                            .into_erased(),
                        )
                    })
                },
            );

            let navigator = navigator(tester);
            navigator.push_named(&mut tester.cell.borrow_mut(), "/next", None);
            tester.pump();
            tester.pump_by(Duration::from_millis(50));

            let page_1 = layers_above(tester, "Page 1");
            let page_2 = layers_above(tester, "Page 2");
            // Page 1 is enlarging, starts from 1.0.
            assert!(first_scale(tester, &page_1) > 1.0);
            // Page 2 is enlarging from the value less than 1.0.
            assert!(first_scale(tester, &page_2) < 1.0);
            // Page 2 is becoming none transparent.
            assert!(first_alpha(tester, &page_2) < 255);

            tester.pump_by(Duration::from_millis(250));
            tester.pump_by(Duration::from_millis(1));

            // Page 2 covers page 1.
            assert_eq!(count_onstage_text(tester, "Page 1"), 0);
            assert_eq!(count_onstage_text(tester, "Page 2"), 1);

            navigator.pop(&mut tester.cell.borrow_mut(), None);
            tester.pump();
            tester.pump_by(Duration::from_millis(100));

            let page_1 = layers_above(tester, "Page 1");
            let page_2 = layers_above(tester, "Page 2");
            // Page 1 is narrowing down, but still larger than 1.0.
            assert!(first_scale(tester, &page_1) > 1.0);
            // Page 2 is smaller than 1.0.
            assert!(first_scale(tester, &page_2) < 1.0);
            // Page 2 is becoming transparent.
            assert!(first_alpha(tester, &page_2) < 255);

            tester.pump_by(Duration::from_millis(200));
            tester.pump_by(Duration::from_millis(1));

            assert_eq!(count_onstage_text(tester, "Page 1"), 1);
            assert_eq!(count_onstage_text(tester, "Page 2"), 0);
        });
    }

    /// The zoom scrim cases: the rect the entering page's zoom transition paints `at` into the
    /// push of a page whose builder is `page`, under a zoom builder of `builder` on `platform`
    /// with the colour scheme's surface `surface`.
    fn zoom_scrim_color(
        platform: TargetPlatform,
        builder: ZoomPageTransitionsBuilder,
        surface: Color,
        at: Duration,
        expected: Color,
    ) {
        test_widgets_variant(TargetPlatformVariant::only(platform), |tester| {
            pump_app(
                tester,
                move |app| {
                    let color_scheme = ThemeData::new(app).color_scheme.with_surface(surface);
                    ThemeData::builder()
                        .color_scheme(color_scheme)
                        .page_transitions_theme(
                            PageTransitionsTheme::new().with_builders(
                                TARGET_PLATFORM_VALUES
                                    .into_iter()
                                    .map(|platform| {
                                        (platform, PageTransitionsBuilderRef::new(builder))
                                    })
                                    .collect(),
                            ),
                        )
                        .build(app)
                },
                |app| app.routes(push_routes()),
            );

            tester.tap(find::text("push"));
            tester.pump();
            tester.pump_by(at);

            let enter = *find::by_type::<ZoomEnterTransition>()
                .evaluate(tester)
                .iter()
                .find(|element| {
                    let app = tester.cell.borrow();
                    tester.widget::<ZoomEnterTransition, _>(**element, |enter| {
                        !enter.reverse && enter.animation.is_animating(&app)
                    })
                })
                .expect("the entering page's zoom transition");
            let render = tester.render_box_of(enter).as_object();
            let ops = tester.painted_ops(render);
            assert_paints(&ops, &[PaintCall::rect(Some(expected))]);

            tester.pump_and_settle();
            assert_eq!(count_onstage_text(tester, "page b"), 1);
        });
    }

    // 'ZoomPageTransitionsBuilder uses theme color during transition effects', on the page
    // without a scaffold.
    #[test]
    fn the_zoom_page_transition_scrim_is_the_color_scheme_surface() {
        let surface = Color::from_argb(255, 195, 255, 0);
        for platform in TARGET_PLATFORM_VALUES {
            // Expect the color to be at exactly 12.2% opacity at this time.
            #[allow(deprecated)]
            let expected = surface.with_opacity(0.122);
            zoom_scrim_color(
                platform,
                ZoomPageTransitionsBuilder::new(),
                surface,
                Duration::from_millis(75),
                expected,
            );
        }
    }

    #[test]
    fn the_zoom_page_transition_scrim_is_the_builders_background_color() {
        let red = Colors::RED.primary();
        for platform in TARGET_PLATFORM_VALUES {
            // Expect the color to be at exactly 59.6% opacity at this time.
            #[allow(deprecated)]
            let expected = red.with_opacity(0.596);
            zoom_scrim_color(
                platform,
                ZoomPageTransitionsBuilder::new().background_color(red),
                Colors::BLUE.primary(),
                Duration::from_millis(125),
                expected,
            );
        }
    }

    #[test]
    fn the_incoming_route_takes_input_during_a_fade_forwards_back_navigation() {
        test_widgets(|tester| {
            pump_app(
                tester,
                move |app| {
                    let color_scheme = ThemeData::new(app)
                        .color_scheme
                        .with_surface(Colors::PINK.primary());
                    ThemeData::builder()
                        .page_transitions_theme(PageTransitionsTheme::new().with_builders(
                            IndexMap::from([(
                                TargetPlatform::Android,
                                PageTransitionsBuilderRef::new(
                                    FadeForwardsPageTransitionsBuilder::new(),
                                ),
                            )]),
                        ))
                        .color_scheme(color_scheme)
                        .build(app)
                },
                |app| {
                    app.routes([
                        (
                            "/".to_string(),
                            button_page("push", |app, context| {
                                Navigator::push_named(app, context, "/b", None);
                            }),
                        ),
                        (
                            "/b".to_string(),
                            button_page("go back", |app, context| {
                                Navigator::pop(app, context, None)
                            }),
                        ),
                    ])
                },
            );

            assert_eq!(count_onstage_text(tester, "push"), 1);
            assert_eq!(count_onstage_text(tester, "go back"), 0);

            // Go to the second route.
            tester.tap(find::text("push"));
            tester.pump();
            tester.pump_by(Duration::from_millis(801));

            assert_eq!(count_onstage_text(tester, "push"), 0);
            assert_eq!(count_onstage_text(tester, "go back"), 1);

            // Tap to go back to the first route.
            tester.tap(find::text("go back"));
            tester.pump();
            tester.pump_by(Duration::from_millis(400));

            assert_eq!(count_onstage_text(tester, "push"), 1);
            assert_eq!(count_onstage_text(tester, "go back"), 1);

            // In the middle of the transition, tap to go back to the second route.
            tester.tap(find::text("push"));

            tester.pump();
            tester.pump_by(Duration::from_millis(401));

            assert_eq!(count_onstage_text(tester, "push"), 1);
            assert_eq!(count_onstage_text(tester, "go back"), 1);

            tester.pump();
            tester.pump_by(Duration::from_millis(400));

            assert_eq!(count_onstage_text(tester, "push"), 0);
            assert_eq!(count_onstage_text(tester, "go back"), 1);
        });
    }

    /// Whether any `SnapshotWidget` above `text` is set to take a snapshot.
    fn is_snapshotting(tester: &WidgetTester, text: &str) -> bool {
        let text = *find::text(text).evaluate(tester).first().expect("the text");
        let ancestors = tester.ancestors(text);
        let app = tester.cell.borrow();
        ancestors.into_iter().any(|ancestor| {
            waft_widgets::downcast_widget::<SnapshotWidget>(&**ancestor.widget(&app))
                .is_some_and(|snapshot| snapshot.controller.allow_snapshotting(&app))
        })
    }

    fn fade_forwards_snapshotting_app(
        tester: &mut WidgetTester,
        builder_allow_snapshotting: bool,
        second_route_allow_snapshotting: bool,
    ) {
        pump_app(
            tester,
            theme_with(
                TargetPlatform::Android,
                FadeForwardsPageTransitionsBuilder::new()
                    .allow_snapshotting(builder_allow_snapshotting),
            ),
            move |app| {
                app.on_generate_route(move |app, settings| {
                    if settings.name.as_deref() == Some("/") {
                        return Some(
                            (MaterialPageRoute::new(
                                app,
                                Rc::new(|_app, _context| {
                                    Material::new().child(Text::new("Page 1")).into_widget()
                                }),
                            ))
                            .into_erased(),
                        );
                    }
                    Some(
                        (MaterialPageRoute::new(
                            app,
                            Rc::new(|_app, _context| {
                                Material::new().child(Text::new("Page 2")).into_widget()
                            }),
                        )
                        .allow_snapshotting(app, second_route_allow_snapshotting))
                        .into_erased(),
                    )
                })
            },
        );
    }

    /// A tenth of the fade-forwards transition.
    const A_TENTH_OF_THE_TRANSITION: Duration =
        Duration::from_millis(FadeForwardsPageTransitionsBuilder::K_TRANSITION_MILLISECONDS / 10);

    #[test]
    fn fade_forwards_snapshots_the_entering_and_exiting_routes_only_while_animating() {
        test_widgets(|tester| {
            fade_forwards_snapshotting_app(tester, true, true);
            assert!(!is_snapshotting(tester, "Page 1"));

            // Push. Part way into the transition, both pages are partially transparent.
            let navigator = navigator(tester);
            navigator.push_named(&mut tester.cell.borrow_mut(), "/2", None);
            tester.pump();
            tester.pump_by(A_TENTH_OF_THE_TRANSITION);
            assert!(is_snapshotting(tester, "Page 1"));
            assert!(is_snapshotting(tester, "Page 2"));

            tester.pump_and_settle();
            assert!(!is_snapshotting(tester, "Page 2"));

            // Pop.
            navigator.pop(&mut tester.cell.borrow_mut(), None);
            tester.pump();
            tester.pump_by(A_TENTH_OF_THE_TRANSITION);
            assert!(is_snapshotting(tester, "Page 1"));
            assert!(is_snapshotting(tester, "Page 2"));

            tester.pump_and_settle();
            assert_eq!(count_onstage_text(tester, "Page 2"), 0);
            assert!(!is_snapshotting(tester, "Page 1"));
        });
    }

    #[test]
    fn a_route_allow_snapshotting_false_disables_fade_forwards_snapshotting_for_that_route_only() {
        test_widgets(|tester| {
            fade_forwards_snapshotting_app(tester, true, false);

            let navigator = navigator(tester);
            navigator.push_named(&mut tester.cell.borrow_mut(), "/2", None);
            tester.pump();
            tester.pump_by(A_TENTH_OF_THE_TRANSITION);
            assert!(is_snapshotting(tester, "Page 1"));
            assert!(!is_snapshotting(tester, "Page 2"));

            tester.pump_and_settle();
        });
    }

    #[test]
    fn fade_forwards_allow_snapshotting_false_disables_snapshotting_for_all_routes() {
        test_widgets(|tester| {
            fade_forwards_snapshotting_app(tester, false, true);

            // Push.
            let navigator = navigator(tester);
            navigator.push_named(&mut tester.cell.borrow_mut(), "/2", None);
            tester.pump();
            tester.pump_by(A_TENTH_OF_THE_TRANSITION);
            assert!(!is_snapshotting(tester, "Page 1"));
            assert!(!is_snapshotting(tester, "Page 2"));

            tester.pump_and_settle();

            // Pop.
            navigator.pop(&mut tester.cell.borrow_mut(), None);
            tester.pump();
            tester.pump_by(A_TENTH_OF_THE_TRANSITION);
            assert!(!is_snapshotting(tester, "Page 1"));
            assert!(!is_snapshotting(tester, "Page 2"));

            tester.pump_and_settle();
        });
    }

    #[test]
    fn the_delegated_transition_of_the_theme_is_its_platform_builders() {
        let theme = PageTransitionsTheme::new();
        // The Cupertino builder's is a function, equal across calls.
        assert_eq!(
            theme.delegated_transition(TargetPlatform::IOS),
            CupertinoPageTransitionsBuilder::new().delegated_transition()
        );
        // The zoom and fade-forwards builders hand out a new closure on every call, as Dart's
        // getters do.
        let zoom = ZoomPageTransitionsBuilder::new();
        assert_ne!(zoom.delegated_transition(), zoom.delegated_transition());
        assert!(
            theme
                .delegated_transition(TargetPlatform::Fuchsia)
                .is_some()
        );
        assert!(
            PredictiveBackPageTransitionsBuilder::new()
                .delegated_transition()
                .is_none()
        );
    }

    #[test]
    fn the_zoom_painters_compare_their_animation_values_to_repaint() {
        test_widgets(|tester| {
            let mut app = tester.cell.borrow_mut();
            let controller = AnimationController::new(
                &mut app,
                None,
                Some(Duration::from_millis(100)),
                None,
                0.0,
                1.0,
                AnimationBehavior::Normal,
                TestVSync,
            );
            let animation = controller.erase::<AnyAnimation<f64>>();
            let complete = k_always_complete_animation(&mut app);
            let first = ZoomExitTransitionPainter::new(
                &mut app,
                false,
                animation.clone(),
                complete.clone(),
                animation.clone(),
            );
            let second = ZoomExitTransitionPainter::new(
                &mut app,
                false,
                animation.clone(),
                complete.clone(),
                animation.clone(),
            );
            assert!(!second.should_repaint(&app, first.erase::<AnySnapshotPainter>().handle()));
            let reversed = ZoomExitTransitionPainter::new(
                &mut app,
                true,
                animation.clone(),
                complete,
                animation,
            );
            assert!(reversed.should_repaint(&app, first.erase::<AnySnapshotPainter>().handle()));
        });
    }

    #[test]
    fn a_zoom_enter_transition_that_flips_its_direction_repaints_with_a_new_painter() {
        test_widgets(|tester| {
            let animation = {
                let mut app = tester.cell.borrow_mut();
                AnimationController::new(
                    &mut app,
                    None,
                    Some(Duration::from_millis(100)),
                    None,
                    0.5,
                    1.0,
                    AnimationBehavior::Normal,
                    TestVSync,
                )
                .into_erased::<AnyAnimation<f64>>()
            };
            let transition = |reverse| ZoomEnterTransition {
                animation: animation.clone(),
                child: Some(SizedBox::new().width(10.0).height(10.0).into_widget()),
                allow_snapshotting: true,
                reverse,
                background_color: Color::from_argb(0xFF, 0, 0, 0),
            };
            tester.pump_widget(transition(false).into_widget());
            tester.pump_widget(transition(true).into_widget());
        });
    }
}