masonry_core 0.5.0

Traits and types of the Masonry toolkit.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
// Copyright 2020 the Xilem Authors and the Druid Authors
// SPDX-License-Identifier: Apache-2.0

//! The context types that are passed into various widget methods.

#![expect(
    missing_debug_implementations,
    reason = "Not sure if it's worth the effort"
)]

use std::any::{Any, TypeId};
use std::collections::hash_map::Entry;

use accesskit::{NodeId, TreeUpdate};
use anymore::AnyDebug;
use dpi::{LogicalPosition, PhysicalPosition};
use parley::{FontContext, LayoutContext};
use tracing::{trace, warn};
use tree_arena::{ArenaMut, ArenaMutList, ArenaRefList};

use crate::app::{MutateCallback, RenderRootSignal, RenderRootState};
use crate::core::{
    AllowRawMut, BrushIndex, ClassSet, ErasedAction, FromDynWidget, NewWidget, PropertiesMut,
    PropertiesRef, PropertyArena, PropertyCache, PropertyStackId, ResizeDirection, SubwindowId,
    SubwindowType, TimerKey, Widget, WidgetArenaNode, WidgetId, WidgetMut, WidgetPod, WidgetRef,
    WidgetState,
};
use crate::kurbo::{Affine, Axis, Insets, Point, Rect, Size, Vec2};
use crate::layout::{LayoutSize, LenDef, Length, SizeDef};
use crate::passes::layout::{place_widget, resolve_length, resolve_size, run_layout_on};
use crate::peniko::Color;
use crate::util::{Duration, Instant, ParentLinkedList, get_debug_color};

// Note - Most methods defined in this file revolve around `WidgetState` fields.
// Consider reading `WidgetState` documentation (especially the documented naming scheme)
// before editing context method code.

/// A macro for implementing methods on multiple contexts.
///
/// There are a lot of methods defined on multiple contexts; this lets us only
/// have to write them out once.
macro_rules! impl_context_method {
    ($ty:ty,  { $($method:item)+ } ) => {
        impl $ty { $($method)+ }
    };
    ( $ty:ty, $($more:ty),+, { $($method:item)+ } ) => {
        impl_context_method!($ty, { $($method)+ });
        impl_context_method!($($more),+, { $($method)+ });
    };
}

/// A context provided inside of [`WidgetMut`].
///
/// When you declare a mutable reference type for your widget, methods of this type
/// will have access to a `MutateCtx`. If that method mutates the widget in a way that
/// requires a later pass (for instance, if your widget has a `set_color` method),
/// you will need to signal that change in the pass (eg [`request_render`](MutateCtx::request_render)).
pub struct MutateCtx<'a> {
    pub(crate) global_state: &'a mut RenderRootState,
    pub(crate) parent_widget_state: Option<&'a mut WidgetState>,
    pub(crate) widget_state: &'a mut WidgetState,
    pub(crate) properties: PropertiesMut<'a>,
    pub(crate) children: ArenaMutList<'a, WidgetArenaNode>,
    pub(crate) property_arena: &'a PropertyArena,
}

/// A context provided to the [`Widget::on_action`] method.
pub struct ActionCtx<'a> {
    pub(crate) global_state: &'a mut RenderRootState,
    pub(crate) widget_state: &'a mut WidgetState,
    pub(crate) children: ArenaMutList<'a, WidgetArenaNode>,
    pub(crate) property_arena: &'a PropertyArena,
    pub(crate) is_handled: bool,
}

/// A context provided inside of [`WidgetRef`].
///
/// This context is passed to methods of widgets requiring shared, read-only access.
#[derive(Clone, Copy)]
pub struct QueryCtx<'a> {
    pub(crate) global_state: &'a RenderRootState,
    pub(crate) widget_state: &'a WidgetState,
    pub(crate) properties: PropertiesRef<'a>,
    pub(crate) children: ArenaRefList<'a, WidgetArenaNode>,
    pub(crate) property_arena: &'a PropertyArena,
}

/// A context given when calling another context's `get_raw_mut()` method.
pub struct RawCtx<'a> {
    pub(crate) global_state: &'a mut RenderRootState,
    pub(crate) parent_widget_state: &'a mut WidgetState,
    pub(crate) widget_state: &'a mut WidgetState,
    pub(crate) children: ArenaMutList<'a, WidgetArenaNode>,
    pub(crate) property_arena: &'a PropertyArena,
}

/// A context provided to event-handling [`Widget`] methods.
pub struct EventCtx<'a> {
    pub(crate) global_state: &'a mut RenderRootState,
    pub(crate) widget_state: &'a mut WidgetState,
    pub(crate) children: ArenaMutList<'a, WidgetArenaNode>,
    pub(crate) property_arena: &'a PropertyArena,
    pub(crate) target: WidgetId,
    pub(crate) allow_pointer_capture: bool,
    pub(crate) is_handled: bool,
}

/// A context provided to the [`Widget::register_children`] method.
pub struct RegisterCtx<'a> {
    pub(crate) global_state: &'a mut RenderRootState,
    pub(crate) children: ArenaMutList<'a, WidgetArenaNode>,
    #[cfg(debug_assertions)]
    pub(crate) registered_ids: Vec<WidgetId>,
}

/// A context provided to the [`Widget::update`] method.
pub struct UpdateCtx<'a> {
    pub(crate) global_state: &'a mut RenderRootState,
    pub(crate) widget_state: &'a mut WidgetState,
    pub(crate) children: ArenaMutList<'a, WidgetArenaNode>,
    pub(crate) ancestors: Option<&'a ParentLinkedList<'a>>,
    pub(crate) property_arena: &'a PropertyArena,
}

/// A context provided to [`Widget::measure`] methods.
pub struct MeasureCtx<'a> {
    pub(crate) global_state: &'a mut RenderRootState,
    pub(crate) widget_state: &'a mut WidgetState,
    pub(crate) children: ArenaMutList<'a, WidgetArenaNode>,
    pub(crate) property_arena: &'a PropertyArena,
    pub(crate) auto_length: LenDef,
    pub(crate) context_size: LayoutSize,
    pub(crate) cache_result: bool,
}

/// A context provided to [`Widget::layout`] methods.
pub struct LayoutCtx<'a> {
    pub(crate) global_state: &'a mut RenderRootState,
    pub(crate) widget_state: &'a mut WidgetState,
    pub(crate) children: ArenaMutList<'a, WidgetArenaNode>,
    pub(crate) property_arena: &'a PropertyArena,
}

/// A context provided to the [`Widget::compose`] method.
pub struct ComposeCtx<'a> {
    pub(crate) global_state: &'a mut RenderRootState,
    pub(crate) widget_state: &'a mut WidgetState,
    pub(crate) children: ArenaMutList<'a, WidgetArenaNode>,
    pub(crate) property_arena: &'a PropertyArena,
}

/// A context passed to [`Widget::paint`] method.
pub struct PaintCtx<'a> {
    pub(crate) global_state: &'a mut RenderRootState,
    pub(crate) widget_state: &'a mut WidgetState,
    pub(crate) children: ArenaMutList<'a, WidgetArenaNode>,
}

/// A context passed to [`Widget::accessibility`] method.
pub struct AccessCtx<'a> {
    pub(crate) global_state: &'a mut RenderRootState,
    pub(crate) widget_state: &'a mut WidgetState,
    pub(crate) children: ArenaMutList<'a, WidgetArenaNode>,
    pub(crate) tree_update: &'a mut TreeUpdate,
}

// --- MARK: GETTERS
// Methods for all context types
impl_context_method!(
    MutateCtx<'_>,
    ActionCtx<'_>,
    QueryCtx<'_>,
    EventCtx<'_>,
    UpdateCtx<'_>,
    MeasureCtx<'_>,
    LayoutCtx<'_>,
    ComposeCtx<'_>,
    PaintCtx<'_>,
    AccessCtx<'_>,
    RawCtx<'_>,
    {
        /// The `WidgetId` of the current widget.
        pub fn widget_id(&self) -> WidgetId {
            self.widget_state.id
        }

        /// The `SubwindowId` of the current subwindow.
        ///
        /// Returns `None` if this widget isn't the root of a subwindow.
        pub fn subwindow_id(&self) -> Option<SubwindowId> {
            self.widget_state.subwindow_id
        }

        #[allow(dead_code, reason = "Copy-pasted for some types that don't need it")]
        /// Helper method to get a direct reference to a child widget from its `WidgetPod`.
        fn get_child<Child: Widget>(&self, child: &'_ WidgetPod<Child>) -> &'_ Child {
            let child_ref = &*self
                .children
                .item(child.id())
                .expect("get_child: child not found")
                .item
                .widget;
            (child_ref as &dyn Any).downcast_ref::<Child>().unwrap()
        }

        #[allow(dead_code, reason = "Copy-pasted for some types that don't need it")]
        /// Helper method to get a direct reference to a child widget from its `WidgetPod`.
        fn get_child_dyn(&self, child: &'_ WidgetPod<impl Widget + ?Sized>) -> &'_ dyn Widget {
            &*self
                .children
                .item(child.id())
                .expect("get_child: child not found")
                .item
                .widget
        }

        #[allow(dead_code, reason = "Copy-pasted for some types that don't need it")]
        /// Helper method to get a direct reference to a child widget's `WidgetState` from its `WidgetPod`.
        fn get_child_state(&self, child: &'_ WidgetPod<impl Widget + ?Sized>) -> &'_ WidgetState {
            &self
                .children
                .item(child.id())
                .expect("get_child_state: child not found")
                .item
                .state
        }

        #[allow(dead_code, reason = "Copy-pasted for some types that don't need it")]
        /// Returns the local transform of this widget.
        ///
        /// This transform is used during the mapping of this widget's border-box coordinate space
        /// to the parent's border-box coordinate space.
        ///
        /// This transform is applied before `scroll_translation` and `origin`.
        pub fn transform(&self) -> Affine {
            self.widget_state.transform
        }
    }
);

// TODO - Merge into other block?
impl_context_method!(
    MutateCtx<'_>,
    ActionCtx<'_>,
    EventCtx<'_>,
    UpdateCtx<'_>,
    MeasureCtx<'_>,
    LayoutCtx<'_>,
    ComposeCtx<'_>,
    PaintCtx<'_>,
    AccessCtx<'_>,
    RawCtx<'_>,
    {
        /// Returns a mutable reference to this widget's property cache.
        pub fn property_cache(&mut self) -> &mut PropertyCache {
            &mut self.widget_state.property_cache
        }
    }
);

impl QueryCtx<'_> {
    /// Returns a reference to this widget's property cache.
    pub fn property_cache(&self) -> &PropertyCache {
        &self.widget_state.property_cache
    }
}

impl_context_method!(
    MutateCtx<'_>,
    ActionCtx<'_>,
    EventCtx<'_>,
    UpdateCtx<'_>,
    MeasureCtx<'_>,
    LayoutCtx<'_>,
    ComposeCtx<'_>,
    RawCtx<'_>,
    {
        /// Helper method to get a mutable reference to a child widget's `WidgetState` from its `WidgetPod`.
        ///
        /// This one isn't defined for `PaintCtx` and `AccessCtx` because those contexts
        /// can't mutate `WidgetState`.
        #[track_caller]
        fn get_child_state_mut<Child: Widget + ?Sized>(
            &mut self,
            child: &'_ mut WidgetPod<Child>,
        ) -> &'_ mut WidgetState {
            &mut self
                .children
                .item_mut(child.id())
                .expect("get_child_state_mut: child not found")
                .item
                .state
        }
    }
);

// --- MARK: WIDGET_MUT
// Methods to get a child WidgetMut from a parent.
impl MutateCtx<'_> {
    /// Returns a [`WidgetMut`] to a child widget.
    pub fn get_mut<'c, Child: Widget + FromDynWidget + ?Sized>(
        &'c mut self,
        child: &'c mut WidgetPod<Child>,
    ) -> WidgetMut<'c, Child> {
        let node_mut = self
            .children
            .item_mut(child.id())
            .expect("get_mut: child not found");
        let child_stack_id = node_mut.item.state.property_stack_id;
        let child_type_id = (*node_mut.item.widget).type_id();
        let child_stack = self.property_arena.get(child_stack_id, child_type_id);
        let child_ctx = MutateCtx {
            global_state: self.global_state,
            parent_widget_state: Some(&mut self.widget_state),
            widget_state: &mut node_mut.item.state,
            properties: PropertiesMut {
                local: &mut node_mut.item.properties,
                default_map: self.properties.default_map,
                stack: child_stack,
                class_set: &node_mut.item.class_set,
            },
            children: node_mut.children,
            property_arena: self.property_arena,
        };
        WidgetMut {
            ctx: child_ctx,
            widget: Child::from_dyn_mut(&mut *node_mut.item.widget).unwrap(),
        }
    }

    pub(crate) fn reborrow_mut(&mut self) -> MutateCtx<'_> {
        MutateCtx {
            global_state: self.global_state,
            // We don't don't reborrow `parent_widget_state`. This avoids running
            // `merge_up` in `WidgetMut::Drop` multiple times for the same state.
            // It will still be called when the original borrow is dropped.
            parent_widget_state: None,
            widget_state: self.widget_state,
            properties: PropertiesMut {
                local: &mut *self.properties.local,
                default_map: self.properties.default_map,
                stack: self.properties.stack,
                class_set: self.properties.class_set,
            },
            children: self.children.reborrow_mut(),
            property_arena: self.property_arena,
        }
    }

    pub(crate) fn update_mut(&mut self) -> UpdateCtx<'_> {
        UpdateCtx {
            global_state: self.global_state,
            widget_state: self.widget_state,
            children: self.children.reborrow_mut(),
            ancestors: None,
            property_arena: self.property_arena,
        }
    }

    /// Sets which property stack this widget uses for property resolution.
    pub fn set_property_stack(&mut self, stack_id: PropertyStackId) {
        self.widget_state.request_update_props = true;
        self.widget_state.needs_update_props = true;
        self.widget_state.property_cache.invalidated = true;
        self.widget_state.property_stack_id = Some(stack_id);
    }
}

// --- MARK: WIDGET_REF
// Methods to get a child WidgetRef from a parent.
impl<'w> QueryCtx<'w> {
    /// Returns a [`WidgetRef`] to a child widget.
    pub fn get(self, child: WidgetId) -> WidgetRef<'w, dyn Widget> {
        let child_node = self.children.item(child).expect("get_mut: child not found");
        let child_type_id = (*child_node.item.widget).type_id();
        let child_stack = self
            .property_arena
            .get(child_node.item.state.property_stack_id, child_type_id);
        let child_ctx = QueryCtx {
            global_state: self.global_state,
            widget_state: &child_node.item.state,
            properties: PropertiesRef {
                local: &child_node.item.properties,
                default_map: self.properties.default_map,
                stack: child_stack,
                class_set: &child_node.item.class_set,
            },
            children: child_node.children,
            property_arena: self.property_arena,
        };
        WidgetRef {
            ctx: child_ctx,
            widget: &*child_node.item.widget,
        }
    }
}

// Methods for all exclusive context types (i.e. those which have exclusive access to the global state).
impl_context_method!(
    MutateCtx<'_>,
    ActionCtx<'_>,
    EventCtx<'_>,
    UpdateCtx<'_>,
    MeasureCtx<'_>,
    LayoutCtx<'_>,
    ComposeCtx<'_>,
    PaintCtx<'_>,
    AccessCtx<'_>,
    RawCtx<'_>,
    {
        /// Returns the Parley contexts needed to build and paint text sections.
        ///
        /// Most users should embed a pre-built label widget
        /// (such as `masonry::widgets::Label`)
        /// as a child for non-interactive text.
        /// These contexts could however be useful for custom text editing, such as for rich text editing.
        ///
        /// Any cached text layouts should be invalidated when receiving [`Update::FontsChanged`].
        ///
        /// [`Update::FontsChanged`]: crate::core::Update::FontsChanged
        pub fn text_contexts(&mut self) -> (&mut FontContext, &mut LayoutContext<BrushIndex>) {
            (
                &mut self.global_state.font_context,
                &mut self.global_state.text_layout_context,
            )
        }
    }
);

impl_context_method!(
    MutateCtx<'_>,
    ActionCtx<'_>,
    EventCtx<'_>,
    UpdateCtx<'_>,
    RawCtx<'_>,
    {
        /// Returns the current monotonic time from the clock used for widget timers.
        pub fn now(&self) -> Instant {
            self.global_state.now()
        }

        /// Sets a one-shot timer for this widget, replacing any pending timer with the same key.
        ///
        /// On expiry the widget receives [`Update::TimerFired`] with the key.
        /// Removing the widget cancels its timers.
        ///
        /// [`Update::TimerFired`]: crate::core::Update::TimerFired
        pub fn set_timer(&mut self, key: TimerKey, delay: Duration) {
            self.global_state.set_timer(self.widget_id(), key, delay);
        }

        /// Cancels the timer with this key for the current widget.
        ///
        /// Cancellation is effective until delivery begins. If the widget has
        /// no pending timer with this key, this has no effect.
        pub fn cancel_timer(&mut self, key: TimerKey) {
            self.global_state.cancel_timer(self.widget_id(), key);
        }

        /// Returns whether the current widget has a pending timer with this key.
        pub fn has_timer(&self, key: TimerKey) -> bool {
            self.global_state.timer_id(self.widget_id(), key).is_some()
        }
    }
);

// --- MARK: EVENT HANDLING
impl EventCtx<'_> {
    /// Captures the pointer in the current widget.
    ///
    /// [Pointer capture] is only allowed during a [`Down`] event. It is a logic error to
    /// capture the pointer during any other event.
    ///
    /// A widget normally only receives pointer events when the pointer is inside the widget's
    /// border-box. Pointer capture causes border-box hit checks to be ignored: when the pointer is
    /// captured by a widget, that widget will continue receiving pointer events when the pointer
    /// is outside the widget's border-box. Other widgets the pointer is over will not receive
    /// events. Events that are not marked as handled by the capturing widget, bubble up to the
    /// widget's ancestors, ignoring their border-boxes as well.
    ///
    /// The pointer cannot be captured by multiple widgets at the same time. If a widget has
    /// captured the pointer and another widget captures it, the first widget loses the pointer
    /// capture.
    ///
    /// # Releasing the pointer
    ///
    /// Any widget can [`release`] the pointer during any event.
    /// The pointer is automatically released after handling of a [`Up`] or [`Cancel`] event completes.
    /// A widget holding the pointer capture will be the target of these events.
    ///
    /// If pointer capture is lost for external reasons (the widget is disabled, the window lost focus,
    /// etc), the widget will still get a [`Cancel`] event.
    ///
    /// [Pointer capture]: crate::doc::masonry_concepts#pointer-capture
    /// [`Down`]: ui_events::pointer::PointerEvent::Down
    /// [`Up`]: ui_events::pointer::PointerEvent::Up
    /// [`Cancel`]: ui_events::pointer::PointerEvent::Cancel
    /// [`release`]: Self::release_pointer
    #[track_caller]
    pub fn capture_pointer(&mut self) {
        let id = self.widget_id();
        if !self.allow_pointer_capture {
            debug_panic!("capture_pointer - '{id}': event does not allow pointer capture");
            return;
        }
        // TODO: plumb pointer capture through to platform (through winit)
        self.global_state.pointer_capture_target = Some(id);
        self.global_state.needs_pointer_pass = true;
    }

    /// Releases the pointer previously [captured] through [`capture_pointer`].
    ///
    /// [captured]: crate::doc::masonry_concepts#pointer-capture
    /// [`capture_pointer`]: EventCtx::capture_pointer
    pub fn release_pointer(&mut self) {
        let id = self.widget_id();
        if self.global_state.pointer_capture_target.is_none() {
            warn!("release_pointer - '{id}': no widget is captured");
            return;
        }
        if self.global_state.pointer_capture_target != Some(self.widget_state.id) {
            warn!("release_pointer - '{id}': widget does not have pointer capture");
            return;
        }
        self.global_state.pointer_capture_target = None;
        self.global_state.needs_pointer_pass = true;
    }

    /// The widget originally targeted by the event.
    ///
    /// This will be different from [`widget_id`](Self::widget_id) during event bubbling.
    pub fn target(&self) -> WidgetId {
        self.target
    }

    /// Converts the given position from the window's coordinate space
    /// to this widget's content-box coordinate space.
    pub fn local_position(&self, p: PhysicalPosition<f64>) -> Point {
        let LogicalPosition { x, y } = p.to_logical(self.global_state.scale_factor);
        self.to_local(Point { x, y })
    }
}

// Methods shared by event and action handling.
impl_context_method!(ActionCtx<'_>, EventCtx<'_>, {
    /// Sends a signal to parent widgets to scroll this widget's border-box into view.
    pub fn request_scroll_to_this(&mut self) {
        let rect = self.widget_state.border_box();
        self.global_state
            .scroll_request_targets
            .push((self.widget_state.id, rect));
    }

    /// Sends a signal to parent widgets to scroll the provided `rect` into view.
    ///
    /// The `rect` must be in this widget's content-box coordinate space.
    pub fn request_scroll_to(&mut self, rect: Rect) {
        // Convert from this widget's content-box space to border-box space.
        let rect = rect + self.widget_state.border_box_translation();
        self.global_state
            .scroll_request_targets
            .push((self.widget_state.id, rect));
    }

    /// Sets the event as "handled", which stops its propagation to parent
    /// widgets.
    pub fn set_handled(&mut self) {
        trace!("set_handled");
        self.is_handled = true;
    }

    /// Determines whether the event has been handled.
    pub fn is_handled(&self) -> bool {
        self.is_handled
    }

    /// Requests [text focus].
    ///
    /// Because only one widget can be focused at a time, multiple focus requests
    /// from different widgets during a single event cycle means that the last
    /// widget that requests focus will override the previous requests.
    ///
    /// [text focus]: crate::doc::masonry_concepts#text-focus
    pub fn request_focus(&mut self) {
        trace!("request_focus");
        // We need to send the request even if we're currently focused,
        // because we may have a sibling widget that already requested focus
        // and we have no way of knowing that yet. We need to override that
        // to deliver on the "last focus request wins" promise.
        let id = self.widget_id();
        self.global_state.next_focused_widget = Some(id);
    }

    /// Transfers [text focus] to the widget with the given `WidgetId`.
    ///
    /// [text focus]: crate::doc::masonry_concepts#text-focus
    pub fn set_focus(&mut self, target: WidgetId) {
        trace!("set_focus target={:?}", target);
        self.global_state.next_focused_widget = Some(target);
    }

    /// Gives up [text focus].
    ///
    /// This should only be called by a widget that currently has focus.
    ///
    /// [text focus]: crate::doc::masonry_concepts#text-focus
    pub fn resign_focus(&mut self) {
        trace!("resign_focus");
        if self.has_focus_target() {
            self.global_state.next_focused_widget = None;
        } else {
            warn!(
                "resign_focus can only be called by the currently focused widget {} \
                 or one of its ancestors.",
                self.widget_id()
            );
        }
    }
});

// --- MARK: ACCESSIBILITY
impl AccessCtx<'_> {
    // TODO - We need access to the TreeUpdate to create sub-nodes for text runs,
    // but this seems too powerful. We should figure out another API.
    /// A mutable reference to the global [`TreeUpdate`] object in which all modified/new
    /// accessibility nodes are stored.
    pub fn tree_update(&mut self) -> &mut TreeUpdate {
        self.tree_update
    }

    /// Returns an id which is guaranteed not to collide with [`WidgetId`]s or with previous ids returned by this function.
    pub fn next_node_id() -> NodeId {
        // TODO - Return from a pool disjoint from widget ids.
        WidgetId::next().into()
    }
}

// --- MARK: COMPUTE LENGTH
impl_context_method!(MeasureCtx<'_>, LayoutCtx<'_>, {
    /// Computes the `child`'s preferred border-box [`Length`] on the given `axis`.
    ///
    /// Container widgets usually call this method as part of their [`measure`] logic,
    /// to help them calculate their own length on the given `axis`. They call it as part
    /// of their [`layout`] logic if they have already chosen a length for one axis.
    /// Read [`measure`] and [`layout`] docs for more details about those processes.
    ///
    /// `auto_length` specifies the fallback behavior if the child's dimension is [`Dim::Auto`].
    /// If you're calling this from within [`measure`] then you usually want to derive
    /// this from `len_req`, probably using [`LenReq::reduce`], i.e. you would call
    /// `len_req.reduce(used_space_on_this_axis).into()`. However, if you're calling this
    /// from within [`layout`] then you usually want to use use [`LenDef::FitContent`]
    /// to ask the child to fit inside the available space. Sometimes a different fallback
    /// makes more sense, e.g. `Grid` uses [`LenDef::Fixed`] to fall back to the exact
    /// allocated child area size.
    ///
    /// `context_size` is the size that is used to resolve relative sizes.
    /// For example [`Ratio(0.5)`] will result in half the context size.
    /// This is usually the container widget's content-box size, i.e. excluding borders and padding.
    /// Examples of exceptions include `Grid` which will provide the child's area size,
    /// i.e. the union of cell sizes that the child occupies, and `Portal` which will provide
    /// its viewport size.
    ///
    /// `cross_length` is the length of the cross axis and is critical information for certain
    /// widgets, e.g. for text max advance or to keep an aspect ratio.
    ///
    /// [`measure`]: Widget::measure
    /// [`layout`]: Widget::layout
    /// [`Ratio(0.5)`]: crate::layout::Dim::Ratio
    /// [`Dim::Auto`]: crate::layout::Dim
    /// [`LenReq::reduce`]: crate::layout::LenReq::reduce
    pub fn compute_length(
        &mut self,
        child: &mut WidgetPod<impl Widget + ?Sized>,
        auto_length: LenDef,
        context_size: LayoutSize,
        axis: Axis,
        cross_length: Option<Length>,
    ) -> Length {
        let id = child.id();
        let node = self.children.item_mut(id).unwrap();
        resolve_length(
            self.global_state,
            self.property_arena,
            node,
            auto_length,
            context_size,
            axis,
            cross_length,
        )
    }
});

// --- MARK: MEASURE
impl MeasureCtx<'_> {
    /// Returns the fallback [`LenDef`] of this measurement.
    ///
    /// This is essential information for widgets that want pass through measurements.
    /// That is, this fallback was chosen by widget A for widget B.
    /// Widget B can call this method and then pass it on via [`compute_length`] to widget C.
    /// Widget C will resolve its size with the fallback originally provided by widget A.
    ///
    /// Even easier, though, is to use [`redirect_measurement`].
    ///
    /// Calling `auto_length` will cause the result of this [`measure`] to not be cached.
    /// This is because `auto_length` is not part of the cache key.
    ///
    /// [`measure`]: Widget::measure
    /// [`compute_length`]: Self::compute_length
    /// [`redirect_measurement`]: Self::redirect_measurement
    pub fn auto_length(&mut self) -> LenDef {
        // We're adding a new variable, auto_length, into the measure function,
        // which is not part of the cache key. Hence, we need to not cache.
        self.cache_result = false;
        self.auto_length
    }

    /// Returns the context size of this measurement.
    ///
    /// This is usually the container widget's content-box size, i.e. excluding borders and padding.
    ///
    /// Examples of exceptions include `Grid` which will provide the child's area size,
    /// i.e. the union of cell sizes that the child occupies, and `Portal` which will provide
    /// its viewport size.
    ///
    /// The context size is used to resolve relative lengths, e.g. a width of [`Ratio(0.5)`]
    /// means half of this space. This resolving is done by Masonry and not manually in [`measure`].
    ///
    /// One or both lengths may be missing if they have not been computed yet,
    /// i.e. when the lengths depend on a child's size.
    ///
    /// This is essential information for widgets that want pass through measurements.
    /// That is, this context size was chosen by widget A for widget B.
    /// Widget B can call this method and then pass it on via [`compute_length`] to widget C.
    /// Widget C will resolve its size in relation to widget A.
    ///
    /// Even easier, though, is to use [`redirect_measurement`].
    ///
    /// Calling `context_size` will cause the result of this [`measure`] to not be cached.
    /// This is because `context_size` is not part of the cache key.
    ///
    /// [`measure`]: Widget::measure
    /// [`Ratio(0.5)`]: crate::layout::Dim::Ratio
    /// [`compute_length`]: Self::compute_length
    /// [`redirect_measurement`]: Self::redirect_measurement
    pub fn context_size(&mut self) -> LayoutSize {
        // We're adding a new variable, context_size, into the measure function,
        // which is not part of the cache key. Hence, we need to not cache.
        self.cache_result = false;
        self.context_size
    }

    /// Configures whether this [`measure`] result will be cached.
    ///
    /// Masonry will, by default, cache the results of measurement. The cache key is derived
    /// from `axis`, `len_req`, and `cross_length`. If the widget uses any other data to influence
    /// the result of the measurement, then the widget is responsible for requesting layout
    /// when any of that data changes. For properties, this is handled in [`property_changed`].
    /// For any other data you reference, the exact mechanism of detecting changes is up to you.
    /// If you can't detect changes of the referenced data, disable the cache with this method.
    ///
    /// [`measure`]: Widget::measure
    /// [`property_changed`]: Widget::property_changed
    pub fn cache_result(&mut self, cache_result: bool) {
        self.cache_result = cache_result;
    }

    /// Redirects the measurement request to a `child`.
    ///
    /// This is meant for thin wrapper widgets that want their children measured instead.
    ///
    /// It is a convenience wrapper over [`compute_length`] that automatically configures
    /// `auto_length` and `context_size` to whatever the outer container used. These could also
    /// be manually accessed via [`auto_length`] and [`context_size`] if you're so inclined.
    ///
    /// Calling `redirect_measurement` will cause the result of your [`measure`] to not be cached.
    /// The child's measurement might still be cached, depending on what policy the child chooses.
    /// This is because the redirection introduces new inputs in the form of [`auto_length`]
    /// and [`context_size`] that are not part of the cache key.
    ///
    /// [`measure`]: Widget::measure
    /// [`compute_length`]: Self::compute_length
    /// [`auto_length`]: Self::auto_length
    /// [`context_size`]: Self::context_size
    pub fn redirect_measurement(
        &mut self,
        child: &mut WidgetPod<impl Widget + ?Sized>,
        axis: Axis,
        cross_length: Option<Length>,
    ) -> Length {
        // We're adding two new variables, auto_length and context_size, into the measure function,
        // which are not part of the cache key. Hence, we need to not cache.
        self.cache_result = false;
        self.compute_length(
            child,
            self.auto_length,
            self.context_size,
            axis,
            cross_length,
        )
    }
}

// --- MARK: UPDATE LAYOUT
impl LayoutCtx<'_> {
    #[track_caller]
    fn assert_layout_done(&self, child: &WidgetPod<impl Widget + ?Sized>, method_name: &str) {
        let child_state = self.get_child_state(child);
        // If debug_assertions are enabled, then request_layout is always true until visited.
        let child_not_visited = cfg!(debug_assertions) && child_state.request_layout;
        if child_state.needs_layout() || child_not_visited {
            debug_panic!(
                "Error in {}: trying to call '{}' with child '{}' {} before computing its layout",
                self.widget_id(),
                method_name,
                self.get_child_dyn(child).short_type_name(),
                child.id(),
            );
        }
    }

    #[track_caller]
    fn assert_placed(&self, child: &WidgetPod<impl Widget + ?Sized>, method_name: &str) {
        if self.get_child_state(child).is_expecting_place_child_call {
            debug_panic!(
                "Error in {}: trying to call '{}' with child '{}' {} before placing it",
                self.widget_id(),
                method_name,
                self.get_child_dyn(child).short_type_name(),
                child.id(),
            );
        }
    }

    /// Computes the `child`'s preferred border-box size.
    ///
    /// The returned size will be finite, non-negative, and in logical pixels.
    ///
    /// Container widgets usually call this method as part of their [`layout`] logic, but
    /// ultimately they can disregard the result and pass a different size to [`run_layout`].
    /// Read [`layout`] docs for more details about that process.
    ///
    /// `auto_size` specifies the fallback behavior if the child has any dimension as [`Dim::Auto`].
    /// Most widgets should use [`SizeDef::fit`] to ask the child to fit inside the
    /// available space. However sometimes a different fallback makes more sense, e.g.
    /// `Grid` uses [`SizeDef::fixed`] to fall back to the exact allocated child area size.
    ///
    /// `context_size` is the size that is used to resolve relative sizes.
    /// For example [`Ratio(0.5)`] will result in half the context size.
    /// This is usually the container widget's content-box size, i.e. excluding borders and padding.
    /// Examples of exceptions include `Grid` which will provide the child's area size,
    /// i.e. the union of cell sizes that the child occupies, and `Portal` which will provide
    /// its viewport size.
    ///
    /// [`layout`]: Widget::layout
    /// [`Ratio(0.5)`]: crate::layout::Dim::Ratio
    /// [`Dim::Auto`]: crate::layout::Dim::Auto
    /// [`run_layout`]: Self::run_layout
    pub fn compute_size(
        &mut self,
        child: &mut WidgetPod<impl Widget + ?Sized>,
        auto_size: SizeDef,
        context_size: LayoutSize,
    ) -> Size {
        let id = child.id();
        let node = self.children.item_mut(id).unwrap();
        resolve_size(
            self.global_state,
            self.property_arena,
            node,
            auto_size,
            context_size,
        )
    }

    /// Lays out the `child` widget with a chosen border-box `size`.
    ///
    /// Container widgets must call this on every child as part of their [`layout`] method.
    ///
    /// The container widget should usually call [`compute_size`] on the `child`
    /// to get its preferred border-box `size`.
    /// However, ultimately the parent is in control and can choose any `size` for the child.
    ///
    /// If the chosen border-box `size` is smaller than what is required to fit the child's
    /// borders and padding, then the `size` will be expanded to meet those constraints.
    ///
    /// The provided `size` must be finite, non-negative, and in logical pixels.
    /// Non-finite or negative size will fall back to zero with a logged warning.
    ///
    /// # Panics
    ///
    /// Panics if the provided `size` is non-finite or negative and debug assertions are enabled.
    ///
    /// [`layout`]: Widget::layout
    /// [`compute_size`]: Self::compute_size
    pub fn run_layout(&mut self, child: &mut WidgetPod<impl Widget + ?Sized>, chosen_size: Size) {
        let id = child.id();
        let node = self.children.item_mut(id).unwrap();

        run_layout_on(self.global_state, self.property_arena, node, chosen_size);

        let state_mut = &mut self.children.item_mut(id).unwrap().item.state;
        self.widget_state.merge_up(state_mut);
    }

    /// Sets the position of the `child` widget, in this widget's content-box coordinate space.
    ///
    /// Container widgets must call this method with each non-stashed child in their
    /// [`layout`] method, after calling `ctx.run_layout(child, size)`.
    ///
    /// # Panics
    ///
    /// This method will panic if [`LayoutCtx::run_layout`] has not been called yet for the child.
    ///
    /// [`layout`]: Widget::layout
    #[track_caller]
    pub fn place_child(&mut self, child: &mut WidgetPod<impl Widget + ?Sized>, origin: Point) {
        self.assert_layout_done(child, "place_child");
        if origin.x.is_nan()
            || origin.x.is_infinite()
            || origin.y.is_nan()
            || origin.y.is_infinite()
        {
            debug_panic!(
                "Error in {}: trying to call 'place_child' with child '{}' {} with invalid origin {:?}",
                self.widget_id(),
                self.get_child_dyn(child).short_type_name(),
                child.id(),
                origin,
            );
        }

        // Convert child's origin from this widget's content-box space to border-box space.
        let translation = self.widget_state.border_box_translation();
        let child_origin = origin + translation;
        let child_state = self.get_child_state_mut(child);

        place_widget(child_state, child_origin);
    }

    /// Sets explicit paint [`Insets`] for this widget.
    ///
    /// The argument is an [`Insets`] struct that indicates where your widget will overpaint,
    /// relative to its layout content-box, as defined by the `size` given to the widget's
    /// [`layout`] method.
    ///
    /// You are only required to notify of painting that actually overflows the layout border-box.
    /// The insets will still be relative to the content-box, it's just that Masonry doesn't
    /// really need to be notified if you're just painting over your padding or borders.
    ///
    /// You are only required to notify of painting done directly by this widget.
    /// Child widget overdraw needs to be reported by those child widgets themselves.
    ///
    /// [`layout`]: Widget::layout
    pub fn set_paint_insets(&mut self, insets: impl Into<Insets>) {
        let insets = insets.into();
        let insets = Insets::new(
            insets.x0 - self.widget_state.border_box_insets.x0,
            insets.y0 - self.widget_state.border_box_insets.y0,
            insets.x1 - self.widget_state.border_box_insets.x1,
            insets.y1 - self.widget_state.border_box_insets.y1,
        );
        self.widget_state.paint_box_insets = insets.nonnegative();
    }

    /// Sets explicit baselines for this widget.
    ///
    /// The baseline positions are used to align widgets that contain text,
    /// such as buttons, labels, and other controls. It may also be used
    /// by other widgets that are opinionated about how they are aligned
    /// relative to neighbouring text, such as switches or checkboxes.
    ///
    /// The provided values must be the distance from the top of this
    /// widget's content-box to its baseline. If there aren't multiple
    /// baselines then set the same baseline as both `first` and `last`.
    ///
    /// Most container widgets can use [`derive_baselines`] instead.
    /// Multi-child containers should derive their baselines using [`child_aligned_baselines`].
    ///
    /// [`derive_baselines`]: Self::derive_baselines
    /// [`child_aligned_baselines`]: Self::child_aligned_baselines
    pub fn set_baselines(&mut self, first_baseline: f64, last_baseline: f64) {
        self.widget_state.first_baseline = first_baseline + self.widget_state.border_box_insets.y0;
        self.widget_state.last_baseline = last_baseline + self.widget_state.border_box_insets.y0;
    }

    /// Sets explicit baselines for this widget such that they match the child's aligned baselines.
    ///
    /// Most container widgets should use this method to derive their baselines from their child.
    /// More complex containers can use [`child_aligned_baselines`] in multi-child scenarios.
    ///
    /// # Panics
    ///
    /// This method will panic if [`LayoutCtx::run_layout`] or [`LayoutCtx::place_child`]
    /// have not been called yet for the child.
    ///
    /// [`child_aligned_baselines`]: Self::child_aligned_baselines
    #[track_caller]
    pub fn derive_baselines(&mut self, child: &WidgetPod<impl Widget + ?Sized>) {
        self.assert_layout_done(child, "derive_baselines");
        self.assert_placed(child, "derive_baselines");

        let child_state = self.get_child_state(child);
        let first_baseline = child_state.origin.y + child_state.aligned_first_baseline();
        let last_baseline = child_state.origin.y + child_state.aligned_last_baseline();
        self.widget_state.first_baseline = first_baseline;
        self.widget_state.last_baseline = last_baseline;
    }

    /// Clears explicitly set baseline positions for this widget.
    ///
    /// This results in the effective baseline being the bottom edge of this widget's border-box.
    pub fn clear_baselines(&mut self) {
        self.widget_state.first_baseline = f64::NAN;
        self.widget_state.last_baseline = f64::NAN;
    }

    /// Returns the insets for converting between content-box and border-box rects.
    ///
    /// Add these insets to the content-box to get the border-box,
    /// and subtract these insets from the border-box to get the content-box.
    pub fn border_box_insets(&mut self) -> Insets {
        self.widget_state.border_box_insets
    }

    /// Returns whether this widget needs to call [`LayoutCtx::run_layout`].
    pub fn needs_layout(&self) -> bool {
        self.widget_state.needs_layout()
    }

    /// Returns whether a child of this widget needs to call [`LayoutCtx::run_layout`].
    pub fn child_needs_layout(&self, child: &WidgetPod<impl Widget + ?Sized>) -> bool {
        self.get_child_state(child).needs_layout()
    }

    /// Returns the `child` widget's `(first, last)` layout baselines.
    ///
    /// The distances are from the top of the child widget's layout border-box to its baseline.
    ///
    /// Call this if the child's baseline plays a role in choosing its placement.
    /// For deriving this widget's baselines call [`child_aligned_baselines`] instead,
    /// or better yet use [`derive_baselines`] if possible.
    ///
    /// # Panics
    ///
    /// This method will panic if [`LayoutCtx::run_layout`] has not been called yet for
    /// the child.
    ///
    /// [`child_aligned_baselines`]: Self::child_aligned_baselines
    /// [`derive_baselines`]: Self::derive_baselines
    #[track_caller]
    pub fn child_layout_baselines(&self, child: &WidgetPod<impl Widget + ?Sized>) -> (f64, f64) {
        self.assert_layout_done(child, "child_layout_baselines");

        let child_state = self.get_child_state(child);
        (
            child_state.layout_first_baseline(),
            child_state.layout_last_baseline(),
        )
    }

    /// Returns the `child` widget's `(first, last)` aligned baselines.
    ///
    /// The distances are from the top of the child widget's aligned border-box to its baseline.
    ///
    /// This aligned version should be used for deriving this widget's own baselines based
    /// on the child's baselines. That is if [`derive_baselines`] can't be used.
    /// For deciding where to place the child based on its baselines,
    /// you need to use [`child_layout_baselines`] instead.
    ///
    /// # Panics
    ///
    /// This method will panic if [`LayoutCtx::run_layout`] or [`LayoutCtx::place_child`]
    /// have not been called yet for the child.
    ///
    /// [`derive_baselines`]: Self::derive_baselines
    /// [`child_layout_baselines`]: Self::child_layout_baselines
    #[track_caller]
    pub fn child_aligned_baselines(&self, child: &WidgetPod<impl Widget + ?Sized>) -> (f64, f64) {
        self.assert_layout_done(child, "child_aligned_baselines");
        self.assert_placed(child, "child_aligned_baselines");

        let child_state = self.get_child_state(child);
        (
            child_state.aligned_first_baseline(),
            child_state.aligned_last_baseline(),
        )
    }

    /// Returns the given child's aligned border-box origin
    /// in this widget's content-box coordinate space.
    ///
    /// # Panics
    ///
    /// This method will panic if [`LayoutCtx::run_layout`] or [`LayoutCtx::place_child`]
    /// have not been called yet for the child.
    #[track_caller]
    pub fn child_origin(&self, child: &WidgetPod<impl Widget + ?Sized>) -> Point {
        self.assert_layout_done(child, "child_origin");
        self.assert_placed(child, "child_origin");
        self.get_child_state(child).origin - self.widget_state.border_box_translation()
    }

    /// Returns the given child's layout border-box size.
    ///
    /// # Panics
    ///
    /// This method will panic if [`LayoutCtx::run_layout`] has not been called yet for
    /// the child.
    #[track_caller]
    pub fn child_size(&self, child: &WidgetPod<impl Widget + ?Sized>) -> Size {
        self.assert_layout_done(child, "child_size");
        self.get_child_state(child).layout_border_box_size
    }

    /// Sets the widget's clip path in the widget's content-box coordinate space.
    ///
    /// A widget's clip path will have two effects:
    /// - It serves as a mask for painting operations of this widget and its children.
    ///   Note that while all painting done by children will be clipped by this path,
    ///   only the painting done in [`paint`] by this widget itself will be clipped.
    ///   The remaining painting done in [`pre_paint`] and [`post_paint`] will not be clipped.
    /// - Pointer events must be inside this path to reach the widget's children.
    ///
    /// [`paint`]: Widget::paint
    /// [`pre_paint`]: Widget::pre_paint
    /// [`post_paint`]: Widget::post_paint
    pub fn set_clip_path(&mut self, path: Rect) {
        // Translate the clip path to the widget's border-box coordinate space.
        let path = path + self.widget_state.border_box_translation();
        // We intentionally always log this because clip paths are:
        // 1) Relatively rare in the tree
        // 2) An easy potential source of items not being visible when expected
        trace!("set_clip_path {path:?}");
        self.widget_state.clip_path = Some(path);
        // TODO - Updating the clip path may have
        // other knock-on effects we'd need to document.
        self.widget_state.request_accessibility = true;
        self.widget_state.needs_accessibility = true;
        self.widget_state.needs_paint = true;
    }

    /// Removes the widget's clip path.
    ///
    /// See [`LayoutCtx::set_clip_path`] for details.
    pub fn clear_clip_path(&mut self) {
        trace!("clear_clip_path");
        self.widget_state.clip_path = None;
        // TODO - Updating the clip path may have
        // other knock-on effects we'd need to document.
        self.widget_state.request_accessibility = true;
        self.widget_state.needs_accessibility = true;
        self.widget_state.needs_paint = true;
    }
}

impl ComposeCtx<'_> {
    /// Sets the scroll translation for the child widget.
    ///
    /// The translation is applied on top of the position from [`LayoutCtx::place_child`].
    ///
    /// The given translation may be quantized so the child's final position
    /// stays pixel-perfect.
    pub fn set_child_scroll_translation(
        &mut self,
        child: &mut WidgetPod<impl Widget + ?Sized>,
        translation: Vec2,
    ) {
        if translation.x.is_nan()
            || translation.x.is_infinite()
            || translation.y.is_nan()
            || translation.y.is_infinite()
        {
            debug_panic!(
                "Error in {}: trying to call 'set_child_scroll_translation' with child '{}' {} with invalid translation {:?}",
                self.widget_id(),
                self.get_child_dyn(child).short_type_name(),
                child.id(),
                translation,
            );
        }

        let translation = translation.round();

        let child = self.get_child_state_mut(child);
        if translation != child.scroll_translation {
            child.scroll_translation = translation;
            child.transform_changed = true;
            child.needs_compose = true;
        }
    }

    /// Sets the scroll translation for the child widget.
    ///
    /// The translation is applied on top of the position from [`LayoutCtx::place_child`].
    ///
    /// Unlike [`Self::set_child_scroll_translation`], doesn't perform pixel-snapping.
    /// This method should be used for intermediary scroll values during scroll animations.
    pub fn set_animated_child_scroll_translation(
        &mut self,
        child: &mut WidgetPod<impl Widget + ?Sized>,
        translation: Vec2,
    ) {
        if translation.x.is_nan()
            || translation.x.is_infinite()
            || translation.y.is_nan()
            || translation.y.is_infinite()
        {
            debug_panic!(
                "Error in {}: trying to call 'set_animated_child_scroll_translation' with child '{}' {} with invalid translation {:?}",
                self.widget_id(),
                self.get_child_dyn(child).short_type_name(),
                child.id(),
                translation,
            );
        }

        let child = self.get_child_state_mut(child);
        if translation != child.scroll_translation {
            child.scroll_translation = translation;
            child.transform_changed = true;
            child.needs_compose = true;
        }
    }
}

// --- MARK: GET GEOMETRY
// Methods on all context types except MeasureCtx and LayoutCtx
// These methods access geometry resolved during layout and compose.
impl_context_method!(
    MutateCtx<'_>,
    ActionCtx<'_>,
    QueryCtx<'_>,
    EventCtx<'_>,
    UpdateCtx<'_>,
    ComposeCtx<'_>,
    PaintCtx<'_>,
    AccessCtx<'_>,
    {
        /// Returns the aligned content-box rect of this widget
        /// in this widget's content-box coordinate space.
        pub fn content_box(&self) -> Rect {
            let translation = self.widget_state.border_box_translation();
            self.widget_state.content_box() - translation
        }

        /// Returns the aligned border-box rect of this widget
        /// in this widget's content-box coordinate space.
        pub fn border_box(&self) -> Rect {
            let translation = self.widget_state.border_box_translation();
            self.widget_state.border_box() - translation
        }

        /// Returns the aligned paint-box rect of this widget
        /// in this widget's content-box coordinate space.
        ///
        /// Covers the area we expect to be invalidated when the widget is painted.
        pub fn paint_box(&self) -> Rect {
            let translation = self.widget_state.border_box_translation();
            self.widget_state.paint_box() - translation
        }

        /// Returns the widget's bounding-box rect in the window's coordinate space.
        ///
        /// It contains this widget and all of its descendents.
        ///
        /// This is the union of clipped effective paint-box rects, i.e. the union of
        /// globally transformed aligned border-box rects with paint insets applied.
        ///
        /// See [bounding box documentation] for more details.
        ///
        /// [bounding box documentation]: crate::doc::masonry_concepts#bounding-box
        pub fn bounding_box(&self) -> Rect {
            self.widget_state.bounding_box
        }

        /// Returns the first baseline relative to the top of the widget's aligned content-box.
        pub fn first_baseline(&self) -> f64 {
            let border_box_baseline = self.widget_state.aligned_first_baseline();
            border_box_baseline - self.widget_state.border_box_insets.y0
        }

        /// Returns the last baseline relative to the top of the widget's aligned content-box.
        pub fn last_baseline(&self) -> f64 {
            let border_box_baseline = self.widget_state.aligned_last_baseline();
            border_box_baseline - self.widget_state.border_box_insets.y0
        }

        /// The clip path of the widget, if any was set.
        ///
        /// The returned clip path will be in this widget's content-box coordinate space.
        ///
        /// For more information, see
        /// [`LayoutCtx::set_clip_path`](crate::core::LayoutCtx::set_clip_path).
        pub fn clip_path(&self) -> Option<Rect> {
            // Translate the clip path to the widget's content-box coordinate space.
            let translation = self.widget_state.border_box_translation();
            self.widget_state.clip_path.map(|path| path - translation)
        }

        /// Returns the [`Vec2`] for translating between this widget's
        /// content-box and border-box coordinate spaces.
        ///
        /// Add this [`Vec2`] to translate from content-box to border-box,
        /// and subtract this [`Vec2`] to translate from border-box to content-box.
        pub fn border_box_translation(&self) -> Vec2 {
            self.widget_state.border_box_translation()
        }

        /// Returns the global transform mapping this widget's content-box coordinate space
        /// to the window's coordinate space.
        ///
        /// Computed from all `transform`, `scroll_translation`, and `origin` values
        /// from this widget all the way up to the window.
        ///
        /// Multiply by this to convert from this widget's content-box coordinate space to the window's,
        /// or use the inverse of this transform to go from window's space to this widget's content-box.
        pub fn window_transform(&self) -> Affine {
            let translation = self.widget_state.border_box_translation();
            self.widget_state
                .window_transform
                .pre_translate(translation)
        }

        /// Converts the `point` from the window's coordinate space
        /// to this widget's content-box coordinate space.
        pub fn to_local(&self, point: Point) -> Point {
            let to_border_box = self.widget_state.window_transform.inverse();
            let to_content_box = -self.widget_state.border_box_translation();
            to_border_box.then_translate(to_content_box) * point
        }

        /// Converts the `point` from this widget's content-box coordinate space
        /// to the window's coordinate space.
        ///
        /// The returned point is relative to the window's content area; it excludes window chrome.
        pub fn to_window(&self, point: Point) -> Point {
            let translation = self.widget_state.border_box_translation();
            self.widget_state.window_transform * (point + translation)
        }

        /// Returns the DPI scaling factor.
        ///
        /// This can be useful for loading image resources meant for a specific scale.
        pub fn scale_factor(&self) -> f64 {
            self.global_state.scale_factor
        }
    }
);

// --- MARK: GET STATUS

// Methods on all context types
// Access status information (hovered/pointer captured/disabled/etc).
impl_context_method!(
    MutateCtx<'_>,
    ActionCtx<'_>,
    QueryCtx<'_>,
    EventCtx<'_>,
    UpdateCtx<'_>,
    MeasureCtx<'_>,
    LayoutCtx<'_>,
    ComposeCtx<'_>,
    PaintCtx<'_>,
    AccessCtx<'_>,
    {
        /// The "hovered" status of a widget.
        ///
        /// A widget is "hovered" when a pointer is hovering over its border-box.
        /// Widgets will often change their appearance as a visual indication that they
        /// will respond to pointer (usually mouse) interaction.
        ///
        /// If the pointer is [captured], then only the capturing widget can have hovered
        /// status. If the pointer is captured but not hovering over the captured
        /// widget, then no widget has the hovered status.
        ///
        /// [captured]: crate::doc::masonry_concepts#pointer-capture
        pub fn is_hovered(&self) -> bool {
            self.widget_state.is_hovered
        }

        /// Whether this widget or any of its descendants are hovered.
        ///
        /// To check if only this specific widget is hovered use [`is_hovered`](Self::is_hovered).
        pub fn has_hovered(&self) -> bool {
            self.widget_state.has_hovered
        }

        /// The "active" status of a widget.
        ///
        /// A widget is "active" when the user is "actively" interacting with it.
        /// Currently, a widget is determined to be active when it has [captured] a pointer,
        /// but this may change in the future to account for e.g. keyboard interactions.
        ///
        /// [captured]: crate::doc::masonry_concepts#pointer-capture
        pub fn is_active(&self) -> bool {
            self.widget_state.is_active
        }

        /// Whether this widget or any of its descendants are active.
        ///
        /// To check if only this specific widget is active use [`is_active`](Self::is_active).
        pub fn has_active(&self) -> bool {
            self.widget_state.has_active
        }

        /// Whether a pointer is [captured] by this widget.
        ///
        /// The pointer will usually be the mouse. In future versions, this
        /// function will take a pointer id as input to test a specific pointer.
        ///
        /// [captured]: crate::doc::masonry_concepts#pointer-capture
        pub fn is_pointer_capture_target(&self) -> bool {
            self.global_state.pointer_capture_target == Some(self.widget_state.id)
        }

        /// The [text focus] status of a widget.
        ///
        /// The focused widget is the one that receives keyboard events.
        ///
        /// Returns `true` if this specific widget is focused.
        /// To check if any descendants are focused use [`has_focus_target`].
        ///
        /// [text focus]: crate::doc::masonry_concepts#text-focus
        /// [`has_focus_target`]: Self::has_focus_target
        pub fn is_focus_target(&self) -> bool {
            self.global_state.focused_widget == Some(self.widget_id())
        }

        /// Whether this widget or any of its descendants are focused.
        ///
        /// To check if only this specific widget is focused use [`is_focus_target`](Self::is_focus_target).
        pub fn has_focus_target(&self) -> bool {
            self.widget_state.has_focus_target
        }

        /// Whether the window is focused.
        pub fn is_window_focused(&self) -> bool {
            self.global_state.window_focused
        }

        /// The widget, if any, which has [pointer capture].
        ///
        /// The pointer will usually be the mouse. In future versions, this
        /// function will take a pointer id as input to test a specific pointer.
        ///
        /// [pointer capture]: crate::doc::masonry_concepts#pointer-capture
        pub fn pointer_capture_target_id(&self) -> Option<WidgetId> {
            self.global_state.pointer_capture_target
        }

        /// The widget, if any, which has [text focus].
        ///
        /// The focused widget is the one that receives keyboard events.
        ///
        /// [text focus]: crate::doc::masonry_concepts#text-focus
        pub fn focus_target_id(&self) -> Option<WidgetId> {
            self.global_state.focused_widget
        }

        /// Whether this widget gets pointer events and hovered status.
        ///
        /// See [`Widget::accepts_pointer_interaction()`] for details.
        pub fn accepts_pointer_interaction(&self) -> bool {
            self.widget_state.accepts_pointer_interaction
        }

        /// Whether this widget should get a tooltip when hovered long enough.
        ///
        /// See [`Widget::accepts_tooltips()`] for details.
        pub fn accepts_tooltips(&self) -> bool {
            self.widget_state.accepts_tooltips
        }

        /// Whether children of this widget get pointer events and hovered status.
        ///
        /// See [`Widget::propagates_pointer_interaction()`] for details.
        pub fn propagates_pointer_interaction(&self) -> bool {
            self.widget_state.propagates_pointer_interaction
        }

        /// Whether this widget gets text focus.
        ///
        /// See [`Widget::accepts_focus()`] for details.
        pub fn accepts_focus(&self) -> bool {
            self.widget_state.accepts_focus
        }

        /// Whether this widget gets IME events.
        ///
        /// See [`Widget::accepts_text_input()`] for details.
        pub fn accepts_text_input(&self) -> bool {
            self.widget_state.accepts_text_input
        }

        /// Whether this widget is [disabled].
        ///
        /// Returns `true` if this widget or any of its ancestors is explicitly disabled.
        /// To make this widget explicitly disabled use [`set_disabled`].
        ///
        /// [disabled]: crate::doc::masonry_concepts#disabled
        /// [`set_disabled`]: EventCtx::set_disabled
        pub fn is_disabled(&self) -> bool {
            self.widget_state.is_disabled
        }

        /// Whether this widget is [stashed].
        ///
        /// [stashed]: crate::doc::masonry_concepts#stashed
        pub fn is_stashed(&self) -> bool {
            self.widget_state.is_stashed
        }

        /// Returns whether the given child is [stashed].
        ///
        /// The result of this function is not affected by `set_stashed` until the next
        /// [`update_stashed`] pass.
        ///
        /// [stashed]: crate::doc::masonry_concepts#stashed
        /// [`update_stashed`]: crate::doc::pass_system#update-passes
        pub fn child_is_stashed(&self, child: &WidgetPod<impl Widget + ?Sized>) -> bool {
            self.get_child_state(child).is_stashed
        }
    }
);

// --- MARK: UPDATE FLAGS
impl_context_method!(
    MutateCtx<'_>,
    ActionCtx<'_>,
    EventCtx<'_>,
    UpdateCtx<'_>,
    RawCtx<'_>,
    {
        /// Requests a [`paint`](crate::core::Widget::paint) and an
        /// [`accessibility`](crate::core::Widget::accessibility) pass.
        pub fn request_render(&mut self) {
            trace!("request_render");
            self.widget_state.request_pre_paint = true;
            self.widget_state.request_paint = true;
            self.widget_state.request_post_paint = true;
            self.widget_state.needs_paint = true;
            self.widget_state.needs_accessibility = true;
            self.widget_state.request_accessibility = true;
        }

        /// Requests a paint pass for the [`pre_paint`](crate::core::Widget::pre_paint) method.
        pub fn request_pre_paint(&mut self) {
            trace!("request_pre_paint");
            self.widget_state.request_pre_paint = true;
            self.widget_state.needs_paint = true;
        }

        /// Requests a paint pass, specifically for the [`paint`] method.
        ///
        /// Unlike [`request_render`], this does not request an [`accessibility`] pass
        /// or a call to [`pre_paint`] or [`post_paint`].
        ///
        /// Use `request_render` unless you're sure those aren't needed.
        ///
        /// [`paint`]: crate::core::Widget::paint
        /// [`request_render`]: Self::request_render
        /// [`accessibility`]: crate::core::Widget::accessibility
        /// [`pre_paint`]: crate::core::Widget::post_paint
        /// [`post_paint`]: crate::core::Widget::post_paint
        pub fn request_paint_only(&mut self) {
            trace!("request_paint_only");
            self.widget_state.request_paint = true;
            self.widget_state.needs_paint = true;
        }

        /// Requests a paint pass for the [`post_paint`](crate::core::Widget::post_paint) method.
        pub fn request_post_paint(&mut self) {
            trace!("request_post_paint");
            self.widget_state.request_post_paint = true;
            self.widget_state.needs_paint = true;
        }

        /// Requests an [`accessibility`](crate::core::Widget::accessibility) pass.
        ///
        /// This doesn't request a [`paint`](crate::core::Widget::paint) pass.
        /// If you want to request both an accessibility pass and a paint pass,
        /// use [`request_render`](Self::request_render).
        pub fn request_accessibility_update(&mut self) {
            trace!("request_accessibility_update");
            self.widget_state.needs_accessibility = true;
            self.widget_state.request_accessibility = true;
        }

        /// Requests a [`layout`] pass.
        ///
        /// Call this method if the widget has changed in a way that requires a layout pass.
        ///
        /// [`layout`]: crate::core::Widget::layout
        pub fn request_layout(&mut self) {
            trace!("request_layout");
            self.widget_state.request_layout = true;
            self.widget_state.set_needs_layout(true);
        }

        /// Requests that this widget's [`compose`] method be called.
        ///
        /// The compose pass is often cheaper than the layout pass,
        /// because it can only transform individual widgets' position.
        /// Use this when widget-owned state read by [`compose`] changes,
        /// such as a scroll offset applied to a child during compose.
        ///
        /// [`compose`]: crate::core::Widget::compose
        pub fn request_compose(&mut self) {
            trace!("request_compose");
            self.widget_state.needs_compose = true;
            self.widget_state.request_compose = true;
        }

        /// Requests an animation frame.
        ///
        /// Use this for visual state that should advance with frame cadence,
        /// such as continuous motion or interpolation. For delayed one-shot UI
        /// behavior like cursor blinking, tooltip delays, debounce, or long
        /// press recognition, prefer [`set_timer`](Self::set_timer).
        pub fn request_anim_frame(&mut self) {
            trace!("request_anim_frame");
            self.widget_state.request_anim = true;
            self.widget_state.needs_anim = true;
        }

        /// Notifies Masonry that the cursor returned by [`Widget::get_cursor`] has changed.
        ///
        /// This is mostly meant for cases where the cursor changes even if the pointer doesn't
        /// move, because the nature of the widget has changed somehow.
        pub fn request_cursor_icon_change(&mut self) {
            trace!("request_cursor_icon_change");
            self.global_state.needs_pointer_pass = true;
        }

        /// Indicates that your children have changed.
        ///
        /// Widgets must call this method after adding a new child.
        ///
        /// This method will also call [`request_layout`](Self::request_layout).
        pub fn children_changed(&mut self) {
            trace!("children_changed");
            self.widget_state.children_changed = true;
            self.widget_state.needs_update_focusable = true;
            self.request_layout();
        }

        /// Indicates that a child is about to be removed from the tree.
        ///
        /// Container widgets should avoid dropping `WidgetPod`s. Instead, they should
        /// pass them to this method.
        ///
        /// This method will also call [`children_changed`](Self::children_changed).
        pub fn remove_child(&mut self, child: WidgetPod<impl Widget + ?Sized>) {
            fn remove_node(
                global_state: &mut RenderRootState,
                parent_state: &mut WidgetState,
                node: ArenaMut<'_, WidgetArenaNode>,
            ) {
                let mut children = node.children;
                let widget = &mut *node.item.widget;
                let state = &mut node.item.state;

                // TODO - Send event to widget

                let parent_name = widget.short_type_name();
                let parent_id = state.id;
                for child_id in widget.children_ids() {
                    let Some(node) = children.item_mut(child_id) else {
                        panic!(
                            "Error in '{parent_name}' {parent_id}: cannot find child {child_id} returned by children_ids()"
                        );
                    };

                    remove_node(global_state, state, node);
                }

                // If we remove the focus anchor, its parent becomes the anchor.
                if global_state.focus_anchor == Some(state.id) {
                    global_state.focus_anchor = Some(parent_state.id);
                }

                global_state.scene_cache.remove(&state.id);
                global_state.remove_widget_timers(state.id);

                if let Some(subwindows) = global_state.attached_subwindows.remove(&state.id) {
                    for (_, subwindow_id) in subwindows {
                        global_state.remove_subwindow(subwindow_id);
                    }
                }
            }

            let id = child.id();
            let node = self
                .children
                .item_mut(id)
                .expect("remove_child: child not found");
            remove_node(self.global_state, self.widget_state, node);

            let _ = self.children.remove(id).unwrap();

            self.children_changed();
        }

        /// Sets the disabled state for this widget.
        ///
        /// Setting this to `false` does not mean a widget is not still disabled; for instance it may
        /// still be disabled by an ancestor. See [`is_disabled`] for more information.
        ///
        /// [`is_disabled`]: EventCtx::is_disabled
        pub fn set_disabled(&mut self, disabled: bool) {
            self.widget_state.needs_update_disabled = true;
            self.widget_state.is_explicitly_disabled = disabled;
        }

        /// Sets the local transform for this widget.
        ///
        /// This maps this widget's border-box coordinate space
        /// to the parent's border-box coordinate space.
        ///
        /// It behaves similarly as CSS transforms.
        pub fn set_transform(&mut self, transform: Affine) {
            self.widget_state.transform = transform;
            self.widget_state.transform_changed = true;
            self.widget_state.needs_compose = true;
        }

        /// Adds a string to this widget's [class set].
        ///
        /// Changes will be applied in the next update pass and may affect property resolution.
        ///
        /// [class]: crate::doc::masonry_concepts#classes
        pub fn add_class(&mut self, class: &str) {
            self.widget_state.class_diff.add(class);
            self.widget_state.request_update_props = true;
            self.widget_state.needs_update_props = true;
        }

        /// Removes a string from this widget's [class set].
        ///
        /// Changes will be applied in the next update pass and may affect property resolution.
        ///
        /// [class]: crate::doc::masonry_concepts#classes
        pub fn remove_class(&mut self, class: &str) {
            self.widget_state.class_diff.remove(class);
            self.widget_state.request_update_props = true;
            self.widget_state.needs_update_props = true;
        }
    }
);

// --- MARK: OTHER METHODS
// Methods on mutable context types
impl_context_method!(
    MutateCtx<'_>,
    ActionCtx<'_>,
    EventCtx<'_>,
    UpdateCtx<'_>,
    MeasureCtx<'_>,
    LayoutCtx<'_>,
    ComposeCtx<'_>,
    RawCtx<'_>,
    {
        // TODO - Remove from MeasureCtx/LayoutCtx/ComposeCtx
        /// Marks child widget as stashed.
        ///
        /// If `stashed` is true, the child will not be painted or listed in the accessibility tree.
        ///
        /// This will *not* trigger a layout pass.
        pub fn set_stashed(&mut self, child: &mut WidgetPod<impl Widget + ?Sized>, stashed: bool) {
            let child_state = self.get_child_state_mut(child);
            // Stashing is generally a property derived from the parent widget's state
            // (rather than set imperatively), so it is likely to be set as part of passes.
            // Therefore, we avoid re-running the update_stashed_pass in most cases.
            if child_state.is_explicitly_stashed != stashed {
                child_state.is_explicitly_stashed = stashed;
                child_state.needs_update_stashed = true;
                self.widget_state.needs_update_stashed = true;
            }
        }

        // TODO - Remove from MutateCtx?
        /// Queues a callback that will be called with a [`WidgetMut`] for this widget.
        ///
        /// The callbacks will be run in the order they were submitted during the mutate pass.
        pub fn mutate_self_later(
            &mut self,
            f: impl FnOnce(WidgetMut<'_, dyn Widget>) + Send + 'static,
        ) {
            let callback = MutateCallback {
                id: self.widget_state.id,
                callback: Box::new(f),
            };
            self.global_state.mutate_callbacks.push(callback);
        }

        /// Queues a callback that will be called with a [`WidgetMut`] for the given child widget.
        ///
        /// The callbacks will be run in the order they were submitted during the mutate pass.
        pub fn mutate_child_later<W: Widget + FromDynWidget + ?Sized>(
            &mut self,
            child: &mut WidgetPod<W>,
            f: impl FnOnce(WidgetMut<'_, W>) + Send + 'static,
        ) {
            let callback = MutateCallback {
                id: child.id(),
                callback: Box::new(|mut widget_mut| f(widget_mut.downcast())),
            };
            self.global_state.mutate_callbacks.push(callback);
        }

        /// Queues a callback that will be called with a [`WidgetMut`] for the widget with the given id.
        ///
        /// The callbacks will be run in the order they were submitted during the mutate pass.
        pub fn mutate_later(
            &mut self,
            // TODO - Use WidgetTag instead?
            target: WidgetId,
            f: impl FnOnce(WidgetMut<'_, dyn Widget>) + Send + 'static,
        ) {
            let callback = MutateCallback {
                id: target,
                callback: Box::new(f),
            };
            self.global_state.mutate_callbacks.push(callback);
        }

        /// Returns direct reference to the stored child, and a context handle for that child.
        pub fn get_raw<Child: Widget + FromDynWidget + ?Sized>(
            &mut self,
            child: &mut WidgetPod<Child>,
        ) -> (&Child, RawCtx<'_>) {
            let node_mut = self
                .children
                .item_mut(child.id())
                .expect("get_mut: child not found");
            let child_ctx = RawCtx {
                global_state: self.global_state,
                parent_widget_state: self.widget_state,
                widget_state: &mut node_mut.item.state,
                children: node_mut.children,
                property_arena: self.property_arena,
            };

            let widget = Child::from_dyn(&*node_mut.item.widget).unwrap();

            (widget, child_ctx)
        }

        /// Returns direct mutable reference to the stored child, and a context handle for that child.
        ///
        /// This context lets you set pass flags for the child widget, which may be tricky.
        /// In general, you should avoid setting the flags of a pass that runs before the
        /// pass you're currently in.
        /// Not doing so might lead to performance cliffs and, hypothetically, panics.
        ///
        /// This method is an escape hatch for cases where a parent widget completely
        /// controls their child, but needs it to be a separate widget for user interaction to
        /// behave as expected.
        /// As such, the child widget must opt-in using the `AllowRawMut` trait.
        ///
        /// See [pass documentation](crate::doc::pass_system) for the pass order.
        pub fn get_raw_mut<Child: Widget + FromDynWidget + AllowRawMut + ?Sized>(
            &mut self,
            child: &mut WidgetPod<Child>,
        ) -> (&mut Child, RawCtx<'_>) {
            let node_mut = self
                .children
                .item_mut(child.id())
                .expect("get_mut: child not found");
            let child_ctx = RawCtx {
                global_state: self.global_state,
                parent_widget_state: self.widget_state,
                widget_state: &mut node_mut.item.state,
                children: node_mut.children,
                property_arena: self.property_arena,
            };

            let widget = Child::from_dyn_mut(&mut *node_mut.item.widget).unwrap();

            (widget, child_ctx)
        }

        /// Submits an action, which indicates that this widget requires something be handled
        /// by the application, such as user input.
        ///
        /// The `Action` type parameter should always be the `Self::Action` associated type
        /// of the widget you're calling this method from.
        /// Masonry will validate this, and this method may panic if this isn't the case.
        ///
        /// For further details see [`ErasedAction`].
        pub fn submit_action<Action: AnyDebug + Send>(&mut self, action: impl Into<Action>) {
            trace!("submit_action");
            let action = action.into();
            if action.type_id() != self.widget_state.action_type {
                #[cfg(debug_assertions)]
                let expected_type = self.widget_state.action_type_name;
                #[cfg(not(debug_assertions))]
                let expected_type = "<Self as Widget>::Action";

                debug_panic!(
                    "Trying to emit action of incorrect type `{}`. Expected type is `{}`.",
                    action.type_name(),
                    expected_type,
                );
                return;
            }
            self.global_state
                .actions
                .push((Box::new(action), self.widget_state.id));
        }

        /// Submits a type-erased action.
        ///
        /// Unlike [`Self::submit_action`], this method lets you submit an action with an
        /// arbitrary type, which may not match `Self::Action`.
        /// This may act as an escape hatch in some situations.
        ///
        /// For further details see [`ErasedAction`].
        pub fn submit_untyped_action(&mut self, action: ErasedAction) {
            trace!("submit_untyped_action");
            self.global_state
                .actions
                .push((action, self.widget_state.id));
        }

        /// Sets the IME cursor area in the widget's content-box coordinate space.
        ///
        /// When this widget is [focused] and [accepts text input], the reported IME area is sent
        /// to the platform. The area can be used by the platform to, for example, place a
        /// candidate box near that area, while ensuring the area is not obscured.
        ///
        /// If no IME area is set, then Masonry will use the widget's aligned border-box rect.
        ///
        /// [focused]: EventCtx::request_focus
        /// [accepts text input]: Widget::accepts_text_input
        pub fn set_ime_area(&mut self, ime_area: Rect) {
            let translation = self.widget_state.border_box_translation();
            self.widget_state.ime_area = Some(ime_area + translation);
        }

        /// Removes the IME cursor area.
        ///
        /// See [`set_ime_area`] for more details.
        ///
        /// [`set_ime_area`]: Self::set_ime_area
        pub fn clear_ime_area(&mut self) {
            self.widget_state.ime_area = None;
        }

        /// Sets the contents of the platform clipboard.
        ///
        /// For example, text widgets should call this for "cut" and "copy" user interactions.
        /// Note that we currently don't support the "Primary" selection buffer on X11/Wayland.
        pub fn set_clipboard(&mut self, contents: String) {
            trace!("set_clipboard");
            self.global_state
                .emit_signal(RenderRootSignal::ClipboardStore(contents));
        }

        /// Starts a window drag.
        ///
        /// Moves the window with the left mouse button until the button is released.
        pub fn drag_window(&mut self) {
            trace!("drag_window");
            self.global_state.emit_signal(RenderRootSignal::DragWindow);
        }

        /// Starts a window resize.
        ///
        /// Resizes the window with the left mouse button until the button is released.
        pub fn drag_resize_window(&mut self, direction: ResizeDirection) {
            trace!("drag_resize_window");
            self.global_state
                .emit_signal(RenderRootSignal::DragResizeWindow(direction));
        }

        /// Toggles the maximized state of the window.
        pub fn toggle_maximized(&mut self) {
            trace!("toggle_maximized");
            self.global_state
                .emit_signal(RenderRootSignal::ToggleMaximized);
        }

        /// Minimizes the window.
        pub fn minimize(&mut self) {
            trace!("minimize");
            self.global_state.emit_signal(RenderRootSignal::Minimize);
        }

        /// Exits the application.
        pub fn exit(&mut self) {
            trace!("exit");
            self.global_state.emit_signal(RenderRootSignal::Exit);
        }

        /// Shows the window menu at a specified position.
        pub fn show_window_menu(&mut self, position: LogicalPosition<f64>) {
            trace!("show_window_menu");
            self.global_state
                .emit_signal(RenderRootSignal::ShowWindowMenu(position));
        }

        /// Creates a new [subwindow] at a specified `position`.
        ///
        /// The given `position` must be in the window's coordinate space.
        ///
        /// # Panics
        ///
        /// If [`W::as_subwindow()`](Widget::as_subwindow) returns `None`.
        ///
        /// [subwindow]: crate::doc::masonry_concepts#subwindows
        pub fn create_subwindow<W: Widget + ?Sized>(
            &mut self,
            subwindow_type: SubwindowType,
            mut fallback_widget: NewWidget<W>,
            position: Point,
        ) -> SubwindowId {
            trace!("create_subwindow");

            if fallback_widget.widget.as_subwindow().is_none() {
                debug_panic!(
                    "cannot create subwindow of type {} - `Widget::as_subwindow()` returned None",
                    fallback_widget.widget.short_type_name()
                );
                return SubwindowId::next();
            }

            let subwindow_id = SubwindowId::next();
            self.global_state
                .emit_signal(RenderRootSignal::NewSubwindow(
                    subwindow_id,
                    subwindow_type,
                    fallback_widget.erased(),
                    position,
                ));
            subwindow_id
        }

        /// Creates a new [subwindow] at a specified `position`, and ties it to the current widget.
        ///
        /// The subwindow will be removed when the current widget is removed from the tree.
        /// A widget can only have one subwindow of any given type `W` at a time:
        /// if a widget creates two subwindows of the same type, the old subwindow will be removed.
        ///
        /// The given `position` must be in the window's coordinate space.
        ///
        /// # Panics
        ///
        /// If [`W::as_subwindow()`](Widget::as_subwindow) returns `None`.
        ///
        /// [subwindow]: crate::doc::masonry_concepts#subwindows
        pub fn create_attached_subwindow<W: Widget + ?Sized>(
            &mut self,
            subwindow_type: SubwindowType,
            mut fallback_widget: NewWidget<W>,
            position: Point,
        ) -> SubwindowId {
            trace!("create_attached_subwindow");

            if fallback_widget.widget.as_subwindow().is_none() {
                debug_panic!(
                    "cannot create subwindow of type {} - `Widget::as_subwindow()` returned None",
                    fallback_widget.widget.short_type_name()
                );
                return SubwindowId::next();
            }

            let self_id = self.widget_id();
            let type_id = TypeId::of::<W>();
            let subwindow_id = SubwindowId::next();

            let subwindows = self
                .global_state
                .attached_subwindows
                .entry(self_id)
                .or_default();
            if let Some(prev) = subwindows.insert(type_id, subwindow_id) {
                self.global_state.remove_subwindow(prev);
            }
            self.global_state
                .emit_signal(RenderRootSignal::NewSubwindow(
                    subwindow_id,
                    subwindow_type,
                    fallback_widget.erased(),
                    position,
                ));
            self.global_state
                .attached_subwindows_rev
                .insert(subwindow_id, (type_id, self_id));

            subwindow_id
        }

        /// Returns the attached subwindow created by this widget with the given type `W`.
        ///
        /// See [`Self::create_attached_subwindow`] for more details.
        pub fn get_attached_subwindow<W: Widget + ?Sized>(&self) -> Option<SubwindowId> {
            self.global_state
                .attached_subwindows
                .get(&self.widget_id())?
                .get(&TypeId::of::<W>())
                .copied()
        }

        /// Removes the subwindow with the specified widget as root.
        pub fn remove_subwindow(&mut self, id: SubwindowId) {
            trace!("remove_subwindow");
            self.global_state.remove_subwindow(id);
        }

        /// Repositions the subwindow with the specified widget as root.
        ///
        /// The given `position` must be in the window's coordinate space.
        pub fn reposition_subwindow(&mut self, id: SubwindowId, position: Point) {
            trace!("reposition_subwindow");
            self.global_state
                .emit_signal(RenderRootSignal::RepositionSubwindow(id, position));
        }
    }
);

impl UpdateCtx<'_> {
    /// Returns the nearest ancestor of this widget that is of type `W`, along with its `WidgetId`.
    ///
    /// This should only be called during [`WidgetAdded`](crate::core::Update::WidgetAdded).
    /// Calling it in other contexts will always return `None`.
    // FIXME: We should move this method out of `UpdateCtx` to avoid having this disclaimer.
    pub fn nearest_ancestor<W: Widget>(&self) -> Option<(&W, WidgetId)> {
        let mut list = self.ancestors;
        while let Some(node) = list {
            if let Some(widget) = W::from_dyn(node.widget) {
                return Some((widget, node.id));
            }
            list = node.parent;
        }
        None
    }
}

impl RegisterCtx<'_> {
    /// Registers a child widget.
    ///
    /// Container widgets should call this on all their children in
    /// their implementation of [`Widget::register_children`].
    pub fn register_child(&mut self, child: &mut WidgetPod<impl Widget + ?Sized>) {
        let Some(NewWidget {
            widget,
            subwindow_id,
            id,
            options,
            properties,
            property_stack_id,
            classes,
            tag,
            action_type,
            #[cfg(debug_assertions)]
            action_type_name,
        }) = child.take_inner()
        else {
            return;
        };

        #[cfg(debug_assertions)]
        {
            self.registered_ids.push(id);
        }

        let state = WidgetState::new(
            id,
            subwindow_id,
            widget.short_type_name(),
            options,
            action_type,
            property_stack_id,
            #[cfg(debug_assertions)]
            action_type_name,
        );

        if let Some(tag) = tag {
            let entry = self.global_state.widget_tags.entry(tag);

            let Entry::Vacant(vacant_entry) = entry else {
                debug_panic!("Tag '{tag}' already exists in the widget tree");
                return;
            };

            vacant_entry.insert(id);
        }

        let node = WidgetArenaNode {
            widget: widget.as_box_dyn(),
            state,
            properties,
            class_set: ClassSet {
                classes,
                ..ClassSet::default()
            },
        };
        self.children.insert(id, node);
    }
}

impl Drop for RawCtx<'_> {
    fn drop(&mut self) {
        self.parent_widget_state.merge_up(self.widget_state);
    }
}

// --- MARK: DEBUG PAINT
impl PaintCtx<'_> {
    /// Whether debug paint is enabled.
    ///
    /// If this property is set, your widget may draw additional debug information
    /// (such as the position of the text baseline).
    /// These should normally use the [debug color][Self::debug_color] for this widget.
    /// Please note that when debug painting is enabled, each widget's layout boundaries are
    /// outlined by Masonry, so you should avoid duplicating that.
    ///
    /// Debug paint can be enabled by setting the environment variable `MASONRY_DEBUG_PAINT`.
    pub fn debug_paint_enabled(&self) -> bool {
        self.global_state.debug_paint
    }

    /// A color used for debug painting in this widget.
    ///
    /// This is normally used to paint additional debugging information
    /// when debug paint is enabled, see [`Self::debug_paint_enabled`].
    pub fn debug_color(&self) -> Color {
        get_debug_color(self.widget_id().to_raw())
    }
}