waft-widgets 0.16.0

Widget framework and widgets for Waft
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
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
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
//! Flutter counterpart: `widgets/overlay.dart`.

use std::any::{Any, TypeId};
use std::cell::Cell;
use std::fmt::{self, Debug, Display};
use std::panic::Location;
use std::rc::Rc;

use waft_embedder::{Clip, Matrix4, Offset, Rect, Size, TextDirection};
use waft_foundation::{
    App, DiagnosticPropertiesBuilder, DiagnosticsNode, DiagnosticsProperty, DiagnosticsTreeStyle,
    EnumProperty, Handle, IntProperty, ListenableObject, Listener, OptionRetained, Retained,
    ValueNotifier, message,
};
use waft_painting::{Alignment, AlignmentGeometry};
use waft_rendering::{
    AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestResult, ClipRectLayer, Constraints,
    ContainerBoxParentData, ContainerParentData, ContainerParentDataMixin,
    ContainerRenderObjectData, ContainerRenderObjectMixin, LayerHandle, PaintingContext,
    ParentData, PipelineOwner, RenderBox, RenderBoxData, RenderHandle, RenderObject,
    RenderObjectData, RenderObjectWithChildData, RenderObjectWithChildMixin,
    RenderObjectWithLayoutCallbackData, RenderObjectWithLayoutCallbackMixin, RenderProxyBoxMixin,
    StackParentData,
};
use waft_scheduler::{
    FrameCallback, SchedulerBinding, SchedulerPhase, Ticker, TickerCallback, TickerProviderObject,
};

use crate::framework::{
    AnyElement, BuildContext, BuildScope, BuildScopeCallback, CreationLocation, Element,
    ElementData, GlobalKey, InheritedWidget, IntoWidget, KeyRef, MultiChildRenderObjectElementBase,
    MultiChildRenderObjectElementData, MultiChildRenderObjectWidget, RenderObjectElement,
    RenderObjectElementData, RenderObjectElementWidget, RenderObjectWidget,
    SingleChildRenderObjectWidget, Slot, State, StateData, StatefulWidget, Widget, WidgetKind,
    WidgetRef, downcast_widget,
};
use crate::view::View;
use crate::widgets::basic::{Builder, Directionality, WidgetBuilder};
use crate::widgets::lookup_boundary::LookupBoundary;
use crate::widgets::media_query::MediaQuery;
use crate::widgets::ticker_provider::{
    TickerMode, TickerProviderStateMixin, TickerProviderStateMixinData,
};
use waft_foundation::Ref;

/// The signature of the widget builder callback used in
/// [`OverlayPortal::overlay_child_layout_builder`].
pub type OverlayChildLayoutBuilder =
    Rc<dyn Fn(&mut App, BuildContext, OverlayChildLayoutInfo) -> WidgetRef>;

/// The additional layout information available to the
/// [`OverlayPortal::overlay_child_layout_builder`] callback.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct OverlayChildLayoutInfo {
    child_size: Size,
    child_paint_transform: Matrix4,
    overlay_size: Size,
}

impl OverlayChildLayoutInfo {
    /// The size of [`OverlayPortal::child`] in its own coordinates.
    pub fn child_size(&self) -> Size {
        self.child_size
    }

    /// The paint transform of [`OverlayPortal::child`], in the target [`Overlay`]'s
    /// coordinates.
    pub fn child_paint_transform(&self) -> Matrix4 {
        self.child_paint_transform
    }

    /// The size of the target [`Overlay`] in its own coordinates.
    pub fn overlay_size(&self) -> Size {
        self.overlay_size
    }
}

// * OverlayEntry Implementation

/// A place in an [`Overlay`] that can contain a widget.
///
/// Overlay entries are inserted into an [`Overlay`] using the [`OverlayState::insert`] or
/// [`OverlayState::insert_all`] functions. To find the closest enclosing overlay for a given
/// [`BuildContext`], use the [`Overlay::of`] function.
///
/// An overlay entry can be in at most one overlay at a time. To remove an entry from its
/// overlay, call the [`remove`](Self::remove) function on the overlay entry.
///
/// Because an [`Overlay`] uses a stack layout, overlay entries can use `Positioned` to
/// position themselves within the overlay.
///
/// By default, if there is an entirely [`opaque`](Self::opaque) entry over this one, then this
/// one will not be included in the widget tree (in particular, stateful widgets within the
/// overlay entry will not be instantiated). To ensure that your overlay entry is still built
/// even if it is not visible, set [`maintain_state`](Self::maintain_state) to true. This is
/// more expensive, so should be done with care.
///
/// `Handle<OverlayEntry>` is a [`Listenable`](waft_foundation::Listenable) that notifies
/// when the widget built by [`builder`](Self::builder) is mounted or unmounted, whose exact
/// state can be queried by [`mounted`](Self::mounted). After the owner of the [`OverlayEntry`] calls
/// [`remove`](Self::remove) and then [`dispose`](Self::dispose), the widget may not be
/// immediately removed from the widget tree. As a result listeners of the [`OverlayEntry`] can
/// get notified for one last time after the `dispose` call, when the widget is eventually
/// unmounted.
///
/// See also:
///
///  * [`Overlay`], a stack of entries that can be managed independently.
///  * [`OverlayState`], the current state of an Overlay.
pub struct OverlayEntry {
    /// This entry will include the widget built by this builder in the overlay at the entry's
    /// position.
    ///
    /// To cause this builder to be called again, call [`mark_needs_build`] on this overlay
    /// entry.
    ///
    /// [`mark_needs_build`]: Self::mark_needs_build
    pub builder: WidgetBuilder,
    opaque: bool,
    maintain_state: bool,
    can_size_overlay: bool,
    /// The currently mounted [`OverlayEntryWidgetState`] built using this [`OverlayEntry`].
    overlay_entry_state_notifier:
        Option<Ref<ValueNotifier<Option<Handle<OverlayEntryWidgetState>>>>>,
    overlay: Option<Handle<OverlayState>>,
    key: GlobalKey,
    disposed_by_owner: bool,
}

impl OverlayEntry {
    /// Creates an overlay entry.
    ///
    /// To insert the entry into an [`Overlay`], first find the overlay using [`Overlay::of`]
    /// and then call [`OverlayState::insert`]. To remove the entry, call
    /// [`remove`](Self::remove) on the overlay entry itself.
    ///
    /// Dart's defaults: `opaque` false, `maintain_state` false, `can_size_overlay` false.
    pub fn new(
        app: &mut App,
        builder: WidgetBuilder,
        opaque: bool,
        maintain_state: bool,
        can_size_overlay: bool,
    ) -> Ref<OverlayEntry> {
        let notifier = app.create(ValueNotifier::new(None));
        app.create(OverlayEntry {
            builder,
            opaque,
            maintain_state,
            can_size_overlay,
            overlay_entry_state_notifier: Some(notifier),
            overlay: None,
            key: GlobalKey::new(),
            disposed_by_owner: false,
        })
    }

    /// Whether this entry occludes the entire overlay.
    ///
    /// If an entry claims to be opaque, then, for efficiency, the overlay will skip building
    /// entries below that entry unless they have [`maintain_state`](Self::maintain_state) set.
    pub fn opaque(self: Handle<Self>, app: &App) -> bool {
        app.get(self).opaque
    }

    /// Sets [`opaque`](Self::opaque).
    pub fn set_opaque(self: Handle<Self>, app: &mut App, value: bool) {
        debug_assert!(!app.get(self).disposed_by_owner);
        if app.get(self).opaque == value {
            return;
        }
        app.get_mut(self).opaque = value;
        if let Some(overlay) = app.get(self).overlay {
            overlay.did_change_entry_opacity(app);
        }
    }

    /// Whether this entry must be included in the tree even if there is a fully
    /// [`opaque`](Self::opaque) entry above it.
    ///
    /// By default, if there is an entirely opaque entry over this one, then this one will not
    /// be included in the widget tree (in particular, stateful widgets within the overlay
    /// entry will not be instantiated). To ensure that your overlay entry is still built even
    /// if it is not visible, set this to true. This is more expensive, so should be done with
    /// care.
    ///
    /// This is used by the `Navigator` and `Route` objects to ensure that routes are kept
    /// around even when in the background.
    pub fn maintain_state(self: Handle<Self>, app: &App) -> bool {
        app.get(self).maintain_state
    }

    /// Sets [`maintain_state`](Self::maintain_state).
    pub fn set_maintain_state(self: Handle<Self>, app: &mut App, value: bool) {
        debug_assert!(!app.get(self).disposed_by_owner);
        if app.get(self).maintain_state == value {
            return;
        }
        app.get_mut(self).maintain_state = value;
        let overlay = app.get(self).overlay.expect("inserted into an Overlay");
        overlay.did_change_entry_opacity(app);
    }

    /// Whether the content of this [`OverlayEntry`] can be used to size the [`Overlay`].
    ///
    /// In most situations the overlay sizes itself based on its incoming constraints to be as
    /// large as possible. However, if that would result in an infinite size, it has to rely on
    /// one of its children to size itself. In this situation, the overlay will consult the
    /// topmost non-positioned overlay entry that has this property set to true, lay it out with
    /// the incoming [`BoxConstraints`] of the overlay, and force all other non-positioned
    /// overlay entries to have the same size.
    ///
    /// Overlay entries that set this to true must be able to handle unconstrained
    /// [`BoxConstraints`].
    pub fn can_size_overlay(self: Handle<Self>, app: &App) -> bool {
        app.get(self).can_size_overlay
    }

    /// Whether the [`OverlayEntry`] is currently mounted in the widget tree.
    ///
    /// The [`OverlayEntry`] notifies its listeners when this value changes.
    pub fn mounted(self: Handle<Self>, app: &App) -> bool {
        app.get(self)
            .overlay_entry_state_notifier
            .as_ref()
            .is_some_and(|notifier| app.get(notifier).value().is_some())
    }

    /// Remove this entry from the overlay.
    ///
    /// This should only be called once.
    ///
    /// This method removes this overlay entry from the overlay immediately. The UI will be
    /// updated in the same frame if this method is called before the overlay rebuild in this
    /// frame; otherwise, the UI will be updated in the next frame.
    pub fn remove(self: Handle<Self>, app: &mut App) {
        let overlay = app
            .get(self)
            .overlay
            .expect("An OverlayEntry should be removed only once.");
        debug_assert!(!app.get(self).disposed_by_owner);
        app.get_mut(self).overlay = None;
        if !overlay.mounted(app) {
            return;
        }

        app.get_mut(overlay).entries.retain(|entry| entry != self);
        if SchedulerBinding::scheduler_phase(app) == SchedulerPhase::PersistentCallbacks {
            SchedulerBinding::add_post_frame_callback(
                app,
                FrameCallback::handle_method(overlay, OverlayState::mark_dirty_after_frame),
                View::maybe_id_of(app, overlay.context(app)),
            );
        } else {
            overlay.mark_dirty(app);
        }
    }

    /// Cause this entry to rebuild during the next pipeline flush.
    ///
    /// You need to call this function if the output of [`builder`](Self::builder) has changed.
    pub fn mark_needs_build(self: Handle<Self>, app: &mut App) {
        debug_assert!(!app.get(self).disposed_by_owner);
        let key = app.get(self).key.clone();
        if let Some(state) = key.current_state::<OverlayEntryWidgetState>(app) {
            state.mark_needs_build(app);
        }
    }

    fn did_unmount(self: Handle<Self>, app: &mut App) {
        debug_assert!(!self.mounted(app));
        if app.get(self).disposed_by_owner {
            self.dispose_notifier(app);
        }
    }

    fn dispose_notifier(self: Handle<Self>, app: &mut App) {
        if let Some(notifier) = app.get_mut(self).overlay_entry_state_notifier.take() {
            notifier.dispose(app);
        }
    }

    /// Discards any resources used by this [`OverlayEntry`].
    ///
    /// The [`remove`](Self::remove) method must be called before this method if the
    /// [`OverlayEntry`] is inserted into an [`Overlay`].
    ///
    /// After this is called, the object is not in a usable state and should be discarded.
    /// However, the listeners registered may not be immediately released until the widget built
    /// using this [`OverlayEntry`] is unmounted from the widget tree.
    ///
    /// This method should only be called by the object's owner.
    pub fn dispose(self: Handle<Self>, app: &mut App) {
        debug_assert!(!app.get(self).disposed_by_owner);
        debug_assert!(
            app.get(self).overlay.is_none(),
            "An OverlayEntry must first be removed from the Overlay before dispose is called."
        );
        app.get_mut(self).disposed_by_owner = true;
        if !self.mounted(app) {
            // If we're still mounted when disposed, then this will be disposed in did_unmount,
            // to allow notifications to occur until the entry is unmounted.
            self.dispose_notifier(app);
        }
    }
}

impl ListenableObject for OverlayEntry {
    fn add_listener(self: Handle<Self>, app: &mut App, listener: Listener) {
        debug_assert!(!app.get(self).disposed_by_owner);
        if let Some(notifier) = app.get(self).overlay_entry_state_notifier.handle() {
            notifier.add_listener(app, listener);
        }
    }

    fn remove_listener(self: Handle<Self>, app: &mut App, listener: &Listener) {
        if let Some(notifier) = app.get(self).overlay_entry_state_notifier.handle() {
            notifier.remove_listener(app, listener);
        }
    }
}

impl Debug for OverlayEntry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "OverlayEntry(opaque: {}; maintainState: {}){}",
            self.opaque,
            self.maintain_state,
            if self.disposed_by_owner {
                "(DISPOSED)"
            } else {
                ""
            }
        )
    }
}

/// Dart's `_OverlayEntryWidget`: the tree node one [`OverlayEntry`] builds into.
#[derive(Debug)]
struct OverlayEntryWidget {
    key: KeyRef,
    entry: Ref<OverlayEntry>,
    overlay_state: Handle<OverlayState>,
    ticker_enabled: bool,
}

impl StatefulWidget for OverlayEntryWidget {
    type State = OverlayEntryWidgetState;

    fn key(&self) -> Option<&KeyRef> {
        Some(&self.key)
    }

    fn create_state(&self) -> OverlayEntryWidgetState {
        OverlayEntryWidgetState {
            state: StateData::new(),
            theater: None,
            sorted_theater_siblings: None,
        }
    }
}

/// Dart's `_OverlayEntryWidgetState`.
struct OverlayEntryWidgetState {
    state: StateData<OverlayEntryWidget>,
    theater: Option<RenderHandle<RenderTheater>>,
    // Manages the stack of theater children whose paint order is sorted by their
    // z_order_index. The children added by OverlayPortal are added to this list, and they
    // will be shown *above* the OverlayEntry tied to this widget. The children with larger
    // z_order_index values (that is, those `show`n recently) will be painted last.
    //
    // This list is lazily created in `add`, and the entries are added/removed via
    // `add`/`remove`, called by OverlayPortals lower in the tree. `add` or `remove` does not
    // cause this widget to rebuild, the list will be read by RenderTheater as part of its
    // render child model. This would ideally be in a RenderObject but there may not be
    // RenderObjects between RenderTheater and the render subtree OverlayEntry builds.
    sorted_theater_siblings: Option<Vec<Ref<OverlayEntryLocation>>>,
}

impl OverlayEntryWidgetState {
    fn theater(self: Handle<Self>, app: &App) -> RenderHandle<RenderTheater> {
        app.get(self).theater.expect("mounted under an Overlay")
    }

    // Worst-case O(N), N being the number of children added to the top spot in the same
    // frame. This can be a bit expensive when there's a lot of global key reparenting in the
    // same frame but N is usually a small number.
    fn add(self: Handle<Self>, app: &mut App, child: Ref<OverlayEntryLocation>) {
        debug_assert!(self.mounted(app));
        let z_order_index = app.get(&child).z_order_index;
        let existing = app
            .get(self)
            .sorted_theater_siblings
            .clone()
            .unwrap_or_default();
        debug_assert!(!existing.contains(&child));
        let mut insert_position = existing.len();
        while insert_position > 0
            && app.get(&existing[insert_position - 1]).z_order_index > z_order_index
        {
            insert_position -= 1;
        }
        app.get_mut(self)
            .sorted_theater_siblings
            .get_or_insert_with(Vec::new)
            .insert(insert_position, child);
    }

    fn remove(self: Handle<Self>, app: &mut App, child: Handle<OverlayEntryLocation>) {
        let children = app.get_mut(self).sorted_theater_siblings.as_mut();
        debug_assert!(children.is_some());
        let Some(children) = children else { return };
        let position = children.iter().position(|other| other == child);
        debug_assert!(position.is_some(), "the child was in the collection");
        if let Some(position) = position {
            children.remove(position);
        }
    }

    // The children in the child model in paint order (from farthest to the user to the
    // closest to the user).
    fn paint_order_children(
        self: Handle<Self>,
        app: &App,
    ) -> Vec<RenderHandle<RenderDeferredLayoutBox>> {
        self.create_child_list(app, false)
    }

    fn create_child_list(
        self: Handle<Self>,
        app: &App,
        reversed: bool,
    ) -> Vec<RenderHandle<RenderDeferredLayoutBox>> {
        let Some(children) = app.get(self).sorted_theater_siblings.as_ref() else {
            return Vec::new();
        };
        let mut boxes: Vec<RenderHandle<RenderDeferredLayoutBox>> = children
            .iter()
            .filter_map(|candidate| app.get(candidate).overlay_child_render_box)
            .collect();
        if reversed {
            boxes.reverse();
        }
        boxes
    }

    fn mark_needs_build(self: Handle<Self>, app: &mut App) {
        // The state that changed is in the builder.
        self.set_state(app, |_state| {});
    }
}

impl State for OverlayEntryWidgetState {
    type Widget = OverlayEntryWidget;

    crate::state_accessors!();

    fn init_state(self: Handle<Self>, app: &mut App) {
        let entry = self.widget(app).entry.handle();
        let notifier = app
            .get(entry)
            .overlay_entry_state_notifier
            .handle()
            .expect("a live OverlayEntry");
        notifier.set_value(app, Some(self));
        let context = self.context(app);
        let theater = context
            .find_ancestor_render_object_of_type::<RenderTheater>(app)
            .expect("an _OverlayEntryWidget is built by an Overlay");
        app.get_mut(self).theater = Some(theater);
        debug_assert!(app.get(self).sorted_theater_siblings.is_none());
    }

    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &OverlayEntryWidget) {
        // OverlayState's build method always returns a RenderObjectWidget Theater, so it is
        // safe to assume that state equality implies render object equality.
        debug_assert!(old_widget.entry == self.widget(app).entry);
        let changed = old_widget.overlay_state != self.widget(app).overlay_state;
        if changed {
            let context = self.context(app);
            let new_theater = context
                .find_ancestor_render_object_of_type::<RenderTheater>(app)
                .expect("an _OverlayEntryWidget is built by an Overlay");
            debug_assert!(app.get(self).theater != Some(new_theater));
            app.get_mut(self).theater = Some(new_theater);
        }
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        let entry = self.widget(app).entry.handle();
        if let Some(notifier) = app.get(entry).overlay_entry_state_notifier.handle() {
            notifier.set_value(app, None);
        }
        entry.did_unmount(app);
        app.get_mut(self).sorted_theater_siblings = None;
    }

    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
        let widget = self.widget(app);
        let (ticker_enabled, entry) = (widget.ticker_enabled, widget.entry.handle());
        let theater = self.theater(app);
        let builder = Rc::clone(&app.get(entry).builder);
        TickerMode::new(
            ticker_enabled,
            // Use a Builder so that `entry.builder` can have access to RenderTheaterMarker::of.
            RenderTheaterMarker {
                theater,
                overlay_entry_widget_state: self,
                child: Builder { key: None, builder }.into_widget(),
            },
        )
        .into_widget()
    }
}

/// A stack of entries that can be managed independently.
///
/// Overlays let independent child widgets "float" visual elements on top of other widgets by
/// inserting them into the overlay's stack. The overlay lets each of these widgets manage their
/// participation in the overlay using [`OverlayEntry`] objects.
///
/// Although you can create an [`Overlay`] directly, it's most common to use the overlay created
/// by the `Navigator`. The navigator uses its overlay to manage the visual appearance of its
/// routes.
///
/// The [`Overlay`] widget uses a custom stack implementation, which is very similar to the
/// `Stack` widget. The main use case of [`Overlay`] is related to navigation and being able to
/// insert widgets on top of the pages in an app. For layout purposes unrelated to navigation,
/// consider using `Stack` instead.
///
/// An [`Overlay`] widget requires a [`Directionality`] widget to be in scope, so that it can
/// resolve direction-sensitive coordinates of any `Positioned::directional` children.
///
/// See also:
///
///  * [`OverlayEntry`], the class that is used for describing the overlay entries.
///  * [`OverlayState`], which is used to insert the entries into the overlay.
#[derive(Debug)]
pub struct Overlay {
    /// See [`Widget::key`].
    pub key: Option<KeyRef>,
    /// The entries to include in the overlay initially.
    ///
    /// These entries are only used when the [`OverlayState`] is initialized. If you are
    /// providing a new [`Overlay`] description for an overlay that's already in the tree, then
    /// the new entries are ignored.
    ///
    /// To add entries to an [`Overlay`] that is already in the tree, use [`Overlay::of`] to
    /// obtain the [`OverlayState`], and then use [`OverlayState::insert`] or
    /// [`OverlayState::insert_all`].
    ///
    /// To remove an entry from an [`Overlay`], use [`OverlayEntry::remove`].
    pub initial_entries: Vec<Ref<OverlayEntry>>,
    /// How to clip the entries that overflow the overlay.
    ///
    /// Defaults to [`Clip::HardEdge`].
    pub clip_behavior: Clip,
    /// Determines that the overlay should always size itself to content.
    ///
    /// Normally overlay will only size itself to content if the incoming constraints are
    /// infinite and there is an [`OverlayEntry`] that can size the overlay. Setting this to
    /// `true` will force this behavior even for finite (but possibly loose) constraints.
    ///
    /// Setting this to true requires an [`OverlayEntry`] that can size the overlay based on
    /// itself ([`OverlayEntry::can_size_overlay`] set to true). If not provided the overlay
    /// panics.
    pub always_size_to_content: bool,
}

impl Overlay {
    /// Creates an overlay; Dart's named arguments are the setters.
    ///
    /// The initial entries will be inserted into the overlay when its associated
    /// [`OverlayState`] is initialized.
    pub fn new() -> Overlay {
        Overlay::default()
    }

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

    /// Dart `Overlay(initialEntries:)`.
    pub fn initial_entries(
        mut self,
        entries: impl IntoIterator<Item = Ref<OverlayEntry>>,
    ) -> Overlay {
        self.initial_entries = entries.into_iter().collect();
        self
    }

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

    /// Dart `Overlay(alwaysSizeToContent:)`.
    pub fn always_size_to_content(mut self, always_size_to_content: bool) -> Overlay {
        self.always_size_to_content = always_size_to_content;
        self
    }

    /// Wrap the provided `child` in an [`Overlay`] to allow other visual elements (packed in
    /// [`OverlayEntry`]s) to float on top of the child.
    ///
    /// This is a convenience method over the regular [`Overlay`] constructor: it creates an
    /// [`Overlay`] and puts the provided `child` in an [`OverlayEntry`] at the bottom of that
    /// newly created Overlay.
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn wrap<K>(child: impl IntoWidget<K>) -> WrappingOverlay {
        WrappingOverlay {
            key: None,
            clip_behavior: Clip::HardEdge,
            always_size_to_content: false,
            child: child.into_widget(),
        }
    }

    /// The [`OverlayState`] from the closest instance of [`Overlay`] that encloses the given
    /// context, and panics if one is not found.
    ///
    /// If `root_overlay` is set to true, the state from the furthest instance of this class is
    /// given instead. Useful for installing overlay entries above all subsequent instances of
    /// [`Overlay`].
    ///
    /// See also:
    ///
    /// * [`Overlay::maybe_of`] for a similar function that returns `None` if an [`Overlay`] is
    ///   not found.
    pub fn of(app: &mut App, context: BuildContext, root_overlay: bool) -> Handle<OverlayState> {
        Overlay::maybe_of(app, context, root_overlay).expect(
            "No Overlay widget found. Some widgets require an Overlay widget ancestor for \
             correct operation. The most common way to add an Overlay to an application is to \
             include a WidgetsApp or Navigator widget in the run_app() call.",
        )
    }

    /// The [`OverlayState`] from the closest instance of [`Overlay`] that encloses the given
    /// context, if any.
    ///
    /// If `root_overlay` is set to true, the state from the furthest instance of this class is
    /// given instead.
    ///
    /// See also:
    ///
    ///  * [`Overlay::of`] for a similar function that panics if an [`Overlay`] is not found.
    pub fn maybe_of(
        app: &mut App,
        context: BuildContext,
        root_overlay: bool,
    ) -> Option<Handle<OverlayState>> {
        let marker = RenderTheaterMarker::maybe_of(app, context, root_overlay, false)?;
        Some(marker.overlay_entry_widget_state.widget(app).overlay_state)
    }
}

impl Default for Overlay {
    fn default() -> Overlay {
        Overlay {
            key: None,
            initial_entries: Vec::new(),
            clip_behavior: Clip::HardEdge,
            always_size_to_content: false,
        }
    }
}

impl StatefulWidget for Overlay {
    type State = OverlayState;

    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn create_state(&self) -> OverlayState {
        OverlayState {
            state: StateData::new(),
            ticker_provider: TickerProviderStateMixinData::new(),
            entries: Vec::new(),
        }
    }
}

/// The current state of an [`Overlay`].
///
/// Used to insert [`OverlayEntry`]s into the overlay using the [`insert`](Self::insert) and
/// [`insert_all`](Self::insert_all) functions.
pub struct OverlayState {
    state: StateData<Overlay>,
    ticker_provider: TickerProviderStateMixinData,
    entries: Vec<Ref<OverlayEntry>>,
}

impl OverlayState {
    fn insertion_index(
        self: Handle<Self>,
        app: &App,
        below: Option<Handle<OverlayEntry>>,
        above: Option<Handle<OverlayEntry>>,
    ) -> usize {
        debug_assert!(above.is_none() || below.is_none());
        let entries = &app.get(self).entries;
        if let Some(below) = below {
            return entries
                .iter()
                .position(|entry| entry == below)
                .expect("`below` is in this Overlay");
        }
        if let Some(above) = above {
            return entries
                .iter()
                .position(|entry| entry == above)
                .expect("`above` is in this Overlay")
                + 1;
        }
        entries.len()
    }

    fn debug_can_insert_entry(self: Handle<Self>, app: &App, entry: Handle<OverlayEntry>) -> bool {
        assert!(
            self.mounted(app),
            "Attempted to insert an OverlayEntry to an already disposed Overlay."
        );
        let current_overlay = app.get(entry).overlay;
        assert!(
            !app.get(self).entries.iter().any(|kept| kept == entry),
            "The specified entry is already present in the target Overlay. Consider calling \
             remove on the OverlayEntry before inserting it to a different Overlay."
        );
        assert!(
            current_overlay.is_none(),
            "The specified entry is already present in a different Overlay. Consider calling \
             remove on the OverlayEntry before inserting it to a different Overlay."
        );
        true
    }

    /// Insert the given entry into the overlay.
    ///
    /// If `below` is non-`None`, the entry is inserted just below `below`. If `above` is
    /// non-`None`, the entry is inserted just above `above`. Otherwise, the entry is inserted
    /// on top.
    ///
    /// It is an error to specify both `above` and `below`.
    pub fn insert(
        self: Handle<Self>,
        app: &mut App,
        entry: Ref<OverlayEntry>,
        below: Option<Handle<OverlayEntry>>,
        above: Option<Handle<OverlayEntry>>,
    ) {
        debug_assert!(self.debug_verify_insert_position(app, above, below, None));
        debug_assert!(self.debug_can_insert_entry(app, entry.handle()));
        app.get_mut(&entry).overlay = Some(self);
        let index = self.insertion_index(app, below, above);
        self.set_state(app, |state| state.entries.insert(index, entry));
    }

    /// Insert all the entries in the given iterable.
    ///
    /// If `below` is non-`None`, the entries are inserted just below `below`. If `above` is
    /// non-`None`, the entries are inserted just above `above`. Otherwise, the entries are
    /// inserted on top.
    ///
    /// It is an error to specify both `above` and `below`.
    pub fn insert_all(
        self: Handle<Self>,
        app: &mut App,
        entries: Vec<Ref<OverlayEntry>>,
        below: Option<Handle<OverlayEntry>>,
        above: Option<Handle<OverlayEntry>>,
    ) {
        debug_assert!(self.debug_verify_insert_position(app, above, below, None));
        if cfg!(debug_assertions) {
            for entry in &entries {
                assert!(self.debug_can_insert_entry(app, entry.handle()));
            }
        }
        if entries.is_empty() {
            return;
        }
        for entry in &entries {
            debug_assert!(app.get(entry).overlay.is_none());
            app.get_mut(entry).overlay = Some(self);
        }
        let index = self.insertion_index(app, below, above);
        self.set_state(app, move |state| {
            state.entries.splice(index..index, entries);
        });
    }

    fn debug_verify_insert_position(
        self: Handle<Self>,
        app: &App,
        above: Option<Handle<OverlayEntry>>,
        below: Option<Handle<OverlayEntry>>,
        new_entries: Option<&[Ref<OverlayEntry>]>,
    ) -> bool {
        assert!(
            above.is_none() || below.is_none(),
            "Only one of `above` and `below` may be specified."
        );
        let present = |entry: Handle<OverlayEntry>| {
            app.get(entry).overlay == Some(self)
                && app.get(self).entries.iter().any(|kept| kept == entry)
                && new_entries.is_none_or(|entries| entries.iter().any(|kept| kept == entry))
        };
        assert!(
            above.is_none_or(present),
            "The provided entry used for `above` must be present in the Overlay."
        );
        assert!(
            below.is_none_or(present),
            "The provided entry used for `below` must be present in the Overlay."
        );
        true
    }

    /// Remove all the entries listed in the given iterable, then reinsert them into the overlay
    /// in the given order.
    ///
    /// Entries mentioned in `new_entries` but absent from the overlay are inserted as if with
    /// [`insert_all`](Self::insert_all).
    ///
    /// Entries not mentioned in `new_entries` but present in the overlay are positioned as a
    /// group in the resulting list relative to the entries that were moved, as specified by one
    /// of `below` or `above`, which, if specified, must be one of the entries in `new_entries`:
    ///
    /// If `below` is non-`None`, the group is positioned just below `below`. If `above` is
    /// non-`None`, the group is positioned just above `above`. Otherwise, the group is left on
    /// top, with all the rearranged entries below.
    ///
    /// It is an error to specify both `above` and `below`.
    pub fn rearrange(
        self: Handle<Self>,
        app: &mut App,
        new_entries: Vec<Ref<OverlayEntry>>,
        below: Option<Handle<OverlayEntry>>,
        above: Option<Handle<OverlayEntry>>,
    ) {
        debug_assert!(self.debug_verify_insert_position(app, above, below, Some(&new_entries)));
        debug_assert!(
            new_entries.iter().all(|entry| {
                let overlay = app.get(entry).overlay;
                overlay.is_none() || overlay == Some(self)
            }),
            "One or more of the specified entries are already present in another Overlay."
        );
        debug_assert!(
            new_entries.iter().all(|entry| {
                let entries = &app.get(self).entries;
                entries.iter().position(|other| other == entry)
                    == entries.iter().rposition(|other| other == entry)
            }),
            "One or more of the specified entries are specified multiple times."
        );
        if new_entries.is_empty() {
            return;
        }
        if app.get(self).entries == new_entries {
            return;
        }
        let old: Vec<Ref<OverlayEntry>> = app
            .get(self)
            .entries
            .iter()
            .filter(|entry| !new_entries.contains(entry))
            .cloned()
            .collect();
        for entry in &new_entries {
            if app.get(entry).overlay.is_none() {
                app.get_mut(entry).overlay = Some(self);
            }
        }
        let index = {
            let entries = &new_entries;
            if let Some(below) = below {
                entries
                    .iter()
                    .position(|entry| entry == below)
                    .expect("`below` is in `new_entries`")
            } else if let Some(above) = above {
                entries
                    .iter()
                    .position(|entry| entry == above)
                    .expect("`above` is in `new_entries`")
                    + 1
            } else {
                entries.len()
            }
        };
        self.set_state(app, move |state| {
            state.entries.clear();
            state.entries.extend(new_entries);
            state.entries.splice(index..index, old);
        });
    }

    fn mark_dirty(self: Handle<Self>, app: &mut App) {
        if self.mounted(app) {
            self.set_state(app, |_state| {});
        }
    }

    fn mark_dirty_after_frame(self: Handle<Self>, app: &mut App, _time_stamp: std::time::Duration) {
        self.mark_dirty(app);
    }

    /// (DEBUG ONLY) Check whether a given entry is visible (i.e., not behind an opaque entry).
    ///
    /// This is an O(N) algorithm, and should not be necessary except for debug asserts. To
    /// avoid people depending on it, this function is implemented only in debug mode, and
    /// always returns false in release mode.
    pub fn debug_is_visible(self: Handle<Self>, app: &App, entry: Handle<OverlayEntry>) -> bool {
        let mut result = false;
        debug_assert!(app.get(self).entries.iter().any(|kept| kept == entry));
        if cfg!(debug_assertions) {
            let entries = app.get(self).entries.clone();
            for index in (1..entries.len()).rev() {
                let candidate = entries[index].handle();
                if candidate == entry {
                    result = true;
                    break;
                }
                if candidate.opaque(app) {
                    break;
                }
            }
        }
        result
    }

    fn did_change_entry_opacity(self: Handle<Self>, app: &mut App) {
        // We use the opacity of the entry in our build function, which means our state has
        // changed.
        self.set_state(app, |_state| {});
    }
}

impl TickerProviderStateMixin for OverlayState {
    fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
        &app.get(self).ticker_provider
    }

    fn ticker_provider_data_mut(
        self: Handle<Self>,
        app: &mut App,
    ) -> &mut TickerProviderStateMixinData {
        &mut app.get_mut(self).ticker_provider
    }
}

impl TickerProviderObject for OverlayState {
    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
        TickerProviderStateMixin::create_ticker(self, app, on_tick)
    }
}

impl State for OverlayState {
    type Widget = Overlay;

    crate::state_accessors!();

    fn debug_fill_properties(
        self: Handle<Self>,
        app: &App,
        properties: &mut DiagnosticPropertiesBuilder,
    ) {
        let entries: Vec<String> = app
            .get(self)
            .entries
            .iter()
            .map(|entry| format!("{:?}", app.get(entry.handle())))
            .collect();
        properties.add(DiagnosticsProperty::<String>::new(
            "entries",
            Some(format!("[{}]", entries.join(", "))),
        ));
    }

    fn init_state(self: Handle<Self>, app: &mut App) {
        let initial = self.widget(app).initial_entries.clone();
        self.insert_all(app, initial, None, None);
    }

    fn activate(self: Handle<Self>, app: &mut App) {
        TickerProviderStateMixin::activate(self, app);
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        TickerProviderStateMixin::dispose(self, app);
    }

    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
        // This list is filled backwards and then reversed below before it is added to the tree.
        let mut children: Vec<WidgetRef> = Vec::new();
        let mut onstage = true;
        let mut onstage_count = 0usize;
        for entry in app.get(self).entries.clone().into_iter().rev() {
            let key: KeyRef = app.get(&entry).key.clone().into();
            let (opaque, maintain_state) = (app.get(&entry).opaque, app.get(&entry).maintain_state);
            if onstage {
                onstage_count += 1;
                children.push(
                    OverlayEntryWidget {
                        key,
                        overlay_state: self,
                        entry,
                        ticker_enabled: true,
                    }
                    .into_widget(),
                );
                if opaque {
                    onstage = false;
                }
            } else if maintain_state {
                children.push(
                    OverlayEntryWidget {
                        key,
                        overlay_state: self,
                        entry,
                        ticker_enabled: false,
                    }
                    .into_widget(),
                );
            }
        }
        let skip_count = children.len() - onstage_count;
        children.reverse();
        let widget = self.widget(app);
        Theater {
            skip_count,
            clip_behavior: widget.clip_behavior,
            always_size_to_content: widget.always_size_to_content,
            children,
        }
        .into_widget()
    }
}

/// Dart's `_WrappingOverlay`: the widget [`Overlay::wrap`] returns.
#[derive(Debug)]
pub struct WrappingOverlay {
    /// See [`Widget::key`].
    pub key: Option<KeyRef>,
    /// See [`Overlay::clip_behavior`].
    pub clip_behavior: Clip,
    /// See [`Overlay::always_size_to_content`].
    pub always_size_to_content: bool,
    /// The widget the created [`Overlay`]'s bottom entry builds.
    pub child: WidgetRef,
}

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

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

    /// Dart `Overlay.wrap(alwaysSizeToContent:)`.
    pub fn always_size_to_content(mut self, always_size_to_content: bool) -> WrappingOverlay {
        self.always_size_to_content = always_size_to_content;
        self
    }
}

impl StatefulWidget for WrappingOverlay {
    type State = WrappingOverlayState;

    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

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

/// Dart's `_WrappingOverlayState`.
pub struct WrappingOverlayState {
    state: StateData<WrappingOverlay>,
    entry: Option<Ref<OverlayEntry>>,
}

impl WrappingOverlayState {
    /// Dart's `late final _entry`, created on its first use.
    fn entry(self: Handle<Self>, app: &mut App) -> Ref<OverlayEntry> {
        if let Some(entry) = app.get(self).entry.clone() {
            return entry;
        }
        let entry = OverlayEntry::new(
            app,
            Rc::new(move |app: &mut App, _context| self.widget(app).child.clone()),
            true,
            false,
            true,
        );
        app.get_mut(self).entry = Some(entry.clone());
        entry
    }
}

impl State for WrappingOverlayState {
    type Widget = WrappingOverlay;

    crate::state_accessors!();

    fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &WrappingOverlay) {
        let entry = self.entry(app);
        entry.mark_needs_build(app);
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        let entry = self.entry(app);
        entry.remove(app);
        entry.dispose(app);
    }

    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
        let entry = self.entry(app);
        let widget = self.widget(app);
        Overlay {
            key: None,
            initial_entries: vec![entry],
            clip_behavior: widget.clip_behavior,
            always_size_to_content: widget.always_size_to_content,
        }
        .into_widget()
    }
}

/// Special version of a stack that doesn't lay out and render the first
/// [`skip_count`](Self::skip_count) children.
///
/// The first `skip_count` children are considered "offstage".
#[derive(Debug)]
struct Theater {
    skip_count: usize,
    clip_behavior: Clip,
    always_size_to_content: bool,
    children: Vec<WidgetRef>,
}

impl RenderObjectWidget for Theater {
    type RenderObject = RenderTheater;

    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
        properties.add(IntProperty::<usize>::new(
            "skipCount",
            Some(self.skip_count),
        ));
    }

    fn debug_check_constructor(&self) {
        debug_assert!(self.children.len() >= self.skip_count);
    }

    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
        let text_direction = Directionality::of(app, context);
        let render_object = RenderTheater::new(
            app,
            text_direction,
            self.skip_count,
            self.clip_behavior,
            self.always_size_to_content,
        );
        render_object.as_object()
    }

    fn update_render_object(
        &self,
        app: &mut App,
        context: BuildContext,
        render_object: RenderHandle<RenderTheater>,
    ) {
        render_object.set_skip_count(app, self.skip_count);
        let text_direction = Directionality::of(app, context);
        render_object.set_text_direction(app, text_direction);
        render_object.set_clip_behavior(app, self.clip_behavior);
        render_object.set_always_size_to_content(app, self.always_size_to_content);
    }
}

impl MultiChildRenderObjectWidget for Theater {
    fn children(&self) -> &[WidgetRef] {
        &self.children
    }

    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
        TheaterElement::new(app, this).as_element()
    }
}

/// Dart's `_TheaterElement`: stamps each child's [`TheaterParentData`] with the
/// [`OverlayEntry`] that built it.
struct TheaterElement {
    element: ElementData,
    render_object_element: RenderObjectElementData,
    multi_child: MultiChildRenderObjectElementData,
}

impl TheaterElement {
    fn new(app: &mut App, widget: WidgetRef) -> Handle<TheaterElement> {
        debug_assert!(downcast_widget::<Theater>(&*widget).is_some());
        app.create(TheaterElement {
            element: ElementData::new(widget),
            render_object_element: RenderObjectElementData::default(),
            multi_child: MultiChildRenderObjectElementData::default(),
        })
        .into_tree_node(app)
    }

    /// The [`OverlayEntry`] of the `OverlayEntryWidget` at the given slot's index.
    fn entry_at_slot(self: Handle<Self>, app: &App, slot: Option<&Slot>) -> Handle<OverlayEntry> {
        let index = <Self as MultiChildRenderObjectElementBase>::indexed_slot(slot).index;
        let widget = Self::widget_of(self.as_element().widget(app));
        downcast_widget::<OverlayEntryWidget>(&*widget.children[index])
            .expect("a Theater's children are _OverlayEntryWidgets")
            .entry
            .handle()
    }
}

impl RenderObjectElementWidget for TheaterElement {
    type Widget = Theater;

    fn widget_of(widget: &WidgetRef) -> &Theater {
        downcast_widget::<Theater>(&**widget).expect("a _TheaterElement holds a _Theater")
    }
}

impl RenderObjectElement for TheaterElement {
    fn render_object_element_data(self: Handle<Self>, app: &App) -> &RenderObjectElementData {
        &app.get(self).render_object_element
    }

    fn render_object_element_data_mut(
        self: Handle<Self>,
        app: &mut App,
    ) -> &mut RenderObjectElementData {
        &mut app.get_mut(self).render_object_element
    }
}

impl MultiChildRenderObjectElementBase for TheaterElement {
    fn multi_child_data(self: Handle<Self>, app: &App) -> &MultiChildRenderObjectElementData {
        &app.get(self).multi_child
    }

    fn multi_child_data_mut(
        self: Handle<Self>,
        app: &mut App,
    ) -> &mut MultiChildRenderObjectElementData {
        &mut app.get_mut(self).multi_child
    }
}

impl Element for TheaterElement {
    crate::element_accessors!();

    const IS_RENDER_OBJECT_ELEMENT: bool = true;

    fn render_object(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
        self.render_object_element_data(app).render_object()
    }

    fn render_object_attaching_child(self: Handle<Self>, _app: &App) -> Option<AnyElement> {
        None
    }

    fn debug_doing_build(self: Handle<Self>, app: &App) -> bool {
        self.render_object_element_data(app).debug_doing_build()
    }

    fn perform_rebuild(self: Handle<Self>, app: &mut App) {
        RenderObjectElement::perform_rebuild(self, app);
    }

    fn deactivate(self: Handle<Self>, app: &mut App) {
        RenderObjectElement::deactivate(self, app);
    }

    fn unmount(self: Handle<Self>, app: &mut App) {
        RenderObjectElement::unmount(self, app);
    }

    fn update_parent_data(self: Handle<Self>, app: &mut App, parent_data_element: AnyElement) {
        RenderObjectElement::update_parent_data(self, app, parent_data_element);
    }

    fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
        RenderObjectElement::update_slot(self, app, new_slot);
    }

    fn attach_render_object(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
        RenderObjectElement::attach_render_object(self, app, new_slot);
    }

    fn detach_render_object(self: Handle<Self>, app: &mut App) {
        RenderObjectElement::detach_render_object(self, app);
    }

    fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
        MultiChildRenderObjectElementBase::visit_children(self, app, visitor);
    }

    /// Dart's `_TheaterElement.debugVisitOnstageChildren`: the children after the theater's
    /// `skip_count`, the entries the overlay keeps onstage.
    fn debug_visit_onstage_children(
        self: Handle<Self>,
        app: &App,
        visitor: &mut dyn FnMut(AnyElement),
    ) {
        let skip_count = Self::widget_of(self.as_element().widget(app)).skip_count;
        let mut children = Vec::new();
        MultiChildRenderObjectElementBase::visit_children(self, app, &mut |child| {
            children.push(child);
        });
        debug_assert!(children.len() >= skip_count);
        children.into_iter().skip(skip_count).for_each(visitor);
    }

    fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
        MultiChildRenderObjectElementBase::forget_child(self, app, child);
    }

    fn mount(
        self: Handle<Self>,
        app: &mut App,
        parent: Option<AnyElement>,
        new_slot: Option<Slot>,
    ) {
        MultiChildRenderObjectElementBase::mount(self, app, parent, new_slot);
    }

    fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
        MultiChildRenderObjectElementBase::update(self, app, new_widget);
    }

    fn insert_render_object_child(
        self: Handle<Self>,
        app: &mut App,
        child: AnyRenderObject,
        slot: Option<Slot>,
    ) {
        MultiChildRenderObjectElementBase::insert_render_object_child(
            self,
            app,
            child,
            slot.clone(),
        );
        let entry = self.entry_at_slot(app, slot.as_ref()).keep(app);
        child
            .parent_data_of_mut::<TheaterParentData>(app)
            .overlay_entry = Some(entry);
    }

    fn move_render_object_child(
        self: Handle<Self>,
        app: &mut App,
        child: AnyRenderObject,
        old_slot: Option<Slot>,
        new_slot: Option<Slot>,
    ) {
        MultiChildRenderObjectElementBase::move_render_object_child(
            self,
            app,
            child,
            old_slot,
            new_slot.clone(),
        );
        if cfg!(debug_assertions) {
            let entry_at_new_slot = self.entry_at_slot(app, new_slot.as_ref());
            let parent_data = child.parent_data_of::<TheaterParentData>(app);
            assert!(parent_data.overlay_entry.handle() == Some(entry_at_new_slot));
        }
    }

    fn remove_render_object_child(
        self: Handle<Self>,
        app: &mut App,
        child: AnyRenderObject,
        slot: Option<Slot>,
    ) {
        MultiChildRenderObjectElementBase::remove_render_object_child(self, app, child, slot);
    }
}

/// Dart's `_TheaterParentData`: [`StackParentData`] plus the entry that created the child.
#[derive(Debug, Default)]
pub struct TheaterParentData {
    stack: StackParentData,
    /// The [`OverlayEntry`] that directly created this child.
    overlay_entry: Option<Ref<OverlayEntry>>,
}

impl TheaterParentData {
    /// Parent data for a child of a [`RenderTheater`] that no entry has claimed yet.
    pub fn new() -> TheaterParentData {
        TheaterParentData {
            stack: StackParentData::new(),
            overlay_entry: None,
        }
    }

    /// The stack half: the positioning a `Positioned` child writes.
    pub fn stack(&self) -> &StackParentData {
        &self.stack
    }

    /// See [`stack`](Self::stack).
    pub fn stack_mut(&mut self) -> &mut StackParentData {
        &mut self.stack
    }

    // An [`OverlayPortal`] makes its overlay child a render child of an ancestor
    // [`Overlay`]. Currently, to make sure the overlay child is painted after its
    // [`OverlayPortal`], and before the next [`OverlayEntry`] (which could be something that
    // should obstruct the overlay child, such as a `ModalRoute`) in the host [`Overlay`], the
    // paint order of each overlay child is managed by the [`OverlayEntry`] that hosts its
    // [`OverlayPortal`].
    //
    // The following methods are exposed to allow easy access to the overlay children's render
    // objects whose order is managed by `overlay_entry`, in the right order.

    // The entry's notifier is cleared in OverlayEntryWidgetState's dispose method. These are
    // only accessed during layout, paint and hit-test so the `expect` is safe.
    fn paint_order_children(&self, app: &App) -> Vec<RenderHandle<RenderDeferredLayoutBox>> {
        match self.child_model(app) {
            Some(child_model) => child_model.paint_order_children(app),
            None => Vec::new(),
        }
    }

    fn child_model(&self, app: &App) -> Option<Handle<OverlayEntryWidgetState>> {
        let notifier = app
            .get(self.overlay_entry.as_ref()?)
            .overlay_entry_state_notifier
            .handle()?;
        Some((*app.get(notifier).value()).expect("the entry is mounted"))
    }

    // A convenience method for traversing `paint_order_children` with a render object
    // visitor.
    fn visit_overlay_portal_children_on_overlay_entry(
        &self,
        app: &App,
        visitor: &mut dyn FnMut(AnyRenderObject),
    ) {
        for child in self.paint_order_children(app) {
            visitor(child.as_object());
        }
    }
}

impl ParentData for TheaterParentData {
    fn detach(&mut self) {
        ContainerParentDataMixin::detach(self);
    }

    fn provide(&self, id: TypeId) -> Option<&dyn Any> {
        if id == TypeId::of::<TheaterParentData>() {
            return Some(self);
        }
        self.stack.provide(id)
    }

    fn provide_mut(&mut self, id: TypeId) -> Option<&mut dyn Any> {
        if id == TypeId::of::<TheaterParentData>() {
            return Some(self);
        }
        self.stack.provide_mut(id)
    }
}

impl ContainerParentDataMixin for TheaterParentData {
    type ChildType = AnyRenderBox;

    fn container_parent_data(&self) -> &ContainerParentData<AnyRenderBox> {
        self.stack.container_parent_data()
    }

    fn container_parent_data_mut(&mut self) -> &mut ContainerParentData<AnyRenderBox> {
        self.stack.container_parent_data_mut()
    }
}

impl ContainerBoxParentData for TheaterParentData {
    fn box_parent_data(&self) -> &waft_rendering::BoxParentData {
        ContainerBoxParentData::box_parent_data(&self.stack)
    }

    fn box_parent_data_mut(&mut self) -> &mut waft_rendering::BoxParentData {
        ContainerBoxParentData::box_parent_data_mut(&mut self.stack)
    }
}

impl Display for TheaterParentData {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Display::fmt(&self.stack, f)
    }
}

/// `RenderStack.layoutPositionedChild` for a child whose parent data is a
/// [`TheaterParentData`].
fn layout_positioned_theater_child(
    app: &mut App,
    child: AnyRenderBox,
    size: Size,
    alignment: Alignment,
) {
    let child_constraints = {
        let parent_data = child.as_object().parent_data_of::<TheaterParentData>(app);
        debug_assert!(parent_data.stack.is_positioned());
        parent_data.stack.positioned_child_constraints(size)
    };
    child.layout(app, child_constraints, true);

    let child_size = child.size(app);
    let parent_data = child.as_object().parent_data_of::<TheaterParentData>(app);
    let x = match (parent_data.stack.left, parent_data.stack.right) {
        (Some(left), _) => left,
        (None, Some(right)) => size.width() - right - child_size.width(),
        (None, None) => alignment.along_offset(size - child_size).dx(),
    };
    let y = match (parent_data.stack.top, parent_data.stack.bottom) {
        (Some(top), _) => top,
        (None, Some(bottom)) => size.height() - bottom - child_size.height(),
        (None, None) => alignment.along_offset(size - child_size).dy(),
    };
    child
        .as_object()
        .parent_data_of_mut::<TheaterParentData>(app)
        .set_offset(Offset::new(x, y));
}

/// An App-aware cursor for Flutter's lazy theater child generators.
///
/// Entry layout can mutate its portal list, so that list is opened only after
/// yielding the entry. Portal candidates advance before yielding, as in Dart.
pub struct TheaterChildren {
    /// The owning theater; absent for a deferred box's single normal child.
    theater: Option<RenderHandle<RenderTheater>>,

    /// The current entry, kept until its portal children have been traversed.
    entry: Option<AnyRenderBox>,

    /// Hit testing traverses portals before entries, from front to back.
    reversed: bool,

    /// Hit-test entries left before reaching the offstage prefix.
    remaining: usize,

    /// The source generator's suspension point between child operations.
    phase: TheaterChildrenPhase,

    /// The next portal location, advanced before yielding its render box.
    candidate: Option<Handle<OverlayEntryLocation>>,
}

/// Suspension points in Flutter's paint-order and hit-test-order generators.
enum TheaterChildrenPhase {
    /// Yields the entry first when traversing in paint order.
    Entry,

    /// Opens the current portal list after the previous yield has completed.
    OpenPortals,

    /// Yields portal boxes while reading links from the current child model.
    Portals,

    /// Advances to the adjacent entry after its portals and entry were yielded.
    NextEntry,
}

impl TheaterChildren {
    /// Creates the one-child generator used by deferred layout boxes.
    fn single(child: Option<AnyRenderBox>) -> Self {
        Self {
            theater: None,
            entry: child,
            reversed: false,
            remaining: 0,
            phase: TheaterChildrenPhase::Entry,
            candidate: None,
        }
    }

    /// Starts at the first or last onstage entry without reading its portals.
    fn theater(theater: RenderHandle<RenderTheater>, app: &App, reversed: bool) -> Self {
        Self {
            theater: Some(theater),
            entry: if reversed {
                theater.last_onstage_child(app)
            } else {
                theater.first_onstage_child(app)
            },
            reversed,
            remaining: theater.child_count(app) - theater.get(app).skip_count,
            phase: TheaterChildrenPhase::Entry,
            candidate: None,
        }
    }

    /// Advances after the caller has finished operating on the previous child.
    pub fn next(&mut self, app: &App) -> Option<AnyRenderBox> {
        let Some(theater) = self.theater else {
            return self.entry.take();
        };
        loop {
            let entry = self.entry?;
            match self.phase {
                TheaterChildrenPhase::Entry => {
                    self.phase = TheaterChildrenPhase::OpenPortals;
                    if !self.reversed {
                        return Some(entry);
                    }
                }
                TheaterChildrenPhase::OpenPortals => {
                    let model = entry
                        .as_object()
                        .parent_data_of::<TheaterParentData>(app)
                        .child_model(app);
                    self.candidate = model.and_then(|model| {
                        let list = app.get(model).sorted_theater_siblings.as_ref()?;
                        if self.reversed {
                            list.last().map(Retained::handle)
                        } else {
                            list.first().map(Retained::handle)
                        }
                    });
                    self.phase = TheaterChildrenPhase::Portals;
                }
                TheaterChildrenPhase::Portals => {
                    if let Some(candidate) = self.candidate {
                        let render_box = app.get(candidate).overlay_child_render_box;
                        self.candidate = (|| {
                            let model = app.get(candidate).child_model;
                            let list = app.get(model).sorted_theater_siblings.as_ref()?;
                            let index = list.iter().position(|value| value == candidate)?;
                            let next = if self.reversed {
                                index.checked_sub(1).and_then(|i| list.get(i))
                            } else {
                                list.get(index + 1)
                            };
                            next.map(Retained::handle)
                        })();
                        if let Some(render_box) = render_box {
                            return Some(render_box.as_box());
                        }
                    } else {
                        self.phase = TheaterChildrenPhase::NextEntry;
                        if self.reversed {
                            return Some(entry);
                        }
                    }
                }
                TheaterChildrenPhase::NextEntry => {
                    self.entry = if self.reversed {
                        self.remaining -= 1;
                        if self.remaining == 0 {
                            None
                        } else {
                            theater.child_before(app, entry)
                        }
                    } else {
                        theater.child_after(app, entry)
                    };
                    self.phase = TheaterChildrenPhase::Entry;
                }
            }
        }
    }

    /// Collects a snapshot for tests that do not mutate children between yields.
    #[cfg(test)]
    fn collect(mut self, app: &App) -> Vec<AnyRenderBox> {
        let mut children = Vec::new();
        while let Some(child) = self.next(app) {
            children.push(child);
        }
        children
    }
}

/// A `RenderBox` that sizes itself to its parent's size, implements the stack layout algorithm
/// and renders its children in the given [`theater`](Self::theater).
///
/// Flutter's `_RenderTheaterMixin`.
pub trait RenderTheaterMixin: RenderBox {
    /// The theater whose child model this box paints from.
    fn theater(self: RenderHandle<Self>, app: &App) -> RenderHandle<RenderTheater>;

    /// The children in paint order: from farthest to the user to the closest to the user.
    fn children_in_paint_order(self: RenderHandle<Self>, app: &App) -> TheaterChildren;

    /// The children in hit-test order: from closest to the user to the farthest.
    fn children_in_hit_test_order(self: RenderHandle<Self>, app: &App) -> TheaterChildren;

    /// The body of Flutter's `setupParentData` override.
    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
        if !child.parent_data_is::<TheaterParentData>(app) {
            child.set_parent_data(app, TheaterParentData::new());
        }
    }

    /// Lays one child out with the stack layout algorithm.
    fn layout_child(
        self: RenderHandle<Self>,
        app: &mut App,
        child: AnyRenderBox,
        non_positioned_child_constraints: BoxConstraints,
    ) {
        let alignment = self.theater(app).resolved_alignment(app);
        let is_positioned = child
            .as_object()
            .parent_data_of::<TheaterParentData>(app)
            .stack
            .is_positioned();
        if !is_positioned {
            // Dart dispatches this through `RenderObject.layout`, which
            // `_RenderDeferredLayoutBox` overrides to hand its subtree to the pipeline
            // owner's dirty list instead of laying it out inside this tree walk.
            match child.as_object().downcast::<RenderDeferredLayoutBox>(app) {
                Some(deferred) => {
                    let parent = child
                        .as_object()
                        .parent(app)
                        .expect("a child being laid out has a parent");
                    deferred.do_layout_from(app, parent, non_positioned_child_constraints);
                }
                None => child.layout(app, non_positioned_child_constraints, true),
            }
            child
                .as_object()
                .parent_data_of_mut::<TheaterParentData>(app)
                .set_offset(Offset::ZERO);
        } else {
            debug_assert!(
                child
                    .as_object()
                    .downcast::<RenderDeferredLayoutBox>(app)
                    .is_none(),
                "all deferred layout boxes must be non-positioned children."
            );
            let size = self.size(app);
            layout_positioned_theater_child(app, child, size, alignment);
        }
    }

    /// The body of Flutter's `hitTestChildren` override.
    fn hit_test_children(
        self: RenderHandle<Self>,
        app: &mut App,
        result: &mut BoxHitTestResult<'_>,
        position: Offset,
    ) -> bool {
        let mut children = self.children_in_hit_test_order(app);
        while let Some(child) = children.next(app) {
            let offset = child
                .as_object()
                .parent_data_of::<TheaterParentData>(app)
                .offset();
            let is_hit = result.add_with_paint_offset(Some(offset), position, |result, local| {
                child.hit_test(app, result, local)
            });
            if is_hit {
                return true;
            }
        }
        false
    }

    /// The body of Flutter's `paint` override.
    fn paint(
        self: RenderHandle<Self>,
        app: &mut App,
        context: &mut PaintingContext,
        offset: Offset,
    ) {
        let mut children = self.children_in_paint_order(app);
        while let Some(child) = children.next(app) {
            let child_offset = child
                .as_object()
                .parent_data_of::<TheaterParentData>(app)
                .offset();
            context.paint_child(app, child.as_object(), child_offset + offset);
        }
    }
}

/// The render object of an [`Overlay`]: a stack that skips its first
/// [`skip_count`](Self::skip_count) children.
///
/// Flutter's `_RenderTheater`.
pub struct RenderTheater {
    render_object: RenderObjectData,
    render_box: RenderBoxData,
    container: ContainerRenderObjectData<AnyRenderBox>,
    alignment_cache: Option<Alignment>,
    text_direction: TextDirection,
    skip_count: usize,
    clip_behavior: Clip,
    clip_rect_layer: LayerHandle<Handle<ClipRectLayer>>,
    always_size_to_content: bool,
    laying_out_size_determining_child: bool,
}

impl RenderTheater {
    /// Creates the render object of an [`Overlay`]. Add children with
    /// [`add`](ContainerRenderObjectMixin::add); Dart's constructor takes them.
    pub fn new(
        app: &mut App,
        text_direction: TextDirection,
        skip_count: usize,
        clip_behavior: Clip,
        always_size_to_content: bool,
    ) -> RenderHandle<RenderTheater> {
        RenderHandle::new_box(
            app,
            RenderTheater {
                render_object: RenderObjectData::new(),
                render_box: RenderBoxData::new(),
                container: ContainerRenderObjectData::new(),
                alignment_cache: None,
                text_direction,
                skip_count,
                clip_behavior,
                clip_rect_layer: LayerHandle::new(),
                always_size_to_content,
                laying_out_size_determining_child: false,
            },
        )
    }

    /// `AlignmentDirectional.topStart` resolved against
    /// [`text_direction`](Self::text_direction), cached until it changes.
    pub fn resolved_alignment(self: RenderHandle<Self>, app: &mut App) -> Alignment {
        if let Some(cached) = self.get(app).alignment_cache {
            return cached;
        }
        let resolved = AlignmentGeometry::TOP_START.resolve(Some(self.get(app).text_direction));
        self.get_mut(app).alignment_cache = Some(resolved);
        resolved
    }

    fn mark_need_resolution(self: RenderHandle<Self>, app: &mut App) {
        self.get_mut(app).alignment_cache = None;
        self.mark_needs_layout(app);
    }

    /// The text direction with which the stack alignment is resolved.
    pub fn text_direction(self: RenderHandle<Self>, app: &App) -> TextDirection {
        self.get(app).text_direction
    }

    /// Sets [`text_direction`](Self::text_direction).
    pub fn set_text_direction(self: RenderHandle<Self>, app: &mut App, value: TextDirection) {
        if self.get(app).text_direction == value {
            return;
        }
        self.get_mut(app).text_direction = value;
        self.mark_need_resolution(app);
    }

    /// How many children at the start of the child list are offstage.
    pub fn skip_count(self: RenderHandle<Self>, app: &App) -> usize {
        self.get(app).skip_count
    }

    /// Sets [`skip_count`](Self::skip_count).
    pub fn set_skip_count(self: RenderHandle<Self>, app: &mut App, value: usize) {
        if self.get(app).skip_count != value {
            self.get_mut(app).skip_count = value;
            self.mark_needs_layout(app);
        }
    }

    /// How to clip the children that overflow the overlay.
    ///
    /// Defaults to [`Clip::HardEdge`].
    pub fn clip_behavior(self: RenderHandle<Self>, app: &App) -> Clip {
        self.get(app).clip_behavior
    }

    /// Sets [`clip_behavior`](Self::clip_behavior).
    pub fn set_clip_behavior(self: RenderHandle<Self>, app: &mut App, value: Clip) {
        if value != self.get(app).clip_behavior {
            self.get_mut(app).clip_behavior = value;
            self.mark_needs_paint(app);
        }
    }

    /// See [`Overlay::always_size_to_content`].
    pub fn always_size_to_content(self: RenderHandle<Self>, app: &App) -> bool {
        self.get(app).always_size_to_content
    }

    /// Sets [`always_size_to_content`](Self::always_size_to_content).
    pub fn set_always_size_to_content(self: RenderHandle<Self>, app: &mut App, value: bool) {
        if self.get(app).always_size_to_content != value {
            self.get_mut(app).always_size_to_content = value;
            self.mark_needs_layout(app);
        }
    }

    // Adding/removing a deferred child does not affect the layout of the other children, or
    // that of the Overlay. Flutter suppresses the `markNeedsLayout` that `adoptChild` and
    // `dropChild` do here; `RenderBox::mark_needs_layout` has no callable base body outside
    // `waft-rendering`, so the Overlay is relaid out instead (see `PORTING.md`).
    fn add_deferred_child(
        self: RenderHandle<Self>,
        app: &mut App,
        child: RenderHandle<RenderDeferredLayoutBox>,
    ) {
        self.adopt_child(app, child.as_object());
        // The Overlay still needs repainting when a deferred child is added.
        self.mark_needs_paint(app);

        // After adding `child` to the render tree, we want to make sure it will be laid out
        // in the same frame. This is done by calling mark_needs_layout on the layout
        // surrogate. This ensures `child` is added to the dirty list (see
        // RenderLayoutSurrogateProxyBox's perform_layout).
        let surrogate = child.get(app).layout_surrogate;
        surrogate.as_object().mark_needs_layout(app);
    }

    fn remove_deferred_child(
        self: RenderHandle<Self>,
        app: &mut App,
        child: RenderHandle<RenderDeferredLayoutBox>,
    ) {
        self.drop_child(app, child.as_object());
        // The Overlay still needs repainting when a deferred child is dropped. See the
        // comment in `add_deferred_child`.
        self.mark_needs_paint(app);
    }

    fn first_onstage_child(self: RenderHandle<Self>, app: &App) -> Option<AnyRenderBox> {
        let skip_count = self.get(app).skip_count;
        if skip_count == self.child_count(app) {
            return None;
        }
        let mut child = self.first_child(app);
        for _ in 0..skip_count {
            let current = child.expect("skip_count is at most child_count");
            child = self.child_after(app, current);
        }
        child
    }

    fn last_onstage_child(self: RenderHandle<Self>, app: &App) -> Option<AnyRenderBox> {
        if self.get(app).skip_count == self.child_count(app) {
            None
        } else {
            self.last_child(app)
        }
    }

    fn find_size_determining_child(self: RenderHandle<Self>, app: &App) -> AnyRenderBox {
        let mut child = self.last_onstage_child(app);
        while let Some(current) = child {
            let parent_data = current.as_object().parent_data_of::<TheaterParentData>(app);
            let can_size = parent_data
                .overlay_entry
                .as_ref()
                .is_some_and(|entry| app.get(entry).can_size_overlay);
            if can_size && !parent_data.stack.is_positioned() {
                return current;
            }
            child = self.child_before(app, current);
        }
        assert!(
            !self.get(app).always_size_to_content,
            "Overlay was asked to size itself to content but does not have a suitable child. \
             When `always_size_to_content` is true, the Overlay requires at least one \
             non-positioned `OverlayEntry` with `can_size_overlay` set to true to determine its \
             size."
        );
        panic!(
            "Overlay was given infinite constraints and cannot be sized by a suitable child. \
             The constraints given to the overlay would result in an illegal infinite size. To \
             avoid that, the Overlay tried to size itself to one of its children, but no \
             suitable non-positioned child that belongs to an OverlayEntry with \
             can_size_overlay set to true could be found."
        );
    }
}

impl ContainerRenderObjectMixin for RenderTheater {
    type ChildType = AnyRenderBox;
    type ParentDataType = TheaterParentData;

    fn container_data(
        self: RenderHandle<Self>,
        app: &App,
    ) -> &ContainerRenderObjectData<AnyRenderBox> {
        &self.get(app).container
    }

    fn container_data_mut(
        self: RenderHandle<Self>,
        app: &mut App,
    ) -> &mut ContainerRenderObjectData<AnyRenderBox> {
        &mut self.get_mut(app).container
    }
}

impl RenderTheaterMixin for RenderTheater {
    fn theater(self: RenderHandle<Self>, _app: &App) -> RenderHandle<RenderTheater> {
        self
    }

    fn children_in_paint_order(self: RenderHandle<Self>, app: &App) -> TheaterChildren {
        TheaterChildren::theater(self, app, false)
    }

    fn children_in_hit_test_order(self: RenderHandle<Self>, app: &App) -> TheaterChildren {
        TheaterChildren::theater(self, app, true)
    }
}

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

    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
        let constraints = self.constraints(app);
        let mut size_determining_child = None;
        if !self.get(app).always_size_to_content && constraints.biggest().is_finite() {
            self.set_size(app, constraints.biggest());
        } else {
            let child = self.find_size_determining_child(app);
            size_determining_child = Some(child);
            self.get_mut(app).laying_out_size_determining_child = true;
            self.layout_child(app, child, constraints);
            self.get_mut(app).laying_out_size_determining_child = false;
            let size = child.size(app);
            self.set_size(app, size);
        }

        // Equivalent to the BoxConstraints RenderStack uses for StackFit.expand.
        let non_positioned_child_constraints = BoxConstraints::tight(self.size(app));
        let mut children = self.children_in_paint_order(app);
        while let Some(child) = children.next(app) {
            if Some(child) != size_determining_child {
                self.layout_child(app, child, non_positioned_child_constraints);
            }
        }
    }

    fn visit_children(
        self: RenderHandle<Self>,
        app: &App,
        visitor: &mut dyn FnMut(AnyRenderObject),
    ) {
        let mut child = self.first_child(app);
        while let Some(current) = child {
            visitor(current.as_object());
            current
                .as_object()
                .parent_data_of::<TheaterParentData>(app)
                .visit_overlay_portal_children_on_overlay_entry(app, visitor);
            child = self.child_after(app, current);
        }
    }

    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
        ContainerRenderObjectMixin::did_attach(self, app, owner);
        let mut child = self.first_child(app);
        while let Some(current) = child {
            let deferred = current
                .as_object()
                .parent_data_of::<TheaterParentData>(app)
                .paint_order_children(app);
            for deferred_child in deferred {
                deferred_child.as_object().attach(app, owner);
            }
            child = self.child_after(app, current);
        }
    }

    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
        ContainerRenderObjectMixin::did_detach(self, app);
        let mut child = self.first_child(app);
        while let Some(current) = child {
            let deferred = current
                .as_object()
                .parent_data_of::<TheaterParentData>(app)
                .paint_order_children(app);
            for deferred_child in deferred {
                deferred_child.as_object().detach(app);
            }
            child = self.child_after(app, current);
        }
    }

    fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
        let mut children = Vec::new();
        RenderObject::visit_children(self, app, &mut |child| children.push(child));
        for child in children {
            self.as_object().redepth_child(app, child);
        }
    }

    fn paint(
        self: RenderHandle<Self>,
        app: &mut App,
        context: &mut PaintingContext,
        offset: Offset,
    ) {
        let clip_behavior = self.clip_behavior(app);
        if clip_behavior != Clip::None {
            let size = self.size(app);
            let old = self.get(app).clip_rect_layer.layer();
            let layer = context.push_clip_rect(
                app,
                self.as_object().needs_compositing(app),
                offset,
                Offset::ZERO & size,
                |app, context, offset| RenderTheaterMixin::paint(self, app, context, offset),
                clip_behavior,
                old,
            );
            LayerHandle::set_layer(app, |app| &mut self.get_mut(app).clip_rect_layer, layer);
        } else {
            LayerHandle::set_layer(app, |app| &mut self.get_mut(app).clip_rect_layer, None);
            RenderTheaterMixin::paint(self, app, context, offset);
        }
    }

    fn debug_fill_properties(
        self: RenderHandle<Self>,
        app: &App,
        properties: &mut DiagnosticPropertiesBuilder,
    ) {
        let this = self.get(app);
        properties.add(IntProperty::<usize>::new(
            "skipCount",
            Some(this.skip_count),
        ));
        properties.add(EnumProperty::<TextDirection>::new(
            "textDirection",
            Some(this.text_direction),
        ));
    }

    fn debug_describe_children(
        self: RenderHandle<Self>,
        app: &App,
    ) -> Vec<Rc<dyn DiagnosticsNode>> {
        let mut offstage_children: Vec<Rc<dyn DiagnosticsNode>> = Vec::new();
        let mut onstage_children: Vec<Rc<dyn DiagnosticsNode>> = Vec::new();

        let mut count = 1;
        let mut onstage = false;
        let first_onstage_child = self.first_onstage_child(app);
        let mut child = self.first_child(app);
        while let Some(current) = child {
            let child_parent_data = current.as_object().parent_data_of::<TheaterParentData>(app);
            if Some(current) == first_onstage_child {
                onstage = true;
                count = 1;
            }

            if onstage {
                onstage_children.push(Rc::new(
                    current
                        .as_object()
                        .to_diagnostics_node(app, format!("onstage {count}")),
                ));
            } else {
                offstage_children.push(Rc::new(
                    current
                        .as_object()
                        .to_diagnostics_node(app, format!("offstage {count}"))
                        .with_style(DiagnosticsTreeStyle::Offstage),
                ));
            }

            let mut portal_children = Vec::new();
            child_parent_data
                .visit_overlay_portal_children_on_overlay_entry(app, &mut |render_object| {
                    portal_children.push(render_object)
                });
            for (index, render_object) in portal_children.into_iter().enumerate() {
                let subcount = index + 1;
                if onstage {
                    onstage_children.push(Rc::new(
                        render_object
                            .to_diagnostics_node(app, format!("onstage {count} - {subcount}")),
                    ));
                } else {
                    offstage_children.push(Rc::new(
                        render_object
                            .to_diagnostics_node(app, format!("offstage {count} - {subcount}"))
                            .with_style(DiagnosticsTreeStyle::Offstage),
                    ));
                }
            }

            child = child_parent_data.next_sibling();
            count += 1;
        }

        let mut result = onstage_children;
        if offstage_children.is_empty() {
            result.push(Rc::new(
                message("no offstage children").with_style(DiagnosticsTreeStyle::Offstage),
            ));
        } else {
            result.extend(offstage_children);
        }
        result
    }

    fn dispose(self: RenderHandle<Self>, app: &mut App) {
        LayerHandle::set_layer(app, |app| &mut self.get_mut(app).clip_rect_layer, None);
        waft_rendering::RenderObjectBase::dispose(self, app);
    }

    /// Dart's `describeApproximatePaintClip`: the theater clips every entry to its bounds
    /// unless [`clip_behavior`](Self::clip_behavior) is [`Clip::None`].
    fn describe_approximate_paint_clip(
        self: RenderHandle<Self>,
        app: &App,
        _child: AnyRenderObject,
    ) -> Option<Rect> {
        match self.clip_behavior(app) {
            Clip::None => None,
            Clip::HardEdge | Clip::AntiAlias | Clip::AntiAliasWithSaveLayer => {
                Some(Offset::ZERO & self.size(app))
            }
        }
    }
}

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

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

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

/// Dart's `_RenderTheaterMarker`: the [`RenderTheater`] and the entry state an
/// [`Overlay`]'s subtree builds under.
#[derive(Debug)]
struct RenderTheaterMarker {
    theater: RenderHandle<RenderTheater>,
    overlay_entry_widget_state: Handle<OverlayEntryWidgetState>,
    child: WidgetRef,
}

/// The two fields of a [`RenderTheaterMarker`], copied out of the tree.
#[derive(Clone, Copy)]
struct TheaterLocation {
    theater: RenderHandle<RenderTheater>,
    overlay_entry_widget_state: Handle<OverlayEntryWidgetState>,
}

impl RenderTheaterMarker {
    fn of(app: &mut App, context: BuildContext, target_root_overlay: bool) -> TheaterLocation {
        RenderTheaterMarker::maybe_of(app, context, target_root_overlay, true).unwrap_or_else(
            || {
                panic!(
                    "No Overlay widget found.\n{} widgets require an Overlay widget ancestor.\n\
                     An overlay lets widgets float on top of other widget children.\n\
                     To introduce an Overlay widget, you can either directly include one, or \
                     use a widget that contains an Overlay itself, such as a Navigator or \
                     WidgetsApp.",
                    context.widget(app).type_name()
                )
            },
        )
    }

    fn maybe_of(
        app: &mut App,
        context: BuildContext,
        target_root_overlay: bool,
        create_dependency: bool,
    ) -> Option<TheaterLocation> {
        let read = |app: &App, element: AnyElement| {
            let widget = element.widget(app);
            let marker = downcast_widget::<RenderTheaterMarker>(&**widget)
                .expect("a _RenderTheaterMarker element holds a _RenderTheaterMarker");
            TheaterLocation {
                theater: marker.theater,
                overlay_entry_widget_state: marker.overlay_entry_widget_state,
            }
        };

        if target_root_overlay {
            let nearest = LookupBoundary::get_element_for_inherited_widget_of_exact_type::<
                RenderTheaterMarker,
            >(app, context);
            let ancestor = RenderTheaterMarker::root_marker_of(app, nearest)?;
            if create_dependency {
                context.depend_on_inherited_element(app, ancestor, None);
            }
            return Some(read(app, ancestor));
        }

        if create_dependency {
            LookupBoundary::depend_on_inherited_widget_of_exact_type::<RenderTheaterMarker>(
                app, context,
            )?;
        }
        let element = LookupBoundary::get_element_for_inherited_widget_of_exact_type::<
            RenderTheaterMarker,
        >(app, context)?;
        Some(read(app, element))
    }

    fn root_marker_of(app: &App, marker_element: Option<AnyElement>) -> Option<AnyElement> {
        let marker_element = marker_element?;
        let mut ancestor = None;
        marker_element.visit_ancestor_elements(app, &mut |element| {
            ancestor = LookupBoundary::get_element_for_inherited_widget_of_exact_type::<
                RenderTheaterMarker,
            >(app, element);
            false
        });
        match ancestor {
            None => Some(marker_element),
            Some(ancestor) => RenderTheaterMarker::root_marker_of(app, Some(ancestor)),
        }
    }
}

impl InheritedWidget for RenderTheaterMarker {
    fn child(&self) -> &WidgetRef {
        &self.child
    }

    fn update_should_notify(&self, old_widget: &RenderTheaterMarker) -> bool {
        old_widget.theater != self.theater
            || old_widget.overlay_entry_widget_state != self.overlay_entry_widget_state
    }
}

// * OverlayPortal Implementation
//  OverlayPortal is inspired by the
//  [flutter_portal](https://pub.dev/packages/flutter_portal) package.
//
// ** RenderObject hierarchy
// The widget works by inserting its overlay child's render subtree directly under
// [`Overlay`]'s render object ([`RenderTheater`]).
//
// To ensure the overlay child render subtree does not do layout twice, the subtree must only
// perform layout after both its RenderTheater and the OverlayPortal's render object
// (RenderLayoutSurrogateProxyBox) have finished layout. This is handled by
// RenderDeferredLayoutBox.
//
// ** Z-Index of an overlay child
// OverlayEntryLocation is a (private) interface that allows an OverlayPortal to insert its
// overlay child into a specific Overlay, as well as specifying the paint order between the
// overlay child and other children of the RenderTheater.
//
// Since OverlayPortal is only allowed to target ancestor Overlays (RenderTheater must finish
// doing layout before RenderDeferredLayoutBox), the RenderTheater should typically be
// acquired using an InheritedWidget (currently, RenderTheaterMarker) in case the
// OverlayPortal gets reparented.

thread_local! {
    /// Dart's `OverlayPortalController._wallTime`.
    static WALL_TIME: Cell<i64> = const { Cell::new(i64::MIN) };
}

/// A class to show, hide and bring to top an [`OverlayPortal`]'s overlay child in the target
/// [`Overlay`].
///
/// An [`OverlayPortalController`] can only be given to at most one [`OverlayPortal`] at a
/// time. When an [`OverlayPortalController`] is moved from one [`OverlayPortal`] to another,
/// its [`is_showing`](Self::is_showing) state does not carry over.
///
/// [`show`](Self::show) and [`hide`](Self::hide) can be called even before the controller is
/// assigned to any [`OverlayPortal`], but they typically should not be called while the
/// widget tree is being rebuilt.
pub struct OverlayPortalController {
    attach_target: Option<Handle<OverlayPortalState>>,
    // A separate z_order_index to allow `show` or `hide` to be called when the controller is
    // not yet attached. Once this controller is attached, the attach target's z_order_index
    // will be used as the source of truth, and this variable will be set to None.
    z_order_index: Option<i64>,
    debug_label: Option<String>,
}

impl OverlayPortalController {
    /// Creates an [`OverlayPortalController`], optionally with a `debug_label`.
    pub fn new(app: &mut App, debug_label: Option<String>) -> Ref<OverlayPortalController> {
        app.create(OverlayPortalController {
            attach_target: None,
            z_order_index: None,
            debug_label,
        })
    }

    // Returns a unique and monotonically increasing timestamp that represents now.
    //
    // The value this method returns increments after each call.
    fn now(self: Handle<Self>, app: &App) -> i64 {
        let now = WALL_TIME.get() + 1;
        WALL_TIME.set(now);
        debug_assert!(app.get(self).z_order_index.is_none_or(|index| index < now));
        debug_assert!(
            app.get(self)
                .attach_target
                .and_then(|target| app.get(target).z_order_index)
                .is_none_or(|index| index < now)
        );
        now
    }

    /// Show the overlay child of the [`OverlayPortal`] this controller is attached to, at the
    /// top of the target [`Overlay`].
    ///
    /// When there is more than one [`OverlayPortal`] that targets the same [`Overlay`], the
    /// overlay child of the last [`OverlayPortal`] to have called
    /// [`show`](Self::show) appears at the top level, unobstructed.
    ///
    /// If [`is_showing`](Self::is_showing) is already true, calling this method brings the
    /// overlay child it controls to the top.
    ///
    /// This method should typically not be called while the widget tree is being rebuilt.
    pub fn show(self: Handle<Self>, app: &mut App) {
        let now = self.now(app);
        match app.get(self).attach_target {
            Some(state) => state.show(app, now),
            None => app.get_mut(self).z_order_index = Some(now),
        }
    }

    /// Hide the [`OverlayPortal`]'s overlay child.
    ///
    /// Once hidden, the overlay child will be removed from the widget tree the next time the
    /// widget tree rebuilds, and stateful widgets in the overlay child may lose state as a
    /// result.
    ///
    /// This method should typically not be called while the widget tree is being rebuilt.
    pub fn hide(self: Handle<Self>, app: &mut App) {
        match app.get(self).attach_target {
            Some(state) => state.hide(app),
            None => {
                debug_assert!(app.get(self).z_order_index.is_some());
                app.get_mut(self).z_order_index = None;
            }
        }
    }

    /// Whether the associated [`OverlayPortal`] should build and show its overlay child,
    /// using its [`overlay_child_builder`](OverlayPortal::overlay_child_builder).
    pub fn is_showing(self: Handle<Self>, app: &App) -> bool {
        match app.get(self).attach_target {
            Some(state) => app.get(state).z_order_index.is_some(),
            None => app.get(self).z_order_index.is_some(),
        }
    }

    /// Convenience method for toggling the current [`is_showing`](Self::is_showing) status.
    ///
    /// This method should typically not be called while the widget tree is being rebuilt.
    pub fn toggle(self: Handle<Self>, app: &mut App) {
        if self.is_showing(app) {
            self.hide(app);
        } else {
            self.show(app);
        }
    }
}

impl Debug for OverlayPortalController {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "OverlayPortalController")?;
        if let Some(label) = &self.debug_label {
            write!(f, "({label})")?;
        }
        if self.attach_target.is_none() {
            write!(f, " DETACHED")?;
        }
        Ok(())
    }
}

/// The location of the [`Overlay`] that an [`OverlayPortal`] renders its overlay child on.
///
/// This is typically used in [`OverlayPortal`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OverlayChildLocation {
    /// The [`OverlayPortal`] renders its overlay child on the closest ancestor [`Overlay`]
    /// above the widget tree.
    NearestOverlay,

    /// The [`OverlayPortal`] renders its overlay child on the root [`Overlay`] above the
    /// widget tree.
    ///
    /// In case of multi-view apps, the root [`Overlay`] refers to the first Overlay below the
    /// `View`.
    RootOverlay,
}

/// A widget that renders its overlay child on an [`Overlay`].
///
/// The overlay child is initially hidden until [`OverlayPortalController::show`] is called on
/// the associated [`controller`](Self::controller). The [`OverlayPortal`] uses
/// [`overlay_child_builder`](Self::overlay_child_builder) to build its overlay child and
/// renders it on the specified [`Overlay`] as if it was inserted using an [`OverlayEntry`],
/// while it can depend on the same set of `InheritedWidget`s that this widget can depend on.
///
/// This widget requires an [`Overlay`] ancestor in the widget tree when its overlay child is
/// showing. The overlay child is rendered by the [`Overlay`] ancestor, not by the widget
/// itself. This allows the overlay child to float above other widgets, independent of its
/// position in the widget tree.
///
/// When [`OverlayPortalController::hide`] is called, the widget built using
/// [`overlay_child_builder`](Self::overlay_child_builder) will be removed from the widget
/// tree the next time the widget rebuilds. Stateful descendants in the overlay child subtree
/// may lose state as a result.
///
/// ### Paint Order
///
/// In an [`Overlay`], an overlay child is painted after the [`OverlayEntry`] associated with
/// its [`OverlayPortal`] (that is, the [`OverlayEntry`] closest to the [`OverlayPortal`] in
/// the widget tree, which usually represents the enclosing `Route`), and before the next
/// [`OverlayEntry`].
///
/// When an [`OverlayEntry`] has multiple associated [`OverlayPortal`]s, the paint order
/// between their overlay children is the order in which [`OverlayPortalController::show`] was
/// called. The last [`OverlayPortal`] to have called `show` gets to paint its overlay child
/// in the foreground.
///
/// ### Differences between [`OverlayPortal`] and [`OverlayEntry`]
///
/// The main difference between [`OverlayEntry`] and [`OverlayPortal`] is that [`OverlayEntry`]
/// builds its widget subtree as a child of the target [`Overlay`], while [`OverlayPortal`]
/// uses [`overlay_child_builder`](Self::overlay_child_builder) to build a child widget of
/// itself. This allows [`OverlayPortal`]'s overlay child to depend on the same set of
/// `InheritedWidget`s as [`OverlayPortal`], and it's also guaranteed that the overlay child
/// will not outlive its [`OverlayPortal`].
///
/// On the other hand, [`OverlayPortal`]'s implementation is more complex. For instance, it
/// does a bit more work than a regular widget during global key reparenting. If the content
/// to be shown on the [`Overlay`] doesn't benefit from being a part of [`OverlayPortal`]'s
/// subtree, consider using an [`OverlayEntry`] instead.
///
/// See also:
///
///  * [`OverlayEntry`], an alternative API for inserting widgets into an [`Overlay`].
///  * `Positioned`, which can be used to size and position the overlay child in relation to
///    the target [`Overlay`]'s boundaries.
pub struct OverlayPortal {
    /// See [`Widget::key`].
    pub key: Option<KeyRef>,
    /// The controller to show, hide and bring to top the overlay child.
    pub controller: Ref<OverlayPortalController>,
    /// A [`WidgetBuilder`] used to build a widget below this widget in the tree, that renders
    /// on the closest [`Overlay`].
    ///
    /// The said widget will only be built and shown in the closest [`Overlay`] once
    /// [`OverlayPortalController::show`] is called on the associated
    /// [`controller`](Self::controller). It will be painted in front of the [`OverlayEntry`]
    /// closest to this widget in the widget tree (which is usually the enclosing `Route`).
    ///
    /// The built overlay child widget is inserted below this widget in the widget tree,
    /// allowing it to depend on `InheritedWidget`s above it, and be notified when the
    /// `InheritedWidget`s change.
    ///
    /// Unlike [`child`](Self::child), the built overlay child can visually extend outside the
    /// bounds of this widget without being clipped, and receive hit-test events outside of
    /// this widget's bounds, as long as it does not extend outside of the [`Overlay`] on
    /// which it is rendered.
    pub overlay_child_builder: WidgetBuilder,
    /// A widget below this widget in the tree.
    pub child: Option<WidgetRef>,
    /// The [`Overlay`] that the widget returned from
    /// [`overlay_child_builder`](Self::overlay_child_builder) is attached to.
    pub overlay_location: OverlayChildLocation,
}

impl OverlayPortal {
    /// Creates an [`OverlayPortal`] that renders the widget `overlay_child_builder` builds on
    /// the closest [`Overlay`] when [`OverlayPortalController::show`] is called.
    ///
    /// The [`overlay_location`](Self::overlay_location) sets which [`Overlay`] this widget
    /// attaches the widget returned by `overlay_child_builder` to. Defaults to
    /// [`OverlayChildLocation::NearestOverlay`].
    pub fn new(
        controller: Ref<OverlayPortalController>,
        overlay_child_builder: impl Fn(&mut App, BuildContext) -> WidgetRef + 'static,
    ) -> OverlayPortal {
        OverlayPortal {
            key: None,
            controller,
            overlay_child_builder: Rc::new(overlay_child_builder),
            child: None,
            overlay_location: OverlayChildLocation::NearestOverlay,
        }
    }

    /// Creates an [`OverlayPortal`] that renders the widget `overlay_child_builder` builds on
    /// the root [`Overlay`] when [`OverlayPortalController::show`] is called.
    ///
    /// Deprecated in Flutter after v3.33.0-0.0.pre: use [`OverlayPortal::new`] with
    /// [`overlay_location`](Self::overlay_location) set to
    /// [`OverlayChildLocation::RootOverlay`] instead.
    #[deprecated(note = "Use OverlayPortal::new with an overlay_location of \
                OverlayChildLocation::RootOverlay instead. This feature was deprecated \
                after v3.33.0-0.0.pre.")]
    pub fn targets_root_overlay(
        controller: Ref<OverlayPortalController>,
        overlay_child_builder: impl Fn(&mut App, BuildContext) -> WidgetRef + 'static,
    ) -> OverlayPortal {
        OverlayPortal {
            key: None,
            controller,
            overlay_child_builder: Rc::new(overlay_child_builder),
            child: None,
            overlay_location: OverlayChildLocation::RootOverlay,
        }
    }

    /// Creates an [`OverlayPortal`] that renders the widget `overlay_child_builder` builds on
    /// the closest [`Overlay`] when [`OverlayPortalController::show`] is called.
    ///
    /// Developers can use `overlay_child_builder` to configure the overlay child based on the
    /// size and the location of [`child`](Self::child) within the target [`Overlay`], as well
    /// as the size of the [`Overlay`] itself. This allows the overlay child to, for example,
    /// always follow [`child`](Self::child) and at the same time resize itself based on how
    /// close it is to the edges of the [`Overlay`].
    ///
    /// The `overlay_child_builder` callback is called during layout. To ensure the paint
    /// transform of [`child`](Self::child) in relation to the target [`Overlay`] is
    /// up-to-date by then, all render objects between the [`OverlayPortal`] and the target
    /// [`Overlay`] must establish their paint transform during the layout phase, which most
    /// render objects do.
    ///
    /// The [`overlay_location`](Self::overlay_location) sets which [`Overlay`] this widget
    /// attaches the widget returned by `overlay_child_builder` to. Defaults to
    /// [`OverlayChildLocation::NearestOverlay`].
    pub fn overlay_child_layout_builder(
        controller: Ref<OverlayPortalController>,
        overlay_child_builder: impl Fn(&mut App, BuildContext, OverlayChildLayoutInfo) -> WidgetRef
        + 'static,
    ) -> OverlayPortal {
        let builder: OverlayChildLayoutBuilder = Rc::new(overlay_child_builder);
        OverlayPortal::new(controller, move |_app, _context| {
            OverlayChildLayoutBuilderWidget {
                builder: Rc::clone(&builder),
                created: None,
            }
            .into_widget()
        })
    }

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

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

    /// Dart `OverlayPortal(overlayLocation:)`.
    pub fn overlay_location(mut self, overlay_location: OverlayChildLocation) -> OverlayPortal {
        self.overlay_location = overlay_location;
        self
    }
}

impl Debug for OverlayPortal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("OverlayPortal")
            .field("overlayLocation", &self.overlay_location)
            .finish_non_exhaustive()
    }
}

impl StatefulWidget for OverlayPortal {
    type State = OverlayPortalState;

    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn create_state(&self) -> OverlayPortalState {
        OverlayPortalState {
            state: StateData::new(),
            z_order_index: None,
            child_model_may_have_changed: true,
            location_cache: None,
        }
    }
}

/// Dart's `_OverlayPortalState`.
pub struct OverlayPortalState {
    state: StateData<OverlayPortal>,
    z_order_index: Option<i64>,
    // The location of the overlay child within the overlay. This object will be used as the
    // slot of the overlay child widget.
    //
    // The developer must call `show` to reveal the overlay so we can get a unique timestamp of
    // the user interaction for determining the z-index of the overlay child in the overlay.
    //
    // Avoid invalidating the cache if possible, since the framework uses identity to compare
    // slots, and OverlayEntryLocation is mutable. Changing slots can be relatively slow.
    child_model_may_have_changed: bool,
    location_cache: Option<Ref<OverlayEntryLocation>>,
}

impl OverlayPortalState {
    fn is_the_same_location(
        app: &App,
        location_cache: Handle<OverlayEntryLocation>,
        marker: &TheaterLocation,
    ) -> bool {
        let cached = app.get(location_cache);
        cached.child_model == marker.overlay_entry_widget_state && cached.theater == marker.theater
    }

    fn get_location(
        self: Handle<Self>,
        app: &mut App,
        z_order_index: i64,
        overlay_location: OverlayChildLocation,
    ) -> Ref<OverlayEntryLocation> {
        let cached_location = app.get(self).location_cache.clone();
        let context = self.context(app);
        let target_root_overlay = overlay_location == OverlayChildLocation::RootOverlay;
        // Dart's `late final marker`: reading it depends on an inherited widget, which the
        // valid-cache path must not do.
        let mut marker = None;
        let is_cache_valid = cached_location.as_ref().is_some_and(|cached| {
            !app.get(self).child_model_may_have_changed || {
                let found = RenderTheaterMarker::of(app, context, target_root_overlay);
                marker = Some(found);
                OverlayPortalState::is_the_same_location(app, cached.handle(), &found)
            }
        });
        app.get_mut(self).child_model_may_have_changed = false;
        if is_cache_valid {
            let cached = cached_location.expect("a valid cache holds a location");
            debug_assert!(app.get(&cached).z_order_index == z_order_index);
            debug_assert!(cached.debug_is_location_valid(app));
            return cached;
        }
        // Otherwise invalidate the cache and create a new location.
        if let Some(cached) = &cached_location {
            cached.debug_mark_location_invalid(app);
        }
        let marker = match marker {
            Some(marker) => marker,
            None => RenderTheaterMarker::of(app, context, target_root_overlay),
        };
        let new_location = OverlayEntryLocation::new(
            app,
            z_order_index,
            marker.overlay_entry_widget_state,
            marker.theater,
        );
        app.get_mut(self).location_cache = Some(new_location.clone());
        new_location
    }

    fn setup_controller(
        self: Handle<Self>,
        app: &mut App,
        controller: Handle<OverlayPortalController>,
    ) {
        debug_assert!(
            app.get(controller).attach_target == Some(self)
                || !app
                    .get(controller)
                    .attach_target
                    .is_some_and(|target| target.mounted(app)),
            "Failed to attach the controller: it is already attached to another OverlayPortal."
        );
        let controller_z_order_index = app.get(controller).z_order_index;
        let z_order_index = app.get(self).z_order_index;
        let takes_controller_index = match (controller_z_order_index, z_order_index) {
            (_, None) => true,
            (Some(controller_index), Some(index)) => controller_index > index,
            (None, Some(_)) => false,
        };
        if takes_controller_index {
            app.get_mut(self).z_order_index = controller_z_order_index;
        }
        let controller_state = app.get_mut(controller);
        controller_state.z_order_index = None;
        controller_state.attach_target = Some(self);
    }

    fn show(self: Handle<Self>, app: &mut App, z_order_index: i64) {
        debug_assert!(
            SchedulerBinding::scheduler_phase(app) != SchedulerPhase::PersistentCallbacks,
            "OverlayPortalController::show should not be called during build."
        );
        self.set_state(app, |state| state.z_order_index = Some(z_order_index));
        if let Some(cached) = app.get(self).location_cache.handle() {
            cached.debug_mark_location_invalid(app);
        }
        app.get_mut(self).location_cache = None;
    }

    fn hide(self: Handle<Self>, app: &mut App) {
        debug_assert!(
            SchedulerBinding::scheduler_phase(app) != SchedulerPhase::PersistentCallbacks,
            "OverlayPortalController::hide should not be called during build."
        );
        self.set_state(app, |state| state.z_order_index = None);
        if let Some(cached) = app.get(self).location_cache.handle() {
            cached.debug_mark_location_invalid(app);
        }
        app.get_mut(self).location_cache = None;
    }
}

impl State for OverlayPortalState {
    type Widget = OverlayPortal;

    crate::state_accessors!();

    fn init_state(self: Handle<Self>, app: &mut App) {
        let controller = self.widget(app).controller.handle();
        self.setup_controller(app, controller);
    }

    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
        app.get_mut(self).child_model_may_have_changed = true;
    }

    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &OverlayPortal) {
        let (old_location, old_controller) =
            (old_widget.overlay_location, old_widget.controller.handle());
        let widget = self.widget(app);
        let (new_location, new_controller) = (widget.overlay_location, widget.controller.handle());
        let state = app.get_mut(self);
        state.child_model_may_have_changed =
            state.child_model_may_have_changed || old_location != new_location;
        if old_controller != new_controller {
            app.get_mut(old_controller).attach_target = None;
            self.setup_controller(app, new_controller);
        }
    }

    fn activate(self: Handle<Self>, app: &mut App) {
        debug_assert!(app.get(&self.widget(app).controller).attach_target == Some(self));
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        let controller = self.widget(app).controller.handle();
        app.get_mut(controller).attach_target = None;
        if let Some(cached) = app.get(self).location_cache.handle() {
            cached.debug_mark_location_invalid(app);
        }
        app.get_mut(self).location_cache = None;
    }

    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
        let child = self.widget(app).child.clone();
        let Some(z_order_index) = app.get(self).z_order_index else {
            return RawOverlayPortal {
                overlay_location: None,
                overlay_child: None,
                child,
                created: None,
            }
            .into_widget();
        };

        let widget_location = self.widget(app).overlay_location;
        let overlay_location = self.get_location(app, z_order_index, widget_location);
        let child_model_context = app.get(&overlay_location).child_model.context(app);
        let overlay_data = MediaQuery::of(app, child_model_context);
        let data = MediaQuery::of(app, context)
            .copy_with()
            .padding(overlay_data.padding)
            .view_insets(overlay_data.view_insets)
            .view_padding(overlay_data.view_padding);
        let builder = Rc::clone(&self.widget(app).overlay_child_builder);
        RawOverlayPortal {
            overlay_location: Some(overlay_location),
            created: None,
            overlay_child: Some(
                DeferredLayout {
                    child: MediaQuery::new(data, Builder { key: None, builder }).into_widget(),
                }
                .into_widget(),
            ),
            child,
        }
        .into_widget()
    }
}

/// A location in an [`Overlay`].
///
/// An [`OverlayEntryLocation`] determines the [`Overlay`] the associated [`OverlayPortal`]
/// should put its overlay child onto, as well as the overlay child's paint order in relation
/// to other contents painted on the [`Overlay`].
//
// An OverlayEntryLocation is a cursor pointing to a location in a particular Overlay's child
// model, and provides methods to insert/remove/move a RenderDeferredLayoutBox to/from its
// target theater.
//
// The occupant (a `RenderBox`) will be painted above the associated OverlayEntry, but below
// the OverlayEntry above that OverlayEntry.
//
// Additionally, `reattach_from_layout_surrogate` and `detach_from_layout_surrogate` are
// called when the overlay child's RawOverlayPortalElement activates/deactivates (for instance,
// during global key reparenting). RawOverlayPortalElement removes its overlay child's render
// object from the target RenderTheater when it deactivates and puts it back on activation.
// These two methods can be used to "hide" a child in the child model without removing it, when
// the child is expensive/difficult to re-insert at the correct location on activation.
//
// ### Equality
//
// An OverlayEntryLocation is used as an Element's slot. These three parts uniquely identify a
// place in an overlay's child model:
// - theater
// - child_model (the OverlayEntry)
// - z_order_index
//
// Since it is mutable, slots compare it by identity, and the same OverlayEntryLocation must
// not be used to represent more than one location.
struct OverlayEntryLocation {
    z_order_index: i64,
    child_model: Handle<OverlayEntryWidgetState>,
    theater: RenderHandle<RenderTheater>,
    overlay_child_render_box: Option<RenderHandle<RenderDeferredLayoutBox>>,
    // The identity a `Slot::Custom` compares: created with the location and never replaced.
    slot_token: Option<Rc<dyn Any>>,
    // Dart records the `StackTrace` of the first `_debugMarkLocationInvalid` call; only the
    // flag is kept here (see `PORTING.md`). The effect is not reversible: once marked invalid,
    // this object cannot be marked valid again.
    debug_location_invalid: bool,
}

impl OverlayEntryLocation {
    fn new(
        app: &mut App,
        z_order_index: i64,
        child_model: Handle<OverlayEntryWidgetState>,
        theater: RenderHandle<RenderTheater>,
    ) -> Ref<OverlayEntryLocation> {
        let this = app.create(OverlayEntryLocation {
            z_order_index,
            child_model,
            theater,
            overlay_child_render_box: None,
            slot_token: None,
            debug_location_invalid: false,
        });
        app.get_mut(&this).slot_token = Some(Rc::new(this.handle()));
        this
    }

    /// The slot the overlay child element occupies: this location, compared by identity.
    fn slot(self: Handle<Self>, app: &App) -> Slot {
        Slot::Custom(Rc::clone(
            app.get(self)
                .slot_token
                .as_ref()
                .expect("the token is created with the location"),
        ))
    }

    /// The location a slot names, if it names one.
    fn from_slot(slot: &Slot) -> Option<Handle<OverlayEntryLocation>> {
        match slot {
            Slot::Custom(token) => token
                .downcast_ref::<Handle<OverlayEntryLocation>>()
                .copied(),
            _ => None,
        }
    }

    fn add_to_child_model(
        self: Handle<Self>,
        app: &mut App,
        child: RenderHandle<RenderDeferredLayoutBox>,
    ) {
        debug_assert!(
            app.get(self).overlay_child_render_box.is_none(),
            "Failed to add the child: this location is already occupied."
        );
        app.get_mut(self).overlay_child_render_box = Some(child);
        let (child_model, theater) = {
            let location = app.get(self);
            (location.child_model, location.theater)
        };
        let kept = self.keep(app);
        child_model.add(app, kept);
        theater.mark_needs_paint(app);
    }

    fn remove_from_child_model(
        self: Handle<Self>,
        app: &mut App,
        child: RenderHandle<RenderDeferredLayoutBox>,
    ) {
        debug_assert!(app.get(self).overlay_child_render_box == Some(child));
        app.get_mut(self).overlay_child_render_box = None;
        let (child_model, theater) = {
            let location = app.get(self);
            (location.child_model, location.theater)
        };
        child_model.remove(app, self);
        theater.mark_needs_paint(app);
    }

    fn add_child(self: Handle<Self>, app: &mut App, child: RenderHandle<RenderDeferredLayoutBox>) {
        debug_assert!(self.debug_is_location_valid(app));
        self.add_to_child_model(app, child);
        let theater = app.get(self).theater;
        theater.add_deferred_child(app, child);
        debug_assert!(child.parent(app) == Some(theater.as_object()));
    }

    fn remove_child(
        self: Handle<Self>,
        app: &mut App,
        child: RenderHandle<RenderDeferredLayoutBox>,
    ) {
        // This call is allowed even when this location is disposed.
        self.remove_from_child_model(app, child);
        let theater = app.get(self).theater;
        theater.remove_deferred_child(app, child);
        debug_assert!(child.parent(app).is_none());
    }

    fn move_child(
        self: Handle<Self>,
        app: &mut App,
        child: RenderHandle<RenderDeferredLayoutBox>,
        from_location: Handle<OverlayEntryLocation>,
    ) {
        debug_assert!(from_location != self);
        debug_assert!(self.debug_is_location_valid(app));
        let from_theater = app.get(from_location).theater;
        let from_model = app.get(from_location).child_model;
        let theater = app.get(self).theater;

        if from_theater != theater {
            from_theater.remove_deferred_child(app, child);
            theater.add_deferred_child(app, child);
        }

        if from_model != app.get(self).child_model
            || app.get(from_location).z_order_index != app.get(self).z_order_index
        {
            from_location.remove_from_child_model(app, child);
            self.add_to_child_model(app, child);
        }
    }

    /// Undoes [`detach_from_layout_surrogate`](Self::detach_from_layout_surrogate) by adding
    /// the given `child` back to the theater.
    ///
    /// This is called when the [`OverlayPortal`] is activated. This call is allowed even when
    /// this location is invalidated.
    fn reattach_from_layout_surrogate(
        self: Handle<Self>,
        app: &mut App,
        child: RenderHandle<RenderDeferredLayoutBox>,
    ) {
        debug_assert!(
            app.get(self).overlay_child_render_box.is_none(),
            "failed to reattach: detach_from_layout_surrogate must be called before \
             reattach_from_layout_surrogate."
        );
        let theater = app.get(self).theater;
        theater.add_deferred_child(app, child);
        app.get_mut(self).overlay_child_render_box = Some(child);
    }

    /// Removes the given `child` from the theater but keeps it in the child list (unlike
    /// [`remove_child`](Self::remove_child)).
    ///
    /// This is typically called when the [`OverlayPortal`] deactivates. Since every render
    /// object in the render tree must be attached, when an [`OverlayPortal`] deactivates, it
    /// must remove the overlay child from the render tree instead of just detaching it.
    ///
    /// This call is allowed even when this location is invalidated.
    fn detach_from_layout_surrogate(
        self: Handle<Self>,
        app: &mut App,
        child: RenderHandle<RenderDeferredLayoutBox>,
    ) {
        let theater = app.get(self).theater;
        theater.remove_deferred_child(app, child);
        app.get_mut(self).overlay_child_render_box = None;
    }

    // Panics if this location is already invalidated and shouldn't be used as an OverlayPortal
    // slot. Must be used in asserts.
    //
    // Generally, `debug_assert!(location.debug_is_location_valid(app))` should be used to
    // prevent invalid accesses to an invalid location. Exceptions to this rule are
    // `remove_child` and `detach_from_layout_surrogate`, which are called when the
    // OverlayPortal is being removed from the widget tree and may use the location information
    // to perform cleanup tasks.
    //
    // Another exception is `reattach_from_layout_surrogate`, which is called shortly after the
    // OverlayPortal activates because it's possible that the widget subtree hasn't been
    // rebuilt at that point, so we'll have to re-attach the overlay child render object using
    // a potentially outdated location.
    fn debug_is_location_valid(self: Handle<Self>, app: &App) -> bool {
        assert!(
            !app.get(self).debug_location_invalid,
            "this OverlayPortal location is already disposed."
        );
        true
    }

    fn debug_mark_location_invalid(self: Handle<Self>, app: &mut App) {
        debug_assert!(self.debug_is_location_valid(app));
        if cfg!(debug_assertions) {
            app.get_mut(self).debug_location_invalid = true;
        }
    }
}

/// Dart's `_OverlayPortal`: the render object widget an [`OverlayPortal`] builds.
#[derive(Debug)]
struct RawOverlayPortal {
    overlay_child: Option<WidgetRef>,
    /// A widget below this widget in the tree.
    child: Option<WidgetRef>,
    overlay_location: Option<Ref<OverlayEntryLocation>>,
    /// Where this widget was made, in a debug build; see [`Widget::creation_location`].
    created: Option<CreationLocation>,
}

impl RawOverlayPortal {
    /// The tree node: a render object widget with its own element, outside the `IntoWidget`
    /// kinds.
    #[cfg_attr(debug_assertions, track_caller)]
    fn into_widget(mut self) -> WidgetRef {
        debug_assert!(self.overlay_child.is_none() || self.overlay_location.is_some());
        self.created = Some(CreationLocation::of_caller());
        Rc::new(self)
    }
}

impl Widget for RawOverlayPortal {
    fn key(&self) -> Option<&KeyRef> {
        None
    }

    fn creation_location(&self) -> Option<&'static Location<'static>> {
        self.created.and_then(CreationLocation::location)
    }

    fn record_creation_location(&mut self, location: CreationLocation) {
        self.created = Some(location);
    }

    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
        RawOverlayPortalElement::new(app, this).as_element()
    }

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

    fn widget_type(&self) -> std::any::TypeId {
        std::any::TypeId::of::<RawOverlayPortal>()
    }

    fn kind(&self) -> WidgetKind {
        WidgetKind::Other
    }
}

impl RenderObjectWidget for RawOverlayPortal {
    type RenderObject = RenderLayoutSurrogateProxyBox;

    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
        RenderLayoutSurrogateProxyBox::new(app, self.overlay_location.clone()).as_object()
    }

    fn update_render_object(
        &self,
        app: &mut App,
        _context: BuildContext,
        render_object: RenderHandle<RenderLayoutSurrogateProxyBox>,
    ) {
        render_object.get_mut(app).overlay_location = self.overlay_location.clone();
    }
}

/// Dart's `_OverlayPortalElement`: it holds the regular child and the overlay child, whose
/// slot is its [`OverlayEntryLocation`].
struct RawOverlayPortalElement {
    element: ElementData,
    render_object_element: RenderObjectElementData,
    overlay_child: Option<AnyElement>,
    child: Option<AnyElement>,
}

impl RawOverlayPortalElement {
    fn new(app: &mut App, widget: WidgetRef) -> Handle<RawOverlayPortalElement> {
        debug_assert!(downcast_widget::<RawOverlayPortal>(&*widget).is_some());
        app.create(RawOverlayPortalElement {
            element: ElementData::new(widget),
            render_object_element: RenderObjectElementData::default(),
            overlay_child: None,
            child: None,
        })
        .into_tree_node(app)
    }

    fn update_children(self: Handle<Self>, app: &mut App) {
        let this = self.as_element();
        let (child_widget, overlay_child_widget, overlay_location) = {
            let widget = Self::widget_of(this.widget(app));
            (
                widget.child.clone(),
                widget.overlay_child.clone(),
                widget.overlay_location.handle(),
            )
        };
        let child = app.get(self).child;
        let child = this.update_child(app, child, child_widget, None);
        app.get_mut(self).child = child;
        let slot = overlay_location.map(|location| location.slot(app));
        let overlay_child = app.get(self).overlay_child;
        let overlay_child = this.update_child(app, overlay_child, overlay_child_widget, slot);
        app.get_mut(self).overlay_child = overlay_child;
    }

    fn surrogate(self: Handle<Self>, app: &App) -> RenderHandle<RenderLayoutSurrogateProxyBox> {
        self.typed_render_object(app)
    }
}

impl RenderObjectElementWidget for RawOverlayPortalElement {
    type Widget = RawOverlayPortal;

    fn widget_of(widget: &WidgetRef) -> &RawOverlayPortal {
        downcast_widget::<RawOverlayPortal>(&**widget)
            .expect("a RawOverlayPortalElement holds a RawOverlayPortal")
    }
}

impl RenderObjectElement for RawOverlayPortalElement {
    fn render_object_element_data(self: Handle<Self>, app: &App) -> &RenderObjectElementData {
        &app.get(self).render_object_element
    }

    fn render_object_element_data_mut(
        self: Handle<Self>,
        app: &mut App,
    ) -> &mut RenderObjectElementData {
        &mut app.get_mut(self).render_object_element
    }
}

impl Element for RawOverlayPortalElement {
    crate::element_accessors!();

    const IS_RENDER_OBJECT_ELEMENT: bool = true;

    fn debug_fill_properties(
        self: Handle<Self>,
        app: &App,
        properties: &mut DiagnosticPropertiesBuilder,
    ) {
        let state = app.get(self);
        properties.add(
            DiagnosticsProperty::<String>::new(
                "child",
                state.child.map(|child| child.to_string_short(app)),
            )
            .default_value(None),
        );
        properties.add(
            DiagnosticsProperty::<String>::new(
                "overlayChild",
                state.overlay_child.map(|child| child.to_string_short(app)),
            )
            .default_value(None),
        );
        properties.add(
            DiagnosticsProperty::<String>::new(
                "overlayLocation",
                state
                    .overlay_child
                    .and_then(|child| child.slot(app))
                    .map(|slot| format!("{slot:?}")),
            )
            .default_value(None),
        );
    }

    fn render_object(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
        self.render_object_element_data(app).render_object()
    }

    fn render_object_attaching_child(self: Handle<Self>, _app: &App) -> Option<AnyElement> {
        None
    }

    fn debug_doing_build(self: Handle<Self>, app: &App) -> bool {
        self.render_object_element_data(app).debug_doing_build()
    }

    fn mount(
        self: Handle<Self>,
        app: &mut App,
        parent: Option<AnyElement>,
        new_slot: Option<Slot>,
    ) {
        RenderObjectElement::mount(self, app, parent, new_slot);
        self.update_children(app);
    }

    fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
        RenderObjectElement::update(self, app, new_widget);
        self.update_children(app);
    }

    fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
        // The overlay child element does not have a key because the DeferredLayout widget does
        // not take a Key, so only the regular child can be taken during global key
        // reparenting.
        debug_assert!(app.get(self).child == Some(child));
        app.get_mut(self).child = None;
    }

    fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
        let state = app.get(self);
        let (child, overlay_child) = (state.child, state.overlay_child);
        if let Some(child) = child {
            visitor(child);
        }
        if let Some(overlay_child) = overlay_child {
            visitor(overlay_child);
        }
    }

    fn perform_rebuild(self: Handle<Self>, app: &mut App) {
        RenderObjectElement::perform_rebuild(self, app);
    }

    fn deactivate(self: Handle<Self>, app: &mut App) {
        RenderObjectElement::deactivate(self, app);
    }

    fn unmount(self: Handle<Self>, app: &mut App) {
        RenderObjectElement::unmount(self, app);
    }

    fn update_parent_data(self: Handle<Self>, app: &mut App, parent_data_element: AnyElement) {
        RenderObjectElement::update_parent_data(self, app, parent_data_element);
    }

    fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
        RenderObjectElement::update_slot(self, app, new_slot);
    }

    fn attach_render_object(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
        RenderObjectElement::attach_render_object(self, app, new_slot);
    }

    fn detach_render_object(self: Handle<Self>, app: &mut App) {
        RenderObjectElement::detach_render_object(self, app);
    }

    fn insert_render_object_child(
        self: Handle<Self>,
        app: &mut App,
        child: AnyRenderObject,
        slot: Option<Slot>,
    ) {
        debug_assert!(child.parent(app).is_none());
        let surrogate = self.surrogate(app);
        match slot.as_ref().and_then(OverlayEntryLocation::from_slot) {
            Some(location) => {
                let deferred = child
                    .downcast::<RenderDeferredLayoutBox>(app)
                    .expect("an overlay child is a DeferredLayout");
                // The deferred child is assigned in DeferredLayout's create_render_object.
                debug_assert!(surrogate.get(app).deferred_layout_child == Some(deferred));
                location.add_child(app, deferred);
            }
            None => surrogate.set_child(app, Some(child.as_box().expect("a box child"))),
        }
    }

    // The DeferredLayout widget does not have a key so there will be no reparenting between
    // the overlay child and the child, hence the non-null slots.
    fn move_render_object_child(
        self: Handle<Self>,
        app: &mut App,
        child: AnyRenderObject,
        old_slot: Option<Slot>,
        new_slot: Option<Slot>,
    ) {
        let old_location = old_slot
            .as_ref()
            .and_then(OverlayEntryLocation::from_slot)
            .expect("an overlay child moves between locations");
        let new_location = new_slot
            .as_ref()
            .and_then(OverlayEntryLocation::from_slot)
            .expect("an overlay child moves between locations");
        debug_assert!(new_location.debug_is_location_valid(app));
        let deferred = child
            .downcast::<RenderDeferredLayoutBox>(app)
            .expect("an overlay child is a DeferredLayout");
        new_location.move_child(app, deferred, old_location);
    }

    fn remove_render_object_child(
        self: Handle<Self>,
        app: &mut App,
        child: AnyRenderObject,
        slot: Option<Slot>,
    ) {
        let surrogate = self.surrogate(app);
        let Some(location) = slot.as_ref().and_then(OverlayEntryLocation::from_slot) else {
            surrogate.set_child(app, None);
            return;
        };
        let deferred = child
            .downcast::<RenderDeferredLayoutBox>(app)
            .expect("an overlay child is a DeferredLayout");
        debug_assert!(surrogate.get(app).deferred_layout_child == Some(deferred));
        location.remove_child(app, deferred);
        surrogate.get_mut(app).deferred_layout_child = None;
    }
}

/// Dart's `_DeferredLayout`: the overlay child's own render object widget.
#[derive(Debug)]
struct DeferredLayout {
    // This widget must not be given a key: reparenting between the overlay child and the child
    // is not supported.
    child: WidgetRef,
}

impl DeferredLayout {
    fn layout_parent(
        app: &App,
        context: BuildContext,
    ) -> RenderHandle<RenderLayoutSurrogateProxyBox> {
        context
            .find_ancestor_render_object_of_type::<RenderLayoutSurrogateProxyBox>(app)
            .expect("a _DeferredLayout is built by an OverlayPortal")
    }
}

impl RenderObjectWidget for DeferredLayout {
    type RenderObject = RenderDeferredLayoutBox;

    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
        let parent = DeferredLayout::layout_parent(app, context);
        let render_object = RenderDeferredLayoutBox::new(app, parent);
        parent.get_mut(app).deferred_layout_child = Some(render_object);
        render_object.as_object()
    }

    fn update_render_object(
        &self,
        app: &mut App,
        context: BuildContext,
        render_object: RenderHandle<RenderDeferredLayoutBox>,
    ) {
        debug_assert!(
            render_object.get(app).layout_surrogate == DeferredLayout::layout_parent(app, context)
        );
        debug_assert!(
            DeferredLayout::layout_parent(app, context)
                .get(app)
                .deferred_layout_child
                == Some(render_object)
        );
    }
}

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

// This render object must be a child of a [`RenderTheater`]. It guarantees that it only does
// layout after the sizes of the render objects from its `layout_surrogate` (which must be a
// descendant of this object's parent) through the parent RenderTheater are known. To this end:
//
// 1. It's a relayout boundary, and adding it to the RenderTheater as a child never dirties its
//    RenderTheater. Instead, it is always added to the PipelineOwner's dirty list when it
//    needs layout (even for the initial layout when it is first added to the tree).
//
// 2. Its layout is driven through `do_layout_from` such that `perform_layout` does not do
//    anything when it is called from the tree walk, preventing the parent RenderTheater from
//    laying out this subtree prematurely (but this object may still be resized). Instead,
//    `mark_needs_layout` is called from within `do_layout_from` to schedule a layout update for
//    this relayout boundary when needed.
//
// When invoked from `PipelineOwner::flush_layout`, this object behaves like an [`Overlay`] that
// has only one entry.
struct RenderDeferredLayoutBox {
    render_object: RenderObjectData,
    render_box: RenderBoxData,
    child: RenderObjectWithChildData<AnyRenderBox>,
    layout_surrogate: RenderHandle<RenderLayoutSurrogateProxyBox>,
    /// Whether this box's layout is currently being driven by the theater's or the layout
    /// surrogate's `perform_layout`.
    doing_layout_from_tree_walk: bool,
    debug_mutations_locked: bool,
}

impl RenderDeferredLayoutBox {
    fn new(
        app: &mut App,
        layout_surrogate: RenderHandle<RenderLayoutSurrogateProxyBox>,
    ) -> RenderHandle<RenderDeferredLayoutBox> {
        RenderHandle::new_box(
            app,
            RenderDeferredLayoutBox {
                render_object: RenderObjectData::new(),
                render_box: RenderBoxData::new(),
                child: RenderObjectWithChildData::new(),
                layout_surrogate,
                doing_layout_from_tree_walk: false,
                debug_mutations_locked: false,
            },
        )
    }

    fn do_layout_from(
        self: RenderHandle<Self>,
        app: &mut App,
        treewalk_parent: AnyRenderObject,
        constraints: BoxConstraints,
    ) {
        debug_assert!(!self.get(app).doing_layout_from_tree_walk);
        self.get_mut(app).doing_layout_from_tree_walk = true;
        self.as_box().layout(app, constraints, false);
        debug_assert!(self.get(app).doing_layout_from_tree_walk);
        self.get_mut(app).doing_layout_from_tree_walk = false;
        debug_assert!(!self.as_object().debug_needs_layout(app));

        // Instead of laying out this subtree via tree walk, add it to the dirty list. This
        // ensures:
        //
        //  1. this node will be laid out by the PipelineOwner *after* the two nodes it depends
        //     on (the theater and the layout surrogate) are laid out, as it has a greater
        //     depth value than its dependencies.
        //
        //  2. when the deferred child's child starts to do layout, the nodes from the layout
        //     surrogate to the theater (exclusive) have finished doing layout, so the deferred
        //     child's child can read their sizes and (usually) compute the paint transform of
        //     the regular child within the Overlay.
        //
        // Invoking mark_needs_layout as a layout callback allows this node to be merged back
        // to the PipelineOwner's dirty list in the right order, if it's not already dirty,
        // such that this subtree does not get laid out twice.
        //
        // Flutter skips this when the subtree is clean and the constraints did not change;
        // `RenderObject`'s dirty flag is not readable outside `waft-rendering` (see
        // `PORTING.md`), so the subtree is always re-scheduled.
        treewalk_parent.invoke_layout_callback(app, |app| {
            RenderBox::mark_needs_layout(self, app);
        });
    }
}

impl RenderObjectWithChildMixin for RenderDeferredLayoutBox {
    type ChildType = AnyRenderBox;

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

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

impl RenderProxyBoxMixin for RenderDeferredLayoutBox {}

impl RenderTheaterMixin for RenderDeferredLayoutBox {
    fn theater(self: RenderHandle<Self>, app: &App) -> RenderHandle<RenderTheater> {
        self.parent(app)
            .and_then(|parent| parent.downcast::<RenderTheater>(app))
            .expect("the parent of a deferred layout box is a RenderTheater")
    }

    fn children_in_paint_order(self: RenderHandle<Self>, app: &App) -> TheaterChildren {
        TheaterChildren::single(self.child(app))
    }

    fn children_in_hit_test_order(self: RenderHandle<Self>, app: &App) -> TheaterChildren {
        RenderTheaterMixin::children_in_paint_order(self, app)
    }
}

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

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

    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
        debug_assert!(!self.get(app).debug_mutations_locked);
        if self.get(app).doing_layout_from_tree_walk {
            return;
        }
        if cfg!(debug_assertions) {
            self.get_mut(app).debug_mutations_locked = true;
        }
        // This method is directly being invoked from `PipelineOwner::flush_layout`, or from
        // the layout surrogate's perform_layout.
        debug_assert!(self.parent(app).is_some());
        let Some(child) = self.child(app) else {
            return;
        };
        let constraints = self.constraints(app);
        debug_assert!(constraints.is_tight());
        self.layout_child(app, child, constraints);
        if cfg!(debug_assertions) {
            self.get_mut(app).debug_mutations_locked = false;
        }
    }

    fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
        // The layout surrogate can be adopted after this box enters the theater. Until then,
        // the surrogate has no owner and cannot redepth this child. Once the surrogate is
        // adopted, its own redepth_children will restore the depth invariant.
        let surrogate = self.get(app).layout_surrogate;
        if surrogate.as_object().attached(app) {
            surrogate.as_object().redepth_child(app, self.as_object());
        }
        if let Some(child) = self.child(app) {
            self.as_object().redepth_child(app, child.as_object());
        }
    }

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

    fn paint(
        self: RenderHandle<Self>,
        app: &mut App,
        context: &mut PaintingContext,
        offset: Offset,
    ) {
        RenderTheaterMixin::paint(self, app, context, offset);
    }
}

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

    fn perform_resize(self: RenderHandle<Self>, app: &mut App) {
        let size = self.constraints(app).biggest();
        self.set_size(app, size);
    }

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

    // Flutter's override translates by the child's parent-data offset, which is what
    // `RenderBox::apply_paint_transform` already does; `RenderProxyBoxMixin`'s no-op one is
    // not used here.

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

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

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

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

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

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

// A proxy box that makes sure its deferred layout child has a greater depth than itself.
//
// This render object also conditionally attaches and detaches the associated
// RenderDeferredLayoutBox when itself attaches and detaches from its PipelineOwner. This
// guarantees that the deferred box's attached status is always kept in sync with both the
// surrogate and its parent theater.
struct RenderLayoutSurrogateProxyBox {
    render_object: RenderObjectData,
    render_box: RenderBoxData,
    child: RenderObjectWithChildData<AnyRenderBox>,
    // This variable is set as soon as the DeferredLayout widget creates it, and it is only set
    // to None when the DeferredLayout widget is being removed from the tree.
    deferred_layout_child: Option<RenderHandle<RenderDeferredLayoutBox>>,
    overlay_location: Option<Ref<OverlayEntryLocation>>,
    debug_is_first_attach: bool,
    did_detach_deferred_child: bool,
}

impl RenderLayoutSurrogateProxyBox {
    fn new(
        app: &mut App,
        overlay_location: Option<Ref<OverlayEntryLocation>>,
    ) -> RenderHandle<RenderLayoutSurrogateProxyBox> {
        RenderHandle::new_box(
            app,
            RenderLayoutSurrogateProxyBox {
                render_object: RenderObjectData::new(),
                render_box: RenderBoxData::new(),
                child: RenderObjectWithChildData::new(),
                deferred_layout_child: None,
                overlay_location,
                debug_is_first_attach: true,
                did_detach_deferred_child: false,
            },
        )
    }
}

impl RenderObjectWithChildMixin for RenderLayoutSurrogateProxyBox {
    type ChildType = AnyRenderBox;

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

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

impl RenderProxyBoxMixin for RenderLayoutSurrogateProxyBox {}

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

    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
        if let Some(child) = self.child(app) {
            child.as_object().attach(app, owner);
        }
        // If did_attach runs after did_detach_deferred_child is set to true then it is always
        // safe to put the deferred child back because the theater must be an ancestor of both
        // render objects.
        if self.get(app).did_detach_deferred_child {
            self.get_mut(app).did_detach_deferred_child = false;
            let deferred = self
                .get(app)
                .deferred_layout_child
                .expect("a detached deferred child was recorded");
            debug_assert!(!self.get(app).debug_is_first_attach);
            let location = self
                .get(app)
                .overlay_location
                .handle()
                .expect("a deferred child has a location");
            location.reattach_from_layout_surrogate(app, deferred);
        }
        if cfg!(debug_assertions) {
            self.get_mut(app).debug_is_first_attach = false;
        }
    }

    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
        // Detaches the deferred child if this node is being detached, but only if the theater
        // isn't already detached (so the deferred child will be detached by the theater).
        if let Some(deferred) = self.get(app).deferred_layout_child
            && deferred.theater(app).as_object().attached(app)
        {
            let location = self
                .get(app)
                .overlay_location
                .handle()
                .expect("a deferred child has a location");
            location.detach_from_layout_surrogate(app, deferred);
            self.get_mut(app).did_detach_deferred_child = true;
        }
        if let Some(child) = self.child(app) {
            child.as_object().detach(app);
        }
    }

    fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
        if let Some(child) = self.child(app) {
            self.as_object().redepth_child(app, child.as_object());
        }
        // If the child is not attached yet, this method will be invoked by the child's real
        // parent (the theater) when it becomes attached.
        if let Some(deferred) = self.get(app).deferred_layout_child
            && deferred.as_object().attached(app)
        {
            self.as_object().redepth_child(app, deferred.as_object());
        }
    }

    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
        RenderProxyBoxMixin::perform_layout(self, app);
        let Some(deferred_child) = self.get(app).deferred_layout_child else {
            return;
        };
        // To make sure all ancestors' perform_layout calls have returned when the deferred
        // child does layout, the deferred child needs to be put in the dirty list if it is
        // dirty, and the deferred child subtree made unreachable via the layout tree walk.
        let theater = deferred_child.theater(app);
        // If the theater is laying out the size-determining child, its size is not available
        // yet. Since the theater always lays out the size-determining child first and the
        // deferred child can never be size-determining, this method does not have to do
        // anything: the theater will update the constraints of the deferred child and resize
        // it or put it in the dirty list if needed.
        if !theater.get(app).laying_out_size_determining_child {
            let theater_constraints = theater.constraints(app);
            let box_size = if theater_constraints.biggest().is_finite() {
                theater_constraints.biggest()
            } else {
                theater.size(app)
            };
            deferred_child.do_layout_from(app, self.as_object(), BoxConstraints::tight(box_size));
        }
    }

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

    fn paint(
        self: RenderHandle<Self>,
        app: &mut App,
        context: &mut PaintingContext,
        offset: Offset,
    ) {
        RenderProxyBoxMixin::paint(self, app, context, offset);
    }
}

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

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

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

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

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

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

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

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

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

/// Dart's `_OverlayChildLayoutBuilder`: the widget
/// [`OverlayPortal::overlay_child_layout_builder`] builds as its overlay child.
///
/// Dart derives it from `AbstractLayoutBuilder<OverlayChildLayoutInfo>` and reuses
/// `layout_builder.dart`'s element; the crate's `LayoutBuilder` is not generic over the
/// layout information, so this is a concrete pair of its own (see `PORTING.md`).
struct OverlayChildLayoutBuilderWidget {
    builder: OverlayChildLayoutBuilder,
    /// Where this widget was made, in a debug build; see [`Widget::creation_location`].
    created: Option<CreationLocation>,
}

impl OverlayChildLayoutBuilderWidget {
    /// The tree node: a render object widget with its own element, outside the `IntoWidget`
    /// kinds.
    #[cfg_attr(debug_assertions, track_caller)]
    fn into_widget(mut self) -> WidgetRef {
        self.created = Some(CreationLocation::of_caller());
        Rc::new(self)
    }

    /// Whether the builder needs to be called again even if the layout information is the
    /// same.
    fn update_should_rebuild(&self, old_widget: &OverlayChildLayoutBuilderWidget) -> bool {
        let _ = old_widget;
        true
    }
}

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

impl Widget for OverlayChildLayoutBuilderWidget {
    fn key(&self) -> Option<&KeyRef> {
        None
    }

    fn creation_location(&self) -> Option<&'static Location<'static>> {
        self.created.and_then(CreationLocation::location)
    }

    fn record_creation_location(&mut self, location: CreationLocation) {
        self.created = Some(location);
    }

    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
        OverlayChildLayoutBuilderElement::new(app, this).as_element()
    }

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

    fn widget_type(&self) -> std::any::TypeId {
        std::any::TypeId::of::<OverlayChildLayoutBuilderWidget>()
    }

    fn kind(&self) -> WidgetKind {
        WidgetKind::Other
    }
}

impl RenderObjectWidget for OverlayChildLayoutBuilderWidget {
    type RenderObject = RenderOverlayChildLayoutBuilder;

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

    // update_render_object is redundant with the logic in the element below.
    fn update_render_object(
        &self,
        _app: &mut App,
        _context: BuildContext,
        _render_object: RenderHandle<RenderOverlayChildLayoutBuilder>,
    ) {
    }

    fn did_unmount_render_object(
        &self,
        app: &mut App,
        render_object: RenderHandle<RenderOverlayChildLayoutBuilder>,
    ) {
        // Flutter cancels the per-frame callback in the render object's `dispose`, which is
        // not an override point here.
        render_object.cancel_frame_callback(app);
    }
}

/// The element of an [`OverlayChildLayoutBuilderWidget`]: it builds its child from within the
/// render object's layout, as `LayoutBuilderElement` does.
struct OverlayChildLayoutBuilderElement {
    element: ElementData,
    render_object_element: RenderObjectElementData,
    child: Option<AnyElement>,
    /// Dart's `late final _buildScope`, created right after the element so its
    /// `scheduleRebuild` can name it.
    build_scope: Option<Ref<BuildScope>>,
    deferred_callback_scheduled: bool,
    previous_layout_info: Option<OverlayChildLayoutInfo>,
    needs_build: bool,
}

impl OverlayChildLayoutBuilderElement {
    fn new(app: &mut App, widget: WidgetRef) -> Handle<OverlayChildLayoutBuilderElement> {
        debug_assert!(downcast_widget::<OverlayChildLayoutBuilderWidget>(&*widget).is_some());
        let this = app
            .create(OverlayChildLayoutBuilderElement {
                element: ElementData::new(widget),
                render_object_element: RenderObjectElementData::default(),
                child: None,
                build_scope: None,
                deferred_callback_scheduled: false,
                previous_layout_info: None,
                needs_build: true,
            })
            .into_tree_node(app);
        let build_scope = BuildScope::new(
            app,
            Some(Listener::handle_method(this, Self::schedule_rebuild)),
        );
        app.get_mut(this).build_scope = Some(build_scope);
        this
    }

    fn render_layout_builder(
        self: Handle<Self>,
        app: &App,
    ) -> RenderHandle<RenderOverlayChildLayoutBuilder> {
        self.typed_render_object(app)
    }

    fn schedule_rebuild(self: Handle<Self>, app: &mut App) {
        if app.get(self).deferred_callback_scheduled {
            return;
        }
        let defer_mark_needs_layout = match SchedulerBinding::scheduler_phase(app) {
            SchedulerPhase::Idle | SchedulerPhase::PostFrameCallbacks => true,
            SchedulerPhase::TransientCallbacks
            | SchedulerPhase::MidFrameMicrotasks
            | SchedulerPhase::PersistentCallbacks => false,
        };
        if !defer_mark_needs_layout {
            self.render_layout_builder(app)
                .schedule_layout_callback(app);
            return;
        }
        app.get_mut(self).deferred_callback_scheduled = true;
        SchedulerBinding::schedule_frame_callback(
            app,
            FrameCallback::new(move |app, _time_stamp| self.frame_callback(app)),
            View::maybe_id_of(app, self.as_element()),
            false,
            true,
        );
    }

    fn frame_callback(self: Handle<Self>, app: &mut App) {
        app.get_mut(self).deferred_callback_scheduled = false;
        if self.as_element().mounted(app) {
            self.render_layout_builder(app)
                .schedule_layout_callback(app);
        }
    }

    fn rebuild_with_constraints(self: Handle<Self>, app: &mut App) {
        let render_object = self.render_layout_builder(app);
        let layout_info = render_object.layout_info(app);
        let this = self.as_element();
        let needs_callback =
            app.get(self).needs_build || Some(layout_info) != app.get(self).previous_layout_info;
        let callback: Option<BuildScopeCallback> = needs_callback.then(|| {
            Box::new(move |app: &mut App| {
                debug_assert!(layout_info == render_object.layout_info(app));
                let builder = Rc::clone(&Self::widget_of(this.widget(app)).builder);
                let built = builder(app, this, layout_info);
                let child = app.get(self).child;
                let child = this.update_child(app, child, Some(built), None);
                debug_assert!(child.is_some());
                let state = app.get_mut(self);
                state.child = child;
                state.needs_build = false;
                state.previous_layout_info = Some(layout_info);
            }) as BuildScopeCallback
        });
        let owner = this.owner(app).expect("a laying-out element has an owner");
        owner.build_scope(app, this, callback);
    }
}

impl RenderObjectElementWidget for OverlayChildLayoutBuilderElement {
    type Widget = OverlayChildLayoutBuilderWidget;

    fn widget_of(widget: &WidgetRef) -> &OverlayChildLayoutBuilderWidget {
        downcast_widget::<OverlayChildLayoutBuilderWidget>(&**widget)
            .expect("an OverlayChildLayoutBuilderElement holds its widget")
    }
}

impl RenderObjectElement for OverlayChildLayoutBuilderElement {
    fn render_object_element_data(self: Handle<Self>, app: &App) -> &RenderObjectElementData {
        &app.get(self).render_object_element
    }

    fn render_object_element_data_mut(
        self: Handle<Self>,
        app: &mut App,
    ) -> &mut RenderObjectElementData {
        &mut app.get_mut(self).render_object_element
    }
}

impl Element for OverlayChildLayoutBuilderElement {
    crate::element_accessors!();

    const IS_RENDER_OBJECT_ELEMENT: bool = true;

    fn render_object(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
        self.render_object_element_data(app).render_object()
    }

    fn render_object_attaching_child(self: Handle<Self>, _app: &App) -> Option<AnyElement> {
        None
    }

    fn debug_doing_build(self: Handle<Self>, _app: &App) -> bool {
        false
    }

    fn build_scope(self: Handle<Self>, app: &App) -> Handle<BuildScope> {
        app.get(self)
            .build_scope
            .handle()
            .expect("created with the element")
    }

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

    fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
        debug_assert!(app.get(self).child == Some(child));
        app.get_mut(self).child = None;
    }

    fn mount(
        self: Handle<Self>,
        app: &mut App,
        parent: Option<AnyElement>,
        new_slot: Option<Slot>,
    ) {
        RenderObjectElement::mount(self, app, parent, new_slot); // Creates the renderObject.
        let render_object = self.render_layout_builder(app);
        render_object.update_callback(
            app,
            Listener::handle_method(self, Self::rebuild_with_constraints),
        );
    }

    fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
        let old_widget = self.as_element().widget(app).clone();
        debug_assert!(!Rc::ptr_eq(&old_widget, &new_widget));
        RenderObjectElement::update(self, app, new_widget.clone());
        let render_object = self.render_layout_builder(app);
        render_object.update_callback(
            app,
            Listener::handle_method(self, Self::rebuild_with_constraints),
        );
        if Self::widget_of(&new_widget).update_should_rebuild(Self::widget_of(&old_widget)) {
            app.get_mut(self).needs_build = true;
            render_object.schedule_layout_callback(app);
        }
    }

    fn mark_needs_build(self: Handle<Self>, app: &mut App) {
        self.render_layout_builder(app)
            .schedule_layout_callback(app);
        app.get_mut(self).needs_build = true;
    }

    fn perform_rebuild(self: Handle<Self>, app: &mut App) {
        self.render_layout_builder(app)
            .schedule_layout_callback(app);
        app.get_mut(self).needs_build = true;
        RenderObjectElement::perform_rebuild(self, app);
    }

    fn deactivate(self: Handle<Self>, app: &mut App) {
        RenderObjectElement::deactivate(self, app);
    }

    fn unmount(self: Handle<Self>, app: &mut App) {
        let render_object = self.render_layout_builder(app);
        render_object.get_mut(app).callback = None;
        RenderObjectElement::unmount(self, app);
    }

    fn update_parent_data(self: Handle<Self>, app: &mut App, parent_data_element: AnyElement) {
        RenderObjectElement::update_parent_data(self, app, parent_data_element);
    }

    fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
        RenderObjectElement::update_slot(self, app, new_slot);
    }

    fn attach_render_object(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
        RenderObjectElement::attach_render_object(self, app, new_slot);
    }

    fn detach_render_object(self: Handle<Self>, app: &mut App) {
        RenderObjectElement::detach_render_object(self, app);
    }

    fn insert_render_object_child(
        self: Handle<Self>,
        app: &mut App,
        child: AnyRenderObject,
        slot: Option<Slot>,
    ) {
        debug_assert!(slot.is_none());
        let render_object = self.render_layout_builder(app);
        render_object.set_child(app, Some(child.as_box().expect("a box child")));
    }

    fn move_render_object_child(
        self: Handle<Self>,
        _app: &mut App,
        _child: AnyRenderObject,
        _old_slot: Option<Slot>,
        _new_slot: Option<Slot>,
    ) {
        debug_assert!(false, "a layout builder has one child");
    }

    fn remove_render_object_child(
        self: Handle<Self>,
        app: &mut App,
        child: AnyRenderObject,
        _slot: Option<Slot>,
    ) {
        let render_object = self.render_layout_builder(app);
        debug_assert!(render_object.child(app).map(|current| current.as_object()) == Some(child));
        render_object.set_child(app, None);
    }
}

// Dart's `_RenderLayoutBuilder`: a render box that
//  - has the same size and paint transform as its parent and its theater; in other words the
//    three boxes describe the same rect on screen.
//  - is a relayout boundary, and gets marked dirty for relayout every frame (but only when a
//    frame is already scheduled, and mark_needs_layout does not schedule a new frame since it
//    is called in a transient callback).
//  - runs a layout callback in perform_layout.
//
// Additionally, like RenderDeferredLayoutBox, this box also uses the stack layout algorithm so
// developers can use the Positioned widget.
struct RenderOverlayChildLayoutBuilder {
    render_object: RenderObjectData,
    render_box: RenderBoxData,
    child: RenderObjectWithChildData<AnyRenderBox>,
    layout_callback: RenderObjectWithLayoutCallbackData,
    callback: Option<Listener>,
    // The size here is the child size of the regular child in its own parent's coordinates.
    layout_info: Option<OverlayChildLayoutInfo>,
    callback_id: Option<i64>,
}

impl RenderOverlayChildLayoutBuilder {
    fn new(app: &mut App) -> RenderHandle<RenderOverlayChildLayoutBuilder> {
        RenderHandle::new_box(
            app,
            RenderOverlayChildLayoutBuilder {
                render_object: RenderObjectData::new(),
                render_box: RenderBoxData::new(),
                child: RenderObjectWithChildData::new(),
                layout_callback: RenderObjectWithLayoutCallbackData::default(),
                callback: None,
                layout_info: None,
                callback_id: None,
            },
        )
    }

    /// The information the builder is given.
    fn layout_info(self: RenderHandle<Self>, app: &App) -> OverlayChildLayoutInfo {
        self.get(app)
            .layout_info
            .expect("the layout callback computes the layout information first")
    }

    /// Change the layout callback and schedule it (Dart's
    /// `RenderAbstractLayoutBuilderMixin.updateCallback`).
    fn update_callback(self: RenderHandle<Self>, app: &mut App, value: Listener) {
        if self.get(app).callback.as_ref() == Some(&value) {
            return;
        }
        self.get_mut(app).callback = Some(value);
        self.schedule_layout_callback(app);
    }

    fn compute_new_layout_info(self: RenderHandle<Self>, app: &App) -> OverlayChildLayoutInfo {
        let theater = self.theater(app);
        let parent = self
            .parent(app)
            .and_then(|parent| parent.downcast::<RenderDeferredLayoutBox>(app))
            .expect("the parent of an overlay child layout builder is a deferred layout box");
        let layout_surrogate = parent.get(app).layout_surrogate;
        debug_assert!(layout_surrogate.has_size(app));
        debug_assert!(
            layout_surrogate
                .child(app)
                .is_none_or(|child| child.size(app) == layout_surrogate.size(app))
        );
        debug_assert!(self.size(app) == theater.size(app));
        let overlay_portal_size = layout_surrogate.size(app);
        let paint_transform = layout_surrogate
            .as_object()
            .get_transform_to(app, Some(theater.as_object()));
        OverlayChildLayoutInfo {
            child_size: overlay_portal_size,
            child_paint_transform: paint_transform,
            overlay_size: self.size(app),
        }
    }

    fn frame_callback(self: RenderHandle<Self>, app: &mut App) {
        self.get_mut(app).callback_id = None;
        RenderBox::mark_needs_layout(self, app);
    }

    fn cancel_frame_callback(self: RenderHandle<Self>, app: &mut App) {
        if let Some(callback_id) = self.get_mut(app).callback_id.take() {
            SchedulerBinding::cancel_frame_callback_with_id(app, callback_id);
        }
    }
}

impl RenderObjectWithChildMixin for RenderOverlayChildLayoutBuilder {
    type ChildType = AnyRenderBox;

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

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

impl RenderProxyBoxMixin for RenderOverlayChildLayoutBuilder {}

impl RenderObjectWithLayoutCallbackMixin for RenderOverlayChildLayoutBuilder {
    fn layout_callback_data(
        self: RenderHandle<Self>,
        app: &App,
    ) -> &RenderObjectWithLayoutCallbackData {
        &self.get(app).layout_callback
    }

    fn layout_callback_data_mut(
        self: RenderHandle<Self>,
        app: &mut App,
    ) -> &mut RenderObjectWithLayoutCallbackData {
        &mut self.get_mut(app).layout_callback
    }

    fn layout_callback(self: RenderHandle<Self>, app: &mut App) {
        let layout_info = self.compute_new_layout_info(app);
        self.get_mut(app).layout_info = Some(layout_info);
        let callback = self
            .get(app)
            .callback
            .clone()
            .expect("a callback is set before layout");
        callback.call(app);
    }
}

impl RenderTheaterMixin for RenderOverlayChildLayoutBuilder {
    fn theater(self: RenderHandle<Self>, app: &App) -> RenderHandle<RenderTheater> {
        self.parent(app)
            .and_then(|parent| parent.downcast::<RenderDeferredLayoutBox>(app))
            .expect("the parent of an overlay child layout builder is a deferred layout box")
            .theater(app)
    }

    fn children_in_paint_order(self: RenderHandle<Self>, app: &App) -> TheaterChildren {
        TheaterChildren::single(self.child(app))
    }

    fn children_in_hit_test_order(self: RenderHandle<Self>, app: &App) -> TheaterChildren {
        RenderTheaterMixin::children_in_paint_order(self, app)
    }
}

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

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

    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
        self.run_layout_callback(app);
        if let Some(child) = self.child(app) {
            let constraints = self.constraints(app);
            self.layout_child(app, child, constraints);
        }
        debug_assert!(self.get(app).callback_id.is_none());
        if self.get(app).callback_id.is_none() {
            let callback_id = SchedulerBinding::schedule_frame_callback(
                app,
                FrameCallback::new(move |app, _time_stamp| self.frame_callback(app)),
                None,
                false,
                false,
            );
            self.get_mut(app).callback_id = Some(callback_id);
        }
    }

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

    fn paint(
        self: RenderHandle<Self>,
        app: &mut App,
        context: &mut PaintingContext,
        offset: Offset,
    ) {
        RenderTheaterMixin::paint(self, app, context, offset);
    }
}

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

    fn perform_resize(self: RenderHandle<Self>, app: &mut App) {
        let size = self.constraints(app).biggest();
        self.set_size(app, size);
    }

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

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_harness::Harness;
    use crate::widgets::basic::SizedBox;
    use crate::widgets::media_query::MediaQueryData;
    use waft_foundation::{AppCell, DiagnosticLevel};

    fn test_entry(app: &mut App) -> Ref<OverlayEntry> {
        OverlayEntry::new(
            app,
            Rc::new(|_app, _context| SizedBox::shrink().into_widget()),
            false,
            false,
            false,
        )
    }

    fn mount_overlay(app: &mut App, entries: Vec<Ref<OverlayEntry>>) -> Harness {
        let tree = MediaQuery::new(
            MediaQueryData::new(),
            Directionality::new(TextDirection::Ltr, Overlay::new().initial_entries(entries)),
        )
        .into_widget();
        let harness = Harness::mount(app, tree);
        harness.pump(app);
        harness
    }

    fn theater_of(harness: &Harness, app: &App) -> RenderHandle<RenderTheater> {
        harness
            .render_root(app)
            .child(app)
            .expect("the overlay's render object")
            .as_object()
            .downcast::<RenderTheater>(app)
            .expect("a RenderTheater")
    }

    fn entry_of(app: &App, child: AnyRenderBox) -> Handle<OverlayEntry> {
        child
            .as_object()
            .parent_data_of::<TheaterParentData>(app)
            .overlay_entry
            .handle()
            .expect("a child built by an entry")
    }

    fn entries_in_render_order(
        app: &App,
        theater: RenderHandle<RenderTheater>,
    ) -> Vec<Handle<OverlayEntry>> {
        let mut order = Vec::new();
        let mut child = theater.first_child(app);
        while let Some(current) = child {
            order.push(entry_of(app, current));
            child = theater.child_after(app, current);
        }
        order
    }

    #[test]
    fn overlay_entries_are_inserted_rearranged_and_removed_in_order() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let (first, second) = (test_entry(&mut app), test_entry(&mut app));
        let harness = mount_overlay(&mut app, vec![first.clone(), second.clone()]);
        let theater = theater_of(&harness, &app);
        assert_eq!(
            entries_in_render_order(&app, theater),
            vec![first.handle(), second.handle()]
        );

        let overlay = app
            .get(&first)
            .overlay
            .expect("inserted by initial_entries");
        let third = test_entry(&mut app);
        overlay.insert(&mut app, third.clone(), Some(first.handle()), None);
        harness.pump(&mut app);
        assert_eq!(
            entries_in_render_order(&app, theater),
            vec![third.handle(), first.handle(), second.handle()]
        );

        let fourth = test_entry(&mut app);
        overlay.insert_all(&mut app, vec![fourth.clone()], None, None);
        harness.pump(&mut app);
        assert_eq!(
            entries_in_render_order(&app, theater),
            vec![
                third.handle(),
                first.handle(),
                second.handle(),
                fourth.handle()
            ]
        );

        // `first` and `second` move to the bottom; the entries not mentioned stay on top.
        overlay.rearrange(&mut app, vec![second.clone(), first.clone()], None, None);
        harness.pump(&mut app);
        assert_eq!(
            entries_in_render_order(&app, theater),
            vec![
                second.handle(),
                first.handle(),
                third.handle(),
                fourth.handle()
            ]
        );

        second.remove(&mut app);
        second.dispose(&mut app);
        harness.pump(&mut app);
        assert_eq!(
            entries_in_render_order(&app, theater),
            vec![first.handle(), third.handle(), fourth.handle()]
        );
    }

    #[test]
    fn an_opaque_entry_takes_the_entries_below_it_offstage() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let bottom = OverlayEntry::new(
            &mut app,
            Rc::new(|_app, _context| SizedBox::shrink().into_widget()),
            false,
            true,
            false,
        );
        let top = OverlayEntry::new(
            &mut app,
            Rc::new(|_app, _context| SizedBox::shrink().into_widget()),
            true,
            false,
            false,
        );
        let harness = mount_overlay(&mut app, vec![bottom.clone(), top.clone()]);
        let theater = theater_of(&harness, &app);

        // `bottom` is kept in the tree by maintain_state, but skipped when painting.
        assert_eq!(theater.child_count(&app), 2);
        assert_eq!(theater.skip_count(&app), 1);
        let painted = RenderTheaterMixin::children_in_paint_order(theater, &app).collect(&app);
        assert_eq!(painted.len(), 1);
        assert_eq!(entry_of(&app, painted[0]), top);

        // Without maintain_state an offstage entry is not built at all.
        bottom.set_maintain_state(&mut app, false);
        harness.pump(&mut app);
        assert_eq!(theater.child_count(&app), 1);
        assert_eq!(theater.skip_count(&app), 0);
        assert_eq!(entries_in_render_order(&app, theater), vec![top.handle()]);

        // Dropping the opacity brings it back onstage.
        top.set_opaque(&mut app, false);
        harness.pump(&mut app);
        assert_eq!(theater.skip_count(&app), 0);
        assert_eq!(
            RenderTheaterMixin::children_in_paint_order(theater, &app)
                .collect(&app)
                .len(),
            2
        );
    }

    #[test]
    fn an_overlay_portal_shows_and_hides_its_overlay_child_in_the_overlay() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let controller = OverlayPortalController::new(&mut app, None);
        let portal_controller = controller.clone();
        let entry = OverlayEntry::new(
            &mut app,
            Rc::new(move |_app: &mut App, _context| {
                OverlayPortal::new(portal_controller.clone(), |_app: &mut App, _context| {
                    SizedBox::square(Some(40.0)).into_widget()
                })
                .child(SizedBox::square(Some(10.0)))
                .into_widget()
            }),
            false,
            false,
            false,
        );
        let harness = mount_overlay(&mut app, vec![entry.clone()]);
        let theater = theater_of(&harness, &app);
        assert!(!controller.is_showing(&app));
        assert_eq!(
            RenderTheaterMixin::children_in_paint_order(theater, &app)
                .collect(&app)
                .len(),
            1
        );

        controller.show(&mut app);
        assert!(controller.is_showing(&app));
        harness.pump(&mut app);
        let painted = RenderTheaterMixin::children_in_paint_order(theater, &app).collect(&app);
        assert_eq!(painted.len(), 2);
        // The overlay child is a render child of the theater, painted above the entry.
        let deferred = painted[1]
            .as_object()
            .downcast::<RenderDeferredLayoutBox>(&app)
            .expect("the overlay child");
        assert_eq!(deferred.parent(&app), Some(theater.as_object()));
        assert_eq!(deferred.size(&app), theater.size(&app));
        assert_eq!(
            deferred.child(&app).expect("built").size(&app),
            theater.size(&app)
        );
        // The theater's child model still holds one entry child.
        assert_eq!(theater.child_count(&app), 1);

        // The overlay child is named after its entry and its position in that entry's paint
        // order, as Dart's `_RenderTheater.debugDescribeChildren` names it.
        let dump = theater
            .as_object()
            .to_string_deep_with(&app, DiagnosticLevel::Info);
        assert!(dump.contains("onstage 1 - 1:"), "{dump}");

        // Resume the lazy generator after entry layout removes its portal.
        let mut children = theater.children_in_paint_order(&app);
        assert_eq!(children.next(&app), Some(painted[0]));
        controller.toggle(&mut app);
        assert!(!controller.is_showing(&app));
        harness.pump(&mut app);
        assert_eq!(children.next(&app), None);
        assert_eq!(
            RenderTheaterMixin::children_in_paint_order(theater, &app)
                .collect(&app)
                .len(),
            1
        );

        controller.toggle(&mut app);
        assert!(controller.is_showing(&app));
        harness.pump(&mut app);
        assert_eq!(
            RenderTheaterMixin::children_in_paint_order(theater, &app)
                .collect(&app)
                .len(),
            2
        );

        controller.hide(&mut app);
        harness.pump(&mut app);
        assert_eq!(
            RenderTheaterMixin::children_in_paint_order(theater, &app)
                .collect(&app)
                .len(),
            1
        );
    }

    #[test]
    fn overlay_layout_builder_resizes_without_requesting_child_dry_layout() {
        use crate::widgets::basic::Positioned;
        use std::cell::Cell;

        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let controller = OverlayPortalController::new(&mut app, None);
        let observed = Rc::new(Cell::new(None::<OverlayChildLayoutInfo>));
        let output = observed.clone();
        let portal_controller = controller.clone();
        let entry = OverlayEntry::new(
            &mut app,
            Rc::new(move |_, _| {
                let output = output.clone();
                Positioned::new(
                    OverlayPortal::overlay_child_layout_builder(
                        portal_controller.clone(),
                        move |_, _, info| {
                            output.set(Some(info));
                            Positioned::new(SizedBox::expand())
                                .left(0.0)
                                .top(0.0)
                                .width(40.0)
                                .height(20.0)
                                .into_widget()
                        },
                    )
                    .child(SizedBox::expand()),
                )
                .left(30.0)
                .top(40.0)
                .width(80.0)
                .height(60.0)
                .into_widget()
            }),
            false,
            false,
            false,
        );
        let harness = mount_overlay(&mut app, vec![entry.clone()]);
        let theater = theater_of(&harness, &app);
        for _ in 0..2 {
            controller.show(&mut app);
            harness.pump(&mut app);
            let info = observed.get().expect("the overlay built after layout");
            assert_eq!(info.child_size(), Size::new(80.0, 60.0));
            assert_eq!(info.overlay_size(), theater.size(&app));
            assert_eq!(
                waft_painting::transform_point(&info.child_paint_transform(), Offset::ZERO),
                Offset::new(30.0, 40.0),
            );
            let painted = RenderTheaterMixin::children_in_paint_order(theater, &app).collect(&app);
            let deferred = painted[1]
                .as_object()
                .downcast::<RenderDeferredLayoutBox>(&app)
                .unwrap();
            let builder = deferred.child(&app).unwrap();
            assert_eq!(deferred.size(&app), theater.size(&app));
            assert_eq!(builder.size(&app), theater.size(&app));
            let builder = builder
                .as_object()
                .downcast::<RenderOverlayChildLayoutBuilder>(&app)
                .unwrap();
            assert_eq!(
                builder.child(&app).unwrap().size(&app),
                Size::new(40.0, 20.0)
            );
            controller.hide(&mut app);
            harness.pump(&mut app);
        }
    }

    /// `overlay_test.dart`'s "OverflowEntries context contains Overlay": the theater names its
    /// onstage children and says when no child is offstage.
    #[test]
    fn a_theater_dump_names_onstage_children_and_says_when_none_are_offstage() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let first = test_entry(&mut app);
        let second = test_entry(&mut app);
        let harness = mount_overlay(&mut app, vec![first, second]);
        let theater = theater_of(&harness, &app);

        let dump = theater
            .as_object()
            .to_string_deep_with(&app, DiagnosticLevel::Info);
        assert!(dump.contains("skipCount: 0"), "{dump}");
        assert!(dump.contains("textDirection: ltr"), "{dump}");
        assert!(
            dump.lines()
                .any(|line| line.contains("onstage 1: RenderConstrainedBox#")),
            "{dump}"
        );
        assert!(
            dump.lines()
                .any(|line| line.contains("onstage 2: RenderConstrainedBox#")),
            "{dump}"
        );
        assert!(dump.contains("╌no offstage children"), "{dump}");
    }

    /// `overlay_test.dart`'s "Offstage overlay": children below the first onstage child are
    /// named offstage and marked with the offstage style.
    #[test]
    fn a_theater_dump_names_offstage_children_and_marks_them_offstage() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let entry = |app: &mut App| {
            OverlayEntry::new(
                app,
                Rc::new(|_app, _context| SizedBox::shrink().into_widget()),
                true,
                true,
                false,
            )
        };
        let first = entry(&mut app);
        let second = entry(&mut app);
        let third = entry(&mut app);
        let harness = mount_overlay(&mut app, vec![first, second, third]);
        let theater = theater_of(&harness, &app);

        let dump = theater
            .as_object()
            .to_string_deep_with(&app, DiagnosticLevel::Info);
        assert!(dump.contains("skipCount: 2"), "{dump}");
        assert!(
            dump.lines()
                .any(|line| line.contains("onstage 1: RenderConstrainedBox#")),
            "{dump}"
        );
        assert!(
            dump.lines()
                .any(|line| line.contains("offstage 1: RenderConstrainedBox#")),
            "{dump}"
        );
        assert!(
            dump.lines()
                .any(|line| line.contains("offstage 2: RenderConstrainedBox#")),
            "{dump}"
        );
        assert!(
            dump.lines()
                .any(|line| line.contains("╌offstage 1: RenderConstrainedBox#")),
            "{dump}"
        );
        assert!(!dump.contains("no offstage children"), "{dump}");
    }

    /// `overlay_test.dart`'s "Overlay can set and update clipBehavior": each clip behavior
    /// decides what the theater says it clips its entries to.
    #[test]
    fn the_theater_describes_its_clip_for_each_clip_behavior() {
        for clip_behavior in [
            Clip::None,
            Clip::HardEdge,
            Clip::AntiAlias,
            Clip::AntiAliasWithSaveLayer,
        ] {
            let cell = AppCell::new();
            let mut app = cell.borrow_mut();
            let entry = test_entry(&mut app);
            let tree = MediaQuery::new(
                MediaQueryData::new(),
                Directionality::new(
                    TextDirection::Ltr,
                    Overlay::new()
                        .clip_behavior(clip_behavior)
                        .initial_entries(vec![entry]),
                ),
            )
            .into_widget();
            let harness = Harness::mount(&mut app, tree);
            harness.pump(&mut app);

            let theater = theater_of(&harness, &app);
            assert_eq!(theater.clip_behavior(&app), clip_behavior);
            let child = theater.first_child(&app).expect("an entry's render object");
            let expected = match clip_behavior {
                Clip::None => None,
                Clip::HardEdge | Clip::AntiAlias | Clip::AntiAliasWithSaveLayer => {
                    Some(Offset::ZERO & theater.size(&app))
                }
            };
            assert_eq!(
                theater
                    .as_object()
                    .describe_approximate_paint_clip(&app, child.as_object()),
                expected,
                "{clip_behavior:?}"
            );
        }
    }
}