1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
//! The tree, the scene stack, and the compositor that turns them into pixels.
use alloc::boxed::Box;
use alloc::vec;
use alloc::vec::{Drain, Vec};
use denise::{
BufferAge, Color, DamageTracker, ElementState, InputEvent, KeyCode, MAX_DAMAGE_RECTS,
MAX_TRACKED_FRAMES, Modifiers, Pen, Point, Rect, Role, Size, Theme,
};
#[cfg(feature = "raster")]
use denise::{Frame, Surface, SurfaceError};
#[cfg(feature = "raster")]
use denise_render::Canvas;
use denise_text::{FontId, GlyphSource, TextEngine};
use crate::arena::{Arena, NodeId};
use crate::cursor::{Cursor, CursorImage};
use crate::node::{Node, Popup, Scene};
use crate::toast::Toasts;
use crate::tooltip::Tooltip;
/// Space between a popup and its anchor, in pixels. Small on purpose: a
/// dropdown visually belongs to its button, and a gap wide enough to see the
/// page through reads as two unrelated panels.
const POPUP_GAP: i32 = 4;
use crate::anchor::{self, Anchors, Dock};
use crate::motion::{Motion, Wake};
use crate::widget::{
Event, EventCtx, Handled, MeasureCtx, Measured, Offer, PaintCtx, VisualState, Void, Widget,
};
use crate::widgets::describe::{DynDescribe, Property, PropertyError, Value};
/// A drawer's life, tracked by the tree.
#[derive(Clone, Copy, Debug)]
struct DrawerState {
container: NodeId,
closing: bool,
}
/// A shelf's node and whether it is on its way out. The same two facts a drawer
/// keeps, for the same reason: the slide has to finish before the node goes.
#[derive(Clone, Copy)]
struct ShelfState {
container: NodeId,
closing: bool,
}
/// How long a drawer takes to slide in or out.
const DRAWER_MS: u64 = 200;
/// How long a shelf takes to slide in or out. A drawer's, because they are
/// the same motion and two numbers would only drift apart.
const SHELF_MS: u64 = DRAWER_MS;
/// A shelf sorts above ordinary content in its scene. Nothing else in the
/// tree sets `z`, so any positive number would do; this one is far enough
/// from zero to leave room underneath for an application that wants some.
const SHELF_Z: i32 = 1_000;
/// The dim behind a drawer: enough to say "modal", light enough to keep the
/// page readable behind it.
const DRAWER_DIM: u8 = 120;
/// One layout being carried from `from` to `to` by the tree.
#[derive(Clone, Copy, Debug)]
struct LayoutTween {
id: NodeId,
from: Rect,
to: Rect,
start_ms: u64,
duration_ms: u64,
}
impl LayoutTween {
/// Where the journey has got to at `now_ms`: integer, monotonic, and
/// exactly `to` from the duration onward.
fn at(&self, now_ms: u64) -> Rect {
let elapsed = now_ms.saturating_sub(self.start_ms);
if elapsed >= self.duration_ms || self.duration_ms == 0 {
return self.to;
}
let lerp = |a: i32, b: i32| -> i32 {
a + (i64::from(b - a) * elapsed as i64 / self.duration_ms as i64) as i32
};
Rect::new(
lerp(self.from.x, self.to.x),
lerp(self.from.y, self.to.y),
lerp(self.from.width, self.to.width),
lerp(self.from.height, self.to.height),
)
}
}
/// A frame whose damage was nothing but one viewport scrolling.
///
/// The damage tracker unions, so a hover highlight *inside* a scrolled viewport
/// vanishes into the viewport's own rectangle and cannot be told apart from it
/// afterwards. Scrolling by moving pixels rather than redrawing them needs
/// exactly that told apart, so it is recorded as it happens rather than
/// reconstructed later. `None` in the ring means "something else changed too",
/// which is most frames.
#[derive(Clone, Copy, PartialEq, Eq)]
struct Scrolled {
/// The viewport that moved, or the widget that moved its own content.
node: NodeId,
/// How far its content moved, this frame.
by: Point,
/// Where the moved content was, so a relayout in the meantime disqualifies
/// it. A viewport's clip; whatever part of itself a widget said moved.
clip: Rect,
}
/// A retained tree of widgets, a stack of scenes, and the damage they generate.
///
/// `M` is the application's message type. Widgets emit `M`; the application drains
/// them with [`Ui::drain_messages`] and decides what they mean. Nothing calls back
/// into the application mid-traversal, so there is no borrow to fight and no
/// `Rc<RefCell<_>>` anywhere in the path.
///
/// # Damage is the tree's job, not the application's
///
/// This is the part worth reading. Every route into mutable widget state runs
/// through the tree, and every one of them marks the node dirty:
///
/// - [`Ui::widget_mut`] invalidates on access, before you have even changed
/// anything. Taking `&mut` to a widget *is* the declaration that it will look
/// different.
/// - Hover, press, focus and enabled are tracked by the tree, so a widget cannot
/// forget to invalidate on a state it does not own.
/// - [`Handled::Yes`] from `on_event` invalidates the node.
/// - Moving, resizing, showing, hiding, adding or removing a node damages the
/// rectangles it vacated and the ones it now occupies.
///
/// The alternative — the application deciding what changed and telling the damage
/// tracker — is where the classic bug lives: some piece of state that decides the
/// pixels is left out of the comparison, and the screen keeps a stale colour until
/// something unrelated repaints over it. That bug is not fixed here so much as made
/// unrepresentable.
pub struct Ui<M: 'static> {
nodes: Arena<Node<M>>,
scenes: Vec<Scene>,
/// Flattened paint order across every scene: parents before children, siblings
/// by z. Rebuilt only on structural or z-order change, never per frame.
order: Vec<NodeId>,
/// Exclusive end index in `order` for each scene.
scene_end: Vec<usize>,
order_dirty: bool,
size: Size,
theme: Theme,
text: TextEngine,
damage: DamageTracker,
/// What each of the last few frames was, when it was only a scroll — the
/// same ring the damage keeps, advanced in step with it. See [`Scrolled`].
scrolled: [Option<Scrolled>; MAX_TRACKED_FRAMES],
/// This frame's slot in that ring.
scroll_head: usize,
pointer: Point,
hovered: Option<NodeId>,
pressed: Option<NodeId>,
/// A touch that landed on a scrollable's background rather than on any
/// interactive widget: subsequent moves drag the scroll. A touch that lands
/// on a widget belongs to the widget — stealing an in-progress press for
/// scrolling is gesture disambiguation, deliberately not attempted yet.
touch_scroll: Option<(NodeId, Point)>,
focused: Option<NodeId>,
cursor: Cursor,
messages: Vec<M>,
now_ms: u64,
next_wake: Option<u64>,
/// Nodes that have asked to animate. Emptied by their own `animate` answers:
/// a widget returning [`Wake::Never`] drops out. Kept deliberately small and
/// deliberately visible — [`Ui::animating`] exists so a test can assert a
/// tree at rest holds nobody awake.
animating: Vec<NodeId>,
/// How fast everything in the tree animates, and whether it does at all.
/// The one place the rate is decided — see [`Motion`].
motion: Motion,
/// Layout tweens in flight: nodes the *tree* is carrying from one
/// rectangle to another. Bounded by construction — every tween has a
/// duration and is removed at arrival — and counted by [`Ui::animating`]
/// alongside the widgets' animations, so the idle-cost evidence covers
/// both kinds of motion.
tweens: Vec<LayoutTween>,
/// The drawer, while one is up: its container, and whether it is on the
/// way out. The scene pops when the closing slide lands — the tree
/// watching its own tween, rather than a public completion hook nobody
/// has asked for yet.
drawer: Option<DrawerState>,
shelf: Option<ShelfState>,
focus_changed: Option<Option<NodeId>>,
occluded: Option<Rect>,
/// Transient notifications. Not nodes, for the reasons in [`crate::toast`].
toasts: Toasts,
/// The hover-dwell bubble. Not a node and not a widget — see
/// [`crate::tooltip`] for why.
tooltip: Tooltip,
/// Whether the tree still gets to decide the cursor's visibility. Cleared by
/// the first `show_cursor`, which is a host taking the decision over.
cursor_auto: bool,
}
impl<M: 'static> Ui<M> {
/// Creates a tree covering a surface of `size`, with one base scene.
pub fn new(size: Size, theme: Theme) -> Self {
let mut nodes = Arena::new();
let root = nodes.insert(Node::new(Box::new(Void), Rect::from_size(size), 0));
Self {
nodes,
scenes: vec![Scene {
root,
dim: 0,
popup: None,
}],
order: Vec::new(),
scene_end: Vec::new(),
order_dirty: true,
size,
theme,
text: TextEngine::new(),
damage: DamageTracker::new(size),
scrolled: [None; MAX_TRACKED_FRAMES],
scroll_head: 0,
pointer: Point::ZERO,
hovered: None,
pressed: None,
touch_scroll: None,
focused: None,
cursor: Cursor::default(),
tooltip: Tooltip::new(),
toasts: Toasts::new(),
messages: Vec::new(),
now_ms: 0,
next_wake: None,
animating: Vec::new(),
motion: Motion::default(),
tweens: Vec::new(),
drawer: None,
shelf: None,
focus_changed: None,
occluded: None,
cursor_auto: true,
}
}
/// Surface extent the tree lays out against.
#[inline]
pub const fn size(&self) -> Size {
self.size
}
/// The active theme.
#[inline]
pub const fn theme(&self) -> &Theme {
&self.theme
}
/// Swaps the theme. Every colour on screen may have changed, so this damages
/// the whole surface — the one case where a full repaint is the honest answer.
pub fn set_theme(&mut self, theme: Theme) {
self.theme = theme;
self.damage.add_full();
}
/// Fonts and the glyph cache.
#[inline]
pub const fn text(&self) -> &TextEngine {
&self.text
}
/// Fonts and the glyph cache, mutably. Measuring fills the cache, so this is
/// how an application asks how wide a string will be before laying it out.
#[inline]
pub const fn text_mut(&mut self) -> &mut TextEngine {
&mut self.text
}
/// Registers a font and returns its id.
///
/// The built-in bitmap font is always registered as `FontId(0)`, so a widget
/// that names no font has one regardless of what else was loaded. Everything
/// on screen may change width, so this damages the whole surface.
pub fn add_font(&mut self, source: alloc::boxed::Box<dyn GlyphSource>) -> FontId {
let id = self.text.add_font(source);
self.damage.add_full();
id
}
/// Draws every widget that names no font in this face.
///
/// The two lines that give a tree a real face:
///
/// ```no_run
/// # use denise::{Size, theme};
/// # use denise_ui::{Ui, Void};
/// # fn load() -> alloc::boxed::Box<dyn denise_text::GlyphSource> { unimplemented!() }
/// # extern crate alloc;
/// # let mut ui: Ui<Void> = Ui::new(Size::new(64, 64), theme::DARK);
/// let id = ui.add_font(load());
/// ui.set_default_font(id);
/// ```
///
/// Every `TextStyle` in this crate names [`FontId::DEFAULT`], which is a
/// redirection rather than a face — so this reaches every widget already
/// built and every widget built afterwards, without any of them knowing.
/// Before it existed, [`add_font`](Ui::add_font) registered a face nothing
/// referred to, and an application had to thread a `TextStyle` through
/// everything it constructed; that was [#130].
///
/// An id that was never registered is ignored, because a panel that drew
/// nothing would be worse than one that drew the bitmap face.
///
/// [#130]: https://github.com/bisand/denise/issues/130
pub fn set_default_font(&mut self, font: FontId) {
self.text.set_default_font(font);
// Every glyph on screen may be a different shape now.
self.damage.add_full();
}
/// Which face a widget that names no font is drawn in.
#[inline]
pub const fn default_font(&self) -> FontId {
self.text.default_font()
}
/// The cursor sprite.
#[inline]
pub const fn cursor(&self) -> &Cursor {
&self.cursor
}
/// Replaces the cursor sprite, damaging both shapes' footprints.
pub fn set_cursor_image(&mut self, image: &'static CursorImage) {
self.dirty(self.cursor.bounds());
self.cursor.image = image;
self.dirty(self.cursor.bounds());
}
/// Shows or hides the cursor sprite, and stops the tree deciding for itself.
///
/// Left alone, the sprite starts hidden, reveals itself on the first pointer
/// motion and hides again when a finger arrives — which is what a panel with
/// no window system underneath it wants, because nothing else is going to
/// draw a pointer.
///
/// Calling this takes that policy over for good, in whichever direction. That
/// matters for an embedded host: a Win32 child window or an `NSView` already
/// has a system cursor, and Denise compositing a second one that lags it by a
/// frame is worse than drawing none. Such a host calls `show_cursor(false)`
/// once at startup and never thinks about it again.
pub fn show_cursor(&mut self, visible: bool) {
self.cursor_auto = false;
if self.cursor.visible == visible {
return;
}
self.dirty(self.cursor.bounds());
self.cursor.visible = visible;
self.dirty(self.cursor.bounds());
}
// ---------------------------------------------------------------- scenes
/// Root node of the base scene.
#[inline]
pub fn root(&self) -> NodeId {
self.scenes[0].root
}
/// Root node of the topmost scene: the one that receives input.
#[inline]
pub fn top_root(&self) -> NodeId {
self.scenes[self.scenes.len() - 1].root
}
/// Number of scenes on the stack, always at least one.
#[inline]
pub fn scene_count(&self) -> usize {
self.scenes.len()
}
/// Pushes a scene over the current one and returns its root.
///
/// `dim` is the alpha of a black backdrop painted under the new scene, `0` for
/// none and `128` for a conventional modal veil. The backdrop is painted per
/// damage region rather than over the whole surface, which matters: a
/// full-screen alpha fill measured 63% of a 60 Hz frame budget on a Pi 3, so a
/// dialog that repaints its own caret must not drag a megapixel of blending
/// along with it.
///
/// The new scene takes all input. Nothing underneath is hittable, focusable or
/// reachable by Tab until it is popped — that is what makes it modal, and it is
/// a property of the stack rather than something each dialog has to enforce.
pub fn push_scene(&mut self, dim: u8) -> NodeId {
let index = self.scenes.len();
let root = self
.nodes
.insert(Node::new(Box::new(Void), Rect::from_size(self.size), index));
self.scenes.push(Scene {
root,
dim,
popup: None,
});
self.order_dirty = true;
self.set_focus(None);
self.cancel_press();
self.set_hovered(None);
if dim > 0 {
self.damage.add_full();
}
root
}
/// Pushes a popup: a scene anchored to a node, dismissed by clicking away.
///
/// The returned container is placed beside `anchor` on the preferred `side`
/// — flipping to the other side when the surface has no room, see
/// [`anchored`](crate::overlay::anchored) — and the caller adds content to
/// it, exactly as [`Tabs`](crate::widgets::Tabs) leaves pages to the
/// caller. The container itself draws nothing; the first child is usually a
/// [`Panel`](crate::widgets::Panel) filling it.
///
/// What makes it a popup rather than a plain scene:
///
/// - **A press outside the container closes it, and is swallowed.** The
/// press must not also reach whatever is underneath — a dropdown that
/// closes *and* activates the button behind it is the classic bug. The
/// swallowing is structural: input only ever reaches the topmost scene,
/// so the press has nowhere else to go; closing consumes it entirely.
/// - **Escape closes it**, before the focused widget sees the key.
/// - **Focus returns to the anchor** on close, however it closes.
///
/// There is no dimming: a popup is not a modal. A dialog that takes over is
/// [`Ui::push_scene`] with a dim, and a tooltip needs no scene at all —
/// just a non-interactive node placed with `anchored` at a high z.
///
/// A popup over a modal is ordinary nesting and works; the popup's own
/// scene captures input while it is up, and popping it returns input to
/// the modal. Popups do not re-anchor when the surface is resized — they
/// are transient, and the honest response to a resize is closing them.
///
/// Returns `None` when `anchor` does not exist.
pub fn push_popup(
&mut self,
anchor: NodeId,
size: Size,
side: crate::overlay::Side,
) -> Option<NodeId> {
let bounds = self.bounds(anchor)?;
self.push_popup_at(anchor, bounds, size, side)
}
/// Pushes a popup beside an explicit rectangle rather than beside the whole
/// of `anchor`.
///
/// Everything [`push_popup`](Ui::push_popup) says still holds — this is that
/// method with the placement rectangle handed in — and `anchor` is still
/// where focus returns when the popup closes.
///
/// Two things need it, and neither can say what it wants with a node:
///
/// - **A menu bar**, whose menu belongs under *one title* and not under the
/// left edge of the whole strip. The titles are drawn by one widget, so
/// there is no node to name.
/// - **A context menu**, which belongs where the pointer was. A one-pixel
/// rectangle at the click is the anchor, and the popup opens beside it
/// like anything else — flipping near an edge for free.
///
/// The rectangle is in surface coordinates, the same as
/// [`bounds`](Ui::bounds) reports. Returns `None` when `anchor` does not
/// exist.
pub fn push_popup_at(
&mut self,
anchor: NodeId,
at: Rect,
size: Size,
side: crate::overlay::Side,
) -> Option<NodeId> {
if !self.contains(anchor) {
return None;
}
let rect = crate::overlay::anchored(self.size, at, size, side, POPUP_GAP);
let root = self.push_scene(0);
let container = self
.add(root, Void, rect)
.expect("a scene root can always take a child");
self.scenes.last_mut().expect("just pushed").popup = Some(Popup { anchor, container });
Some(container)
}
/// Closes the topmost scene if it is a popup, returning focus to its
/// anchor. Returns `false` when the top scene is not a popup.
///
/// This is what a press outside the popup and the Escape key call; an
/// application closes a popup the same way after acting on a selection.
pub fn close_popup(&mut self) -> bool {
match self.scenes.last() {
Some(scene) if scene.popup.is_some() => self.pop_scene(),
_ => false,
}
}
/// Slides a panel in from an edge of the screen, over a dimmed backdrop,
/// and returns its container for the application to fill.
///
/// A drawer is modality plus motion, and both halves already exist: this
/// composes [`Ui::push_scene`] with [`Ui::animate_layout`]. `size` is the
/// drawer's width for [`Side::Before`](crate::Side::Before)/[`Side::After`](crate::Side::After) and its height for
/// [`Side::Above`](crate::Side::Above)/[`Side::Below`](crate::Side::Below); the other dimension spans the screen.
///
/// Escape closes it, a press on the dim closes it, and
/// [`Ui::close_drawer`] closes it from the application — all by sliding
/// out first: the scene pops when the slide lands, and focus returns to
/// where it was, [`Ui::push_popup`]'s conventions. One drawer at a time;
/// pushing over an open one returns `None`.
pub fn push_drawer(&mut self, side: crate::overlay::Side, size: i32) -> Option<NodeId> {
if self.drawer.is_some() {
return None;
}
let (resting, offstage) = self.edge_rects(side, size);
let root = self.push_scene(DRAWER_DIM);
let container = self
.add(root, Void, offstage)
.expect("a scene root can always take a child");
self.animate_layout(container, resting, DRAWER_MS);
self.drawer = Some(DrawerState {
container,
closing: false,
});
Some(container)
}
/// Slides the drawer out; the scene pops when the slide lands.
///
/// Returns `false` when no drawer is up. Calling again while one is
/// already closing does nothing — the slide finishes on its own.
pub fn close_drawer(&mut self) -> bool {
let Some(state) = self.drawer else {
return false;
};
if state.closing {
return true;
}
let Some(layout) = self.layout(state.container) else {
self.drawer = None;
return false;
};
let screen = Rect::from_size(self.size);
// Back out the way it came in: whichever screen edge is nearest.
let offstage = if layout.x <= 0 && layout.width < screen.width {
Rect::new(-layout.width, layout.y, layout.width, layout.height)
} else if layout.right() >= screen.width && layout.width < screen.width {
Rect::new(screen.width, layout.y, layout.width, layout.height)
} else if layout.y <= 0 {
Rect::new(layout.x, -layout.height, layout.width, layout.height)
} else {
Rect::new(layout.x, screen.height, layout.width, layout.height)
};
self.animate_layout(state.container, offstage, DRAWER_MS);
self.drawer = Some(DrawerState {
closing: true,
..state
});
true
}
/// Whether a drawer is up, closing included.
#[inline]
pub fn drawer_open(&self) -> bool {
self.drawer.is_some()
}
/// Where a panel of `size` rests against `side`, and where it waits offstage.
///
/// The full width or height of the screen in the other dimension. Shared by
/// [`Ui::push_drawer`] and [`Ui::push_shelf`], which differ in everything
/// except the arithmetic.
fn edge_rects(&self, side: crate::overlay::Side, size: i32) -> (Rect, Rect) {
use crate::overlay::Side;
let screen = Rect::from_size(self.size);
let size = size.clamp(1, screen.width.max(screen.height));
match side {
Side::Before => (
Rect::new(0, 0, size, screen.height),
Rect::new(-size, 0, size, screen.height),
),
Side::After => (
Rect::new(screen.width - size, 0, size, screen.height),
Rect::new(screen.width, 0, size, screen.height),
),
Side::Above => (
Rect::new(0, 0, screen.width, size),
Rect::new(0, -size, screen.width, size),
),
Side::Below => (
Rect::new(0, screen.height - size, screen.width, size),
Rect::new(0, screen.height, screen.width, size),
),
}
}
/// Slides a panel in from an edge and leaves everything else alone.
///
/// A drawer is modality plus motion; a shelf is the motion without the
/// modality. It pushes no scene, so **focus does not move**, input still
/// reaches what is underneath, and a press outside does not dismiss it.
/// The application closes it, because the application is the only thing
/// that knows when it is done.
///
/// That is the whole difference, and it is what an on-screen keyboard
/// needs: it exists to type into a field that must stay focused while it
/// is up. A status strip, a notification shade and a media bar over a
/// video want the same thing.
///
/// The container sits above ordinary content in the base scene, painting over
/// it — and *under* any scene pushed later, which is why a modal covers a
/// shelf rather than fighting it. One at a time; pushing over an open one
/// returns `None`.
///
/// `size` is the width for [`Side::Before`](crate::Side::Before) and
/// [`Side::After`](crate::Side::After), the height for
/// [`Side::Above`](crate::Side::Above) and [`Side::Below`](crate::Side::Below).
///
/// ```
/// # use denise::{Size, theme};
/// # use denise_ui::{Side, Ui};
/// # enum Msg { Noop }
/// # let mut ui: Ui<Msg> = Ui::new(Size::new(800, 480), theme::DARK);
/// let shelf = ui.push_shelf(Side::Below, 200).expect("nothing else is up");
/// assert!(ui.shelf_open());
/// ```
pub fn push_shelf(&mut self, side: crate::overlay::Side, size: i32) -> Option<NodeId> {
if self.shelf.is_some() {
return None;
}
let (resting, offstage) = self.edge_rects(side, size);
let base = self.root();
let container = self.add(base, Void, offstage)?;
self.set_z(container, SHELF_Z);
self.animate_layout(container, resting, SHELF_MS);
// Where it will be, not where it is: something focused during the slide
// should be revealed clear of the keyboard's resting place rather than
// scrolled twice.
self.occluded = Some(resting);
self.shelf = Some(ShelfState {
container,
closing: false,
});
Some(container)
}
/// Slides the shelf out; the node is removed when the slide lands.
///
/// Returns `false` when none is up. Calling again while one is already
/// closing does nothing — the slide finishes on its own.
pub fn close_shelf(&mut self) -> bool {
let Some(state) = self.shelf else {
return false;
};
if state.closing {
return true;
}
let Some(layout) = self.layout(state.container) else {
self.shelf = None;
return false;
};
let screen = Rect::from_size(self.size);
// Back out the way it came in: whichever screen edge is nearest.
let offstage = if layout.x <= 0 && layout.width < screen.width {
Rect::new(-layout.width, layout.y, layout.width, layout.height)
} else if layout.right() >= screen.width && layout.width < screen.width {
Rect::new(screen.width, layout.y, layout.width, layout.height)
} else if layout.y <= 0 {
Rect::new(layout.x, -layout.height, layout.width, layout.height)
} else {
Rect::new(layout.x, screen.height, layout.width, layout.height)
};
self.animate_layout(state.container, offstage, SHELF_MS);
// Given back when it starts leaving rather than when it lands: it is on
// its way out, and a field focused now belongs on the whole screen.
self.occluded = None;
self.shelf = Some(ShelfState {
closing: true,
..state
});
true
}
/// Where focus went since this was last asked, or `None` if it has not moved.
///
/// Drained on read, like [`Ui::drain_messages`], and read in the same place:
/// the application's turn, once a frame. `Some(None)` is focus *lost* —
/// somebody clicked the background — which is a different event from focus
/// not having moved, and the two are worth telling apart.
///
/// The tree reports the movement and takes no view on what it means. Whether
/// a node deserves an on-screen keyboard is a question only the application
/// can answer, and answering it here would mean `denise-ui` knowing what a
/// keyboard is.
///
/// ```
/// # use denise::{Rect, Size, theme};
/// # use denise_ui::{Ui, widgets::TextInput};
/// # #[derive(Clone, Debug)] enum Msg { Noop }
/// # let mut ui: Ui<Msg> = Ui::new(Size::new(800, 480), theme::DARK);
/// # let root = ui.root();
/// let field = ui.add(root, TextInput::new(), Rect::new(0, 0, 200, 40)).unwrap();
/// ui.focus(Some(field));
/// assert_eq!(ui.focus_changed(), Some(Some(field)));
/// assert_eq!(ui.focus_changed(), None, "drained on read");
/// ```
pub fn focus_changed(&mut self) -> Option<Option<NodeId>> {
self.focus_changed.take()
}
/// The part of the surface a shelf is covering, if one is up.
///
/// A shelf is the one thing that hides content without capturing input, so
/// it is the one thing the tree has to remember is in the way. Revealing a
/// focused node already scrolls clear of it — see
/// [`Ui::focus_changed`] for what an application does with the movement —
/// and this is for the case scrolling cannot fix: a layout with fixed
/// rectangles, where getting a field out from under the keyboard means the
/// application moving something.
///
/// The resting rectangle from the moment the shelf is pushed, so a reveal
/// during the slide aims where the shelf is going rather than where it has
/// got to. `None` from the moment it starts leaving.
#[inline]
pub const fn occluded(&self) -> Option<Rect> {
self.occluded
}
/// Whether a shelf is up, closing included.
#[inline]
pub fn shelf_open(&self) -> bool {
self.shelf.is_some()
}
/// Whether a popup — a dropdown's option list, a tooltip's anchor menu — is up.
///
/// The companion to [`drawer_open`](Ui::drawer_open), and it exists for the
/// same reason: these two and only these two make the tree claim Escape. An
/// application that binds Escape itself asks both before acting, so a key that
/// should dismiss a dropdown does not quit the program instead.
#[inline]
pub fn popup_open(&self) -> bool {
self.scenes.last().is_some_and(|s| s.popup.is_some())
}
/// Pops the topmost scene and everything in it. The base scene cannot be
/// popped; returns `false` if that is all there is.
///
/// A popped popup returns focus to its anchor — through here, so it holds
/// however the popup is closed.
pub fn pop_scene(&mut self) -> bool {
if self.scenes.len() <= 1 {
return false;
}
self.ensure_order();
let scene = self.scenes.pop().expect("checked non-empty");
let start = if self.scenes.is_empty() {
0
} else {
self.scene_end[self.scenes.len() - 1]
};
// Repaint exactly what the scene covered: every node's clip, plus the whole
// surface if it was dimming what was underneath.
if scene.dim > 0 {
self.damage.add_full();
} else {
for i in start..self.order.len() {
let id = self.order[i];
if let Some(node) = self.nodes.get(id) {
let clip = node.clip;
self.dirty(clip);
}
}
}
self.drop_subtree(scene.root);
self.order_dirty = true;
self.set_focus(None);
self.cancel_press();
self.set_hovered(None);
if let Some(popup) = scene.popup {
// Focus goes back where the popup came from, not to nothing: a
// keyboard user who opened a dropdown and pressed Escape is
// standing exactly where they were before it opened.
self.focus(Some(popup.anchor));
}
true
}
// ------------------------------------------------------------------ tree
/// Adds `widget` under `parent`, positioned relative to the parent's origin.
///
/// Returns `None` if `parent` no longer exists.
pub fn add(&mut self, parent: NodeId, widget: impl Widget<M>, layout: Rect) -> Option<NodeId> {
let scene = self.nodes.get(parent)?.scene;
let id = self
.nodes
.insert(Node::new(Box::new(widget), layout, scene));
self.nodes[id].parent = Some(parent);
self.nodes[parent].children.push(id);
self.sort_children(parent);
// Into a stack, a new child pushes its siblings down; the reflow and
// the damage have to cover them, not just the newcomer.
let root = self.reflow_root(id);
self.reflow(root);
self.damage_subtree(root);
self.order_dirty = true;
Some(id)
}
/// Removes a node and its descendants. Scene roots cannot be removed this way;
/// use [`Ui::pop_scene`].
pub fn remove(&mut self, id: NodeId) -> bool {
if !self.nodes.contains_key(id) || self.scenes.iter().any(|s| s.root == id) {
return false;
}
self.damage_subtree(id);
let parent = self.nodes[id].parent;
if let Some(parent) = parent
&& let Some(node) = self.nodes.get_mut(parent)
{
node.children.retain(|&c| c != id);
}
self.drop_subtree(id);
// Out of a stack, the siblings below close the gap.
if let Some(parent) = parent
&& self.nodes.get(parent).is_some_and(|n| n.stack.is_some())
{
self.reflow(parent);
self.damage_subtree(parent);
}
self.order_dirty = true;
true
}
/// Returns `true` if the node still exists.
#[inline]
pub fn contains(&self, id: NodeId) -> bool {
self.nodes.contains_key(id)
}
/// Absolute bounds of a node, before ancestor clipping.
#[inline]
pub fn bounds(&self, id: NodeId) -> Option<Rect> {
self.nodes.get(id).map(|n| n.bounds)
}
/// Position and extent relative to the parent.
#[inline]
pub fn layout(&self, id: NodeId) -> Option<Rect> {
self.nodes.get(id).map(|n| n.layout)
}
/// Moves or resizes a node, damaging the rectangles it left and the ones it
/// now occupies.
/// Marks a node as a viewport the tree may scroll: wheel over it, page
/// keys inside it, and reveal requests from its content all move its
/// [`Ui::scroll`] offset. Content is clipped to the node either way — this
/// flag is about who may *move* it.
///
/// Explicit rather than inferred from overflowing content, so a panel with
/// a decoratively clipped child does not start moving under the wheel.
pub fn set_scrollable(&mut self, id: NodeId, scrollable: bool) {
if let Some(node) = self.nodes.get_mut(id) {
node.scrollable = scrollable;
}
}
/// Shows a transient notification, which fades in, holds and goes by itself.
///
/// The overlay counterpart of [`Alert`](crate::widgets::Alert): an alert
/// sits *in* the layout where the thing it is about would be, and a toast
/// is the same message when there is nowhere in the layout to put it. It is
/// not a node, so it never takes focus, never appears in the tab order and
/// nothing has to remove it.
///
/// A press inside a toast dismisses it **and is swallowed**, so somebody
/// clearing a notification does not also press the button it was covering.
///
/// It costs almost nothing while it holds: the tree asks to be woken once,
/// at the instant the fade-out starts. Only the fades draw frames.
pub fn toast(&mut self, text: impl Into<alloc::string::String>, role: Role) {
self.toast_for(text, role, crate::toast::HOLD_MS);
}
/// A toast that holds for a stated time before fading.
///
/// For the message somebody needs longer to read, or the one that should
/// barely register. The fades are fixed either way.
pub fn toast_for(&mut self, text: impl Into<alloc::string::String>, role: Role, hold_ms: u64) {
self.toasts.push(text.into(), role, hold_ms, self.now_ms);
self.damage_toasts();
// A toast added between ticks must not wait for an unrelated event to
// appear: the loop may be blocked on input right now.
self.next_wake = Some(self.now_ms);
}
/// How many notifications are on screen.
#[inline]
pub fn toasts(&self) -> usize {
self.toasts.len()
}
/// Removes every notification, read or not.
pub fn clear_toasts(&mut self) {
if self.toasts.len() == 0 {
return;
}
self.damage_toasts();
self.toasts.clear();
}
/// Shows `text` when the pointer rests on this node.
///
/// A **pointer** affordance: it needs hover, and a touchscreen has none, so
/// on a touch-only panel this does nothing at all. That is the honest
/// outcome rather than a gap — the panels that want tooltips are the
/// mouse-driven HMIs and the controls embedded in desktop applications
/// where every other control has one.
///
/// The tree owns everything else about it: the dwell delay, the placement
/// (below the node, flipping above near an edge), the dismissal on any
/// press or key, and the drawing — above every widget, below the cursor.
/// It is not a node, so it is never hit-tested and never takes focus.
pub fn set_tooltip(&mut self, id: NodeId, text: impl Into<alloc::string::String>) {
if let Some(node) = self.nodes.get_mut(id) {
node.tooltip = Some(text.into());
}
}
/// The size every tooltip's text is drawn at, in physical pixels.
///
/// The one thing about a tooltip the tree does not decide for itself, and it
/// has to be sayable for the same reason a widget's own text size does: the
/// tree has no idea what the display's scale factor is, and a
/// scale-aware application multiplies its sizes once, at construction. A
/// tooltip left at the default on a 2x display is the only thing on the
/// screen still drawn at half size — which is exactly what it was on the
/// designer until this existed.
///
/// Takes effect on the next bubble; one already on screen keeps the size it
/// was measured at, because its footprint is what the damage tracker was
/// told about.
pub fn set_tooltip_size(&mut self, size_px: u16) {
self.tooltip.set_size(size_px);
}
/// Removes a node's tooltip.
pub fn clear_tooltip(&mut self, id: NodeId) {
if let Some(node) = self.nodes.get_mut(id) {
node.tooltip = None;
}
if self.hovered == Some(id) {
if self.tooltip.is_shown() {
self.damage_tooltip();
}
self.tooltip.dismiss();
}
}
/// How far a node's content is scrolled. `Point::ZERO` until somebody
/// scrolls.
pub fn scroll(&self, id: NodeId) -> Point {
self.nodes.get(id).map_or(Point::ZERO, |n| n.scroll)
}
/// The furthest a node can scroll: how far its content extends past its
/// own rectangle, axis by axis. Zero when everything fits.
pub fn max_scroll(&self, id: NodeId) -> Point {
let Some(node) = self.nodes.get(id) else {
return Point::ZERO;
};
let mut right = 0;
let mut bottom = 0;
match node.stack {
None => {
for &child in &node.children {
if let Some(child) = self.nodes.get(child) {
right = right.max(child.layout.right());
bottom = bottom.max(child.layout.bottom());
}
}
}
// A stack places children at the running y, not at their layout's,
// so the content's extent is the same arithmetic `reflow` runs: the
// visible heights plus the gaps between them. Reading the layouts
// here would make a scrollable stacked column — a settings page of
// cards — report almost no range at all.
Some(spacing) => {
let mut running = 0i32;
let mut any = false;
for &child in &node.children {
if let Some(child) = self.nodes.get(child)
&& child.visible
{
right = right.max(child.layout.right());
running = running
.saturating_add(child.layout.height.max(0))
.saturating_add(spacing);
any = true;
}
}
if any {
bottom = running - spacing;
}
}
}
Point::new(
(right - node.layout.width).max(0),
(bottom - node.layout.height).max(0),
)
}
/// Scrolls a node's content to `offset`, clamped to what its content
/// actually extends to — a viewport cannot be scrolled past its last child
/// or into negative space.
///
/// Damages the whole viewport, deliberately: scrolling moves every visible
/// pixel in it, and the honest damage for that is the viewport itself.
pub fn set_scroll(&mut self, id: NodeId, offset: Point) {
let limit = self.max_scroll(id);
let Some(node) = self.nodes.get_mut(id) else {
return;
};
let clamped = Point::new(offset.x.clamp(0, limit.x), offset.y.clamp(0, limit.y));
if node.scroll == clamped {
return;
}
let was = node.scroll;
node.scroll = clamped;
let clip = node.clip;
let by = Point::new(clamped.x - was.x, clamped.y - was.y);
// Recorded *before* the damage, and not through `dirty`: this is the
// scroll, and the scroll is what the record is about.
self.note_scroll(id, by, clip);
self.damage.add(clip);
self.reflow(id);
// The pointer has not moved, but what is under it has.
self.update_hover();
}
/// Scrolls a node's content by a delta, clamped like [`Ui::set_scroll`].
pub fn scroll_by(&mut self, id: NodeId, dx: i32, dy: i32) {
let current = self.scroll(id);
self.set_scroll(
id,
Point::new(current.x.saturating_add(dx), current.y.saturating_add(dy)),
);
}
/// How big a node would like to be, given what the caller can promise.
///
/// [`Measured::NOTHING`] when the node has no opinion, which is most of
/// them, and when there is no node of that id.
///
/// **This exists because of a borrow.** Measuring needs the widget and the
/// text engine at once, and both live in this struct — so
/// `widget.preferred_width(ui.text_mut())` cannot be written by anybody
/// outside it, however much they are holding. An application that *is*
/// holding the widget, before it goes in the tree, should keep calling the
/// widget's own `preferred_width`/`preferred_height`: they are the nicer
/// call and this is a wrapper over the same arithmetic.
///
/// **The tree never calls this itself.** See [`Widget::measure`] for why
/// that sentence is the whole point.
///
/// ```
/// # use denise::{Rect, Size, theme};
/// # use denise_ui::{Measured, Offer, Ui, Void, widgets::{Label, Panel}};
/// let mut ui: Ui<Void> = Ui::new(Size::new(320, 240), theme::DARK);
/// let root = ui.root();
/// let hello = ui.add(root, Label::new("Hello"), Rect::new(0, 0, 10, 10)).unwrap();
/// let panel = ui.add(root, Panel::default(), Rect::new(0, 0, 10, 10)).unwrap();
///
/// // A label is as wide as its text, whatever rectangle it was given.
/// let wanted = ui.measure(hello, Offer::NOTHING);
/// assert!(wanted.width.is_some_and(|w| w > 0));
///
/// // A panel is the background other things sit on, and has no view.
/// assert_eq!(ui.measure(panel, Offer::NOTHING), Measured::NOTHING);
/// ```
pub fn measure(&mut self, id: NodeId, offered: Offer) -> Measured {
// The disjoint-field borrow the paint path already relies on: `nodes` is
// read while `text` is written, which is allowed inside this type and
// expressible nowhere else.
let Some(node) = self.nodes.get(id) else {
return Measured::NOTHING;
};
let mut ctx = MeasureCtx {
theme: &self.theme,
text: &mut self.text,
};
node.widget.measure(&mut ctx, offered)
}
/// Moves or resizes a node, damaging the rectangles it left and the ones it
/// now occupies. Siblings in a [stack](Ui::set_stack) move with it.
///
/// Cancels any [`Ui::animate_layout`] in flight on this node: the
/// application wrote state, and state written is state shown — the
/// silent-setter rule applied to the tree itself.
pub fn set_layout(&mut self, id: NodeId, layout: Rect) {
self.tweens.retain(|t| t.id != id);
// A new layout is a new design, stated against whatever the parent is
// now, so anchoring re-baselines against the box this node is next
// placed in. `apply_layout` deliberately does not: it is also the path a
// tween drives, and re-baselining every frame would leave an anchored
// node standing still while its parent moved around it.
if let Some(node) = self.nodes.get_mut(id) {
node.anchor_base = None;
}
self.apply_layout(id, layout);
}
/// [`Ui::set_layout`] without the tween cancellation — the path the tween
/// itself drives, so advancing a tween does not cancel it.
fn apply_layout(&mut self, id: NodeId, layout: Rect) {
let Some(node) = self.nodes.get(id) else {
return;
};
if node.layout == layout {
return;
}
// The stack parent, when there is one: a resized child moves every
// sibling below it, so the damage and the reflow both start there.
let root = self.reflow_root(id);
self.damage_subtree(root);
self.nodes[id].layout = layout;
self.reflow(root);
self.damage_subtree(root);
// Content that shrank may have left a viewport scrolled past its own
// last child, which paints as a band of nothing at the bottom and no
// way to reach what is above it — collapse a section, hide a widget,
// take rows out of a list, or give back the room an on-screen keyboard
// was borrowing. `max_scroll` is computed on demand and was already
// right; the stored offset was the stale half.
self.clamp_scroll_above(id);
}
/// Re-clamps this node's scroll and every scrollable ancestor's.
///
/// Upwards because the node that changed size is the *content*: the
/// viewport whose offset is now out of range is one of its parents. Itself
/// too, since a node can be both.
fn clamp_scroll_above(&mut self, id: NodeId) {
let mut next = Some(id);
while let Some(current) = next {
let Some(node) = self.nodes.get(current) else {
return;
};
next = node.parent;
if node.scroll == Point::ZERO {
continue;
}
let limit = self.max_scroll(current);
let scroll = self.nodes[current].scroll;
let clamped = Point::new(scroll.x.clamp(0, limit.x), scroll.y.clamp(0, limit.y));
if clamped != scroll {
self.nodes[current].scroll = clamped;
let clip = self.nodes[current].clip;
self.dirty(clip);
self.reflow(current);
}
}
}
/// Carries a node's layout to `to` over `duration_ms`, through the same
/// path [`Ui::set_layout`] uses — so damage and reflow, stacks included,
/// come along on every frame.
///
/// Runs on [`Ui::tick`], at about 20 fps while flying, and lands *exactly*
/// on `to`. A second call mid-flight retargets from the current mid-flight
/// rectangle, so a section told to close while opening turns around
/// smoothly. A plain [`Ui::set_layout`] cancels the journey; hiding the
/// node completes it instantly, because a hidden node must not keep the
/// device awake and half-moved is the one dishonest place to stop.
///
/// Counted by [`Ui::animating`], so the idle-cost evidence covers it.
pub fn animate_layout(&mut self, id: NodeId, to: Rect, duration_ms: u64) {
let Some(node) = self.nodes.get(id) else {
return;
};
let from = node.layout;
self.tweens.retain(|t| t.id != id);
if duration_ms == 0 || from == to {
self.apply_layout(id, to);
return;
}
self.tweens.push(LayoutTween {
id,
from,
to,
start_ms: self.now_ms,
duration_ms,
});
// Wake immediately, as a widget's request_animation does: the first
// frame belongs to the next tick, however far away the event loop
// thought its next deadline was.
self.next_wake = Some(self.next_wake.map_or(self.now_ms, |w| w.min(self.now_ms)));
}
/// Makes a node a vertical stack: its visible children are placed
/// top-to-bottom in order, `spacing` pixels apart, each keeping its own
/// x, width and height.
///
/// Not a layout engine, and not the intrinsic-size protocol — the tree
/// still asks widgets nothing, and every height is the same explicit
/// rectangle as ever. It is scrolling's argument again: paint, damage,
/// clipping and hit testing must agree about where a moved sibling is,
/// and one reflow rule is how they agree. Combined with
/// [`Ui::animate_layout`] on one child's height, the stack re-places the
/// rest on every frame — which is the whole accordion mechanism.
///
/// A hidden child takes no space; children are placed in paint order, so
/// [`Ui::set_z`] reorders the stack too.
pub fn set_stack(&mut self, id: NodeId, spacing: i32) {
if let Some(node) = self.nodes.get_mut(id) {
node.stack = Some(spacing);
let root = self.reflow_root(id);
self.reflow(root);
self.damage_subtree(root);
}
}
/// Sets which of its parent's edges a node keeps its distance from.
///
/// [`Anchors::TOP_LEFT`] by default — the node keeps its rectangle whatever
/// its parent does, which is what the tree did before anchoring existed.
/// See the [`anchor`](crate::anchor) module for what each combination means.
///
/// Not a layout engine: this is one derived rectangle per child, in the
/// reflow the tree already runs. The node's own `layout` is never rewritten.
///
/// ```
/// # use denise::{Rect, Size, theme};
/// # use denise_ui::{Anchors, Ui, Void};
/// # use denise_ui::widgets::Panel;
/// let mut ui: Ui<Void> = Ui::new(Size::new(200, 100), theme::DARK);
/// let root = ui.root();
/// let bar = ui.add(root, Panel::default(), Rect::new(10, 10, 180, 20)).unwrap();
///
/// // Held at both ends, so it spans whatever width there is.
/// ui.set_anchors(bar, Anchors::new(true, true, true, false));
/// assert_eq!(ui.bounds(bar).unwrap().width, 180);
/// ```
pub fn set_anchors(&mut self, id: NodeId, anchors: Anchors) {
let Some(node) = self.nodes.get_mut(id) else {
return;
};
if node.anchors == anchors {
return;
}
node.anchors = anchors;
let root = self.reflow_root(id);
self.damage_subtree(root);
self.reflow(root);
self.damage_subtree(root);
self.clamp_scroll_above(id);
}
/// Whether this node is drawn and reachable.
///
/// The counterpart to [`Ui::set_visible`]. A designer needs it: a hidden node
/// still has bounds — it may be shown again, and its children lay out
/// against them — so "what is under the pointer" has to ask, or clicking an
/// empty canvas would select the invisible sheet covering it.
pub fn visible(&self, id: NodeId) -> bool {
self.nodes.get(id).is_some_and(|node| node.visible)
}
/// This node's sort key among its siblings. See [`Ui::set_z`].
pub fn z(&self, id: NodeId) -> i32 {
self.nodes.get(id).map_or(0, |node| node.z)
}
/// Whether this node takes input and paints as live. See [`Ui::set_enabled`].
///
/// A node whose *parent* is disabled still answers `true` here: this is what
/// was asked of the node itself, which is what a caller wanting to put it
/// back needs to know.
pub fn enabled(&self, id: NodeId) -> bool {
self.nodes.get(id).is_some_and(|node| node.enabled)
}
/// The text this node shows on a dwell, if it was given one. See
/// [`Ui::set_tooltip`].
pub fn tooltip(&self, id: NodeId) -> Option<&str> {
self.nodes.get(id).and_then(|node| node.tooltip.as_deref())
}
/// Which of its parent's edges this node keeps its distance from.
pub fn anchors(&self, id: NodeId) -> Anchors {
self.nodes.get(id).map_or(Anchors::TOP_LEFT, |n| n.anchors)
}
/// Gives a node an entire edge of what is left of its parent, or takes it
/// back with `None`.
///
/// Docked children are placed in paint order, each taking its edge from what
/// the ones before it left, and everything undocked is placed in what
/// remains — so docking a bar to the top moves the rest down rather than
/// covering it. Only the node's extent along the docking axis is used: a
/// [`Dock::Top`] keeps its `height` and is given the full width.
///
/// ```
/// # use denise::{Rect, Size, theme};
/// # use denise_ui::{Dock, Ui, Void};
/// # use denise_ui::widgets::Panel;
/// let mut ui: Ui<Void> = Ui::new(Size::new(200, 100), theme::DARK);
/// let root = ui.root();
/// let bar = ui.add(root, Panel::default(), Rect::new(0, 0, 0, 24)).unwrap();
/// let body = ui.add(root, Panel::default(), Rect::new(0, 0, 0, 0)).unwrap();
///
/// ui.set_dock(bar, Some(Dock::Top));
/// ui.set_dock(body, Some(Dock::Fill));
/// assert_eq!(ui.bounds(bar).unwrap(), Rect::new(0, 0, 200, 24));
/// assert_eq!(ui.bounds(body).unwrap(), Rect::new(0, 24, 200, 76));
/// ```
pub fn set_dock(&mut self, id: NodeId, dock: Option<Dock>) {
let Some(node) = self.nodes.get_mut(id) else {
return;
};
if node.dock == dock {
return;
}
node.dock = dock;
// Docking changes the box every *sibling* is placed in, so the reflow and
// the damage start at the parent whether or not it stacks — and climb
// from there, since the parent may be docked itself.
let parent = node.parent;
let root = parent.map_or(id, |p| self.reflow_root(p));
self.damage_subtree(root);
self.reflow(root);
self.damage_subtree(root);
self.clamp_scroll_above(id);
}
/// Which edge of its parent this node takes, if any.
pub fn dock(&self, id: NodeId) -> Option<Dock> {
self.nodes.get(id).and_then(|n| n.dock)
}
/// Stops stacking: children return to their own layout positions.
pub fn clear_stack(&mut self, id: NodeId) {
if let Some(node) = self.nodes.get_mut(id)
&& node.stack.take().is_some()
{
let root = self.reflow_root(id);
self.reflow(root);
self.damage_subtree(root);
}
}
/// Whether `id` is `ancestor` or sits anywhere under it.
fn is_descendant_or_self(&self, id: NodeId, ancestor: NodeId) -> bool {
let mut current = Some(id);
while let Some(node) = current {
if node == ancestor {
return true;
}
current = self.nodes.get(node).and_then(|n| n.parent);
}
false
}
/// Where a reflow triggered by `id` has to start: the parent when it
/// stacks, because the change moves siblings, and the node itself
/// otherwise.
/// Where a reflow touching `id` has to start.
///
/// Usually `id` itself. But a node whose rectangle depends on its *siblings*
/// cannot be computed without them, and there are two ways for that to be
/// true: the node **docks**, so it takes an edge of whatever the siblings
/// before it left; or its parent **arranges** its children — a stack, or any
/// docked sibling shrinking the box the rest are placed in.
///
/// Either way the reflow, and the damage, start at the parent. And it climbs:
/// a docked node inside a docked column depends on its siblings, which depend
/// on theirs, all the way to whoever is placed on their own terms. Stopping
/// after one step leaves the node it stopped at holding the rectangle its
/// `layout` happens to say, which for a docked node is not a position at all.
fn reflow_root(&self, id: NodeId) -> NodeId {
let mut at = id;
loop {
let Some(node) = self.nodes.get(at) else {
return at;
};
let Some(parent) = node.parent else {
return at;
};
let Some(above) = self.nodes.get(parent) else {
return at;
};
let arranged = node.dock.is_some()
|| above.stack.is_some()
|| above
.children
.iter()
.any(|&c| self.nodes.get(c).is_some_and(|n| n.dock.is_some()));
if !arranged {
return at;
}
at = parent;
}
}
/// Sets the sibling sort key. Higher paints later, so higher is on top.
pub fn set_z(&mut self, id: NodeId, z: i32) {
let Some(node) = self.nodes.get_mut(id) else {
return;
};
if node.z == z {
return;
}
node.z = z;
let parent = node.parent;
if let Some(parent) = parent {
self.sort_children(parent);
}
self.damage_subtree(id);
// A stack places children in paint order, so reordering moves them.
let root = self.reflow_root(id);
if root != id {
self.reflow(root);
self.damage_subtree(root);
}
self.order_dirty = true;
}
/// Shows or hides a node and its descendants.
pub fn set_visible(&mut self, id: NodeId, visible: bool) {
let Some(node) = self.nodes.get_mut(id) else {
return;
};
if node.visible == visible {
return;
}
node.visible = visible;
// The order excludes hidden subtrees, so it has to be rebuilt.
self.order_dirty = true;
self.damage_subtree(id);
// In a stack, appearing and disappearing move the siblings below.
let root = self.reflow_root(id);
if root != id {
self.reflow(root);
self.damage_subtree(root);
}
if !visible {
// A hidden node's layout tween completes instantly: it must not
// keep the device awake, and half-moved is the one dishonest
// place to stop. Descendants' tweens too — hiding a panel hides
// everything it contains.
let snapping: alloc::vec::Vec<LayoutTween> = self
.tweens
.iter()
.copied()
.filter(|t| self.is_descendant_or_self(t.id, id))
.collect();
self.tweens
.retain(|t| !snapping.iter().any(|snap| snap.id == t.id));
for tween in snapping {
self.apply_layout(tween.id, tween.to);
}
self.forget(id);
// A hidden widget must not keep the device awake: an invisible
// spinner spinning forever is the exact failure the animation set
// exists to make visible. Disabling, by contrast, does *not* stop
// animation — a disabled toggle mid-slide still gets to finish
// rather than freeze part-way.
self.stop_animating_subtree(id);
}
}
/// Enables or disables a node and its descendants. Disabled widgets are not
/// hittable, not focusable, and paint with [`VisualState::DISABLED`].
pub fn set_enabled(&mut self, id: NodeId, enabled: bool) {
let Some(node) = self.nodes.get_mut(id) else {
return;
};
if node.enabled == enabled {
return;
}
node.enabled = enabled;
self.reflow(id);
self.damage_subtree(id);
if !enabled {
self.forget(id);
}
}
/// Borrows a widget as its concrete type.
pub fn widget<W: Widget<M>>(&self, id: NodeId) -> Option<&W> {
self.nodes.get(id)?.widget.as_any().downcast_ref::<W>()
}
/// Borrows a widget mutably as its concrete type, **marking it dirty**.
///
/// Invalidation happens on access rather than on change, because the tree
/// cannot see what you did through the `&mut`. The cost of being conservative
/// is repainting one widget; the cost of being clever would be the class of bug
/// this whole design exists to remove.
///
/// # Do not poll with it
///
/// "Repainting one widget" is the cost of *one* call. Calling it over many
/// nodes every frame to see whether any of them has something for you costs
/// a repaint of all of them, every frame — and past
/// [`MAX_DAMAGE_RECTS`](denise::MAX_DAMAGE_RECTS) rectangles the tracker
/// collapses to their bounding box, so the answer is not even "sixty small
/// repaints" but one large one.
///
/// This is not hypothetical: it is how the on-screen keyboard came to
/// repaint itself on every frame anything else woke the tree for, which on a
/// panel showed up as a keyboard that flickers. Read through
/// [`widget`](Ui::widget) to find the node worth writing to, and use this on
/// that one.
pub fn widget_mut<W: Widget<M>>(&mut self, id: NodeId) -> Option<&mut W> {
let clip = self.nodes.get(id)?.clip;
self.dirty(clip);
self.nodes
.get_mut(id)?
.widget
.as_any_mut()
.downcast_mut::<W>()
}
// ----------------------------------------------------------- properties
/// What kind of widget a node holds, as a form file spells it.
///
/// `None` for a widget that does not describe itself — see
/// [`Widget::describe`].
pub fn kind(&self, id: NodeId) -> Option<&'static str> {
self.nodes.get(id)?.widget.describe().map(DynDescribe::kind)
}
/// Every property a node's widget accepts.
///
/// Empty for a widget that does not describe itself. A property inspector
/// walks this to decide which editors to show, so it never names a widget.
pub fn properties(&self, id: NodeId) -> &'static [Property] {
self.nodes
.get(id)
.and_then(|node| node.widget.describe())
.map_or(&[], DynDescribe::properties)
}
/// The current value of one property.
///
/// `None` for a node that does not exist, a widget that does not describe
/// itself, a property it does not have, and a property that is simply not
/// set — [`Describe::get`](crate::widgets::Describe::get) explains why those
/// last two share an answer.
pub fn get_property(&self, id: NodeId, name: &str) -> Option<Value> {
self.nodes.get(id)?.widget.describe()?.get_property(name)
}
/// Sets one property by name, and marks the node for repaint.
///
/// The one place a string becomes a typed call on a widget: a form file's
/// `role=primary` and a property inspector's dropdown arrive here and go no
/// further apart. An error names the widget, the property and what would
/// have been accepted.
///
/// Returns `None` if the node does not exist or its widget does not describe
/// itself; that is a different thing from a property that was refused, which
/// is the `Err` inside.
pub fn set_property(
&mut self,
id: NodeId,
name: &str,
value: Value,
) -> Option<Result<(), PropertyError>> {
let node = self.nodes.get_mut(id)?;
let result = node.widget.describe_mut()?.set_property(name, value);
// The widget does not own its damage, so setting a property that changed
// what it draws would otherwise leave a stale rectangle on the panel.
// Invalidating unconditionally costs one widget-sized repaint on a
// no-op, which is the cheap way to be wrong.
let clip = node.clip;
self.dirty(clip);
Some(result)
}
// ---------------------------------------------------------------- focus
/// Every node Tab can reach, in the order it reaches them.
///
/// The same list [`Ui::focus_step`](Ui) walks, which is why it is here
/// rather than rebuilt by whoever wants it: a tool drawing the tab order
/// and the tree walking it must not be able to disagree.
///
/// Tree order, depth first, siblings by `z` — a node drawn in front of its
/// siblings is also reached after them. Only the topmost scene, because only
/// the topmost scene is reachable.
///
/// ```
/// # use denise::{Rect, Size, theme};
/// # use denise_ui::{Ui, Void, widgets::{Button, Label, TextInput}};
/// let mut ui: Ui<Void> = Ui::new(Size::new(200, 200), theme::DARK);
/// let root = ui.root();
/// let field = ui.add(root, TextInput::<Void>::new(), Rect::new(0, 0, 100, 30)).unwrap();
/// // A label is drawn and is not a stop.
/// ui.add(root, Label::new("Heading"), Rect::new(0, 40, 100, 20));
/// let go = ui.add(root, Button::<Void>::inert("Go"), Rect::new(0, 70, 100, 30)).unwrap();
///
/// assert_eq!(ui.tab_stops(), vec![field, go]);
/// ```
pub fn tab_stops(&mut self) -> alloc::vec::Vec<NodeId> {
self.ensure_order();
let (start, end) = self.input_span();
self.order[start..end]
.iter()
.copied()
.filter(|id| self.is_focusable(*id))
.collect()
}
/// The node holding keyboard focus.
#[inline]
pub const fn focused(&self) -> Option<NodeId> {
self.focused
}
/// The node under the pointer.
#[inline]
pub const fn hovered(&self) -> Option<NodeId> {
self.hovered
}
/// Moves keyboard focus, refusing nodes that are gone, hidden, disabled,
/// unfocusable, or in a scene under a modal.
pub fn focus(&mut self, id: Option<NodeId>) {
let id = id.filter(|&id| self.is_focusable(id));
self.set_focus(id);
}
/// Topmost node under `p` that accepts pointer input, within the input scene.
pub fn hit_test(&mut self, p: Point) -> Option<NodeId> {
self.ensure_order();
let (start, end) = self.input_span();
self.order[start..end].iter().rev().copied().find(|&id| {
self.nodes
.get(id)
.is_some_and(|n| n.paintable() && self.is_interactive(n) && n.clip.contains(p))
})
}
/// Dismisses a toast under `p`, reporting whether the press was consumed.
///
/// A toast is not a node, so nothing else would stop the press reaching
/// what is underneath — and somebody clearing a notification would press
/// the button it was covering.
fn dismiss_toast(&mut self, p: Point) -> bool {
if self.toasts.len() == 0 {
return false;
}
self.damage_toasts();
let now = self.now_ms;
self.toasts.dismiss_at(p, self.size, &mut self.text, now)
}
/// Whether a press at `p` should close the topmost popup instead of being
/// delivered: the top scene is a popup and the press is outside its
/// container.
/// Whether the topmost scene is an open drawer's — the state in which
/// Escape and a press on the dim belong to the drawer.
fn drawer_on_top(&self) -> bool {
self.drawer.is_some_and(|state| {
!state.closing
&& self
.nodes
.get(state.container)
.is_some_and(|n| n.scene + 1 == self.scenes.len())
})
}
/// Whether a press at `p` is on the drawer's dim rather than the drawer,
/// and should close it — swallowed entirely, like a popup's.
fn dismisses_drawer(&self, p: Point) -> bool {
self.drawer_on_top()
&& self
.drawer
.and_then(|state| self.nodes.get(state.container))
.is_some_and(|n| !n.bounds.contains(p))
}
fn dismisses_popup(&mut self, p: Point) -> bool {
let Some(popup) = self.scenes.last().and_then(|s| s.popup) else {
return false;
};
self.ensure_order();
!self
.nodes
.get(popup.container)
.is_some_and(|node| node.clip.contains(p))
}
/// The innermost scrollable whose viewport contains `p`, in the scene input
/// currently reaches. Innermost, so a scrollable inside a scrollable
/// scrolls the one the pointer is actually over.
fn scroll_target(&mut self, p: Point) -> Option<NodeId> {
self.ensure_order();
let (start, end) = self.input_span();
self.order[start..end].iter().rev().copied().find(|&id| {
self.nodes
.get(id)
.is_some_and(|n| n.scrollable && n.visible && n.clip.contains(p))
})
}
/// The nearest scrollable ancestor of `id`, itself included.
fn scrollable_ancestor(&self, id: Option<NodeId>) -> Option<NodeId> {
let mut current = id;
while let Some(id) = current {
let node = self.nodes.get(id)?;
if node.scrollable {
return Some(id);
}
current = node.parent;
}
None
}
/// Scrolls ancestors of `id` so that `rect` (absolute) becomes visible in
/// each of their viewports — the mechanism behind focus following and a
/// widget's [`EventCtx::reveal`].
///
/// Walks inside-out, so a scrollable inside a scrollable brings the target
/// into its own viewport first and the outer one then brings *that* into
/// view.
/// Scrolls whatever has the focus back into view.
///
/// Focus reveals itself the moment it moves, which is the only moment the
/// tree can act on unprompted. When what is *around* the focus changes
/// instead — a keyboard slides up over it, an application gives a page more
/// room to scroll into — nothing about the focus has changed, so nothing
/// re-runs the reveal and the caret stays where it was left. This is how an
/// application says the geometry moved underneath it.
///
/// Nothing focused, or nowhere left to scroll, and it does nothing.
pub fn reveal_focused(&mut self) {
let Some(id) = self.focused else {
return;
};
let Some(bounds) = self.nodes.get(id).map(|node| node.bounds) else {
return;
};
self.reveal_rect(id, bounds);
}
/// `view` with any occluded band taken off it.
///
/// A shelf lies against one screen edge and spans it, so removing it from a
/// viewport leaves a rectangle rather than an L — which is what makes this
/// arithmetic rather than a region.
///
/// Without this, revealing a focused node scrolls it into its viewport and
/// stops, and a viewport that extends under the keyboard happily reveals a
/// field underneath it: solved-looking, and not solved.
fn unoccluded(&self, view: Rect) -> Rect {
let Some(occ) = self.occluded else {
return view;
};
let screen = Rect::from_size(self.size);
let (mut top, mut bottom) = (view.y, view.bottom());
let (mut left, mut right) = (view.x, view.right());
if occ.width >= screen.width {
if occ.y <= screen.y {
top = top.max(occ.bottom());
} else {
bottom = bottom.min(occ.y);
}
} else if occ.height >= screen.height {
if occ.x <= screen.x {
left = left.max(occ.right());
} else {
right = right.min(occ.x);
}
}
Rect::new(left, top, (right - left).max(0), (bottom - top).max(0))
}
fn reveal_rect(&mut self, id: NodeId, rect: Rect) {
let mut rect = rect;
let mut current = self.nodes.get(id).and_then(|n| n.parent);
while let Some(ancestor) = current {
let Some(node) = self.nodes.get(ancestor) else {
return;
};
current = node.parent;
if !node.scrollable {
continue;
}
let view = self.unoccluded(node.bounds);
let scroll = node.scroll;
// How far the viewport must move so the rect's near edge is inside.
// A rect taller than the viewport reveals its top, which is where
// reading starts.
let dy = if rect.bottom() > view.bottom() {
(rect.bottom() - view.bottom()).min(rect.y - view.y)
} else if rect.y < view.y {
rect.y - view.y
} else {
0
};
let dx = if rect.right() > view.right() {
(rect.right() - view.right()).min(rect.x - view.x)
} else if rect.x < view.x {
rect.x - view.x
} else {
0
};
if dx != 0 || dy != 0 {
let before = self.scroll(ancestor);
self.set_scroll(ancestor, Point::new(before.x + dx, before.y + dy));
let after = self.scroll(ancestor);
// The rect moved with the content; the outer loop must judge it
// where it now is.
rect = rect.translate(before.x - after.x, before.y - after.y);
}
let _ = scroll;
}
}
// ---------------------------------------------------------------- input
/// Routes a batch of input events into the tree.
pub fn handle(&mut self, events: &[InputEvent]) {
self.ensure_order();
for event in events {
self.handle_one(event);
}
}
/// Advances time-based state for every node that asked to animate.
///
/// A node gets into that set through [`EventCtx::request_animation`] or
/// [`Ui::request_animation`], and out of it by its own answer: an
/// [`Animation`](crate::Animation) with [`Wake::Never`] is the widget
/// saying it is done. The
/// tree never keeps a widget animating; the widget keeps itself animating,
/// and the tree keeps the evidence — see [`Ui::animating`].
///
/// **How often** a moving widget is asked is the tree's decision, not the
/// widget's: a widget answers [`Wake::Animating`] and [`Ui::motion`] turns
/// that into a time. A widget answering [`Wake::At`] has named a deadline
/// instead, and the rate does not touch it.
pub fn tick(&mut self, now_ms: u64) {
self.now_ms = now_ms;
let interval = self.motion.interval_ms();
let mut wake: Option<u64> = None;
let mut i = 0;
while i < self.animating.len() {
let id = self.animating[i];
let Some(node) = self.nodes.get_mut(id) else {
// Removed while animating; nothing to settle.
self.animating.swap_remove(i);
continue;
};
// Under `Motion::None` a widget is asked to land rather than to
// move, once, and is then expected to have nothing left to do.
let animation = match interval {
Some(_) => node.widget.animate(now_ms),
None => node.widget.snap(now_ms),
};
let clip = node.clip;
if animation.repaint {
self.dirty(clip);
}
// The scene wakes for the most impatient animation, and everybody is
// asked again at that point. A widget's `animate` must therefore
// tolerate being called before the time it asked for — all of them
// already did, because `tick`'s clock was always the caller's.
let next = match animation.next {
Wake::Never => None,
// The saturating add that every widget used to do for itself.
// `Wake::Animating` under `Motion::None` is a widget that could
// not land: there is no rate to come back at, so it stops.
Wake::Animating => interval.map(|ms| now_ms.saturating_add(ms)),
Wake::At(due) => Some(due),
};
match next {
Some(next) => {
wake = Some(wake.map_or(next, |w: u64| w.min(next)));
i += 1;
}
None => {
self.animating.swap_remove(i);
}
}
}
// Layout tweens: the tree's own animation. Advanced through the same
// apply path the application's set_layout uses, so damage — the
// rectangles left behind and the ones now occupied, stacked siblings
// included — comes along on every frame. A tween that has arrived
// lands exactly on its target and is gone.
let mut i = 0;
while i < self.tweens.len() {
let tween = self.tweens[i];
if !self.nodes.contains_key(tween.id) {
self.tweens.swap_remove(i);
continue;
}
// The tree's own animation, sampled at the tree's own rate — and
// with no rate at all, a tween is a `set_layout` that happens to
// have been asked for politely.
let rect = match interval {
Some(_) => tween.at(now_ms),
None => tween.to,
};
self.apply_layout(tween.id, rect);
if rect == tween.to {
self.tweens.swap_remove(i);
continue;
}
// Only reachable with an interval: a tween with no rate landed on
// `to` above and is already gone.
if let Some(ms) = interval {
let next = now_ms.saturating_add(ms);
wake = Some(wake.map_or(next, |w: u64| w.min(next)));
}
i += 1;
}
// A closing drawer pops its scene the moment its slide has landed —
// the first thing in the tree to happen *because* a tween arrived.
// Also the cleanup for a drawer whose scene somebody popped directly.
if let Some(state) = self.drawer {
if !self.nodes.contains_key(state.container) {
self.drawer = None;
} else if state.closing && !self.tweens.iter().any(|t| t.id == state.container) {
self.drawer = None;
self.pop_scene();
}
}
// The same landing, for a shelf. It has no scene to pop, so what goes
// is the node itself — and with it every key that was on it.
if let Some(state) = self.shelf {
if !self.nodes.contains_key(state.container) {
self.shelf = None;
} else if state.closing && !self.tweens.iter().any(|t| t.id == state.container) {
self.shelf = None;
self.remove(state.container);
}
if self.shelf.is_none() {
self.occluded = None;
}
}
// The tooltip's dwell deadline is a wake reason too, and the one most
// easily forgotten: a kiosk blocks on input until the tree says it
// wants waking, so a deadline left out here is a bubble that appears
// the next time something unrelated happens.
let hovered = self.hovered;
let anchor = hovered.and_then(|id| self.nodes.get(id)).map(|n| n.bounds);
let text = hovered
.and_then(|id| self.nodes.get(id))
.and_then(|n| n.tooltip.clone());
if self
.tooltip
.tick(now_ms, text.as_deref(), anchor.unwrap_or(Rect::ZERO))
{
self.damage_tooltip();
}
// Notifications repaint only when they are actually changing — mid-fade,
// or expiring. A holding toast is a still picture, and damaging it every
// tick would repaint the bottom of the screen for four seconds to show
// something that never moved.
if self.toasts.is_changing(now_ms) {
self.damage_toasts();
self.toasts.retire(now_ms);
}
// The other two reasons the tree wants waking: a tooltip's dwell
// deadline and a toast's next frame. Folded in here rather than
// anywhere else, because this is the one answer the event loop asks
// for and a deadline left out of it is a feature that never fires.
for deadline in [self.tooltip.next_wake(), self.toasts.next_wake(now_ms)]
.into_iter()
.flatten()
{
wake = Some(wake.map_or(deadline, |w: u64| w.min(deadline)));
}
self.next_wake = wake;
}
/// Damages whatever the notifications cover.
///
/// Measured before any change that would move them, for the reason the
/// tooltip's damage had to learn: a stack that has already forgotten where
/// it was cannot say what to repaint.
fn damage_toasts(&mut self) {
let now = self.now_ms;
if let Some(bounds) = self.toasts.bounds(self.size, &mut self.text, now) {
self.dirty(bounds);
}
}
/// Damages whatever the tooltip covers.
///
/// It is not a node, so nothing else will do it: the bubble sits over
/// arbitrary widgets and its footprint has to be repainted when it appears
/// and again when it goes.
fn damage_tooltip(&mut self) {
if let Some(bounds) = self.tooltip.bounds(self.size, &mut self.text) {
self.dirty(bounds);
}
}
/// Asks the tree to start animating `id`.
///
/// The widget's [`Widget::animate`] is called from the next [`Ui::tick`],
/// and keeps being called until it answers with `next_ms: None`. Wanting
/// frames is almost always decided inside an event handler, where
/// [`EventCtx::request_animation`] does this without an id — this entry
/// point is for the widget that starts moving without being touched, a
/// spinner being the canonical case.
///
/// # The cost of asking
///
/// A bounded transition — a knob crossing, a toast fading — costs its
/// duration and then stops asking. An *unbounded* animation is expressible,
/// because a spinner genuinely is one, and it is exactly what would keep a
/// kiosk's CPU awake at frame rate for a year if one is left running on a
/// screen nobody looks at. Hide the node or remove it and the animation
/// stops with it; [`Ui::animating`] is how a test proves there is nothing
/// left running.
pub fn request_animation(&mut self, id: NodeId) {
if !self.nodes.contains_key(id) || self.animating.contains(&id) {
return;
}
self.animating.push(id);
// Wake immediately: the event loop may already be deciding how long to
// sleep, and the newly animating widget has not been asked yet.
self.next_wake = Some(self.next_wake.map_or(self.now_ms, |w| w.min(self.now_ms)));
}
/// How fast the tree animates, and whether it does at all.
#[inline]
pub const fn motion(&self) -> Motion {
self.motion
}
/// Sets the rate every moving thing in the tree runs at.
///
/// One decision covering spinners, knobs crossing, carousel slides, layout
/// tweens and toast fades — see [`Motion`] for what it is and is not.
///
/// ```
/// # use denise::{Size, theme};
/// # use denise_ui::{Motion, Ui};
/// # enum Msg { Noop }
/// # let mut ui: Ui<Msg> = Ui::new(Size::new(1920, 1080), theme::DARK);
/// ui.set_motion(Motion::Every(33)); // 30 fps: half the wakes
/// ui.set_motion(Motion::None); // reduced motion
/// ```
///
/// # Where the setting belongs
///
/// Here rather than on [`Theme`], although the theme already carries
/// `metrics` and `depth` and motion tokens would not be absurd beside them.
/// A theme is an **identity** — swapping dark for light must not change the
/// power budget — while the frame rate is a **deployment** decision, and the
/// same panel wants a different answer on a bench and on a battery. Putting
/// it on the tree also puts it next to the thing it acts on: the animating
/// set is here, and so is the wake this feeds.
///
/// Takes effect at the next [`Ui::tick`], which is asked for immediately —
/// an event loop may be blocked on input right now with a sleep it worked
/// out under the old setting.
pub fn set_motion(&mut self, motion: Motion) {
self.motion = motion;
// The notification stack is not a node, so `tick` cannot reach it the
// way it reaches widgets.
self.toasts.set_motion(motion);
if self.animating() > 0 || self.toasts.len() > 0 {
self.next_wake = Some(self.now_ms);
}
}
/// How many nodes are currently animating.
///
/// Zero is the number a panel at rest must report, and the README's idle
/// measurements depend on it. A test that asserts this stays zero is the
/// guard against a widget quietly holding the device awake.
#[inline]
pub fn animating(&self) -> usize {
self.animating.len() + self.tweens.len()
}
/// When something wants to be woken, in the same clock as [`Ui::tick`].
///
/// `None` means nothing is animating and the event loop may block on input
/// indefinitely, which is the state a kiosk should be in almost all the time.
#[inline]
pub const fn next_wake_ms(&self) -> Option<u64> {
self.next_wake
}
/// Messages emitted since the last drain.
///
/// **Drain every frame.** The queue has no ceiling, and it is the one thing
/// in the tree that does not: toasts cap at three and drop the oldest, damage
/// coalesces into [`MAX_DAMAGE_RECTS`](denise::MAX_DAMAGE_RECTS) and then
/// collapses to its bounds, but messages accumulate for as long as an
/// application keeps handling events without reading them. That is deliberate
/// — dropping one silently would lose a button press, and no widget can know
/// which press mattered — so it is the application's contract to keep, and
/// the failure mode is a slow leak on a panel expected to run for a year.
///
/// An application that deliberately ignores messages for a while should call
/// this and discard the result rather than let them pile up.
#[inline]
pub fn drain_messages(&mut self) -> Drain<'_, M> {
self.messages.drain(..)
}
/// Messages emitted since the last drain, without consuming them.
#[inline]
pub fn messages(&self) -> &[M] {
&self.messages
}
// --------------------------------------------------------------- painting
/// Marks a rectangle for repaint.
///
/// The one door every damaging path in this file goes through, so that
/// "this frame was nothing but a scroll" stays knowable: anything landing
/// *inside* a scrolled viewport is a change the union would hide, and hides
/// it by taking the record away. See [`Scrolled`].
fn dirty(&mut self, rect: Rect) {
if self.scrolled[self.scroll_head].is_some_and(|it| it.clip.intersects(&rect)) {
self.scrolled[self.scroll_head] = None;
}
self.damage.add(rect);
}
/// Records that a viewport scrolled, for a frame that has done nothing else.
///
/// A second viewport scrolling in the same frame gives up rather than
/// growing a list: two moving at once is a case worth having and not a case
/// worth being clever about the first time.
fn note_scroll(&mut self, node: NodeId, by: Point, clip: Rect) {
let slot = &mut self.scrolled[self.scroll_head];
*slot = match *slot {
None if self.damage.is_clean() => Some(Scrolled { node, by, clip }),
Some(it) if it.node == node && it.clip == clip => Some(Scrolled {
node,
by: Point::new(it.by.x + by.x, it.by.y + by.y),
clip,
}),
_ => None,
};
}
/// Returns `true` if anything has been marked dirty since the last present.
#[inline]
pub fn needs_paint(&self) -> bool {
!self.damage.is_clean()
}
/// Marks the whole surface for repaint.
#[inline]
pub fn invalidate_all(&mut self) {
self.scrolled[self.scroll_head] = None;
self.damage.add_full();
}
/// Marks one node's rectangle for repaint.
pub fn invalidate(&mut self, id: NodeId) {
if let Some(node) = self.nodes.get(id) {
let clip = node.clip;
self.dirty(clip);
}
}
/// The regions [`Ui::paint`] last drew. Pass this to
/// [`Surface::present`](denise::Surface::present).
#[inline]
pub fn damage(&self) -> &[Rect] {
self.damage.resolved()
}
/// What has changed since the last present, before [`Ui::paint`] has run.
///
/// [`Ui::damage`] cannot answer this: it reports what `paint` last resolved,
/// so before this frame is painted it still describes the previous one. A
/// backend that must know the dirty region *before* drawing — anything
/// marking damage from `DeniseApp::update`, which happens ahead of `render`
/// — asks here instead, and gets this frame's rectangles.
///
/// Empty when the whole surface is dirty, which [`Ui::needs_paint`]
/// distinguishes from nothing being dirty at all.
#[inline]
pub fn pending_damage(&self) -> &[Rect] {
self.damage.pending()
}
/// Retires this frame's damage. Call after a successful present.
#[inline]
pub fn presented(&mut self) {
self.damage.end_frame();
self.scroll_head = (self.scroll_head + 1) % MAX_TRACKED_FRAMES;
self.scrolled[self.scroll_head] = None;
}
/// Moves the rows a scroll left still valid, and hands back what moved and
/// the strip that came into view.
///
/// A viewport scrolled by `dy` has the same content, moved. Copying what is
/// still good and drawing only what is new turns a 1584x1016 repaint into a
/// 1584x20 one, which on a Pi at 1080p is the difference between 25 ms and
/// about 8 — see [#46](https://github.com/bisand/denise/issues/46).
///
/// The copy is *within the target being drawn into*, through
/// [`Pen::scroll_rows`]: that target is `age` frames old, so it holds the
/// content from `age` frames ago, and the scroll since then is what the
/// ring in [`Scrolled`] has been recording. A painter that cannot move its
/// own pixels answers `false`, and the viewport is repainted as it always
/// was.
///
/// `None` for anything at all uncertain, and every one of these is a case
/// where the caller repaints the viewport exactly as it always has:
///
/// - the buffer's age is unknown or older than the ring;
/// - any of those frames did something other than scroll that one viewport;
/// - the viewport moved or resized in the meantime;
/// - the scroll was sideways, or further than the viewport is tall;
/// - anything is drawn *over* it — a scene, a tooltip, a toast, the cursor,
/// a node painted later in the order — because an overlay would be
/// copied along with the rows and leave a ghost where it used to be;
/// - something inside the viewport is dirty besides the scroll itself.
///
/// Damage *outside* the moved rectangle is fine: it is painted as usual,
/// with the rectangle cut out of whatever the tracker merged it into.
fn scroll_blit_with(&mut self, canvas: &mut Pen<'_>, age: BufferAge) -> Option<(Rect, Rect)> {
let frames = match age {
denise::BufferAge::Frames(n) if (n as usize) <= MAX_TRACKED_FRAMES => n as usize,
_ => return None,
};
if frames == 0 {
return None;
}
// Every frame this buffer is behind by has to have been the same
// viewport scrolling, or the content it holds is not what this thinks.
let first = self.scrolled[self.scroll_head]?;
let mut moved = Point::new(0, 0);
for step in 0..frames {
let slot = (self.scroll_head + MAX_TRACKED_FRAMES - step) % MAX_TRACKED_FRAMES;
let was = self.scrolled[slot]?;
if was.node != first.node || was.clip != first.clip {
return None;
}
moved = Point::new(moved.x + was.by.x, moved.y + was.by.y);
}
// Sideways is a different copy and a different strip. The case that
// matters is vertical; the other waits until it does.
if moved.x != 0 || moved.y == 0 {
return None;
}
if self.scenes.len() > 1 || self.tooltip.is_shown() || self.toasts.len() > 0 {
return None;
}
if self.cursor.bounds().intersects(&first.clip) {
return None;
}
let clip = first.clip.intersect(&Rect::from_size(self.size))?;
if moved.y.unsigned_abs() as i32 >= clip.height {
return None;
}
// A node painted after this one that reaches into the rectangle — a
// bar the application floated over its log, a panel beside it that
// overlaps by a pixel — would be moved with the rows. Its own
// descendants are the rows.
let start = self.order.iter().position(|&id| id == first.node)?;
let end = self.scene_end.first().copied().unwrap_or(self.order.len());
let covered = self.order[(start + 1).min(end)..end].iter().any(|&id| {
!self.is_descendant_or_self(id, first.node)
&& self
.nodes
.get(id)
.is_some_and(|node| node.paintable() && node.clip.intersects(&clip))
});
if covered {
return None;
}
// Anything dirty inside the rectangle other than the scroll itself
// means the rows are not what they were. The scroll's own damage is
// the rectangle, possibly merged into something larger by the
// tracker; a rectangle that cuts into it is neither.
let consistent = self
.damage
.resolve(age)
.iter()
.all(|r| !r.intersects(&clip) || r.contains_rect(&clip));
if !consistent {
return None;
}
if !canvas.scroll_rows(clip, moved.y) {
return None;
}
let strip = if moved.y > 0 {
Rect::new(clip.x, clip.bottom() - moved.y, clip.width, moved.y)
} else {
Rect::new(clip.x, clip.y, clip.width, -moved.y)
};
Some((clip, strip))
}
/// Draws every damaged region of the scene stack through `canvas`.
///
/// The pipeline, in order: clear, base scene, each further scene over its
/// backdrop, cursor sprite. All of it inside the damage clip, so an untouched
/// panel costs nothing and a moved cursor costs two sprite-sized rectangles.
///
/// `age` is the buffer age the pen's target was acquired with, which decides
/// how far back the damage has to reach. This is the entry point that knows
/// nothing about how the pixels are produced; [`Ui::paint`] is the one that
/// takes a [`Frame`] and rasterises into it with `denise-render`.
///
/// A frame that was nothing but one viewport scrolling is drawn by moving
/// the rows still on screen and painting the strip that came into view,
/// when the painter can move its own pixels ([`Pen::scroll_rows`]); one
/// that cannot repaints the viewport, which on anything that composites
/// was never the expensive part. What is *reported* as damage is untouched
/// either way: the screen still needs the whole viewport, because the
/// rows moved in this target and not in the one on the panel.
pub fn paint_with(&mut self, canvas: &mut Pen<'_>, age: BufferAge) {
self.ensure_order();
let blitted = self.scroll_blit_with(canvas, age);
self.paint_regions(canvas, age, blitted);
}
/// Draws every damaged region of the scene stack into `frame`.
///
/// [`Ui::paint_with`] with a [`Canvas`] over `frame`, which is a painter
/// that can move rows, so a scrolled viewport costs its strip here.
#[cfg(feature = "raster")]
pub fn paint(&mut self, frame: &mut Frame<'_>) {
let age = frame.age();
let mut raster = Canvas::new(frame);
let mut canvas = Pen::new(&mut raster);
self.paint_with(&mut canvas, age);
}
/// `blitted` is what [`Ui::scroll_blit_with`] moved and the strip it left
/// to paint: the strip replaces the moved rectangle in the regions, and
/// the rectangle is cut out of any region the tracker merged it into.
fn paint_regions(
&mut self,
canvas: &mut Pen<'_>,
age: BufferAge,
blitted: Option<(Rect, Rect)>,
) {
// The tracker's rectangles, plus what cutting one of them around a
// moved rectangle can add: at most one contains it, and that one
// becomes up to four.
let mut regions = [Rect::ZERO; MAX_DAMAGE_RECTS + 4];
let count = {
let resolved = self.damage.resolve(age);
regions[..resolved.len()].copy_from_slice(resolved);
resolved.len()
};
let count = match blitted {
Some((moved, strip)) => {
let mut cut = [Rect::ZERO; MAX_DAMAGE_RECTS + 4];
cut[0] = strip;
let mut n = 1;
for region in ®ions[..count] {
for piece in region.difference(&moved) {
cut[n] = piece;
n += 1;
}
}
regions = cut;
n
}
None => count,
};
let base = self.theme.color(Role::Base100);
for region in ®ions[..count] {
let mut region_canvas = canvas.with_clip(*region);
if region_canvas.is_clipped_out() {
continue;
}
region_canvas.clear(base);
// Only the topmost veil paints. Two modals stacked would otherwise
// double-dim everything under both, and a popup inside a modal must
// not darken the modal it serves.
let top_veil = self.scenes.iter().rposition(|s| s.dim > 0);
let mut start = 0;
for (index, scene) in self.scenes.iter().enumerate() {
let end = self.scene_end[index];
if scene.dim > 0 && top_veil == Some(index) {
let veil = region_canvas.clip();
region_canvas.fill_rect(veil, Color::rgba(0, 0, 0, scene.dim));
}
for &id in &self.order[start..end] {
let Some(node) = self.nodes.get(id) else {
continue;
};
if !node.paintable() || !node.clip.intersects(region) {
continue;
}
let mut ctx = PaintCtx {
theme: &self.theme,
text: &mut self.text,
bounds: node.bounds,
state: node.state,
now_ms: self.now_ms,
};
let mut widget_canvas = region_canvas.with_clip(node.clip);
node.widget.paint(&mut ctx, &mut widget_canvas);
}
start = end;
}
self.toasts.paint(
&self.theme,
self.size,
&mut self.text,
self.now_ms,
&mut region_canvas,
);
// Above every widget, below the pointer: a bubble the cursor
// covers is a bubble nobody can read.
self.tooltip
.paint(&self.theme, self.size, &mut self.text, &mut region_canvas);
self.cursor.paint(&self.theme, &mut region_canvas);
}
}
/// Acquires, paints and presents in one call. Returns `false` when nothing was
/// dirty and no frame was drawn.
///
/// A [`Surface`] hands out a [`Frame`] of words, so this is the rasterising
/// path by construction; without the `raster` feature, drive
/// [`Ui::paint_with`] from your own loop instead.
#[cfg(feature = "raster")]
pub fn render(&mut self, surface: &mut impl Surface) -> Result<bool, SurfaceError> {
if !self.needs_paint() {
return Ok(false);
}
let mut frame = surface.acquire()?;
self.paint(&mut frame);
drop(frame);
surface.present(self.damage.resolved())?;
self.damage.end_frame();
Ok(true)
}
// -------------------------------------------------------------- internals
fn handle_one(&mut self, event: &InputEvent) {
// Anything but a bare pointer move means the person moved on.
if !matches!(event, InputEvent::PointerMoved { .. }) && self.tooltip.dismiss_wanted(event) {
if self.tooltip.is_shown() {
self.damage_tooltip();
}
self.tooltip.dismiss();
}
match event {
InputEvent::PointerMoved { position } => {
self.move_pointer(*position, true);
if let Some(id) = self.pressed.or(self.hovered) {
self.dispatch(id, &Event::Input(event));
}
}
InputEvent::PointerButton {
state: ElementState::Down,
position,
..
} => {
if self.dismiss_toast(*position) {
return;
}
if self.dismisses_popup(*position) {
// Swallowed entirely: the press closed the popup, and must
// not also reach whatever was underneath. The matching Up
// finds nothing pressed and activates nothing.
self.close_popup();
return;
}
if self.dismisses_drawer(*position) {
self.close_drawer();
return;
}
self.move_pointer(*position, true);
self.press(event);
}
InputEvent::PointerButton {
state: ElementState::Up,
position,
..
} => {
self.move_pointer(*position, true);
self.release(event);
}
InputEvent::PointerScroll {
position,
delta_x,
delta_y,
} => {
self.move_pointer(*position, true);
// The hovered widget sees the wheel first — a widget may make
// it mean something else. Unconsumed, it scrolls the innermost
// scrollable under the pointer.
let handled = match self.hovered {
Some(id) => self.dispatch(id, &Event::Input(event)).is_handled(),
None => false,
};
if !handled && let Some(target) = self.scroll_target(*position) {
self.scroll_by(target, *delta_x as i32, *delta_y as i32);
}
}
InputEvent::PointerLeft => {
self.show_cursor(false);
self.set_hovered(None);
}
InputEvent::TouchDown { position, .. } => {
if self.dismiss_toast(*position) {
return;
}
if self.dismisses_popup(*position) {
self.close_popup();
return;
}
if self.dismisses_drawer(*position) {
self.close_drawer();
return;
}
self.move_pointer(*position, false);
self.press(event);
if self.pressed.is_none() {
// Nothing interactive claimed the finger; if it landed in a
// viewport, moving it drags the scroll.
self.touch_scroll = self.scroll_target(*position).map(|id| (id, *position));
}
}
InputEvent::TouchMoved { position, .. } => {
self.move_pointer(*position, false);
if let Some((target, last)) = self.touch_scroll {
// Content follows the finger: dragging up moves the scroll
// down.
self.scroll_by(target, last.x - position.x, last.y - position.y);
self.touch_scroll = Some((target, *position));
} else if let Some(id) = self.pressed {
self.dispatch(id, &Event::Input(event));
}
}
InputEvent::TouchUp { position, .. } => {
self.touch_scroll = None;
self.move_pointer(*position, false);
self.release(event);
self.set_hovered(None);
}
InputEvent::Key {
code: KeyCode::Tab,
state: ElementState::Down,
modifiers,
..
} => {
// Tab belongs to the toolkit, not to the focused widget. A panel
// with no pointer is driven entirely by this.
self.focus_step(modifiers.contains(Modifiers::SHIFT));
}
InputEvent::Key {
code: KeyCode::Escape,
state: ElementState::Down,
..
} if self.scenes.last().is_some_and(|s| s.popup.is_some()) => {
// Escape belongs to the popup before it belongs to the focused
// widget: a dropdown open over a text field closes on Escape
// rather than handing the key to the field behind it.
self.close_popup();
}
InputEvent::Key {
code: KeyCode::Escape,
state: ElementState::Down,
..
} if self.drawer_on_top() => {
// And to the drawer, for the same reason.
self.close_drawer();
}
InputEvent::Key {
code: code @ (KeyCode::PageUp | KeyCode::PageDown),
state: ElementState::Down,
..
} => {
// The focused widget sees the page keys first; unconsumed, they
// page the scrollable that contains the focus, by its own
// height.
let handled = match self.focused {
Some(id) => self.dispatch(id, &Event::Input(event)).is_handled(),
None => false,
};
if !handled && let Some(target) = self.scrollable_ancestor(self.focused) {
let page = self.nodes[target].layout.height;
let dy = if matches!(code, KeyCode::PageDown) {
page
} else {
-page
};
self.scroll_by(target, 0, dy);
}
}
InputEvent::Key { .. } | InputEvent::Text { .. } => {
if let Some(id) = self.focused {
self.dispatch(id, &Event::Input(event));
}
}
InputEvent::SurfaceResized { size, .. } => self.resize(*size),
_ => {}
}
}
fn move_pointer(&mut self, position: Point, show_cursor: bool) {
// `show_cursor` here is the *input kind* — a pointer wants a sprite, a
// finger does not. It only decides anything while nobody has said
// otherwise; see `Ui::show_cursor`.
let visible = if self.cursor_auto {
show_cursor
} else {
self.cursor.visible
};
if self.pointer != position || self.cursor.visible != visible {
self.dirty(self.cursor.bounds());
self.pointer = position;
self.cursor.position = position;
self.cursor.visible = visible;
self.dirty(self.cursor.bounds());
}
self.update_hover();
}
fn update_hover(&mut self) {
let hit = self.hit_test(self.pointer);
match self.pressed {
// While a button is held the hover does not wander off to other
// widgets, and the pressed one shows its state only while the pointer
// is still over it — which is how a drag-off-then-release cancels.
Some(pressed) => {
let inside = hit == Some(pressed);
self.set_hovered(inside.then_some(pressed));
self.set_state(pressed, VisualState::PRESSED, inside);
}
None => self.set_hovered(hit),
}
}
fn press(&mut self, event: &InputEvent) {
let hit = self.hit_test(self.pointer);
self.pressed = hit;
match hit {
Some(id) => {
self.set_state(id, VisualState::PRESSED, true);
self.set_hovered(Some(id));
// A widget that preserves focus is asking to be pressed without
// being noticed by the focus ring at all — neither taking it nor
// clearing it, which is what a keyboard key needs while the field
// it types into stays live.
if !self
.nodes
.get(id)
.is_some_and(|node| node.widget.preserves_focus())
{
let focus = self.is_focusable(id).then_some(id);
self.set_focus(focus);
}
self.dispatch(id, &Event::Input(event));
}
// Clicking the background drops focus, which is what makes a text
// field commit and stop blinking.
None => self.set_focus(None),
}
}
/// Drops a held press that no release will ever arrive for.
///
/// A scene pushed over the pressed node, the scene it lives in popped, its
/// node removed or disabled: the press is over and nothing in the pointer
/// stream says so. Clearing the flag alone left the widget looking pressed
/// and — for one that drives a timer from being held — believing a finger
/// was still there.
fn cancel_press(&mut self) {
let Some(id) = self.pressed.take() else {
return;
};
if !self.nodes.contains_key(id) {
return;
}
self.set_state(id, VisualState::PRESSED, false);
self.dispatch(id, &Event::PressCancelled);
}
fn release(&mut self, event: &InputEvent) {
if let Some(id) = self.pressed {
self.set_state(id, VisualState::PRESSED, false);
self.dispatch(id, &Event::Input(event));
}
self.pressed = None;
self.update_hover();
}
/// Delivers an event and applies whatever the widget asked for.
fn dispatch(&mut self, id: NodeId, event: &Event<'_>) -> Handled {
let (handled, wants_focus) = self.deliver(id, event);
if wants_focus && self.is_focusable(id) {
self.set_focus(Some(id));
}
handled
}
fn deliver(&mut self, id: NodeId, event: &Event<'_>) -> (Handled, bool) {
let Some(node) = self.nodes.get_mut(id) else {
return (Handled::No, false);
};
if node.state.contains(VisualState::DISABLED) {
return (Handled::No, false);
}
let mut ctx = EventCtx::new(
node.bounds,
&self.theme,
&mut self.text,
node.state,
self.now_ms,
&mut self.messages,
);
let handled = node.widget.on_event(event, &mut ctx);
let outcome = ctx.finish();
let clip = node.clip;
match outcome.scrolled {
// The widget moved its own content: recorded the way a viewport's
// scroll is, before the damage and not through `dirty`, which
// would take the record away. What the move did not cover — a
// scrollbar, a header — is dirtied like anything else.
Some((within, by)) if !outcome.dirty => match within.intersect(&clip) {
Some(within) => {
self.note_scroll(id, by, within);
self.damage.add(within);
for rest in clip.difference(&within) {
self.dirty(rest);
}
}
None => self.dirty(clip),
},
_ if outcome.dirty || handled.is_handled() => self.dirty(clip),
_ => {}
}
if outcome.wants_animation {
self.request_animation(id);
}
if let Some(rect) = outcome.reveal {
self.reveal_rect(id, rect);
}
// A widget asking to be a different height. See
// [`EventCtx::resize_height`] for why that is a request and not a call.
if let Some((height, duration_ms)) = outcome.resize
&& let Some(layout) = self.nodes.get(id).map(|node| node.layout)
{
let to = Rect::new(layout.x, layout.y, layout.width, height);
self.animate_layout(id, to, duration_ms);
}
(handled, outcome.wants_focus)
}
fn set_hovered(&mut self, id: Option<NodeId>) {
if self.hovered == id {
return;
}
// Moving on restarts the dwell, or ends it. The footprint is damaged
// *first*: every state change here forgets where the bubble was, so
// measuring afterwards measures nothing and the pixels stay on a
// display that repaints only what it was told to.
let has_tooltip = id
.and_then(|id| self.nodes.get(id))
.is_some_and(|node| node.tooltip.is_some());
if self.tooltip.is_shown() {
self.damage_tooltip();
}
self.tooltip.hover_changed(has_tooltip, self.now_ms);
if let Some(old) = self.hovered {
self.set_state(old, VisualState::HOVERED, false);
}
self.hovered = id;
if let Some(new) = id {
self.set_state(new, VisualState::HOVERED, true);
}
}
fn set_focus(&mut self, id: Option<NodeId>) {
if self.focused == id {
return;
}
if let Some(old) = self.focused {
self.set_state(old, VisualState::FOCUSED, false);
self.focused = None;
self.deliver(old, &Event::FocusLost);
}
self.focused = id;
// One place records it because one place changes it, and the early
// return above means a focus that did not move is never reported.
self.focus_changed = Some(id);
if let Some(new) = id {
self.set_state(new, VisualState::FOCUSED, true);
self.deliver(new, &Event::FocusGained);
// Focus must be visible: tabbing to a widget below the fold scrolls
// it into view, or a keyboard-only panel focuses something nobody
// can see.
if let Some(node) = self.nodes.get(new) {
let bounds = node.bounds;
self.reveal_rect(new, bounds);
}
}
}
fn set_state(&mut self, id: NodeId, flag: VisualState, on: bool) {
let Some(node) = self.nodes.get_mut(id) else {
return;
};
if node.state.contains(flag) == on {
return;
}
node.state = node.state.set(flag, on);
let clip = node.clip;
self.dirty(clip);
}
/// Drops a subtree out of the animating set — used on hide and removal.
fn stop_animating_subtree(&mut self, id: NodeId) {
let mut i = 0;
while i < self.animating.len() {
if self.subtree_contains(id, Some(self.animating[i])) {
self.animating.swap_remove(i);
} else {
i += 1;
}
}
}
/// Drops a node out of hover, press and focus — used when it is removed,
/// hidden or disabled, so no stale id keeps receiving events.
fn forget(&mut self, id: NodeId) {
if self.subtree_contains(id, self.hovered) {
self.set_hovered(None);
}
if self.subtree_contains(id, self.pressed) {
self.cancel_press();
}
if self.subtree_contains(id, self.focused) {
self.set_focus(None);
}
}
fn subtree_contains(&self, root: NodeId, id: Option<NodeId>) -> bool {
let Some(mut cursor) = id else {
return false;
};
loop {
if cursor == root {
return true;
}
match self.nodes.get(cursor).and_then(|n| n.parent) {
Some(parent) => cursor = parent,
None => return false,
}
}
}
fn focus_step(&mut self, backwards: bool) {
// The same list `tab_stops` hands out, because it is the same call: a
// tool drawing the order and the tree walking it cannot drift apart if
// there is only one of them.
let candidates = self.tab_stops();
if candidates.is_empty() {
self.set_focus(None);
return;
}
let current = self
.focused
.and_then(|f| candidates.iter().position(|&c| c == f));
let next = match (current, backwards) {
(Some(i), false) => (i + 1) % candidates.len(),
(Some(i), true) => (i + candidates.len() - 1) % candidates.len(),
(None, false) => 0,
(None, true) => candidates.len() - 1,
};
self.set_focus(Some(candidates[next]));
}
fn is_focusable(&self, id: NodeId) -> bool {
self.nodes.get(id).is_some_and(|node| {
// A clipped-out node is still reachable when a scrollable ancestor
// can bring it back: taking focus is what scrolls it into view, so
// demanding visibility first would make everything below the fold
// permanently unreachable by keyboard — the catch-22 the scrolling
// tests caught on their first run.
let reachable = node.visible
&& (!node.clip.is_empty() || self.scrollable_ancestor(node.parent).is_some());
reachable
&& !node.state.contains(VisualState::DISABLED)
&& node.widget.focusable()
// Only the topmost scene is reachable. Scanning the paint order
// for this would be O(n) per candidate and O(n²) per Tab; the
// node already knows which scene it belongs to.
&& node.scene + 1 == self.scenes.len()
})
}
fn is_interactive(&self, node: &Node<M>) -> bool {
!node.state.contains(VisualState::DISABLED) && node.widget.accepts_pointer()
}
/// Range of `order` belonging to the topmost scene.
fn input_span(&self) -> (usize, usize) {
match self.scene_end.len() {
0 => (0, 0),
1 => (0, self.scene_end[0]),
n => (self.scene_end[n - 2], self.scene_end[n - 1]),
}
}
fn resize(&mut self, size: Size) {
if size == self.size {
return;
}
self.size = size;
self.damage.resize(size);
let roots: Vec<NodeId> = self.scenes.iter().map(|s| s.root).collect();
for root in roots {
if let Some(node) = self.nodes.get_mut(root) {
node.layout = Rect::from_size(size);
}
self.reflow(root);
}
self.damage.add_full();
}
fn sort_children(&mut self, parent: NodeId) {
// Siblings are kept in paint order, so the flatten below is a plain
// depth-first walk rather than a sort of the whole tree every frame.
let mut children = match self.nodes.get_mut(parent) {
Some(node) => core::mem::take(&mut node.children),
None => return,
};
let mut keys: Vec<(i32, NodeId)> = children
.iter()
.map(|&id| (self.nodes.get(id).map_or(0, |n| n.z), id))
.collect();
keys.sort_by_key(|&(z, _)| z);
children.clear();
children.extend(keys.into_iter().map(|(_, id)| id));
if let Some(node) = self.nodes.get_mut(parent) {
node.children = children;
}
}
fn ensure_order(&mut self) {
if !self.order_dirty {
return;
}
self.order.clear();
self.scene_end.clear();
let roots: Vec<NodeId> = self.scenes.iter().map(|s| s.root).collect();
let mut stack = Vec::new();
for root in roots {
stack.clear();
stack.push(root);
while let Some(id) = stack.pop() {
let Some(node) = self.nodes.get(id) else {
continue;
};
// A hidden node takes its descendants with it, which is what
// `set_visible` promises. Skipping the subtree here is what
// makes that true of *everything* this list drives -- painting,
// hit testing, tab stops and scroll targets all read it, and
// each one used to ask only whether the node itself was
// visible. So a button inside a hidden container was drawn,
// clickable, tabbable and scrollable.
if !node.visible {
continue;
}
self.order.push(id);
// Reversed, because the stack pops last-in first.
stack.extend(node.children.iter().rev().copied());
}
self.scene_end.push(self.order.len());
}
self.order_dirty = false;
}
/// A rectangle's extent as a [`Size`], never negative.
fn extent(rect: Rect) -> Size {
Size::new(rect.width.max(0) as u32, rect.height.max(0) as u32)
}
/// Turns layouts into absolute bounds for a subtree.
///
/// The one place that happens. Four rules meet here and their order is the
/// contract: **docking** takes edges from the parent's content box, then a
/// **stack** or **anchoring** places what is left, then the **scroll offset**
/// shifts all of it. Everything downstream — bounds, clip, paint, damage,
/// hit testing — reads only what this loop wrote, so none of them can
/// disagree about where a node ended up.
///
/// No rule rewrites a node's `layout`. Each derives a rectangle from it, so
/// the application's rectangles stay the application's, and a form file keeps
/// one rectangle per node however it is being placed.
fn reflow(&mut self, id: NodeId) {
// A docked node's rectangle is a statement about its siblings, so it
// cannot be computed from the node alone. Climbing here rather than at
// every call site is what makes that true of *every* path into the
// reflow — a layout set, a stack turned on, a scroll clamped — instead of
// only the ones that remembered.
let id = self.reflow_root(id);
let (rect, clip, disabled) = match self.nodes.get(id).and_then(|n| n.parent) {
Some(parent) => {
let Some(node) = self.nodes.get(parent) else {
return;
};
let (clip, disabled) = (node.clip, node.state.contains(VisualState::DISABLED));
let origin =
Point::new(node.bounds.x - node.scroll.x, node.bounds.y - node.scroll.y);
let available = Self::extent(node.bounds);
// Reaching here means the parent does not arrange its children:
// `reflow_root` sends a node whose parent stacks or docks to the
// parent instead, because such a node cannot be placed without
// its siblings. So the box is the parent's whole content box.
let Some(child) = self.nodes.get(id) else {
return;
};
let base = child.anchor_base.unwrap_or(available);
let local = anchor::anchored(child.layout, base, available, child.anchors);
if let Some(child) = self.nodes.get_mut(id) {
child.anchor_base.get_or_insert(available);
}
(local.translate(origin.x, origin.y), clip, disabled)
}
None => match self.nodes.get(id) {
Some(node) => (node.layout, Rect::from_size(self.size), false),
None => return,
},
};
let mut work = vec![(id, rect, clip, disabled)];
while let Some((id, rect, clip, disabled)) = work.pop() {
let Some(node) = self.nodes.get_mut(id) else {
continue;
};
node.bounds = rect;
node.clip = rect.intersect(&clip).unwrap_or(Rect::ZERO);
let disabled = disabled || !node.enabled;
node.state = node.state.set(VisualState::DISABLED, disabled);
// The scroll offset happens here and only here.
let origin = Point::new(rect.x - node.scroll.x, rect.y - node.scroll.y);
let child_clip = node.clip;
let stack = node.stack;
let children = node.children.clone();
// Docked children take their edges first, in paint order, each from
// what the ones before it left — so two bars docked to the top are
// two stacked bars, and what remains is the box everything else is
// placed in. A hidden child takes no room, as in a stack.
let mut remaining = Rect::new(0, 0, rect.width, rect.height);
for &c in &children {
let Some(child) = self.nodes.get(c) else {
continue;
};
let (Some(dock), true) = (child.dock, child.visible) else {
continue;
};
let (taken, rest) = anchor::docked(child.layout, remaining, dock);
remaining = rest;
work.push((c, taken.translate(origin.x, origin.y), child_clip, disabled));
}
let available = Self::extent(remaining);
let mut running = 0i32;
for c in children {
let Some(child) = self.nodes.get(c) else {
continue;
};
if child.dock.is_some() && child.visible {
continue;
}
let local = match stack {
// A stack places its visible children top-to-bottom at the
// running y, keeping their own x, width and height — which
// is what lets a layout tween on one child move every
// sibling below it without anybody keeping books.
Some(spacing) if child.visible => {
let placed = Rect::new(
child.layout.x,
running,
child.layout.width,
child.layout.height,
);
running = running
.saturating_add(child.layout.height.max(0))
.saturating_add(spacing);
placed
}
// A hidden child takes no space and moves nobody, but still
// needs bounds: it may be shown again, and its own children
// are reflowed from them.
Some(_) => child.layout,
None => {
let base = child.anchor_base.unwrap_or(available);
let local = anchor::anchored(child.layout, base, available, child.anchors);
if let Some(child) = self.nodes.get_mut(c) {
child.anchor_base.get_or_insert(available);
}
local
}
};
work.push((
c,
local.translate(origin.x + remaining.x, origin.y + remaining.y),
child_clip,
disabled,
));
}
}
}
fn damage_subtree(&mut self, id: NodeId) {
let mut stack = vec![id];
while let Some(id) = stack.pop() {
let Some(node) = self.nodes.get(id) else {
continue;
};
let clip = node.clip;
stack.extend(node.children.iter().copied());
self.dirty(clip);
}
}
fn drop_subtree(&mut self, id: NodeId) {
self.forget(id);
self.stop_animating_subtree(id);
let mut stack = vec![id];
while let Some(id) = stack.pop() {
let Some(node) = self.nodes.remove(id) else {
continue;
};
stack.extend(node.children.iter().copied());
}
}
}
impl<M: 'static> core::fmt::Debug for Ui<M> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Ui")
.field("nodes", &self.nodes.len())
.field("scenes", &self.scenes.len())
.field("size", &self.size)
.field("theme", &self.theme.name)
.field("glyphs", &self.text.atlas().len())
.field("focused", &self.focused)
.field("hovered", &self.hovered)
.finish_non_exhaustive()
}
}