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
//! Types for creating reusable widgets (aka components or views).

use std::any::Any;
use std::clone::Clone;
use std::fmt::{self, Debug};
use std::ops::{ControlFlow, Deref, DerefMut};
use std::sync::atomic::{self, AtomicU64};
use std::sync::Arc;
use std::{slice, vec};

use alot::LotId;
use figures::units::{Px, UPx};
use figures::{IntoSigned, IntoUnsigned, Point, Rect, Size, Zero};
use intentional::Assert;
use kludgine::app::winit::event::{Ime, MouseButton, MouseScrollDelta, TouchPhase};
use kludgine::app::winit::keyboard::ModifiersState;
use kludgine::app::winit::window::CursorIcon;
use kludgine::Color;
use parking_lot::{Mutex, MutexGuard};

use crate::app::Run;
use crate::context::sealed::Trackable as _;
use crate::context::{
    AsEventContext, EventContext, GraphicsContext, LayoutContext, ManageWidget, WidgetContext,
};
use crate::styles::components::{HorizontalAlignment, IntrinsicPadding, VerticalAlignment};
use crate::styles::{
    ComponentDefinition, ContainerLevel, ContextFreeComponent, Dimension, DimensionRange, Edges,
    FlexibleDimension, HorizontalAlign, IntoComponentValue, IntoDynamicComponentValue, Styles,
    ThemePair, VisualOrder,
};
use crate::tree::{Tree, WeakTree};
use crate::value::{Dynamic, Generation, IntoDynamic, IntoValue, Source, Validation, Value};
use crate::widgets::checkbox::{Checkable, CheckboxState};
use crate::widgets::layers::{OverlayLayer, Tooltipped};
use crate::widgets::list::List;
use crate::widgets::shortcuts::{ShortcutKey, Shortcuts};
use crate::widgets::{
    Align, Button, Checkbox, Collapse, Container, Disclose, Expand, Layers, Resize, Scroll, Space,
    Stack, Style, Themed, ThemedMode, Validated, Wrap,
};
use crate::window::sealed::WindowCommand;
use crate::window::{
    DeviceId, KeyEvent, MakeWindow, Rgb8, RunningWindow, StandaloneWindowBuilder, ThemeMode,
    VirtualRecorderBuilder, Window, WindowBehavior, WindowHandle, WindowLocal,
};
use crate::ConstraintLimit;

/// A type that makes up a graphical user interface.
///
/// This type can go by many names in other UI frameworks: View, Component,
/// Control.
///
/// # Widgets are hierarchical
///
/// Cushy's widgets are organized in a hierarchical structure: widgets can
/// contain other widgets. A window in Cushy contains a single root widget,
/// which may contain one or more additional widgets.
///
/// # How Widgets are created
///
/// Cushy offers several approaches to creating widgets. The primary trait that
/// is used to instantiate a widget is [`MakeWidget`]. This trait is
/// automatically implemented for all types that implement [`Widget`].
///
/// [`MakeWidget::make_widget`] is responsible for returning a
/// [`WidgetInstance`]. This is a wrapper for a type that implements [`Widget`]
/// that can be used without knowing the original type of the [`Widget`].
///
/// While all [`MakeWidget`] is automatically implemented for all [`Widget`]
/// types, it can also be implemented by types that do not implement [`Widget`].
/// This is a useful strategy when designing reusable widgets that are able to
/// be completely represented by composing existing widgets. The
/// [`ProgressBar`](crate::widgets::ProgressBar) type uses this strategy, as it
/// uses either a [`Spinner`](crate::widgets::progress::Spinner) or a
/// [`Slider`](crate::widgets::Slider) to show its progress.
///
/// One last convenience trait is provided to help create widgets that contain
/// exactly one child: [`WrapperWidget`]. [`WrapperWidget`] exposes most of the
/// same functions, but provides purpose-built functions for tweaking child's
/// layout and rendering behavior to minimize the amount of redundant code
/// between these types of widgets.
///
/// # Identifying Widgets
///
/// Once a widget has been instantiated as a [`WidgetInstance`], it will be
/// assigned a unique [`WidgetId`]. Sometimes, it may be helpful to pre-create a
/// [`WidgetId`] before the widget has been created. For these situations,
/// [`WidgetTag`] allows creating a tag that can be passed to
/// [`MakeWidgetWithTag::make_with_tag`] to set the returned
/// [`WidgetInstance`]'s id.
///
/// # How to "talk" to another widget
///
/// Once a widget has been wrapped inside of a [`WidgetInstance`], it is no
/// longer possible to invoke [`Widget`]/s functions directly. Instead, a
/// context must be created for that widget. In each of the [`Widget`]
/// functions, a context is provided that represents the current widget. Each
/// context type has a `for_other()` function that accepts any widget type: a
/// [`WidgetId`], a [`WidgetInstance`], a [`MountedWidget`], or a [`WidgetRef`].
/// The returned context will represent the associate widget, allowing access to
/// the exposed APIs through the context.
///
/// While [`WidgetInstance::lock`] can be used to gain access to the underlying
/// [`Widget`] type, this behavior should only be reserved for limited
/// situations. It should be preferred to pass data between widgets using
/// [`Dynamic`]s or style components if possible. This ensures that your code
/// can work with as many other widgets as possible, instead of restricting
/// features to a specific set of types.
///
/// # How layout and rendering works
///
/// When a window is rendered, the root widget has its
/// [`layout()`](Self::layout) function called with both constraints specifying
/// [`ConstraintLimit::SizeToFit`] with the window's inner size. The root widget
/// measures its content to try to fit within the specified constraints, and
/// returns its calculated size. If a widget has children, it can invoke
/// [`LayoutContext::layout()`] on a context for each of its children to
/// determine their required sizes.
///
/// Next, the window sets the root's layout. When a widget contains another
/// widget, it must call [`LayoutContext::set_child_layout`] for the child to be
/// able to be rendered. This tells Cushy the location to draw the widget. While
/// it is possible to provide any rectangle, Cushy clips all widgets and their
/// children so that they cannot draw outside of their assigned bounds.
///
/// Once the layout has been determined, the window will invoke the root
/// widget's [`redraw()`](Self::redraw) function. If a widget contains one or
/// more children, it needs to invoke [`GraphicsContext::redraw()`] on a context
/// for each of its children during its own render function. This allows full
/// control over the order of drawing calls, allowing widgets to draw behind,
/// in-between, or in front of their children.
///
/// The last responsibility the window has each frame is size adjustment. The
/// window will potentially adjust its size automatically based on the root
/// widget's [`root_behavior()`](Self::root_behavior).
///
/// # Controlling Invalidation and Redrawing
///
/// Cushy only redraws window contents when requested by the operating system or
/// a tracked [`Dynamic`] is updated. Similarly, Cushy caches the known layout
/// sizes and locations for widgets unless they are *invalidated*. Invalidation
/// is done automatically when the window size changes or a tracked [`Dynamic`]
/// is updated.
///
/// These systems require Cushy to track which [`Dynamic`] values a widget
/// depends on for redrawing and invalidation. During a widget's redraw and
/// layout functions, it needs to ensure that all depended upon [`Dynamic`]s are
/// tracked using one of the various
/// `*_tracking_redraw()`/`*_tracking_invalidate()` functions. For example,
/// [`Source::get_tracking_redraw()`](crate::value::Source::get_tracking_redraw)
/// and
/// [`Source::get_tracking_invalidate()`](crate::value::Source::get_tracking_invalidate).
///
/// # Hover State: Hit Testing
///
/// Before any cursor-related events are sent to a widget, the cursor's position
/// is tested with [`Widget::hit_test`]. When a widget returns true for a
/// position, it is eligible to receive events such as mouse buttons.
///
/// When a widget returns false, it will not receive any cursor related events
/// with one exception: hover events. Hover events will fire for widgets whose
/// children are currently being hovered, regardless of whether
/// [`Widget::hit_test`] returned true.
///
/// The provided [`Widget::hit_test`] implementation returns false.
///
/// As the cursor moves across the window, the window will look at the render
/// information to see what widgets are positioned under the cursor and the
/// order in which they were drawn. Beginning at the topmost widget,
/// [`Widget::hit_test`] is called on each widget.
///
/// The currently hovered widget state is tracked for events that target widgets
/// beneath the current cursor.
///
/// # Mouse Button Events
///
/// When a window receives an event for a mouse button being pressed, it calls
/// the hovered widget's [`mouse_down()`](Self::mouse_down) function. If the
/// function returns [`HANDLED`]/[`ControlFlow::Break`], the widget becomes the
/// *tracking* widget for that mouse button.
///
/// If the widget returns [`IGNORED`]/[`ControlFlow::Continue`], the window will
/// call the parent's `mouse_down()` function. This repeats until the root
/// widget is reached or a widget returns `HANDLED`.
///
/// Once a tracking widget is found, any cursor-related movements will cause
/// [`Widget::mouse_drag()`] to be called. Upon the mouse button being released,
/// the tracking widget's [`mouse_up()`](Self::mouse_up) function will be
/// called.
///
/// # User Input Focus
///
/// A window can have a widget be *focused* for user input. For example, a text
/// [`Input`](crate::widgets::Input) only responds to keyboard input once user
/// input focus has been directed at the widget. This state is generally
/// represented by drawing the theme's highlight color around the border of the
/// widget. [`GraphicsContext::draw_focus_ring`] can be used to draw the
/// standard focus ring for rectangular-shaped widgets.
///
/// The most direct way to give a widget focus is to call
/// [`WidgetContext::focus`]. However, not all widgets can accept focus. If a
/// widget returns true from its [`accept_focus()`](Self::accept_focus)
/// function, focus will be given to it and its [`focus()`](Self::focus)
/// function will be invoked.
///
/// If a widget returns false from its `accept_focus()` function, the window
/// will perform these steps:
///
/// 1. If the widget has any children, sort its children visually and attempt to
///    focus each one until a widget accepts focus. If any of these children
///    have children, those children should also be checked.
/// 2. The widget asks its parent to find the next focus after itself. The
///    parent finds the current widget in that list and attempts to focus each
///    widget after the current widget in the visual order.
/// 3. This repeats until the root widget is reached, at which point focus is
///    attempted using this algorithm until either a focused widget is found or
///    the original widget is reached again. If no widget can be found in a full
///    cycle of the widget tree, focus will be cleared.
///
/// When a window first opens, it call [`focus()`][WidgetContext::focus] on the
/// root widget's context.
///
/// ## Losing Focus
///
/// A Widget can deny the ability for focus to be taken away from it by
/// returning `false` from [`Widget::allow_blur()`]. In general, widgets should
/// not do this. However, some user interfaces are designed to always keep focus
/// on a single widget, and this feature enables that functionality.
///
/// When a widget currently has focused and loses it, its [`blur()`](Self::blur)
/// function will be invoked.
///
/// # Styling
///
/// Cushy allows widgets to receive styling information through the widget
/// hierarchy using [`Styles`]. Cushy calculates the effectives styles for each
/// widget by inheriting all inheritable styles from its parent.
///
/// The [`Style`] widget allows assigining [`Styles`] to all of its children
/// widget. It works by calling [`WidgetContext::attach_styles`], and Cushy
/// takes care of the rest.
///
/// Styling in Cushy aims to be simple, easy-to-understand, and extensible.
///
/// # Color Themes
///
/// Cushy aims to make it easy for developers to customize the appearance of its
/// applications. The way color themes work in Cushy begins with the
/// [`ColorScheme`](crate::styles::ColorScheme). A color scheme is a set of
/// [`ColorSource`](crate::styles::ColorSource) that are used to generate a
/// variety of shades of colors for various roles color plays in a user
/// interface. In a way, coloring Cushy apps is a bit like paint-by-number,
/// where the number is the name of the color role.
///
/// A `ColorScheme` can be used to create a [`ThemePair`], which is theme
/// definition that a theme for light and dark mode.
///
/// In [the repository][repo], the `theme` example is a good way to explore how
/// the color system works in Cushy.
///
/// [repo]: https://github.com/khonsulabs/cushy
pub trait Widget: Send + Debug + 'static {
    /// Redraw the contents of this widget.
    fn redraw(&mut self, context: &mut GraphicsContext<'_, '_, '_, '_>);

    /// Writes a summary of this widget into `fmt`.
    ///
    /// The default implementation calls [`Debug::fmt`]. This function allows
    /// widget authors to print only publicly relevant information that will
    /// appear when debug formatting a [`WidgetInstance`].
    fn summarize(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Debug::fmt(self, f)
    }

    /// Returns true if this widget handles all built-in style components that
    /// apply.
    ///
    /// These components are:
    ///
    /// - [`Opacity`](crate::styles::components::Opacity)
    /// - [`WidgetBackground`](crate::styles::components::WidgetBackground)
    /// - [`FontFamily`]
    /// - [`TextSize`]
    /// - [`LineHeight`]
    /// - [`FontStyle`]
    /// - [`FontWeight`]
    fn full_control_redraw(&self) -> bool {
        false
    }

    /// Layout this widget and returns the ideal size based on its contents and
    /// the `available_space`.
    #[allow(unused_variables)]
    fn layout(
        &mut self,
        available_space: Size<ConstraintLimit>,
        context: &mut LayoutContext<'_, '_, '_, '_>,
    ) -> Size<UPx> {
        available_space.map(ConstraintLimit::min)
    }

    /// The widget has been mounted into a parent widget.
    ///
    /// Widgets that contain [`MountedWidget`] references should call
    /// [`MountedWidget::remount_if_needed`] in this function.
    #[allow(unused_variables)]
    fn mounted(&mut self, context: &mut EventContext<'_>) {}

    /// The widget has been removed from its parent widget.
    #[allow(unused_variables)]
    fn unmounted(&mut self, context: &mut EventContext<'_>) {}

    /// Returns true if this widget should respond to mouse input at `location`.
    ///
    /// This function is critical for how event propagation works for these
    /// functions:
    ///
    /// - [`Self::hover`]
    /// - [`Self::unhover`]
    /// - [`Self::mouse_down`]
    /// - [`Self::mouse_up`]
    /// - [`Self::mouse_drag`]
    /// - [`Self::mouse_wheel`]
    ///
    /// See [Hover State: Hit Testing](Self#hover-state-hit-testing) for an
    /// explanation of how these events work together.
    #[allow(unused_variables)]
    fn hit_test(&mut self, location: Point<Px>, context: &mut EventContext<'_>) -> bool {
        false
    }

    /// The widget is currently has a cursor hovering it at `location`.
    ///
    /// This function will not be invoked if [`Self::hit_test`] returns false.
    /// See [Hover State: Hit Testing](Self#hover-state-hit-testing) for more
    /// information on how hover state is handled in Cushy.
    #[allow(unused_variables)]
    fn hover(&mut self, location: Point<Px>, context: &mut EventContext<'_>) -> Option<CursorIcon> {
        None
    }

    /// The widget is no longer being hovered.
    ///
    /// This function will only be invoked after [`Self::hover`].
    #[allow(unused_variables)]
    fn unhover(&mut self, context: &mut EventContext<'_>) {}

    /// This widget has been targeted to be focused. If this function returns
    /// true, the widget will be focused. If false, Cushy will continue
    /// searching for another focus target.
    #[allow(unused_variables)]
    fn accept_focus(&mut self, context: &mut EventContext<'_>) -> bool {
        false
    }

    /// The widget has received focus for user input.
    #[allow(unused_variables)]
    fn focus(&mut self, context: &mut EventContext<'_>) {}

    /// The widget should switch to the next focusable area within this widget,
    /// honoring `direction` in a consistent manner. Returning `HANDLED` will
    /// cause the search for the next focus widget stop.
    #[allow(unused_variables)]
    fn advance_focus(
        &mut self,
        direction: VisualOrder,
        context: &mut EventContext<'_>,
    ) -> EventHandling {
        IGNORED
    }

    /// The widget is about to lose focus. Returning true allows the focus to
    /// switch away from this widget.
    #[allow(unused_variables)]
    fn allow_blur(&mut self, context: &mut EventContext<'_>) -> bool {
        true
    }

    /// The widget is no longer focused for user input.
    #[allow(unused_variables)]
    fn blur(&mut self, context: &mut EventContext<'_>) {}

    /// The widget has become the active widget.
    #[allow(unused_variables)]
    fn activate(&mut self, context: &mut EventContext<'_>) {}

    /// The widget is no longer active.
    #[allow(unused_variables)]
    fn deactivate(&mut self, context: &mut EventContext<'_>) {}

    /// A mouse button event has occurred at `location`. Returns whether the
    /// event has been handled or not.
    ///
    /// If an event is handled, the widget will receive callbacks for
    /// [`mouse_drag`](Self::mouse_drag) and [`mouse_up`](Self::mouse_up). See
    /// [Mouse Button Events](Self#mouse-button-events) for more information on
    /// how mouse events work in Cushy.
    ///
    /// This function will only be invoked if it or a child is the currently
    /// hovered widget. See [Hover State: Hit
    /// Testing](Self#hover-state-hit-testing) for more information on how hover
    /// state is handled in Cushy.
    #[allow(unused_variables)]
    fn mouse_down(
        &mut self,
        location: Point<Px>,
        device_id: DeviceId,
        button: MouseButton,
        context: &mut EventContext<'_>,
    ) -> EventHandling {
        IGNORED
    }

    /// A mouse button is being held down as the cursor is moved across the
    /// widget.
    ///
    /// This function will only be invoked if [`Self::mouse_down`] returns
    /// [`HANDLED`]. See [Mouse Button Events](Self#mouse-button-events) for
    /// more information on how mouse events work in Cushy.
    #[allow(unused_variables)]
    fn mouse_drag(
        &mut self,
        location: Point<Px>,
        device_id: DeviceId,
        button: MouseButton,
        context: &mut EventContext<'_>,
    ) {
    }

    /// A mouse button is no longer being pressed.
    ///
    /// This function will only be invoked if [`Self::mouse_down`] returns
    /// [`HANDLED`]. See [Mouse Button Events](Self#mouse-button-events) for
    /// more information on how mouse events work in Cushy.
    #[allow(unused_variables)]
    fn mouse_up(
        &mut self,
        location: Option<Point<Px>>,
        device_id: DeviceId,
        button: MouseButton,
        context: &mut EventContext<'_>,
    ) {
    }

    /// A keyboard event has been sent to this widget. Returns whether the event
    /// has been handled or not.
    #[allow(unused_variables)]
    fn keyboard_input(
        &mut self,
        device_id: DeviceId,
        input: KeyEvent,
        is_synthetic: bool,
        context: &mut EventContext<'_>,
    ) -> EventHandling {
        IGNORED
    }

    /// An input manager event has been sent to this widget. Returns whether the
    /// event has been handled or not.
    #[allow(unused_variables)]
    fn ime(&mut self, ime: Ime, context: &mut EventContext<'_>) -> EventHandling {
        IGNORED
    }

    /// A mouse wheel event has been sent to this widget. Returns whether the
    /// event has been handled or not.
    ///
    /// This function will only be invoked if it or a child is the currently
    /// hovered widget. See [Hover State: Hit
    /// Testing](Self#hover-state-hit-testing) for more information on how hover
    /// state is handled in Cushy.
    #[allow(unused_variables)]
    #[allow(unused_variables)]
    fn mouse_wheel(
        &mut self,
        device_id: DeviceId,
        delta: MouseScrollDelta,
        phase: TouchPhase,
        context: &mut EventContext<'_>,
    ) -> EventHandling {
        IGNORED
    }

    /// Returns a reference to a single child widget if this widget is a widget
    /// that primarily wraps a single other widget to customize its behavior.
    #[must_use]
    #[allow(unused_variables)]
    fn root_behavior(
        &mut self,
        context: &mut EventContext<'_>,
    ) -> Option<(RootBehavior, WidgetInstance)> {
        None
    }
}

// ANCHOR: run
impl<T> Run for T
where
    T: MakeWidget,
{
    fn run(self) -> crate::Result {
        Window::for_widget(self).run()
    }
}
// ANCHOR_END: run

/// A behavior that should be applied to a root widget.
#[derive(Debug, Clone, Copy)]
pub enum RootBehavior {
    /// This widget does not care about root behaviors, and its child should be
    /// allowed to specify a behavior.
    PassThrough,
    /// This widget will try to expand to fill the window.
    Expand,
    /// This widget will measure its contents to fit its child, but Cushy should
    /// still stretch this widget to fill the window.
    Align,
    /// This widget adjusts its child layout with padding.
    Pad(Edges<Dimension>),
    /// This widget changes the size of its child.
    Resize(Size<DimensionRange>),
}

/// The layout of a [wrapped](WrapperWidget) child widget.
#[derive(Clone, Copy, Debug)]
pub struct WrappedLayout {
    /// The region the child widget occupies within its parent.
    pub child: Rect<Px>,
    /// The size the wrapper widget should report as.
    pub size: Size<UPx>,
}

impl WrappedLayout {
    /// Returns a layout that positions `size` within `available_space` while
    /// respecting [`HOrizontalAlignment`] and [`VerticalAlignment`].
    pub fn aligned(
        size: Size<UPx>,
        available_space: Size<ConstraintLimit>,
        context: &mut LayoutContext<'_, '_, '_, '_>,
    ) -> Self {
        let child_size = size.into_signed();
        let fill_width = available_space
            .width
            .fit_measured(child_size.width)
            .into_signed();
        let (padded_width, x, width) = if fill_width <= child_size.width {
            (child_size.width, Px::ZERO, child_size.width)
        } else {
            let x = context
                .get(&HorizontalAlignment)
                .alignment_offset(child_size.width, fill_width);
            (fill_width, x, child_size.width)
        };
        let fill_height = available_space
            .height
            .fit_measured(child_size.height)
            .into_signed();
        let (padded_height, y, height) = if fill_height <= child_size.height {
            (child_size.height, Px::ZERO, child_size.height)
        } else {
            let y = context
                .get(&VerticalAlignment)
                .align(child_size.height, fill_height);
            (fill_height, y, child_size.height)
        };
        WrappedLayout {
            child: Rect::new(Point::new(x, y), Size::new(width, height)),
            size: Size::new(padded_width, padded_height).into_unsigned(),
        }
    }
}

impl From<Size<Px>> for WrappedLayout {
    fn from(size: Size<Px>) -> Self {
        WrappedLayout {
            child: size.into(),
            size: size.into_unsigned(),
        }
    }
}

impl From<Size<UPx>> for WrappedLayout {
    fn from(size: Size<UPx>) -> Self {
        WrappedLayout {
            child: size.into_signed().into(),
            size,
        }
    }
}

/// A [`Widget`] that contains a single child.
pub trait WrapperWidget: Debug + Send + 'static {
    /// Returns the child widget.
    fn child_mut(&mut self) -> &mut WidgetRef;

    /// Writes a summary of this widget into `fmt`.
    ///
    /// The default implementation calls [`Debug::fmt`]. This function allows
    /// widget authors to print only publicly relevant information that will
    /// appear when debug formatting a [`WidgetInstance`].
    fn summarize(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Debug::fmt(self, f)
    }

    /// Returns the behavior this widget should apply when positioned at the
    /// root of the window.
    ///
    /// The provided implementation for `WrapperWidget` returns
    /// [`RootBehavior::PassThrough`]. This is different from the provided
    /// implementation for [`Widget`].
    #[allow(unused_variables)]
    fn root_behavior(&mut self, context: &mut EventContext<'_>) -> Option<RootBehavior> {
        Some(RootBehavior::PassThrough)
    }

    /// Draws the background of the widget.
    ///
    /// This is invoked before the wrapped widget is drawn.
    #[allow(unused_variables)]
    fn redraw_background(&mut self, context: &mut GraphicsContext<'_, '_, '_, '_>) {}

    /// Draws the foreground of the widget.
    ///
    /// This is invoked after the wrapped widget is drawn.
    #[allow(unused_variables)]
    fn redraw_foreground(&mut self, context: &mut GraphicsContext<'_, '_, '_, '_>) {}

    /// Returns the rectangle that the child widget should occupy given
    /// `available_space`.
    #[allow(unused_variables)]
    fn layout_child(
        &mut self,
        available_space: Size<ConstraintLimit>,
        context: &mut LayoutContext<'_, '_, '_, '_>,
    ) -> WrappedLayout {
        let adjusted_space = self.adjust_child_constraints(available_space, context);
        let child = self.child_mut().mounted(&mut context.as_event_context());
        let size = context
            .for_other(&child)
            .layout(adjusted_space)
            .into_signed();

        self.position_child(size, available_space, context)
    }

    /// Returns the adjusted contraints to use when laying out the child.
    #[allow(unused_variables)]
    #[must_use]
    fn adjust_child_constraints(
        &mut self,
        available_space: Size<ConstraintLimit>,
        context: &mut LayoutContext<'_, '_, '_, '_>,
    ) -> Size<ConstraintLimit> {
        available_space
    }

    /// Returns the layout after positioning the child that occupies `size`.
    #[allow(unused_variables)]
    #[must_use]
    fn position_child(
        &mut self,
        size: Size<Px>,
        available_space: Size<ConstraintLimit>,
        context: &mut LayoutContext<'_, '_, '_, '_>,
    ) -> WrappedLayout {
        WrappedLayout::aligned(size.into_unsigned(), available_space, context)
    }

    /// Returns the background color to render behind the wrapped widget.
    #[allow(unused_variables)]
    #[must_use]
    fn background_color(&mut self, context: &WidgetContext<'_>) -> Option<Color> {
        // WidgetBackground is already filled, so we don't need to do anything
        // else by default.
        None
    }

    /// The widget has been mounted into a parent widget.
    #[allow(unused_variables)]
    fn mounted(&mut self, context: &mut EventContext<'_>) {}

    /// The widget has been removed from its parent widget.
    #[allow(unused_variables)]
    fn unmounted(&mut self, context: &mut EventContext<'_>) {
        self.child_mut().unmount_in(context);
    }

    /// Returns true if this widget should respond to mouse input at `location`.
    #[allow(unused_variables)]
    fn hit_test(&mut self, location: Point<Px>, context: &mut EventContext<'_>) -> bool {
        false
    }

    /// The widget is currently has a cursor hovering it at `location`.
    #[allow(unused_variables)]
    fn hover(&mut self, location: Point<Px>, context: &mut EventContext<'_>) -> Option<CursorIcon> {
        None
    }

    /// The widget is no longer being hovered.
    #[allow(unused_variables)]
    fn unhover(&mut self, context: &mut EventContext<'_>) {}

    /// This widget has been targeted to be focused. If this function returns
    /// true, the widget will be focused. If false, Cushy will continue
    /// searching for another focus target.
    #[allow(unused_variables)]
    fn accept_focus(&mut self, context: &mut EventContext<'_>) -> bool {
        false
    }

    /// The widget should switch to the next focusable area within this widget,
    /// honoring `direction` in a consistent manner. Returning `HANDLED` will
    /// cause the search for the next focus widget stop.
    #[allow(unused_variables)]
    fn advance_focus(
        &mut self,
        direction: VisualOrder,
        context: &mut EventContext<'_>,
    ) -> EventHandling {
        IGNORED
    }

    /// The widget has received focus for user input.
    #[allow(unused_variables)]
    fn focus(&mut self, context: &mut EventContext<'_>) {}

    /// The widget is about to lose focus. Returning true allows the focus to
    /// switch away from this widget.
    #[allow(unused_variables)]
    fn allow_blur(&mut self, context: &mut EventContext<'_>) -> bool {
        true
    }

    /// The widget is no longer focused for user input.
    #[allow(unused_variables)]
    fn blur(&mut self, context: &mut EventContext<'_>) {}

    /// The widget has become the active widget.
    #[allow(unused_variables)]
    fn activate(&mut self, context: &mut EventContext<'_>) {
        let child = self.child_mut().mounted(context);
        context.for_other(&child).activate();
    }

    /// The widget is no longer active.
    #[allow(unused_variables)]
    fn deactivate(&mut self, context: &mut EventContext<'_>) {}

    /// A mouse button event has occurred at `location`. Returns whether the
    /// event has been handled or not.
    ///
    /// If an event is handled, the widget will receive callbacks for
    /// [`mouse_drag`](Self::mouse_drag) and [`mouse_up`](Self::mouse_up).
    #[allow(unused_variables)]
    fn mouse_down(
        &mut self,
        location: Point<Px>,
        device_id: DeviceId,
        button: MouseButton,
        context: &mut EventContext<'_>,
    ) -> EventHandling {
        IGNORED
    }

    /// A mouse button is being held down as the cursor is moved across the
    /// widget.
    #[allow(unused_variables)]
    fn mouse_drag(
        &mut self,
        location: Point<Px>,
        device_id: DeviceId,
        button: MouseButton,
        context: &mut EventContext<'_>,
    ) {
    }

    /// A mouse button is no longer being pressed.
    #[allow(unused_variables)]
    fn mouse_up(
        &mut self,
        location: Option<Point<Px>>,
        device_id: DeviceId,
        button: MouseButton,
        context: &mut EventContext<'_>,
    ) {
    }

    /// A keyboard event has been sent to this widget. Returns whether the event
    /// has been handled or not.
    #[allow(unused_variables)]
    fn keyboard_input(
        &mut self,
        device_id: DeviceId,
        input: KeyEvent,
        is_synthetic: bool,
        context: &mut EventContext<'_>,
    ) -> EventHandling {
        IGNORED
    }

    /// An input manager event has been sent to this widget. Returns whether the
    /// event has been handled or not.
    #[allow(unused_variables)]
    fn ime(&mut self, ime: Ime, context: &mut EventContext<'_>) -> EventHandling {
        IGNORED
    }

    /// A mouse wheel event has been sent to this widget. Returns whether the
    /// event has been handled or not.
    #[allow(unused_variables)]
    fn mouse_wheel(
        &mut self,
        device_id: DeviceId,
        delta: MouseScrollDelta,
        phase: TouchPhase,
        context: &mut EventContext<'_>,
    ) -> EventHandling {
        IGNORED
    }
}

impl<T> Widget for T
where
    T: WrapperWidget,
{
    fn root_behavior(
        &mut self,
        context: &mut EventContext<'_>,
    ) -> Option<(RootBehavior, WidgetInstance)> {
        T::root_behavior(self, context)
            .map(|behavior| (behavior, T::child_mut(self).widget().clone()))
    }

    fn redraw(&mut self, context: &mut GraphicsContext<'_, '_, '_, '_>) {
        let background_color = self.background_color(context);
        if let Some(color) = background_color {
            context.fill(color);
        }

        self.redraw_background(context);

        let child = self.child_mut().mounted(&mut context.as_event_context());
        context.for_other(&child).redraw();

        self.redraw_foreground(context);
    }

    fn layout(
        &mut self,
        available_space: Size<ConstraintLimit>,
        context: &mut LayoutContext<'_, '_, '_, '_>,
    ) -> Size<UPx> {
        let layout = self.layout_child(available_space, context);
        let child = self.child_mut().mounted(&mut context.as_event_context());
        context.set_child_layout(&child, layout.child);
        layout.size
    }

    fn mounted(&mut self, context: &mut EventContext<'_>) {
        T::mounted(self, context);
    }

    fn unmounted(&mut self, context: &mut EventContext<'_>) {
        T::unmounted(self, context);
    }

    fn hit_test(&mut self, location: Point<Px>, context: &mut EventContext<'_>) -> bool {
        T::hit_test(self, location, context)
    }

    fn hover(&mut self, location: Point<Px>, context: &mut EventContext<'_>) -> Option<CursorIcon> {
        T::hover(self, location, context)
    }

    fn unhover(&mut self, context: &mut EventContext<'_>) {
        T::unhover(self, context);
    }

    fn accept_focus(&mut self, context: &mut EventContext<'_>) -> bool {
        T::accept_focus(self, context)
    }

    fn focus(&mut self, context: &mut EventContext<'_>) {
        T::focus(self, context);
    }

    fn blur(&mut self, context: &mut EventContext<'_>) {
        T::blur(self, context);
    }

    fn activate(&mut self, context: &mut EventContext<'_>) {
        T::activate(self, context);
    }

    fn deactivate(&mut self, context: &mut EventContext<'_>) {
        T::deactivate(self, context);
    }

    fn mouse_down(
        &mut self,
        location: Point<Px>,
        device_id: DeviceId,
        button: MouseButton,
        context: &mut EventContext<'_>,
    ) -> EventHandling {
        T::mouse_down(self, location, device_id, button, context)
    }

    fn mouse_drag(
        &mut self,
        location: Point<Px>,
        device_id: DeviceId,
        button: MouseButton,
        context: &mut EventContext<'_>,
    ) {
        T::mouse_drag(self, location, device_id, button, context);
    }

    fn mouse_up(
        &mut self,
        location: Option<Point<Px>>,
        device_id: DeviceId,
        button: MouseButton,
        context: &mut EventContext<'_>,
    ) {
        T::mouse_up(self, location, device_id, button, context);
    }

    fn keyboard_input(
        &mut self,
        device_id: DeviceId,
        input: KeyEvent,
        is_synthetic: bool,
        context: &mut EventContext<'_>,
    ) -> EventHandling {
        T::keyboard_input(self, device_id, input, is_synthetic, context)
    }

    fn ime(&mut self, ime: Ime, context: &mut EventContext<'_>) -> EventHandling {
        T::ime(self, ime, context)
    }

    fn mouse_wheel(
        &mut self,
        device_id: DeviceId,
        delta: MouseScrollDelta,
        phase: TouchPhase,
        context: &mut EventContext<'_>,
    ) -> EventHandling {
        T::mouse_wheel(self, device_id, delta, phase, context)
    }

    fn advance_focus(
        &mut self,
        direction: VisualOrder,
        context: &mut EventContext<'_>,
    ) -> EventHandling {
        T::advance_focus(self, direction, context)
    }

    fn allow_blur(&mut self, context: &mut EventContext<'_>) -> bool {
        T::allow_blur(self, context)
    }

    fn summarize(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        T::summarize(self, fmt)
    }
}

/// A type that can create a [`WidgetInstance`].
pub trait MakeWidget: Sized {
    /// Returns a new widget.
    fn make_widget(self) -> WidgetInstance;

    /// Returns a new window containing `self` as the root widget.
    fn into_window(self) -> Window {
        self.make_window()
    }

    /// Returns a builder for a standalone window.
    ///
    /// A standalone window can be either a
    /// [`VirtualWindow`](crate::window::VirtualWindow) or a
    /// [`CushyWindow`](crate::window::CushyWindow).
    fn build_standalone_window(self) -> StandaloneWindowBuilder {
        StandaloneWindowBuilder::new(self)
    }

    /// Returns a builder for a [`VirtualRecorder`](crate::window::VirtualRecorder)
    fn build_recorder(self) -> VirtualRecorderBuilder<Rgb8> {
        VirtualRecorderBuilder::new(self)
    }

    /// Associates `styles` with this widget.
    ///
    /// This is equivalent to `Style::new(styles, self)`.
    fn with_styles(self, styles: impl IntoValue<Styles>) -> Style
    where
        Self: Sized,
    {
        Style::new(styles, self)
    }

    /// Associates a style component with `self`.
    fn with<C: ComponentDefinition>(
        self,
        name: &C,
        component: impl IntoValue<C::ComponentType>,
    ) -> Style
    where
        Value<C::ComponentType>: IntoComponentValue,
    {
        Style::new(Styles::new().with(name, component), self)
    }

    /// Associates a style component with `self`, ensuring that no child widgets
    /// inherit this component.
    fn with_local<C: ComponentDefinition>(
        self,
        name: &C,
        component: impl IntoValue<C::ComponentType>,
    ) -> Style
    where
        Value<C::ComponentType>: IntoComponentValue,
    {
        Style::new(Styles::new().with_local(name, component), self)
    }

    /// Associates a style component with `self`, resolving its value using
    /// `dynamic` at runtime.
    fn with_dynamic<C: ComponentDefinition>(
        self,
        name: &C,
        dynamic: impl IntoDynamicComponentValue,
    ) -> Style
    where
        C::ComponentType: IntoComponentValue,
    {
        Style::new(Styles::new().with_dynamic(name, dynamic), self)
    }

    /// Associates a style component with `self`, resolving its value using
    /// `dynamic` at runtime. This component will not be inherited to child
    /// widgets.
    fn with_local_dynamic<C: ComponentDefinition>(
        self,
        name: &C,
        dynamic: impl IntoDynamicComponentValue,
    ) -> Style
    where
        C::ComponentType: IntoComponentValue,
    {
        Style::new(Styles::new().with_local_dynamic(name, dynamic), self)
    }

    /// Invokes `callback` when `key` is pressed while `modifiers` are pressed.
    ///
    /// This shortcut will only be invoked if focus is within `self` or a child
    /// of `self`, or if the returned widget becomes the root widget of a
    /// window.
    #[must_use]
    fn with_shortcut<F>(
        self,
        key: impl Into<ShortcutKey>,
        modifiers: ModifiersState,
        callback: F,
    ) -> Shortcuts
    where
        F: FnMut(KeyEvent) -> EventHandling + Send + 'static,
    {
        Shortcuts::new(self).with_shortcut(key, modifiers, callback)
    }

    /// Invokes `callback` when `key` is pressed while `modifiers` are pressed.
    /// If the shortcut is held, the callback will be invoked on repeat events.
    ///
    /// This shortcut will only be invoked if focus is within `self` or a child
    /// of `self`, or if the returned widget becomes the root widget of a
    /// window.
    #[must_use]
    fn with_repeating_shortcut<F>(
        self,
        key: impl Into<ShortcutKey>,
        modifiers: ModifiersState,
        callback: F,
    ) -> Shortcuts
    where
        F: FnMut(KeyEvent) -> EventHandling + Send + 'static,
    {
        Shortcuts::new(self).with_repeating_shortcut(key, modifiers, callback)
    }

    /// Styles `self` with the largest of 6 heading styles.
    fn h1(self) -> Style {
        Style::new(Styles::default(), self).h1()
    }

    /// Styles `self` with the second largest of 6 heading styles.
    fn h2(self) -> Style {
        Style::new(Styles::default(), self).h2()
    }

    /// Styles `self` with the third largest of 6 heading styles.
    fn h3(self) -> Style {
        Style::new(Styles::default(), self).h3()
    }

    /// Styles `self` with the third smallest of 6 heading styles.
    fn h4(self) -> Style {
        Style::new(Styles::default(), self).h4()
    }

    /// Styles `self` with the second smallest of 6 heading styles.
    fn h5(self) -> Style {
        Style::new(Styles::default(), self).h5()
    }

    /// Styles `self` with the smallest of 6 heading styles.
    fn h6(self) -> Style {
        Style::new(Styles::default(), self).h6()
    }

    /// Styles `self` with the largest text size.
    #[must_use]
    fn xxxx_large(self) -> Style {
        Style::new(Styles::default(), self).xxxx_large()
    }

    /// Styles `self` with the second largest text size.
    #[must_use]
    fn xxx_large(self) -> Style {
        Style::new(Styles::default(), self).xxx_large()
    }

    /// Styles `self` with the third largest text size.
    #[must_use]
    fn xx_large(self) -> Style {
        Style::new(Styles::default(), self).xx_large()
    }

    /// Styles `self` with the fourth largest text size.
    #[must_use]
    fn x_large(self) -> Style {
        Style::new(Styles::default(), self).x_large()
    }

    /// Styles `self` with the fifth largest text size.
    #[must_use]
    fn large(self) -> Style {
        Style::new(Styles::default(), self).large()
    }

    /// Styles `self` with the third smallest text size.
    #[must_use]
    fn default_size(self) -> Style {
        Style::new(Styles::default(), self).default_size()
    }

    /// Styles `self` with the second smallest text size.
    #[must_use]
    fn small(self) -> Style {
        Style::new(Styles::default(), self).small()
    }

    /// Styles `self` with the smallest text size.
    #[must_use]
    fn x_small(self) -> Style {
        Style::new(Styles::default(), self).x_small()
    }

    /// Styles `self` as an informational hint message.
    fn hint(self) -> Style {
        Style::new(Styles::default(), self).hint()
    }

    /// Attaches `hint` as an informational hint message below `self`.
    ///
    /// The spacing between `self` and `hint` is half of [`IntrinsicPadding`].
    fn with_hint(self, hint: impl MakeWidget) -> Stack {
        let probe = IntrinsicPadding.probe();
        let padding = probe
            .value()
            .map_each(|padding| FlexibleDimension::Dimension(*padding / 2));
        self.and(probe)
            .and(
                hint.hint()
                    .with(&HorizontalAlignment, HorizontalAlign::Left),
            )
            .into_rows()
            .gutter(padding)
    }

    /// Sets the widget that should be focused next.
    ///
    /// Cushy automatically determines reverse tab order by using this same
    /// relationship.
    fn with_next_focus(self, next_focus: impl IntoValue<Option<WidgetId>>) -> WidgetInstance {
        self.make_widget().with_next_focus(next_focus)
    }

    /// Sets this widget to be enabled/disabled based on `enabled` and returns
    /// self.
    ///
    /// If this widget is disabled, all children widgets will also be disabled.
    ///
    /// # Panics
    ///
    /// This function can only be called when one instance of the widget exists.
    /// If any clones exist, a panic will occur.
    fn with_enabled(self, enabled: impl IntoValue<bool>) -> WidgetInstance {
        self.make_widget().with_enabled(enabled)
    }

    /// Sets this widget as a "default" widget.
    ///
    /// Default widgets are automatically activated when the user signals they
    /// are ready for the default action to occur.
    ///
    /// Example widgets this is used for are:
    ///
    /// - Submit buttons on forms
    /// - Ok buttons
    #[must_use]
    fn into_default(self) -> WidgetInstance {
        self.make_widget().into_default()
    }

    /// Sets this widget as an "escape" widget.
    ///
    /// Escape widgets are automatically activated when the user signals they
    /// are ready to escape their current situation.
    ///
    /// Example widgets this is used for are:
    ///
    /// - Close buttons
    /// - Cancel buttons
    #[must_use]
    fn into_escape(self) -> WidgetInstance {
        self.make_widget().into_escape()
    }

    /// Returns a collection of widgets using `self` and `other`.
    fn and(self, other: impl MakeWidget) -> WidgetList {
        let mut children = WidgetList::new();
        children.push(self);
        children.push(other);
        children
    }

    /// Chains `self` and `others` into a [`WidgetList`].
    fn chain<W: MakeWidget>(self, others: impl IntoIterator<Item = W>) -> WidgetList {
        let others = others.into_iter();
        let mut widgets = WidgetList::with_capacity(others.size_hint().0 + 1);
        widgets.push(self);
        widgets.extend(others);
        widgets
    }

    /// Expands `self` to grow to fill its parent.
    #[must_use]
    fn expand(self) -> Expand {
        Expand::new(self)
    }

    /// Expands `self` to grow to fill its parent proportionally with other
    /// weighted siblings.
    #[must_use]
    fn expand_weighted(self, weight: u8) -> Expand {
        Expand::weighted(weight, self)
    }

    /// Expands `self` to grow to fill its parent horizontally.
    #[must_use]
    fn expand_horizontally(self) -> Expand {
        Expand::horizontal(self)
    }

    /// Expands `self` to grow to fill its parent vertically.
    #[must_use]
    fn expand_vertically(self) -> Expand {
        Expand::vertical(self)
    }

    /// Resizes `self` to `size`.
    #[must_use]
    fn size<T>(self, size: Size<T>) -> Resize
    where
        T: Into<DimensionRange>,
    {
        Resize::to(size, self)
    }

    /// Resizes `self` to `width`.
    ///
    /// `width` can be an any of:
    ///
    /// - [`Dimension`]
    /// - [`Px`]
    /// - [`Lp`](crate::figures::units::Lp)
    /// - A range of any fo the above.
    #[must_use]
    fn width(self, width: impl Into<DimensionRange>) -> Resize {
        Resize::from_width(width, self)
    }

    /// Resizes `self` to `height`.
    ///
    /// `height` can be an any of:
    ///
    /// - [`Dimension`]
    /// - [`Px`]
    /// - [`Lp`](crate::figures::units::Lp)
    /// - A range of any fo the above.
    #[must_use]
    fn height(self, height: impl Into<DimensionRange>) -> Resize {
        Resize::from_height(height, self)
    }

    /// Returns this widget as the contents of a clickable button.
    fn into_button(self) -> Button {
        Button::new(self)
    }

    /// Returns this widget as the contents of a clickable button.
    fn to_button(&self) -> Button
    where
        Self: Clone,
    {
        self.clone().into_button()
    }

    /// Returns this widget as the label of a Checkbox.
    fn into_checkbox(self, value: impl IntoDynamic<CheckboxState>) -> Checkbox {
        value.into_checkbox().labelled_by(self)
    }

    /// Returns this widget as the label of a Checkbox.
    fn to_checkbox(&self, value: impl IntoDynamic<CheckboxState>) -> Checkbox
    where
        Self: Clone,
    {
        self.clone().into_checkbox(value)
    }

    /// Aligns `self` to the center vertically and horizontally.
    #[must_use]
    fn centered(self) -> Align {
        Align::centered(self)
    }

    /// Aligns `self` to the left.
    fn align_left(self) -> Align {
        self.centered().align_left()
    }

    /// Aligns `self` to the right.
    fn align_right(self) -> Align {
        self.centered().align_right()
    }

    /// Aligns `self` to the top.
    fn align_top(self) -> Align {
        self.centered().align_top()
    }

    /// Aligns `self` to the bottom.
    fn align_bottom(self) -> Align {
        self.centered().align_bottom()
    }

    /// Fits `self` horizontally within its parent.
    fn fit_horizontally(self) -> Align {
        self.centered().fit_horizontally()
    }

    /// Fits `self` vertically within its parent.
    fn fit_vertically(self) -> Align {
        self.centered().fit_vertically()
    }

    /// Allows scrolling `self` both vertically and horizontally.
    #[must_use]
    fn scroll(self) -> Scroll {
        Scroll::new(self)
    }

    /// Allows scrolling `self` vertically.
    #[must_use]
    fn vertical_scroll(self) -> Scroll {
        Scroll::vertical(self)
    }

    /// Allows scrolling `self` horizontally.
    #[must_use]
    fn horizontal_scroll(self) -> Scroll {
        Scroll::horizontal(self)
    }

    /// Creates a [`WidgetRef`] for use as child widget.
    #[must_use]
    fn into_ref(self) -> WidgetRef {
        WidgetRef::new(self)
    }

    /// Wraps `self` in a [`Container`].
    fn contain(self) -> Container {
        Container::new(self)
    }

    /// Wraps `self` in a [`Container`] with the specified level.
    fn contain_level(self, level: impl IntoValue<ContainerLevel>) -> Container {
        self.contain().contain_level(level)
    }

    /// Returns a new widget that renders `color` behind `self`.
    fn background_color(self, color: impl IntoValue<Color>) -> Container {
        self.contain().pad_by(Px::ZERO).background_color(color)
    }

    /// Wraps `self` with the default padding.
    fn pad(self) -> Container {
        self.contain().transparent()
    }

    /// Wraps `self` with the specified padding.
    fn pad_by(self, padding: impl IntoValue<Edges<Dimension>>) -> Container {
        self.contain().transparent().pad_by(padding)
    }

    /// Applies `theme` to `self` and its children.
    fn themed(self, theme: impl IntoValue<ThemePair>) -> Themed {
        Themed::new(theme, self)
    }

    /// Applies `mode` to `self` and its children.
    fn themed_mode(self, mode: impl IntoValue<ThemeMode>) -> ThemedMode {
        ThemedMode::new(mode, self)
    }

    /// Returns a widget that collapses `self` horizontally based on the dynamic boolean value.
    ///
    /// This widget will be collapsed when the dynamic contains `true`, and
    /// revealed when the dynamic contains `false`.
    fn collapse_horizontally(self, collapse_when: impl IntoDynamic<bool>) -> Collapse {
        Collapse::horizontal(collapse_when, self)
    }

    /// Returns a widget that collapses `self` vertically based on the dynamic
    /// boolean value.
    ///
    /// This widget will be collapsed when the dynamic contains `true`, and
    /// revealed when the dynamic contains `false`.
    fn collapse_vertically(self, collapse_when: impl IntoDynamic<bool>) -> Collapse {
        Collapse::vertical(collapse_when, self)
    }

    /// Returns a new widget that allows hiding and showing `contents`.
    fn disclose(self) -> Disclose {
        Disclose::new(self)
    }

    /// Returns a widget that shows validation errors and/or hints.
    fn validation(self, validation: impl IntoDynamic<Validation>) -> Validated {
        Validated::new(validation, self)
    }

    /// Returns a widget that shows `tip` on `layer` when `self` is hovered.
    fn tooltip(self, layer: &OverlayLayer, tip: impl MakeWidget) -> Tooltipped {
        layer.new_tooltip(tip, self)
    }
}

/// A type that can create a [`WidgetInstance`] with a preallocated
/// [`WidgetId`].
pub trait MakeWidgetWithTag: Sized {
    /// Returns a new [`WidgetInstance`] whose [`WidgetId`] comes from `tag`.
    fn make_with_tag(self, tag: WidgetTag) -> WidgetInstance;
}

impl<T> MakeWidgetWithTag for T
where
    T: Widget,
{
    fn make_with_tag(self, id: WidgetTag) -> WidgetInstance {
        WidgetInstance::with_id(self, id)
    }
}

impl<T> MakeWidget for T
where
    T: MakeWidgetWithTag,
{
    fn make_widget(self) -> WidgetInstance {
        self.make_with_tag(WidgetTag::unique())
    }
}

impl MakeWidget for WidgetInstance {
    fn make_widget(self) -> WidgetInstance {
        self
    }
}

impl MakeWidgetWithTag for Color {
    fn make_with_tag(self, id: WidgetTag) -> WidgetInstance {
        Space::colored(self).make_with_tag(id)
    }
}

/// A type that represents whether an event has been handled or ignored.
pub type EventHandling = ControlFlow<EventHandled, EventIgnored>;

/// A marker type that represents a handled event.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]

pub struct EventHandled;
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
/// A marker type that represents an ignored event.
pub struct EventIgnored;

/// An [`EventHandling`] value that represents a handled event.
pub const HANDLED: EventHandling = EventHandling::Break(EventHandled);

/// An [`EventHandling`] value that represents an ignored event.
pub const IGNORED: EventHandling = EventHandling::Continue(EventIgnored);

pub(crate) trait AnyWidget: Widget {
    fn as_any(&self) -> &dyn Any;
    fn as_any_mut(&mut self) -> &mut dyn Any;
}

impl<T> AnyWidget for T
where
    T: Widget,
{
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}

/// An instance of a [`Widget`].
#[derive(Clone)]
pub struct WidgetInstance {
    data: Arc<WidgetInstanceData>,
}

impl Debug for WidgetInstance {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.data.widget.try_lock() {
            Some(widget) => widget.summarize(f),
            None => f.debug_struct("WidgetInstance").finish_non_exhaustive(),
        }
    }
}

#[derive(Debug)]
struct WidgetInstanceData {
    id: WidgetId,
    default: bool,
    cancel: bool,
    next_focus: Value<Option<WidgetId>>,
    enabled: Value<bool>,
    widget: Box<Mutex<dyn AnyWidget>>,
}

impl WidgetInstance {
    /// Returns a new instance containing `widget` that is assigned the unique
    /// `id` provided.
    pub fn with_id<W>(widget: W, id: WidgetTag) -> Self
    where
        W: Widget,
    {
        Self {
            data: Arc::new(WidgetInstanceData {
                id: id.into(),
                next_focus: Value::default(),
                default: false,
                cancel: false,
                widget: Box::new(Mutex::new(widget)),
                enabled: Value::Constant(true),
            }),
        }
    }

    /// Returns a new instance containing `widget`.
    pub fn new<W>(widget: W) -> Self
    where
        W: Widget,
    {
        Self::with_id(widget, WidgetTag::unique())
    }

    /// Returns the unique id of this widget instance.
    #[must_use]
    pub fn id(&self) -> WidgetId {
        self.data.id
    }

    /// Sets the widget that should be focused next.
    ///
    /// Cushy automatically determines reverse tab order by using this same
    /// relationship.
    ///
    /// # Panics
    ///
    /// This function can only be called when one instance of the widget exists.
    /// If any clones exist, a panic will occur.
    #[must_use]
    pub fn with_next_focus(
        mut self,
        next_focus: impl IntoValue<Option<WidgetId>>,
    ) -> WidgetInstance {
        let data = Arc::get_mut(&mut self.data)
            .expect("with_next_focus can only be called on newly created widget instances");
        data.next_focus = next_focus.into_value();
        self
    }

    /// Sets this widget to be enabled/disabled based on `enabled` and returns
    /// self.
    ///
    /// If this widget is disabled, all children widgets will also be disabled.
    ///
    /// # Panics
    ///
    /// This function can only be called when one instance of the widget exists.
    /// If any clones exist, a panic will occur.
    #[must_use]
    pub fn with_enabled(mut self, enabled: impl IntoValue<bool>) -> WidgetInstance {
        let data = Arc::get_mut(&mut self.data)
            .expect("with_enabled can only be called on newly created widget instances");
        data.enabled = enabled.into_value();
        self
    }

    /// Sets this widget as a "default" widget.
    ///
    /// Default widgets are automatically activated when the user signals they
    /// are ready for the default action to occur.
    ///
    /// Example widgets this is used for are:
    ///
    /// - Submit buttons on forms
    /// - Ok buttons
    ///
    /// # Panics
    ///
    /// This function can only be called when one instance of the widget exists.
    /// If any clones exist, a panic will occur.
    #[must_use]
    pub fn into_default(mut self) -> WidgetInstance {
        let data = Arc::get_mut(&mut self.data)
            .expect("with_next_focus can only be called on newly created widget instances");
        data.default = true;
        self
    }

    /// Sets this widget as an "escape" widget.
    ///
    /// Escape widgets are automatically activated when the user signals they
    /// are ready to escape their current situation.
    ///
    /// Example widgets this is used for are:
    ///
    /// - Close buttons
    /// - Cancel buttons
    ///
    /// # Panics
    ///
    /// This function can only be called when one instance of the widget exists.
    /// If any clones exist, a panic will occur.
    #[must_use]
    pub fn into_escape(mut self) -> WidgetInstance {
        let data = Arc::get_mut(&mut self.data)
            .expect("with_next_focus can only be called on newly created widget instances");
        data.cancel = true;
        self
    }

    /// Locks the widget for exclusive access. Locking widgets should only be
    /// done for brief moments of time when you are certain no deadlocks can
    /// occur due to other widget locks being held.
    #[must_use]
    pub fn lock(&self) -> WidgetGuard<'_> {
        WidgetGuard(self.data.widget.lock())
    }

    /// Returns the id of the widget that should receive focus after this
    /// widget.
    ///
    /// This value comes from [`MakeWidget::with_next_focus()`].
    #[must_use]
    pub fn next_focus(&self) -> Option<WidgetId> {
        self.data.next_focus.get()
    }

    /// Returns true if this is a default widget.
    ///
    /// See [`MakeWidget::into_default()`] for more information.
    #[must_use]
    pub fn is_default(&self) -> bool {
        self.data.default
    }

    /// Returns true if this is an escape widget.
    ///
    /// See [`MakeWidget::into_escape()`] for more information.
    #[must_use]
    pub fn is_escape(&self) -> bool {
        self.data.cancel
    }

    pub(crate) fn enabled(&self, context: &WindowHandle) -> bool {
        if let Value::Dynamic(dynamic) = &self.data.enabled {
            dynamic.inner_redraw_when_changed(context.clone());
        }
        self.data.enabled.get()
    }

    /// Returns a new window containing `self` as the root widget.
    pub fn to_window(&self) -> Window<Self>
    where
        Self: Clone,
    {
        self.clone().make_window()
    }
}

impl AsRef<WidgetId> for WidgetInstance {
    fn as_ref(&self) -> &WidgetId {
        &self.data.id
    }
}

impl Eq for WidgetInstance {}

impl PartialEq for WidgetInstance {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.data, &other.data)
    }
}

impl WindowBehavior for WidgetInstance {
    type Context = Self;

    fn initialize(
        _window: &mut RunningWindow<kludgine::app::Window<'_, WindowCommand>>,
        context: Self::Context,
    ) -> Self {
        context
    }

    fn make_root(&mut self) -> WidgetInstance {
        self.clone()
    }
}

/// A function that can be invoked with a parameter (`T`) and returns `R`.
///
/// This type is used by widgets to signal various events.
pub struct Callback<T = (), R = ()>(Box<dyn CallbackFunction<T, R>>);

impl<T, R> Debug for Callback<T, R> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("Callback")
            .field(&std::ptr::from_ref::<Self>(self))
            .finish()
    }
}

impl<T, R> Eq for Callback<T, R> {}

impl<T, R> PartialEq for Callback<T, R> {
    fn eq(&self, _other: &Self) -> bool {
        false
    }
}

impl<T, R> Callback<T, R> {
    /// Returns a new instance that calls `function` each time the callback is
    /// invoked.
    pub fn new<F>(function: F) -> Self
    where
        F: FnMut(T) -> R + Send + 'static,
    {
        Self(Box::new(function))
    }

    /// Invokes the wrapped function and returns the produced value.
    pub fn invoke(&mut self, value: T) -> R {
        self.0.invoke(value)
    }
}

trait CallbackFunction<T, R>: Send {
    fn invoke(&mut self, value: T) -> R;
}

impl<T, R, F> CallbackFunction<T, R> for F
where
    F: FnMut(T) -> R + Send,
{
    fn invoke(&mut self, value: T) -> R {
        self(value)
    }
}

/// A [`Callback`] that can be cloned.
///
/// Only one thread can be invoking a shared callback at any given time.
pub struct SharedCallback<T = (), R = ()>(Arc<Mutex<Callback<T, R>>>);

impl<T, R> SharedCallback<T, R> {
    /// Returns a new instance that calls `function` each time the callback is
    /// invoked.
    pub fn new<F>(function: F) -> Self
    where
        F: FnMut(T) -> R + Send + 'static,
    {
        Self::from(Callback::new(function))
    }

    /// Invokes the wrapped function and returns the produced value.
    pub fn invoke(&self, value: T) -> R {
        self.0.lock().invoke(value)
    }
}

impl<T, R> Debug for SharedCallback<T, R> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("SharedCallback")
            .field(&Arc::as_ptr(&self.0))
            .finish()
    }
}

impl<T, R> Eq for SharedCallback<T, R> {}

impl<T, R> PartialEq for SharedCallback<T, R> {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.0, &other.0)
    }
}

impl<T, R> Clone for SharedCallback<T, R> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<T, R> From<Callback<T, R>> for SharedCallback<T, R> {
    fn from(callback: Callback<T, R>) -> Self {
        Self(Arc::new(Mutex::new(callback)))
    }
}

/// A function that can be invoked once with a parameter (`T`) and returns `R`.
///
/// This type is used by widgets to signal an event that can happen only onceq.
pub struct OnceCallback<T = (), R = ()>(Box<dyn OnceCallbackFunction<T, R>>);

impl<T, R> Debug for OnceCallback<T, R> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("OnceCallback")
            .field(&std::ptr::from_ref::<Self>(self))
            .finish()
    }
}

impl<T, R> Eq for OnceCallback<T, R> {}

impl<T, R> PartialEq for OnceCallback<T, R> {
    fn eq(&self, _other: &Self) -> bool {
        false
    }
}

impl<T, R> OnceCallback<T, R> {
    /// Returns a new instance that calls `function` when the callback is
    /// invoked.
    pub fn new<F>(function: F) -> Self
    where
        F: FnOnce(T) -> R + Send + 'static,
    {
        Self(Box::new(Some(function)))
    }

    /// Invokes the wrapped function and returns the produced value.
    pub fn invoke(mut self, value: T) -> R {
        self.0.invoke(value)
    }
}

trait OnceCallbackFunction<T, R>: Send {
    fn invoke(&mut self, value: T) -> R;
}

impl<T, R, F> OnceCallbackFunction<T, R> for Option<F>
where
    F: FnOnce(T) -> R + Send,
{
    fn invoke(&mut self, value: T) -> R {
        (self.take().assert("invoked once"))(value)
    }
}

/// A [`Widget`] that has been attached to a widget hierarchy.
///
/// Because [`WidgetInstance`]s can be reused, a mounted widget can be unmounted
/// and eventually remounted. To ensure the widget is in a consistent state, all
/// types that own `MountedWidget`s should call
/// [`MountedWidget::remount_if_needed`] during their `mount()` functions.
#[derive(Clone)]
pub struct MountedWidget {
    pub(crate) node_id: LotId,
    pub(crate) widget: WidgetInstance,
    pub(crate) tree: WeakTree,
}

impl Debug for MountedWidget {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        Debug::fmt(&self.widget, f)
    }
}

impl MountedWidget {
    pub(crate) fn tree(&self) -> Tree {
        self.tree.upgrade().expect("tree missing")
    }

    /// Remounts this widget, if it was previously unmounted.
    pub fn remount_if_needed(&mut self, context: &mut EventContext<'_>) {
        if !self.is_mounted() {
            *self = context.push_child(self.widget.clone());
        }
    }

    /// Returns true if this widget is still mounted in a window.
    #[must_use]
    pub fn is_mounted(&self) -> bool {
        let Some(tree) = self.tree.upgrade() else {
            return false;
        };
        tree.widget_is_valid(self.node_id)
    }

    /// Locks the widget for exclusive access. Locking widgets should only be
    /// done for brief moments of time when you are certain no deadlocks can
    /// occur due to other widget locks being held.
    #[must_use]
    pub fn lock(&self) -> WidgetGuard<'_> {
        self.widget.lock()
    }

    /// Invalidates this widget.
    pub fn invalidate(&self) {
        let Some(tree) = self.tree.upgrade() else {
            return;
        };
        tree.invalidate(self.node_id, false);
    }

    pub(crate) fn set_layout(&self, rect: Rect<Px>) {
        self.tree().set_layout(self.node_id, rect);
    }

    /// Returns the unique id of this widget instance.
    #[must_use]
    pub fn id(&self) -> WidgetId {
        self.widget.id()
    }

    /// Returns the underlying widget instance
    #[must_use]
    pub const fn instance(&self) -> &WidgetInstance {
        &self.widget
    }

    /// Returns the next widget to focus after this widget.
    ///
    /// This function returns the value set in
    /// [`MakeWidget::with_next_focus()`].
    #[must_use]
    pub fn next_focus(&self) -> Option<MountedWidget> {
        self.widget
            .next_focus()
            .and_then(|next_focus| self.tree.upgrade()?.widget(next_focus))
    }

    /// Returns the widget to focus before this widget.
    ///
    /// There is no direct way to set this value. This relationship is created
    /// automatically using [`MakeWidget::with_next_focus()`].
    #[must_use]
    pub fn previous_focus(&self) -> Option<MountedWidget> {
        self.tree.upgrade()?.previous_focus(self.id())
    }

    /// Returns the next or previous focus target, if one was set using
    /// [`MakeWidget::with_next_focus()`].
    #[must_use]
    pub fn explicit_focus_target(&self, advance: bool) -> Option<MountedWidget> {
        if advance {
            self.next_focus()
        } else {
            self.previous_focus()
        }
    }

    /// Returns the region that the widget was last rendered at.
    #[must_use]
    pub fn last_layout(&self) -> Option<Rect<Px>> {
        self.tree.upgrade()?.layout(self.node_id)
    }

    /// Returns the effective styles for the current tree.
    #[must_use]
    pub fn effective_styles(&self) -> Styles {
        self.tree().effective_styles(self.node_id)
    }

    /// Returns true if this widget is the currently active widget.
    #[must_use]
    pub fn active(&self) -> bool {
        self.tree().active_widget() == Some(self.node_id)
    }

    pub(crate) fn enabled(&self, handle: &WindowHandle) -> bool {
        self.tree().is_enabled(self.node_id, handle)
    }

    /// Returns true if this widget is currently the hovered widget.
    #[must_use]
    pub fn hovered(&self) -> bool {
        self.tree().is_hovered(self.node_id)
    }

    /// Returns true if this widget that is directly beneath the cursor.
    #[must_use]
    pub fn primary_hover(&self) -> bool {
        self.tree().hovered_widget() == Some(self.node_id)
    }

    /// Returns true if this widget is the currently focused widget.
    #[must_use]
    pub fn focused(&self) -> bool {
        self.tree().focused_widget() == Some(self.node_id)
    }

    /// Returns the parent of this widget.
    #[must_use]
    pub fn parent(&self) -> Option<MountedWidget> {
        let tree = self.tree.upgrade()?;

        tree.parent(self.node_id)
            .and_then(|id| tree.widget_from_node(id))
    }

    /// Returns true if this node has a parent.
    #[must_use]
    pub fn has_parent(&self) -> bool {
        let Some(tree) = self.tree.upgrade() else {
            return false;
        };
        tree.parent(self.node_id).is_some()
    }

    pub(crate) fn attach_styles(&self, styles: Value<Styles>) {
        self.tree().attach_styles(self.node_id, styles);
    }

    pub(crate) fn attach_theme(&self, theme: Value<ThemePair>) {
        self.tree().attach_theme(self.node_id, theme);
    }

    pub(crate) fn attach_theme_mode(&self, theme: Value<ThemeMode>) {
        self.tree().attach_theme_mode(self.node_id, theme);
    }

    pub(crate) fn overridden_theme(
        &self,
    ) -> (Styles, Option<Value<ThemePair>>, Option<Value<ThemeMode>>) {
        self.tree().overridden_theme(self.node_id)
    }

    pub(crate) fn begin_layout(&self, constraints: Size<ConstraintLimit>) -> Option<Size<UPx>> {
        self.tree().begin_layout(self.node_id, constraints)
    }

    pub(crate) fn persist_layout(&self, constraints: Size<ConstraintLimit>, size: Size<UPx>) {
        self.tree().persist_layout(self.node_id, constraints, size);
    }

    pub(crate) fn visually_ordered_children(&self, order: VisualOrder) -> Vec<MountedWidget> {
        self.tree().visually_ordered_children(self.node_id, order)
    }
}

impl AsRef<WidgetId> for MountedWidget {
    fn as_ref(&self) -> &WidgetId {
        self.widget.as_ref()
    }
}

impl PartialEq for MountedWidget {
    fn eq(&self, other: &Self) -> bool {
        self.widget == other.widget
    }
}

impl PartialEq<WidgetInstance> for MountedWidget {
    fn eq(&self, other: &WidgetInstance) -> bool {
        &self.widget == other
    }
}

/// Exclusive access to a widget.
///
/// This type is powered by a `Mutex`, which means care must be taken to prevent
/// deadlocks.
pub struct WidgetGuard<'a>(MutexGuard<'a, dyn AnyWidget>);

impl WidgetGuard<'_> {
    pub(crate) fn as_widget(&mut self) -> &mut dyn AnyWidget {
        &mut *self.0
    }

    /// Returns a reference to `T` if it is the type contained.
    #[must_use]
    pub fn downcast_ref<T>(&self) -> Option<&T>
    where
        T: 'static,
    {
        self.0.as_any().downcast_ref()
    }

    /// Returns an exclusive reference to `T` if it is the type contained.
    #[must_use]
    pub fn downcast_mut<T>(&mut self) -> Option<&mut T>
    where
        T: 'static,
    {
        self.0.as_any_mut().downcast_mut()
    }
}

/// A list of [`Widget`]s without a layout strategy.
///
/// To use a `WidgetList` in a user interface, a choice must be made for how
/// each child should be positioned. The built-in widgets that can layout a
/// `WidgetList` are:
///
/// - As rows: [`Stack::rows`] / [`Self::into_rows`]
/// - As columns: [`Stack::columns`] / [`Self::into_columns`]
/// - Positioned on top of each other in the Z orientation: [`Layers::new`] /
///   [`Self::into_layers`]
/// - Layout horizontally, wrapping into multiple rows as needed: [`Wrap::new`]
///   / [`Self::into_wrap`].
#[derive(Default, Eq, PartialEq)]
#[must_use]
pub struct WidgetList {
    ordered: Vec<WidgetInstance>,
}

impl WidgetList {
    /// Returns an empty list.
    pub const fn new() -> Self {
        Self {
            ordered: Vec::new(),
        }
    }

    /// Returns a list with enough capacity to hold `capacity` widgets without
    /// reallocation.
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            ordered: Vec::with_capacity(capacity),
        }
    }

    /// Pushes `widget` into the list.
    pub fn push<W>(&mut self, widget: W)
    where
        W: MakeWidget,
    {
        self.ordered.push(widget.make_widget());
    }

    /// Inserts `widget` into the list at `index`.
    pub fn insert<W>(&mut self, index: usize, widget: W)
    where
        W: MakeWidget,
    {
        self.ordered.insert(index, widget.make_widget());
    }

    /// Removes the widget at `index`.
    ///
    /// # Panics
    ///
    /// This function will panic if `index` is out of the range of this
    /// collection.
    pub fn remove(&mut self, index: usize) -> WidgetInstance {
        self.ordered.remove(index)
    }

    /// Retains all widgets where `func` returns true.
    pub fn retain<F>(&mut self, func: F)
    where
        F: FnMut(&WidgetInstance) -> bool,
    {
        self.ordered.retain(func);
    }

    /// Extends this collection with the contents of `iter`.
    pub fn extend<T, Iter>(&mut self, iter: Iter)
    where
        Iter: IntoIterator<Item = T>,
        T: MakeWidget,
    {
        self.ordered.extend(iter.into_iter().map(T::make_widget));
    }

    /// Adds `widget` to self and returns the updated list.
    pub fn and<W>(mut self, widget: W) -> Self
    where
        W: MakeWidget,
    {
        self.push(widget);
        self
    }

    /// Chains `self` and `others` into a [`WidgetList`].
    pub fn chain<T, Iter>(mut self, iter: Iter) -> Self
    where
        Iter: IntoIterator<Item = T>,
        T: MakeWidget,
    {
        self.extend(iter);
        self
    }

    /// Returns the number of widgets in this list.
    #[must_use]
    pub fn len(&self) -> usize {
        self.ordered.len()
    }

    /// Returns true if there are no widgets in this list.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.ordered.is_empty()
    }

    /// Truncates the collection of children to `length`.
    ///
    /// If this collection is already smaller or the same size as `length`, this
    /// function does nothing.
    pub fn truncate(&mut self, length: usize) {
        self.ordered.truncate(length);
    }

    /// Clear the list
    pub fn clear(&mut self) {
        self.ordered.clear();
    }

    /// Returns `self` as a vertical [`Stack`] of rows.
    #[must_use]
    pub fn into_rows(self) -> Stack {
        Stack::rows(self)
    }

    /// Returns `self` as a horizontal [`Stack`] of columns.
    #[must_use]
    pub fn into_columns(self) -> Stack {
        Stack::columns(self)
    }

    /// Returns `self` as [`Layers`], with the widgets being stacked in the Z
    /// direction.
    #[must_use]
    pub fn into_layers(self) -> Layers {
        Layers::new(self)
    }

    /// Returns a [`Wrap`] that lays the children out horizontally, wrapping
    /// into additional rows as needed.
    #[must_use]
    pub fn into_wrap(self) -> Wrap {
        Wrap::new(self)
    }

    /// Returns `self` as an unordered [`List`].
    #[must_use]
    pub fn into_list(self) -> List {
        List::new(self)
    }

    /// Synchronizes this list of children with another collection.
    ///
    /// This function updates `collection` by calling `change_fn` for each
    /// operation that needs to be performed to synchronize. The algorithm first
    /// mounts/inserts all new children before sending a final change to
    /// `change_fn`: [`ChildrenSyncChange::Truncate`].
    pub fn synchronize_with<Collection>(
        &self,
        collection: &mut Collection,
        get_index: impl Fn(&Collection, usize) -> Option<&WidgetInstance>,
        mut change_fn: impl FnMut(&mut Collection, ChildrenSyncChange),
    ) {
        for (index, widget) in self.iter().enumerate() {
            if get_index(collection, index).map_or(true, |child| child != widget) {
                // These entries do not match. See if we can find the
                // new id somewhere else, if so we can swap the entries.
                if let Some(Some(swap_index)) = (index + 1..usize::MAX).find_map(|index| {
                    if let Some(child) = get_index(collection, index) {
                        if widget == child {
                            Some(Some(index))
                        } else {
                            None
                        }
                    } else {
                        Some(None)
                    }
                }) {
                    change_fn(collection, ChildrenSyncChange::Swap(index, swap_index));
                } else {
                    change_fn(
                        collection,
                        ChildrenSyncChange::Insert(index, widget.clone()),
                    );
                }
            }
        }

        change_fn(collection, ChildrenSyncChange::Truncate(self.len()));
    }
}

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

impl Dynamic<WidgetList> {
    /// Returns `self` as a vertical [`Stack`] of rows.
    #[must_use]
    pub fn into_rows(self) -> Stack {
        Stack::rows(self)
    }

    /// Returns `self` as a vertical [`Stack`] of rows.
    #[must_use]
    pub fn to_rows(&self) -> Stack {
        self.clone().into_rows()
    }

    /// Returns `self` as a horizontal [`Stack`] of columns.
    #[must_use]
    pub fn into_columns(self) -> Stack {
        Stack::columns(self)
    }

    /// Returns `self` as a horizontal [`Stack`] of columns.
    #[must_use]
    pub fn to_columns(&self) -> Stack {
        self.clone().into_columns()
    }

    /// Returns `self` as [`Layers`], with the widgets being stacked in the Z
    /// direction.
    #[must_use]
    pub fn into_layers(self) -> Layers {
        Layers::new(self)
    }

    /// Returns `self` as [`Layers`], with the widgets being stacked in the Z
    /// direction.
    #[must_use]
    pub fn to_layers(&self) -> Layers {
        self.clone().into_layers()
    }

    /// Returns `self` as an unordered [`List`].
    #[must_use]
    pub fn into_list(self) -> List {
        List::new(self)
    }

    /// Returns `self` as an unordered [`List`].
    #[must_use]
    pub fn to_list(self) -> List {
        self.clone().into_list()
    }

    /// Returns a [`Wrap`] that lays the children out horizontally, wrapping
    /// into additional rows as needed.
    #[must_use]
    pub fn into_wrap(self) -> Wrap {
        Wrap::new(self)
    }

    /// Returns a [`Wrap`] that lays the children out horizontally, wrapping
    /// into additional rows as needed.
    #[must_use]
    pub fn to_wrap(&self) -> Wrap {
        self.clone().into_wrap()
    }
}

impl FromIterator<WidgetList> for WidgetList {
    fn from_iter<T: IntoIterator<Item = WidgetList>>(iter: T) -> Self {
        let mut iter = iter.into_iter();
        let Some(mut dest) = iter.next() else {
            return Self::new();
        };
        for other in iter {
            dest.extend(other);
        }
        dest
    }
}

impl<W> FromIterator<W> for WidgetList
where
    W: MakeWidget,
{
    fn from_iter<T: IntoIterator<Item = W>>(iter: T) -> Self {
        Self {
            ordered: iter.into_iter().map(MakeWidget::make_widget).collect(),
        }
    }
}

impl Deref for WidgetList {
    type Target = [WidgetInstance];

    fn deref(&self) -> &Self::Target {
        &self.ordered
    }
}

impl DerefMut for WidgetList {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.ordered
    }
}

impl IntoIterator for WidgetList {
    type IntoIter = std::vec::IntoIter<WidgetInstance>;
    type Item = WidgetInstance;

    fn into_iter(self) -> Self::IntoIter {
        self.ordered.into_iter()
    }
}

impl<'a> IntoIterator for &'a WidgetList {
    type IntoIter = slice::Iter<'a, WidgetInstance>;
    type Item = &'a WidgetInstance;

    fn into_iter(self) -> Self::IntoIter {
        self.ordered.iter()
    }
}

impl<I: IntoIterator> MakeWidgetList for I
where
    I::Item: MakeWidget,
{
    fn make_widget_list(self) -> WidgetList {
        self.into_iter().collect()
    }
}

/// Allows to convert collections or iterators directly into [`Stack`], [`Layers`], etc.
///
/// ```
/// use cushy::widget::{MakeWidget, MakeWidgetList};
///
/// vec!["hello", "label"].into_rows();
///
/// vec!["hello", "button"]
///     .into_iter()
///     .map(|l| l.into_button())
///     .into_columns();
/// ```
pub trait MakeWidgetList: Sized {
    /// Returns self as a `WidgetList`.
    fn make_widget_list(self) -> WidgetList;

    /// Adds `widget` to self and returns the updated list.
    fn and<W>(self, widget: W) -> WidgetList
    where
        W: MakeWidget,
    {
        let mut list = self.make_widget_list();
        list.push(widget);
        list
    }
}

/// A type that can be converted to a `Value<WidgetList>`.
pub trait IntoWidgetList: Sized {
    /// Returns this list of widgets as a `Value<WidgetList>`.
    fn into_widget_list(self) -> Value<WidgetList>;

    /// Returns `self` as a vertical [`Stack`] of rows.
    #[must_use]
    fn into_rows(self) -> Stack {
        Stack::rows(self.into_widget_list())
    }

    /// Returns `self` as a horizontal [`Stack`] of columns.
    #[must_use]
    fn into_columns(self) -> Stack {
        Stack::columns(self.into_widget_list())
    }

    /// Returns `self` as [`Layers`], with the widgets being stacked in the Z
    /// direction.
    #[must_use]
    fn into_layers(self) -> Layers {
        Layers::new(self.into_widget_list())
    }

    /// Returns a [`Wrap`] that lays the children out horizontally, wrapping
    /// into additional rows as needed.
    #[must_use]
    fn into_wrap(self) -> Wrap {
        Wrap::new(self.into_widget_list())
    }

    /// Returns `self` as an unordered [`List`].
    #[must_use]
    fn into_list(self) -> List {
        List::new(self.into_widget_list())
    }
}

impl<T> IntoWidgetList for T
where
    T: MakeWidgetList,
{
    fn into_widget_list(self) -> Value<WidgetList> {
        Value::Constant(self.make_widget_list())
    }
}

impl IntoWidgetList for Dynamic<WidgetList> {
    fn into_widget_list(self) -> Value<WidgetList> {
        Value::Dynamic(self)
    }
}

impl IntoWidgetList for Value<WidgetList> {
    fn into_widget_list(self) -> Value<WidgetList> {
        self
    }
}

/// A change to perform during [`WidgetList::synchronize_with`].
pub enum ChildrenSyncChange {
    /// Insert a new widget at the given index.
    Insert(usize, WidgetInstance),
    /// Swap the widgets at the given indices.
    Swap(usize, usize),
    /// Truncate the collection to the length given.
    Truncate(usize),
}

/// A collection of mounted children.
///
/// This collection is a helper aimed at making it easier to build widgets that
/// contain multiple children widgets. It is used in conjunction with a
/// `Value<WidgetList>`.
#[derive(Debug)]
pub struct MountedChildren<T = MountedWidget> {
    generation: Option<Generation>,
    children: Vec<T>,
}

impl<T> MountedChildren<T>
where
    T: MountableChild,
{
    /// Mounts and unmounts all children needed to be in sync with `children`.
    pub fn synchronize_with(
        &mut self,
        children: &Value<WidgetList>,
        context: &mut EventContext<'_>,
    ) {
        let current_generation = children.generation();
        if current_generation.map_or_else(
            || children.map(WidgetList::len) != self.children.len(),
            |gen| Some(gen) != self.generation,
        ) {
            self.generation = current_generation;
            children.map(|children| {
                children.synchronize_with(
                    self,
                    |this, index| {
                        this.children
                            .get(index)
                            .map(|mounted| mounted.widget().instance())
                    },
                    |this, change| match change {
                        ChildrenSyncChange::Insert(index, widget) => {
                            this.children
                                .insert(index, T::mount(context.push_child(widget), this, index));
                        }
                        ChildrenSyncChange::Swap(a, b) => {
                            this.children.swap(a, b);
                        }
                        ChildrenSyncChange::Truncate(length) => {
                            for removed in this.children.drain(length..) {
                                context.remove_child(&removed.unmount());
                            }
                        }
                    },
                );
            });
        }
    }

    /// Returns an iterator that contains every widget in this collection.
    ///
    /// When the iterator is dropped, this collection will be empty.
    pub fn drain(&mut self) -> vec::Drain<'_, T> {
        self.generation = None;
        self.children.drain(..)
    }

    /// Returns a reference to the children.
    #[must_use]
    pub fn children(&self) -> &[T] {
        &self.children
    }
}

impl<T> Default for MountedChildren<T> {
    fn default() -> Self {
        Self {
            generation: None,
            children: Vec::default(),
        }
    }
}

/// A child in a [`MountedChildren`] collection.
pub trait MountableChild: Sized {
    /// Returns the mounted representation of `widget`.
    fn mount(widget: MountedWidget, into: &MountedChildren<Self>, index: usize) -> Self;
    /// Returns the widget and performs any other cleanup for this widget being unmounted.q
    fn unmount(self) -> MountedWidget;
    /// Returns a reference to the widget.
    fn widget(&self) -> &MountedWidget;
}

impl MountableChild for MountedWidget {
    fn mount(widget: MountedWidget, _into: &MountedChildren<Self>, _index: usize) -> Self {
        widget
    }

    fn widget(&self) -> &MountedWidget {
        self
    }

    fn unmount(self) -> MountedWidget {
        self
    }
}

/// A child widget
#[derive(Clone)]
pub struct WidgetRef {
    instance: WidgetInstance,
    mounted: WindowLocal<MountedWidget>,
}

impl WidgetRef {
    /// Returns a new unmounted child
    pub fn new(widget: impl MakeWidget) -> Self {
        Self {
            instance: widget.make_widget(),
            mounted: WindowLocal::default(),
        }
    }

    /// Returns this child, mounting it in the process if necessary.
    fn mounted_for_context(&mut self, context: &mut impl AsEventContext) -> &MountedWidget {
        let mut context = context.as_event_context();
        self.mounted
            .entry(&context)
            .and_modify(|w| {
                w.remount_if_needed(&mut context.as_event_context());
            })
            .or_insert_with(|| context.push_child(self.instance.clone()))
    }

    /// Returns this child, mounting it in the process if necessary.
    pub fn mount_if_needed(&mut self, context: &mut impl AsEventContext) {
        self.mounted_for_context(context);
    }

    /// Returns this child, mounting it in the process if necessary.
    pub fn mounted(&mut self, context: &mut impl AsEventContext) -> MountedWidget {
        self.mounted_for_context(context).clone()
    }

    /// Returns this child, if it has been mounted.
    #[must_use]
    pub fn as_mounted(&self, context: &WidgetContext<'_>) -> Option<&MountedWidget> {
        self.mounted.get(context)
    }

    /// Returns the a reference to the underlying widget instance.
    #[must_use]
    pub const fn widget(&self) -> &WidgetInstance {
        &self.instance
    }

    /// Unmounts this widget from the window belonging to `context`, if needed.
    pub fn unmount_in(&mut self, context: &mut impl AsEventContext) {
        let mut context = context.as_event_context();
        if let Some(mounted) = self.mounted.clear_for(&context) {
            context.remove_child(&mounted);
        }
    }
}

impl From<WidgetRef> for WindowLocal<MountedWidget> {
    fn from(value: WidgetRef) -> Self {
        value.mounted
    }
}

impl From<WidgetInstance> for WidgetRef {
    fn from(value: WidgetInstance) -> Self {
        Self::new(value)
    }
}

impl AsRef<WidgetId> for WidgetRef {
    fn as_ref(&self) -> &WidgetId {
        self.instance.as_ref()
    }
}

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

impl Eq for WidgetRef {}

impl PartialEq for WidgetRef {
    fn eq(&self, other: &Self) -> bool {
        self.instance == other.instance
    }
}

impl ManageWidget for WidgetRef {
    type Managed = Option<MountedWidget>;

    fn manage(&self, context: &WidgetContext<'_>) -> Self::Managed {
        self.mounted
            .get(context)
            .cloned()
            .or_else(|| context.tree.widget(self.instance.id()))
    }
}

/// The unique id of a [`WidgetInstance`].
///
/// Each [`WidgetInstance`] is guaranteed to have a unique [`WidgetId`] across
/// the lifetime of an application.
#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash, Ord, PartialOrd)]
pub struct WidgetId(u64);

impl WidgetId {
    fn unique() -> Self {
        static COUNTER: AtomicU64 = AtomicU64::new(0);
        Self(COUNTER.fetch_add(1, atomic::Ordering::Acquire))
    }

    /// Finds this widget mounted in this window, if present.
    #[must_use]
    pub fn find_in(self, context: &WidgetContext<'_>) -> Option<MountedWidget> {
        context.tree.widget(self)
    }
}

/// A [`WidgetId`] that has not been assigned to a [`WidgetInstance`].
///
/// This type is passed to [`MakeWidgetWithTag::make_with_tag()`] to create a
/// [`WidgetInstance`] with a preallocated id.
///
/// This type cannot be cloned or copied to ensure only a single widget can be
/// assigned a given [`WidgetId`]. The contained [`WidgetId`] can be accessed
/// via [`id()`](Self::id), `Into<WidgetId>`, or `Deref`.
#[derive(Eq, PartialEq, Debug)]
pub struct WidgetTag(WidgetId);

impl WidgetTag {
    /// Returns a unique tag and its contained id.
    #[must_use]
    pub fn new() -> (Self, WidgetId) {
        let tag = Self::unique();
        let id = *tag;
        (tag, id)
    }

    /// Returns a newly allocated [`WidgetId`] that is guaranteed to be unique
    /// for the lifetime of the application.
    #[must_use]
    pub fn unique() -> Self {
        Self(WidgetId::unique())
    }

    /// Returns the contained widget id.
    #[must_use]
    pub const fn id(&self) -> WidgetId {
        self.0
    }
}

impl From<WidgetTag> for WidgetId {
    fn from(value: WidgetTag) -> Self {
        value.0
    }
}

impl Deref for WidgetTag {
    type Target = WidgetId;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}