1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
//! Callback handling for layout events
//!
//! This module provides the CallbackInfo struct and related types for handling
//! UI callbacks. Callbacks need access to layout information (node sizes, positions,
//! hierarchy), which is why this module lives in azul-layout instead of azul-core.
// Re-export callback macro from azul-core
use alloc::{
boxed::Box,
collections::{btree_map::BTreeMap, VecDeque},
sync::Arc,
vec::Vec,
};
#[cfg(feature = "std")]
use std::sync::Mutex;
use azul_core::{
resources::UpdateImageType,
callbacks::{CoreCallback, FocusTarget, FocusTargetPath, HidpiAdjustedBounds, Update},
dom::{DomId, DomIdVec, DomNodeId, IdOrClass, NodeId, NodeType},
geom::{LogicalPosition, LogicalRect, LogicalSize, OptionLogicalPosition, OptionCursorNodePosition, OptionScreenPosition, OptionDragDelta, CursorNodePosition, ScreenPosition, DragDelta},
gl::OptionGlContextPtr,
gpu::GpuValueCache,
hit_test::ScrollPosition,
id::NodeId as CoreNodeId,
impl_callback,
menu::Menu,
refany::{OptionRefAny, RefAny},
resources::{ImageCache, ImageMask, ImageRef, LoadedFont, LoadedFontVec, RendererResources},
selection::{Selection, SelectionRange, SelectionRangeVec, SelectionState, TextCursor},
styled_dom::{NodeHierarchyItemId, NodeHierarchyItemIdVec, StyledDom},
task::{self, GetSystemTimeCallback, Instant, ThreadId, ThreadIdVec, TimerId, TimerIdVec},
window::{KeyboardState, Monitor, MonitorVec, MouseState, OptionMonitor, RawWindowHandle, WindowFlags, WindowSize},
FastBTreeSet, OrderedMap,
};
use azul_css::{
css::CssPath,
props::{
basic::FontRef,
property::{CssProperty, CssPropertyType, CssPropertyVec},
},
system::SystemStyle,
corety::{OptionString, OptionUsize},
AzString, OptionU8Vec, StringVec, U8Vec,
};
use rust_fontconfig::FcFontCache;
#[cfg(feature = "icu")]
use crate::icu::{
FormatLength, IcuDate, IcuDateTime, IcuLocalizerHandle, IcuResult,
IcuStringVec, IcuTime, ListType, PluralCategory,
};
use crate::{
hit_test::FullHitTest,
managers::{
file_drop::FileDropManager,
focus_cursor::FocusManager,
gesture::{GestureAndDragManager, InputSample, PenState},
gpu_state::GpuStateManager,
hover::{HoverManager, InputPointId},
virtual_view::VirtualViewManager,
scroll_state::{AnimatedScrollState, ScrollManager},
selection::ClipboardContent,
text_input::{PendingTextEdit, TextInputManager},
undo_redo::{UndoRedoManager, UndoableOperation},
},
text3::cache::{TextShapingCache as TextLayoutCache, UnifiedLayout},
thread::{CreateThreadCallback, Thread},
timer::Timer,
window::{DomLayoutResult, LayoutWindow},
window_state::{FullWindowState, FullWindowStateVec, WindowCreateOptions},
};
use azul_css::{impl_option, impl_option_inner};
// ============================================================================
// FFI-safe wrapper types for tuple returns
// ============================================================================
/// FFI-safe wrapper for pen tilt angles (`x_tilt`, `y_tilt`) in degrees
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
#[repr(C)]
pub struct PenTilt {
/// X-axis tilt angle in degrees (-90 to 90)
pub x_tilt: f32,
/// Y-axis tilt angle in degrees (-90 to 90)
pub y_tilt: f32,
}
impl From<(f32, f32)> for PenTilt {
fn from((x, y): (f32, f32)) -> Self {
Self {
x_tilt: x,
y_tilt: y,
}
}
}
impl_option!(
PenTilt,
OptionPenTilt,
[Debug, Clone, Copy, PartialEq, PartialOrd]
);
/// FFI-safe wrapper for select-all result (`full_text`, `selected_range`)
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C)]
pub struct SelectAllResult {
/// The full text content of the node
pub full_text: AzString,
/// The range that would be selected
pub selection_range: SelectionRange,
}
impl From<(String, SelectionRange)> for SelectAllResult {
fn from((text, range): (String, SelectionRange)) -> Self {
Self {
full_text: text.into(),
selection_range: range,
}
}
}
impl_option!(
SelectAllResult,
OptionSelectAllResult,
copy = false,
[Debug, Clone, PartialEq, Eq]
);
/// FFI-safe wrapper for delete inspection result (`range_to_delete`, `deleted_text`)
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(C)]
pub struct DeleteResult {
/// The range that would be deleted
pub range_to_delete: SelectionRange,
/// The text that would be deleted
pub deleted_text: AzString,
}
impl From<(SelectionRange, String)> for DeleteResult {
fn from((range, text): (SelectionRange, String)) -> Self {
Self {
range_to_delete: range,
deleted_text: text.into(),
}
}
}
impl_option!(
DeleteResult,
OptionDeleteResult,
copy = false,
[Debug, Clone, PartialEq, Eq]
);
/// Represents a change made by a callback that will be applied after the callback returns
///
/// This transaction-based system provides:
/// - Clear separation between read-only queries and modifications
/// - Atomic application of all changes
/// - Easy debugging and logging of callback actions
/// - Future extensibility for new change types
#[derive(Debug, Clone)]
pub enum CallbackChange {
// Window State Changes
/// Modify the window state (size, position, title, etc.)
ModifyWindowState { state: FullWindowState },
/// Inject a platform-native gesture-recognizer result into the
/// in-process `GestureAndDragManager`. Read by the next
/// `detect_long_press` / `detect_swipe_direction` / `detect_pinch` /
/// `detect_rotation` / `detect_double_click` call, then cleared.
InjectNativeGesture {
gesture: crate::managers::gesture::NativeGestureEvent,
},
/// Queue multiple window state changes to be applied in sequence across frames.
/// This is needed for simulating clicks (mouse down -> wait -> mouse up) where each
/// state change needs to trigger separate event processing.
QueueWindowStateSequence { states: Vec<FullWindowState> },
/// Create a new window
CreateNewWindow { options: WindowCreateOptions },
/// Close the current window (via `Update::CloseWindow` return value, tracked here for logging)
CloseWindow,
// Focus Management
/// Change keyboard focus to a specific node or clear focus
SetFocusTarget { target: FocusTarget },
// Event Propagation Control
/// Stop event from propagating to parent nodes (W3C stopPropagation).
/// Remaining handlers on the *current* node still fire, but no handlers
/// on ancestor / descendant nodes in subsequent phases.
StopPropagation,
/// Stop event propagation immediately (W3C stopImmediatePropagation).
/// No further handlers fire - not even remaining handlers on the same node.
StopImmediatePropagation,
/// Prevent default browser behavior (e.g., block text input from being applied)
PreventDefault,
// Timer Management
/// Add a new timer to the window
AddTimer { timer_id: TimerId, timer: Timer },
/// Remove an existing timer
RemoveTimer { timer_id: TimerId },
// Thread Management
/// Add a new background thread
AddThread { thread_id: ThreadId, thread: Thread },
/// Remove an existing thread
RemoveThread { thread_id: ThreadId },
// Content Modifications
/// Change the text content of a node
ChangeNodeText { node_id: DomNodeId, text: AzString },
/// Change the image of a node
ChangeNodeImage {
dom_id: DomId,
node_id: NodeId,
image: ImageRef,
update_type: UpdateImageType,
},
/// Re-render an image callback (for resize/animation)
/// This triggers re-invocation of the `RenderImageCallback`
UpdateImageCallback { dom_id: DomId, node_id: NodeId },
/// Re-render ALL image callbacks across all DOMs.
///
/// This is the most efficient way to update animated GL textures:
/// it triggers only texture re-rendering without DOM rebuild or
/// display list resubmission. Used by timer callbacks that need
/// to update OpenGL textures every frame.
UpdateAllImageCallbacks,
/// Trigger re-rendering of a `VirtualView` with a new DOM
/// This forces the `VirtualView` to call its callback and update the display list
UpdateVirtualView { dom_id: DomId, node_id: NodeId },
/// Re-render EVERY `VirtualView` on the existing DOM (no node id needed).
/// For shared-dataset changes that arrive out-of-band (e.g. a background
/// tile-fetch writeback): the views re-read their cloned dataset in place.
UpdateAllVirtualViews,
/// Change the image mask of a node
ChangeNodeImageMask {
dom_id: DomId,
node_id: NodeId,
mask: ImageMask,
},
/// Change CSS properties of a node
ChangeNodeCssProperties {
dom_id: DomId,
node_id: NodeId,
properties: CssPropertyVec,
},
/// Override CSS properties on a node via the user-override channel
/// (`CssPropertyCache::user_overridden_properties`). Unlike
/// `ChangeNodeCssProperties`, this does not mutate the node's static
/// `css_props` - the override layer is read at higher priority by the
/// property resolution pipeline, so animating a handful of properties
/// per frame stays cheap. Passing `CssProperty::Initial` for a property
/// removes any prior override for that type on the same node.
OverrideNodeCssProperties {
dom_id: DomId,
node_id: NodeId,
properties: CssPropertyVec,
},
// Scroll Management
/// Scroll a node to a specific position
ScrollTo {
dom_id: DomId,
node_id: NodeHierarchyItemId,
position: LogicalPosition,
/// When true, skip clamping to [0, `max_scroll`] bounds.
/// Used by the scroll physics timer for rubber-banding/overscroll.
unclamped: bool,
},
/// Scroll a node into view (W3C scrollIntoView API)
/// The scroll adjustments are calculated and applied when the change is processed
ScrollIntoView {
node_id: DomNodeId,
options: crate::managers::scroll_into_view::ScrollIntoViewOptions,
},
// Image Cache Management
/// Add an image to the image cache
AddImageToCache { id: AzString, image: ImageRef },
/// Remove an image from the image cache
RemoveImageFromCache { id: AzString },
// Font Cache Management
/// Reload system fonts (expensive operation)
ReloadSystemFonts,
// Menu Management
/// Open a context menu or dropdown menu
/// Whether it's native or fallback depends on `window.state.flags.use_native_context_menus`
OpenMenu {
menu: Menu,
/// Optional position override (if None, uses menu.position)
position: Option<LogicalPosition>,
},
// Tooltip Management
/// Show a tooltip at a specific position
///
/// Platform-specific implementation:
/// - Windows: Uses native tooltip window (`TOOLTIPS_CLASS`)
/// - macOS: Uses `NSPopover` or custom `NSWindow` with tooltip styling
/// - X11: Creates transient window with _`NET_WM_WINDOW_TYPE_TOOLTIP`
/// - Wayland: Creates surface with `zwlr_layer_shell_v1` (overlay layer)
ShowTooltip {
text: AzString,
position: LogicalPosition,
},
/// Hide the currently displayed tooltip
HideTooltip,
// Text Editing
/// Insert text at the current cursor position or replace selection
InsertText {
dom_id: DomId,
node_id: NodeId,
text: AzString,
},
/// Delete text backward (backspace) at cursor
DeleteBackward { dom_id: DomId, node_id: NodeId },
/// Delete text forward (delete key) at cursor
DeleteForward { dom_id: DomId, node_id: NodeId },
/// Move cursor to a specific position
MoveCursor {
dom_id: DomId,
node_id: NodeId,
cursor: TextCursor,
},
/// Set text selection range
SetSelection {
dom_id: DomId,
node_id: NodeId,
selection: Selection,
},
/// Set/override the text changeset for the current text input operation
/// This allows callbacks to modify what text will be inserted during text input events
SetTextChangeset { changeset: PendingTextEdit },
// Cursor Movement Operations
/// Move cursor left (arrow left)
MoveCursorLeft {
dom_id: DomId,
node_id: NodeId,
extend_selection: bool,
},
/// Move cursor right (arrow right)
MoveCursorRight {
dom_id: DomId,
node_id: NodeId,
extend_selection: bool,
},
/// Move cursor up (arrow up)
MoveCursorUp {
dom_id: DomId,
node_id: NodeId,
extend_selection: bool,
},
/// Move cursor down (arrow down)
MoveCursorDown {
dom_id: DomId,
node_id: NodeId,
extend_selection: bool,
},
/// Move cursor to line start (Home key)
MoveCursorToLineStart {
dom_id: DomId,
node_id: NodeId,
extend_selection: bool,
},
/// Move cursor to line end (End key)
MoveCursorToLineEnd {
dom_id: DomId,
node_id: NodeId,
extend_selection: bool,
},
/// Move cursor to document start (Ctrl+Home)
MoveCursorToDocumentStart {
dom_id: DomId,
node_id: NodeId,
extend_selection: bool,
},
/// Move cursor to document end (Ctrl+End)
MoveCursorToDocumentEnd {
dom_id: DomId,
node_id: NodeId,
extend_selection: bool,
},
// Multi-Cursor Operations
/// Add an additional cursor at the specified position (Ctrl+Click from C API)
AddCursor {
dom_id: DomId,
node_id: NodeId,
cursor: TextCursor,
},
/// Add an additional selection range (for multi-cursor)
AddSelectionRange {
dom_id: DomId,
node_id: NodeId,
range: SelectionRange,
},
/// Remove a specific selection by its stable ID
RemoveSelectionById {
selection_id: azul_core::selection::SelectionId,
},
// Clipboard Operations (Override)
/// Override clipboard content for copy operation
SetCopyContent {
target: DomNodeId,
content: ClipboardContent,
},
/// Override clipboard content for cut operation
SetCutContent {
target: DomNodeId,
content: ClipboardContent,
},
/// Override selection range for select-all operation
SetSelectAllRange {
target: DomNodeId,
range: SelectionRange,
},
// Hit Test Request (for Debug API)
/// Request a hit test update at a specific position
///
/// This is used by the Debug API to update the hover manager's hit test
/// data after modifying the mouse position, ensuring that callbacks
/// can find the correct nodes under the cursor.
RequestHitTestUpdate { position: LogicalPosition },
// Text Selection (for Debug API)
/// Process a text selection click at a specific position
///
/// This is used by the Debug API to trigger text selection directly,
/// bypassing the normal event pipeline. The handler will:
/// 1. Hit-test IFC roots to find selectable text at the position
/// 2. Create a text cursor at the clicked position
/// 3. Update the selection manager with the new selection
ProcessTextSelectionClick {
position: LogicalPosition,
time_ms: u64,
},
// Cursor Blinking (System Timer Control)
/// Set the cursor visibility state (called by blink timer)
SetCursorVisibility { visible: bool },
/// Toggle cursor visibility based on blink timing
ToggleCursorVisibility,
/// Reset cursor blink state on user input (makes cursor visible, records time)
ResetCursorBlink,
/// Start the cursor blink timer for the focused contenteditable element
StartCursorBlinkTimer,
/// Stop the cursor blink timer (when focus leaves contenteditable)
StopCursorBlinkTimer,
// Scroll cursor/selection into view
/// Scroll the active text cursor into view within its scrollable container
/// This is automatically triggered after text input or cursor movement
ScrollActiveCursorIntoView,
// Create Text Input Event (for Debug API / Programmatic Text Input)
/// Create a synthetic text input event
///
/// This simulates receiving text input from the OS. The text input flow will:
/// 1. Record the text in `TextInputManager` (creating a `PendingTextEdit`)
/// 2. Generate synthetic `TextInput` events
/// 3. Invoke user callbacks (which can intercept/reject via preventDefault)
/// 4. Apply the changeset if not rejected
/// 5. Mark dirty nodes for re-render
CreateTextInput {
/// The text to insert
text: AzString,
},
// Window Move (Compositor-Managed)
/// Request the compositor to begin an interactive window move.
/// On Wayland: calls `xdg_toplevel_move(toplevel`, seat, serial).
/// On other platforms: this is a no-op (use `set_window_position` instead).
BeginInteractiveMove,
// Drag-and-Drop Data Transfer
/// Set drag data for a MIME type (W3C: dataTransfer.setData)
/// Should be called in a `DragStart` callback to populate the drag data.
SetDragData {
mime_type: AzString,
data: Vec<u8>,
},
/// Accept the current drop on this target (W3C: `event.preventDefault()` in `DragOver`)
/// Must be called from a `DragOver` or `DragEnter` callback for the Drop event to fire.
AcceptDrop,
/// Set the drop effect (W3C: dataTransfer.dropEffect)
SetDropEffect {
effect: azul_core::drag::DropEffect,
},
// DOM Mutation (for Debug API)
/// Insert a new child node into the DOM tree.
/// Creates a minimal `StyledDom` from the given `node_type` and appends it
/// as a child of `parent_node_id`. If position is Some, inserts at that
/// child index; otherwise appends at the end.
InsertChildNode {
dom_id: DomId,
parent_node_id: NodeId,
/// The tag/type of the new node (e.g. "div", "p", "text:Hello")
node_type_str: AzString,
/// Optional child index to insert at (None = append at end)
position: Option<usize>,
/// Optional CSS classes for the new node
classes: Vec<AzString>,
/// Optional ID for the new node
id: Option<AzString>,
},
/// Delete a node from the DOM tree (and all its children).
/// The node is "tombstoned" (set to an empty anonymous Div) rather than
/// physically removed, to preserve node ID stability.
DeleteNode {
dom_id: DomId,
node_id: NodeId,
},
/// Set the IDs and classes on an existing node.
SetNodeIdsAndClasses {
dom_id: DomId,
node_id: NodeId,
ids_and_classes: azul_core::dom::IdOrClassVec,
},
// Routing
/// Switch to a different route.
///
/// On desktop: swaps `FullWindowState.layout_callback` to the matched
/// route's callback, stores the `RouteMatch`, and triggers `RefreshDom`.
/// On web: additionally calls `history.pushState()`.
SwitchRoute {
/// Route pattern to switch to (e.g. `"/user/:id"`)
pattern: AzString,
/// Route parameters (e.g. `[("id", "42")]`)
params: azul_core::window::StringPairVec,
},
// App-global Undo / Redo
/// Commit a snapshot of the current app state into the undo history.
CommitUndoSnapshot,
/// Undo the last committed app-state change (restores previous snapshot).
UndoAppState,
/// Redo a previously undone app-state change.
RedoAppState,
}
/// Main callback type for UI event handling
pub type CallbackType = extern "C" fn(RefAny, CallbackInfo) -> Update;
/// Stores a function pointer that is executed when the given UI element is hit
///
/// Must return an `Update` that denotes if the screen should be redrawn.
#[repr(C)]
pub struct Callback {
pub cb: CallbackType,
/// For FFI: stores the foreign callable (e.g., `PyFunction`)
/// Native Rust code sets this to None
pub ctx: OptionRefAny,
}
impl_callback!(Callback, CallbackType);
// Host-invoker plumbing for managed-FFI bindings (Lua, Ruby, Perl, ...).
// See `azul_core::host_invoker` for the design. This expands to a static
// `az_callback_thunk` that the framework dispatches by-value args to, an
// `AzCallback_createFromHostHandle` C-ABI export the host calls per
// `set_on_click(...)` site, plus the `AzApp_setCallbackInvoker` setter the
// host calls once at module load to register its libffi closure.
azul_core::impl_managed_callback! {
wrapper: Callback,
info_ty: CallbackInfo,
return_ty: Update,
default_ret: Update::DoNothing,
invoker_static: CALLBACK_INVOKER,
invoker_ty: AzCallbackInvoker,
thunk_fn: az_callback_thunk,
setter_fn: AzApp_setCallbackInvoker,
from_handle_fn: AzCallback_createFromHostHandle,
}
impl Callback {
/// Create a callback from a raw `CallbackType` function pointer (ctx = None).
///
/// The concrete `cb: CallbackType` parameter is a coercion site, so callers
/// can pass a bare `extern "C" fn` item without an `as CallbackType` cast
/// (unlike `Callback::from`, where trait-impl selection happens before the
/// fn-item -> fn-pointer coercion could apply).
#[must_use]
pub fn from_ptr(cb: CallbackType) -> Self {
Self::from(cb)
}
/// Create a new callback with just a function pointer (for native Rust code)
pub fn create<C: Into<Self>>(cb: C) -> Self {
cb.into()
}
/// Convert from `CoreCallback` (stored as usize) to Callback (actual function pointer)
///
/// Preserves `ctx` so that callbacks registered via the host-invoker path
/// (e.g. `Callback::create_from_host_handle`) keep their host-handle ctx
/// across the dispatch cycle. Without this, `info.get_ctx()` inside the
/// generated thunk would see `OptionRefAny::None` and bail out with the
/// kind's default value - which makes managed-FFI click handlers
/// silently no-op.
///
/// # Safety
/// The caller must ensure that the usize in CoreCallback.cb was originally a valid
/// function pointer of type `CallbackType`. This is guaranteed when `CoreCallback`
/// is created through standard APIs, but unsafe code could violate this.
#[must_use] pub fn from_core(core: CoreCallback) -> Self {
debug_assert!(core.cb != 0, "CoreCallback.cb is null");
Self {
cb: unsafe { core::mem::transmute::<usize, CallbackType>(core.cb) },
ctx: core.ctx,
}
}
/// Convert to `CoreCallback` (function pointer stored as usize)
///
/// This is always safe - we're just casting the function pointer to usize for storage.
#[must_use] pub fn to_core(self) -> CoreCallback {
CoreCallback {
cb: self.cb as usize,
ctx: self.ctx,
}
}
}
/// Allow Callback to be passed to functions expecting `C: Into<CoreCallback>`
impl From<Callback> for CoreCallback {
fn from(callback: Callback) -> Self {
callback.to_core()
}
}
impl Callback {
/// Safely invoke the callback with the given data and info
///
/// This is a safe wrapper around calling the function pointer directly.
#[must_use] pub fn invoke(&self, data: RefAny, info: CallbackInfo) -> Update {
(self.cb)(data, info)
}
}
#[allow(variant_size_differences)] // repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size disparity accepted
/// FFI-safe Option<Callback> type for C interop.
///
/// This enum provides an ABI-stable alternative to `Option<Callback>`
/// that can be safely passed across FFI boundaries.
#[derive(Debug, Eq, Clone, PartialEq, PartialOrd, Ord, Hash)]
#[repr(C, u8)]
pub enum OptionCallback {
/// No callback is present.
None,
/// A callback is present.
Some(Callback),
}
impl OptionCallback {
/// Converts this FFI-safe option into a standard Rust `Option<Callback>`.
#[must_use] pub fn into_option(self) -> Option<Callback> {
match self {
Self::None => None,
Self::Some(c) => Some(c),
}
}
/// Returns `true` if a callback is present.
#[must_use] pub const fn is_some(&self) -> bool {
matches!(self, Self::Some(_))
}
/// Returns `true` if no callback is present.
#[must_use] pub const fn is_none(&self) -> bool {
matches!(self, Self::None)
}
}
impl From<Option<Callback>> for OptionCallback {
fn from(o: Option<Callback>) -> Self {
o.map_or_else(|| Self::None, Self::Some)
}
}
impl From<OptionCallback> for Option<Callback> {
fn from(o: OptionCallback) -> Self {
o.into_option()
}
}
/// Reference data container for `CallbackInfo` (all read-only fields)
///
/// This struct consolidates all readonly references that callbacks need to query window state.
/// By grouping these into a single struct, we reduce the number of parameters to
/// `CallbackInfo::new()` from 13 to 3, making the API more maintainable and easier to extend.
///
/// This is pure syntax sugar - the struct lives on the stack in the caller and is passed by
/// reference.
#[derive(Debug)]
pub struct CallbackInfoRefData<'a> {
/// Pointer to the `LayoutWindow` containing all layout results (READ-ONLY for queries)
pub layout_window: &'a LayoutWindow,
/// Necessary to query `FontRefs` from callbacks
pub renderer_resources: &'a RendererResources,
/// Previous window state (for detecting changes)
pub previous_window_state: &'a Option<FullWindowState>,
/// State of the current window that the callback was called on (read only!)
pub current_window_state: &'a FullWindowState,
/// An Rc to the OpenGL context, in order to be able to render to OpenGL textures
pub gl_context: &'a OptionGlContextPtr,
/// Immutable reference to where the nodes are currently scrolled (current position)
pub current_scroll_manager: &'a BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>>,
/// Handle of the current window
pub current_window_handle: &'a RawWindowHandle,
/// Callbacks for creating threads and getting the system time (since this crate uses `no_std`)
pub system_callbacks: &'a ExternalSystemCallbacks,
/// Platform-specific system style (colors, spacing, etc.)
/// Arc allows safe cloning in callbacks without unsafe pointer manipulation
pub system_style: Arc<SystemStyle>,
/// Shared monitor list - initialized once at app start, updated by the platform
/// layer on monitor topology changes (e.g. `WM_DISPLAYCHANGE`, `NSScreenParametersChanged`).
/// Callbacks lock the mutex to read; platform locks to write.
pub monitors: Arc<Mutex<MonitorVec>>,
/// ICU4X localizer cache for internationalized formatting (numbers, dates, lists, plurals)
/// Caches localizers for multiple locales. Only available when the "icu" feature is enabled.
#[cfg(feature = "icu")]
pub icu_localizer: IcuLocalizerHandle,
/// The callable for FFI language bindings (Python, etc.)
/// Cloned from the Callback struct before invocation. Native Rust callbacks have this as None.
pub ctx: OptionRefAny,
}
/// `CallbackInfo` is a lightweight wrapper around pointers to stack-local data.
///
/// It can be safely copied because it only contains pointers - the underlying
/// data lives on the stack and outlives the callback invocation.
/// This allows callbacks to "consume" `CallbackInfo` by value while the caller
/// retains access to the same underlying data.
///
/// Information about the callback that is passed to the callback whenever a callback is invoked
///
/// # Architecture
///
/// `CallbackInfo` uses a transaction-based system:
/// - **Read-only pointers**: Access to layout data, window state, managers for queries
/// - **Change vector**: All modifications are recorded as `CallbackChange` items
/// - **Processing**: Changes are applied atomically after callback returns
///
/// This design provides clear separation between queries and modifications, makes debugging
/// easier, and allows for future extensibility.
///
/// The `changes` field uses a pointer to Arc<Mutex<...>> so that cloned `CallbackInfo` instances
/// (e.g., passed to timer callbacks) still push changes to the original collection,
/// while keeping `CallbackInfo` as Copy.
#[derive(Debug, Clone, Copy)]
#[repr(C)]
pub struct CallbackInfo {
// Read-only Data (Query Access)
/// Single reference to all readonly reference data
/// This consolidates 8 individual parameters into 1, improving API ergonomics
ref_data: *const CallbackInfoRefData<'static>,
// Context Info (Immutable Event Data)
/// The ID of the DOM + the node that was hit
hit_dom_node: DomNodeId,
/// The (x, y) position of the mouse cursor, **relative to top left of the element that was
/// hit**
cursor_relative_to_item: OptionLogicalPosition,
/// The (x, y) position of the mouse cursor, **relative to top left of the window**
cursor_in_viewport: OptionLogicalPosition,
// Transaction Container (New System) - Uses pointer to Arc<Mutex> for shared access across clones
/// All changes made by the callback, applied atomically after callback returns
/// Stored as raw pointer so `CallbackInfo` remains Copy
#[cfg(feature = "std")]
changes: *const Arc<Mutex<Vec<CallbackChange>>>,
#[cfg(not(feature = "std"))]
changes: *mut Vec<CallbackChange>,
}
impl CallbackInfo {
#[cfg(feature = "std")]
pub const fn new<'a>(
ref_data: &'a CallbackInfoRefData<'a>,
changes: &'a Arc<Mutex<Vec<CallbackChange>>>,
hit_dom_node: DomNodeId,
cursor_relative_to_item: OptionLogicalPosition,
cursor_in_viewport: OptionLogicalPosition,
) -> Self {
Self {
// Read-only data (single reference to consolidated refs)
// SAFETY: We cast away the lifetime 'a to 'static because CallbackInfo
// only lives for the duration of the callback, which is shorter than 'a
// SAFETY: pointer cast only - erases lifetime 'a to 'static.
// CallbackInfo only lives for the duration of the callback, which is shorter than 'a.
ref_data: std::ptr::from_ref::<CallbackInfoRefData<'a>>(ref_data).cast::<CallbackInfoRefData<'static>>(),
// Context info (immutable event data)
hit_dom_node,
cursor_relative_to_item,
cursor_in_viewport,
// Transaction container - store pointer to Arc<Mutex> for shared access
changes: std::ptr::from_ref::<Arc<Mutex<Vec<CallbackChange>>>>(changes),
}
}
#[cfg(not(feature = "std"))]
pub fn new<'a>(
ref_data: &'a CallbackInfoRefData<'a>,
changes: &'a mut Vec<CallbackChange>,
hit_dom_node: DomNodeId,
cursor_relative_to_item: OptionLogicalPosition,
cursor_in_viewport: OptionLogicalPosition,
) -> Self {
Self {
// SAFETY: pointer cast only - erases lifetime 'a to 'static.
ref_data: ref_data as *const CallbackInfoRefData<'a> as *const CallbackInfoRefData<'static>,
hit_dom_node,
cursor_relative_to_item,
cursor_in_viewport,
changes: changes as *mut Vec<CallbackChange>,
}
}
/// Get the callable for FFI language bindings (Python, etc.)
///
/// Returns the cloned `OptionRefAny` if a callable was set, or None if this
/// is a native Rust callback.
#[must_use] pub fn get_ctx(&self) -> OptionRefAny {
unsafe { (*self.ref_data).ctx.clone() }
}
/// Returns the OpenGL context if available
#[must_use] pub fn get_gl_context(&self) -> OptionGlContextPtr {
unsafe { (*self.ref_data).gl_context.clone() }
}
// Helper methods for transaction system
/// Push a change to be applied after the callback returns
/// This is the primary method for modifying window state from callbacks
#[cfg(feature = "std")]
pub fn push_change(&mut self, change: CallbackChange) {
// SAFETY: The pointer is valid for the lifetime of the callback
unsafe {
if let Ok(mut changes) = (*self.changes).lock() {
changes.push(change);
}
}
}
#[cfg(not(feature = "std"))]
pub fn push_change(&mut self, change: CallbackChange) {
unsafe { (*self.changes).push(change) }
}
/// Snapshot the current app state into the undo history (mini-git commit).
pub fn commit_undo_snapshot(&mut self) {
self.push_change(CallbackChange::CommitUndoSnapshot);
}
/// Undo the last committed app-state change; relayouts all windows.
pub fn undo_app_state(&mut self) {
self.push_change(CallbackChange::UndoAppState);
}
/// Redo a previously undone app-state change; relayouts all windows.
pub fn redo_app_state(&mut self) {
self.push_change(CallbackChange::RedoAppState);
}
/// Debug helper to get the changes pointer for debugging
#[cfg(feature = "std")]
#[must_use] pub const fn get_changes_ptr(&self) -> *const () {
self.changes.cast::<()>()
}
/// Get the collected changes (consumes them from the Arc<Mutex>)
#[cfg(feature = "std")]
#[must_use] pub fn take_changes(&self) -> Vec<CallbackChange> {
// SAFETY: The pointer is valid for the lifetime of the callback
unsafe {
(*self.changes).lock().map_or_else(
|_| Vec::new(),
|mut changes| core::mem::take(&mut *changes),
)
}
}
#[cfg(not(feature = "std"))]
pub fn take_changes(&self) -> Vec<CallbackChange> {
unsafe { core::mem::take(&mut *self.changes) }
}
/// Check if pending changes require relayout before the next step.
///
/// Returns true for `ModifyWindowState` (resize) and `ScrollTo` (scroll),
/// which both need the event loop to re-run layout so that subsequent
/// operations (like `take_screenshot`) see updated content.
///
/// Used by the E2E test runner to detect when it needs to yield.
#[cfg(feature = "std")]
#[must_use] pub fn has_pending_relayout_change(&self) -> bool {
unsafe {
(*self.changes).lock().is_ok_and(|changes| changes.iter().any(|c| matches!(c,
CallbackChange::ModifyWindowState { .. } |
CallbackChange::ScrollTo { .. } |
// Synthetic input (E2E `click` = move/down/up applied one
// state per frame): the runner MUST yield here, or every
// post-click step executes against the pre-click DOM and
// the queued states only apply after the test finishes.
CallbackChange::QueueWindowStateSequence { .. }
)))
}
}
// Modern Api (using CallbackChange transactions)
/// Add a timer to this window (applied after callback returns)
pub fn add_timer(&mut self, timer_id: TimerId, timer: Timer) {
self.push_change(CallbackChange::AddTimer { timer_id, timer });
}
/// Remove a timer from this window (applied after callback returns)
pub fn remove_timer(&mut self, timer_id: TimerId) {
self.push_change(CallbackChange::RemoveTimer { timer_id });
}
/// Add a thread to this window (applied after callback returns)
pub fn add_thread(&mut self, thread_id: ThreadId, thread: Thread) {
self.push_change(CallbackChange::AddThread { thread_id, thread });
}
/// Remove a thread from this window (applied after callback returns)
pub fn remove_thread(&mut self, thread_id: ThreadId) {
self.push_change(CallbackChange::RemoveThread { thread_id });
}
/// Stop event propagation (applied after callback returns)
///
/// W3C `stopPropagation()`: remaining handlers on the *current* node
/// still fire, but no handlers on ancestor/descendant nodes are called.
pub fn stop_propagation(&mut self) {
self.push_change(CallbackChange::StopPropagation);
}
/// Stop event propagation immediately (applied after callback returns)
///
/// W3C `stopImmediatePropagation()`: no further handlers fire,
/// not even remaining handlers registered on the same node.
pub fn stop_immediate_propagation(&mut self) {
self.push_change(CallbackChange::StopImmediatePropagation);
}
/// Set keyboard focus target (applied after callback returns)
pub fn set_focus(&mut self, target: FocusTarget) {
self.push_change(CallbackChange::SetFocusTarget { target });
}
/// Create a new window (applied after callback returns)
pub fn create_window(&mut self, options: WindowCreateOptions) {
self.push_change(CallbackChange::CreateNewWindow { options });
}
/// Close the current window (applied after callback returns)
pub fn close_window(&mut self) {
self.push_change(CallbackChange::CloseWindow);
}
/// Switch to a different route (applied after callback returns).
///
/// On desktop: swaps the layout callback and triggers `RefreshDom`.
/// On web: also calls `history.pushState()`.
///
/// # C API
/// ```c
/// AzCallbackInfo_switchRoute(&info, AzString_fromConstStr("/user/:id"),
/// AzStringPairVec_fromConstSlice(&[AzStringPair { key: "id", value: "42" }]));
/// ```
pub fn switch_route(&mut self, pattern: AzString, params: azul_core::window::StringPairVec) {
self.push_change(CallbackChange::SwitchRoute { pattern, params });
}
/// Get the current active route pattern (e.g. `"/user/:id"`).
///
/// Returns empty string if no route is active.
///
/// # C API
/// ```c
/// AzString pattern = AzCallbackInfo_getRoutePattern(&info);
/// ```
#[must_use] pub fn get_route_pattern(&self) -> AzString {
match &self.get_current_window_state().active_route {
azul_core::resources::OptionRouteMatch::Some(rm) => rm.pattern.clone(),
azul_core::resources::OptionRouteMatch::None => AzString::from_const_str(""),
}
}
/// Get a route parameter by key (e.g. `"id"` from `/user/:id`).
///
/// Returns empty string if the parameter doesn't exist or no route is active.
///
/// # C API
/// ```c
/// AzString id = AzCallbackInfo_getRouteParam(&info, AzString_fromConstStr("id"));
/// ```
// FFI-exported (AzCallbackInfo_getRouteParam): the owned AzString key is the api.json signature.
#[allow(clippy::needless_pass_by_value)]
#[must_use] pub fn get_route_param(&self, key: AzString) -> AzString {
match &self.get_current_window_state().active_route {
azul_core::resources::OptionRouteMatch::Some(rm) => {
rm.get_param(key.as_str())
.cloned()
.unwrap_or_else(|| AzString::from_const_str(""))
}
azul_core::resources::OptionRouteMatch::None => AzString::from_const_str(""),
}
}
/// Set a route parameter value and trigger re-render.
///
/// This modifies the active route's params in-place and triggers a DOM refresh.
/// On web, this also updates the URL via `history.replaceState()`.
///
/// # C API
/// ```c
/// AzCallbackInfo_setRouteParam(&info, AzString_fromConstStr("id"), AzString_fromConstStr("99"));
/// ```
pub fn set_route_param(&mut self, key: AzString, value: AzString) {
let ws = self.get_current_window_state();
let pattern = match &ws.active_route {
azul_core::resources::OptionRouteMatch::Some(rm) => rm.pattern.clone(),
azul_core::resources::OptionRouteMatch::None => return,
};
let mut params = match &ws.active_route {
azul_core::resources::OptionRouteMatch::Some(rm) => {
rm.params.as_ref().to_vec()
}
azul_core::resources::OptionRouteMatch::None => return,
};
// Update or insert the parameter
if let Some(existing) = params.iter_mut().find(|p| p.key.as_str() == key.as_str()) {
existing.value = value;
} else {
params.push(azul_core::window::AzStringPair { key, value });
}
self.push_change(CallbackChange::SwitchRoute {
pattern,
params: azul_core::window::StringPairVec::from_vec(params),
});
}
/// Modify the window state (applied after callback returns)
pub fn modify_window_state(&mut self, state: FullWindowState) {
self.push_change(CallbackChange::ModifyWindowState { state });
}
/// Request the compositor to begin an interactive window move.
///
/// On Wayland: calls `xdg_toplevel_move(toplevel, seat, serial)` which lets
/// the compositor handle the move. This is the only way to move windows on Wayland.
/// On other platforms: this is a no-op; use `modify_window_state()` to set position.
pub fn begin_interactive_move(&mut self) {
self.push_change(CallbackChange::BeginInteractiveMove);
}
/// Queue multiple window state changes to be applied in sequence.
/// Each state triggers a separate event processing cycle, which is needed
/// for simulating clicks where mouse down and mouse up must be separate events.
pub fn queue_window_state_sequence(&mut self, states: FullWindowStateVec) {
self.push_change(CallbackChange::QueueWindowStateSequence {
states: states.into_library_owned_vec(),
});
}
/// Change the text content of a node (applied after callback returns)
///
/// This method was previously called `set_string_contents` in older API versions.
///
/// # Arguments
/// * `node_id` - The text node to modify (`DomNodeId` containing both DOM and node IDs)
/// * `text` - The new text content
pub fn change_node_text(&mut self, node_id: DomNodeId, text: AzString) {
self.push_change(CallbackChange::ChangeNodeText { node_id, text });
}
/// Change the image of a node (applied after callback returns)
pub fn change_node_image(
&mut self,
dom_id: DomId,
node_id: NodeId,
image: ImageRef,
update_type: UpdateImageType,
) {
self.push_change(CallbackChange::ChangeNodeImage {
dom_id,
node_id,
image,
update_type,
});
}
/// Re-render an image callback (for resize/animation updates)
///
/// This triggers re-invocation of the `RenderImageCallback` associated with the node.
/// Useful for:
/// - Responding to window resize (image needs to match new size)
/// - Animation frames (update OpenGL texture each frame)
/// - Interactive content (user input changes rendering)
pub fn update_image_callback(&mut self, dom_id: DomId, node_id: NodeId) {
self.push_change(CallbackChange::UpdateImageCallback { dom_id, node_id });
}
/// Re-render ALL image callbacks across all DOMs (applied after callback returns)
///
/// This is the most efficient way to update animated GL textures.
/// Unlike returning `Update::RefreshDom`, this triggers only:
/// - Re-invocation of all `RenderImageCallback` functions
/// - GL texture swap in `WebRender`
///
/// It does NOT trigger:
/// - DOM rebuild (no `layout()` callback)
/// - Display list resubmission (`WebRender` reuses existing scene)
/// - Relayout
///
/// Ideal for timer callbacks that animate OpenGL content at 60fps.
pub fn update_all_image_callbacks(&mut self) {
self.push_change(CallbackChange::UpdateAllImageCallbacks);
}
/// Trigger re-rendering of a `VirtualView` (applied after callback returns)
///
/// This forces the `VirtualView` to call its layout callback with reason `DomRecreated`
/// and submit a new display list to `WebRender`. The `VirtualView`'s pipeline will be updated
/// without affecting other parts of the window.
///
/// Useful for:
/// - Live preview panes (update when source code changes)
/// - Dynamic content that needs manual refresh
/// - Editor previews (re-parse and display new DOM)
pub fn trigger_virtual_view_rerender(&mut self, dom_id: DomId, node_id: NodeId) {
self.push_change(CallbackChange::UpdateVirtualView { dom_id, node_id });
}
/// Re-render EVERY `VirtualView` on the existing DOM - no node id required.
///
/// Use from a callback that mutated a dataset shared with a `VirtualView`'s
/// `refany` (the two are clones of one `RefAny`, so they point at the same
/// underlying data). The canonical case is a background thread writeback:
/// e.g. the `MapWidget`'s tile-fetch worker decodes a tile, writes it into
/// the shared `MapTileCache`, then calls this so the pure `VirtualView`
/// content callback re-reads the cache and rebuilds its child DOM in place -
/// WITHOUT a `RefreshDom` (which would rebuild the DOM and orphan the
/// worker's clone of the cache).
pub fn trigger_all_virtual_view_rerender(&mut self) {
self.push_change(CallbackChange::UpdateAllVirtualViews);
}
// Dom Tree Navigation
/// Find a node by ID attribute in the layout tree
///
/// Returns the `NodeId` of the first node with the given ID attribute, or None if not found.
#[must_use] pub fn get_node_id_by_id_attribute(&self, dom_id: DomId, id: &str) -> Option<NodeId> {
let layout_window = self.get_layout_window();
let layout_result = layout_window.layout_results.get(&dom_id)?;
let styled_dom = &layout_result.styled_dom;
// Search through all nodes to find one with matching ID attribute
for (node_idx, node_data) in styled_dom.node_data.as_ref().iter().enumerate() {
if node_data.has_id(id) {
return Some(NodeId::new(node_idx));
}
}
None
}
/// Get the parent node of the given node
///
/// Returns None if the node has no parent (i.e., it's the root node)
#[must_use] pub fn get_parent_node(&self, dom_id: DomId, node_id: NodeId) -> Option<NodeId> {
let layout_window = self.get_layout_window();
let layout_result = layout_window.layout_results.get(&dom_id)?;
let node_hierarchy = &layout_result.styled_dom.node_hierarchy;
let node = node_hierarchy.as_ref().get(node_id.index())?;
node.parent_id()
}
/// Get the next sibling of the given node
///
/// Returns None if the node has no next sibling
#[must_use] pub fn get_next_sibling_node(&self, dom_id: DomId, node_id: NodeId) -> Option<NodeId> {
let layout_window = self.get_layout_window();
let layout_result = layout_window.layout_results.get(&dom_id)?;
let node_hierarchy = &layout_result.styled_dom.node_hierarchy;
let node = node_hierarchy.as_ref().get(node_id.index())?;
node.next_sibling_id()
}
/// Get the previous sibling of the given node
///
/// Returns None if the node has no previous sibling
#[must_use] pub fn get_previous_sibling_node(&self, dom_id: DomId, node_id: NodeId) -> Option<NodeId> {
let layout_window = self.get_layout_window();
let layout_result = layout_window.layout_results.get(&dom_id)?;
let node_hierarchy = &layout_result.styled_dom.node_hierarchy;
let node = node_hierarchy.as_ref().get(node_id.index())?;
node.previous_sibling_id()
}
/// Get the first child of the given node
///
/// Returns None if the node has no children
#[must_use] pub fn get_first_child_node(&self, dom_id: DomId, node_id: NodeId) -> Option<NodeId> {
let layout_window = self.get_layout_window();
let layout_result = layout_window.layout_results.get(&dom_id)?;
let node_hierarchy = &layout_result.styled_dom.node_hierarchy;
let node = node_hierarchy.as_ref().get(node_id.index())?;
node.first_child_id(node_id)
}
/// Get the last child of the given node
///
/// Returns None if the node has no children
#[must_use] pub fn get_last_child_node(&self, dom_id: DomId, node_id: NodeId) -> Option<NodeId> {
let layout_window = self.get_layout_window();
let layout_result = layout_window.layout_results.get(&dom_id)?;
let node_hierarchy = &layout_result.styled_dom.node_hierarchy;
let node = node_hierarchy.as_ref().get(node_id.index())?;
node.last_child_id()
}
/// Get all direct children of the given node
///
/// Returns an empty vector if the node has no children.
/// Uses the contiguous node layout for efficient iteration.
#[must_use] pub fn get_all_children_nodes(&self, dom_id: DomId, node_id: NodeId) -> NodeHierarchyItemIdVec {
let layout_window = self.get_layout_window();
let Some(layout_result) = layout_window.layout_results.get(&dom_id) else {
return NodeHierarchyItemIdVec::from_const_slice(&[]);
};
let node_hierarchy = layout_result.styled_dom.node_hierarchy.as_container();
let Some(hier_item) = node_hierarchy.get(node_id) else {
return NodeHierarchyItemIdVec::from_const_slice(&[]);
};
// Get first child - if none, return empty
let Some(first_child) = hier_item.first_child_id(node_id) else {
return NodeHierarchyItemIdVec::from_const_slice(&[]);
};
// Collect children by walking the sibling chain
let mut children: Vec<NodeHierarchyItemId> = Vec::new();
children.push(NodeHierarchyItemId::from_crate_internal(Some(first_child)));
let mut current = first_child;
while let Some(next_sibling) = node_hierarchy
.get(current)
.and_then(azul_core::styled_dom::NodeHierarchyItem::next_sibling_id)
{
children.push(NodeHierarchyItemId::from_crate_internal(Some(next_sibling)));
current = next_sibling;
}
NodeHierarchyItemIdVec::from(children)
}
/// Get the number of direct children of the given node
///
/// Uses the contiguous node layout for efficient counting.
#[must_use] pub fn get_children_count(&self, dom_id: DomId, node_id: NodeId) -> usize {
let layout_window = self.get_layout_window();
let Some(layout_result) = layout_window.layout_results.get(&dom_id) else {
return 0;
};
let node_hierarchy = layout_result.styled_dom.node_hierarchy.as_container();
let Some(hier_item) = node_hierarchy.get(node_id) else {
return 0;
};
// Get first child - if none, return 0
let Some(first_child) = hier_item.first_child_id(node_id) else {
return 0;
};
// Count children by walking the sibling chain
let mut count = 1;
let mut current = first_child;
while let Some(next_sibling) = node_hierarchy
.get(current)
.and_then(azul_core::styled_dom::NodeHierarchyItem::next_sibling_id)
{
count += 1;
current = next_sibling;
}
count
}
/// Change the image mask of a node (applied after callback returns)
pub fn change_node_image_mask(&mut self, dom_id: DomId, node_id: NodeId, mask: ImageMask) {
self.push_change(CallbackChange::ChangeNodeImageMask {
dom_id,
node_id,
mask,
});
}
/// Change CSS properties of a node (applied after callback returns)
pub fn change_node_css_properties(
&mut self,
dom_id: DomId,
node_id: NodeId,
properties: CssPropertyVec,
) {
self.push_change(CallbackChange::ChangeNodeCssProperties {
dom_id,
node_id,
properties,
});
}
/// Set a single CSS property on a node (convenience method for widgets)
///
/// This is a helper method that wraps `change_node_css_properties` for the common case
/// of setting a single property. It uses the hit node's DOM ID automatically.
///
/// # Arguments
/// * `node_id` - The node to set the property on (uses hit node's DOM ID)
/// * `property` - The CSS property to set
/// # Panics
///
/// Panics if `node_id.node` is None; the target must reference a concrete node.
pub fn set_css_property(&mut self, node_id: DomNodeId, property: CssProperty) {
let dom_id = node_id.dom;
let internal_node_id = node_id
.node
.into_crate_internal()
.expect("DomNodeId node should not be None");
self.change_node_css_properties(dom_id, internal_node_id, vec![property].into());
}
/// Quickly override CSS properties on a node for animation or other
/// transient visual changes. Writes go through
/// `CssPropertyCache::user_overridden_properties`, which is consulted at
/// higher priority than the static cascade, so this does not invalidate
/// the styled DOM's CSS rules. Pass `CssProperty::Initial` for a given
/// property type to remove any prior override for that type.
pub fn override_node_css_properties(
&mut self,
dom_id: DomId,
node_id: NodeId,
properties: CssPropertyVec,
) {
self.push_change(CallbackChange::OverrideNodeCssProperties {
dom_id,
node_id,
properties,
});
}
/// Convenience wrapper for `override_node_css_properties` that targets a
/// single property on the hit node's DOM (typical for animation callbacks).
/// # Panics
///
/// Panics if `node_id.node` is None; the target must reference a concrete node.
pub fn override_css_property(&mut self, node_id: DomNodeId, property: CssProperty) {
let dom_id = node_id.dom;
let internal_node_id = node_id
.node
.into_crate_internal()
.expect("DomNodeId node should not be None");
self.override_node_css_properties(dom_id, internal_node_id, vec![property].into());
}
/// Scroll a node to a specific position (applied after callback returns)
pub fn scroll_to(
&mut self,
dom_id: DomId,
node_id: NodeHierarchyItemId,
position: LogicalPosition,
) {
self.push_change(CallbackChange::ScrollTo {
dom_id,
node_id,
position,
unclamped: false,
});
}
/// Scroll a node to a specific position without clamping.
/// Used by the scroll physics timer for rubber-banding/overscroll.
pub fn scroll_to_unclamped(
&mut self,
dom_id: DomId,
node_id: NodeHierarchyItemId,
position: LogicalPosition,
) {
self.push_change(CallbackChange::ScrollTo {
dom_id,
node_id,
position,
unclamped: true,
});
}
/// Scroll a node into view (W3C scrollIntoView API)
///
/// Scrolls the element into the visible area of its scroll container.
/// This is the recommended way to programmatically scroll elements into view.
///
/// # Arguments
///
/// * `node_id` - The node to scroll into view
/// * `options` - Scroll alignment and animation options
///
/// # Note
///
/// This uses the transactional change system - the scroll is queued and applied
/// after the callback returns. The actual scroll adjustments are calculated
/// during change processing.
pub fn scroll_node_into_view(
&mut self,
node_id: DomNodeId,
options: crate::managers::scroll_into_view::ScrollIntoViewOptions,
) {
self.push_change(CallbackChange::ScrollIntoView {
node_id,
options,
});
}
/// Add an image to the image cache (applied after callback returns)
pub fn add_image_to_cache(&mut self, id: AzString, image: ImageRef) {
self.push_change(CallbackChange::AddImageToCache { id, image });
}
/// Remove an image from the image cache (applied after callback returns)
pub fn remove_image_from_cache(&mut self, id: AzString) {
self.push_change(CallbackChange::RemoveImageFromCache { id });
}
/// Reload system fonts (applied after callback returns)
///
/// Note: This is an expensive operation that rebuilds the entire font cache
pub fn reload_system_fonts(&mut self) {
self.push_change(CallbackChange::ReloadSystemFonts);
}
// Text Input / Changeset Api
/// Get the current text changeset being processed (if any)
///
/// This allows callbacks to inspect what text input is about to be applied.
/// Returns None if no text input is currently being processed.
///
/// Use `set_text_changeset()` to modify the text that will be inserted,
/// and `prevent_default()` to block the text input entirely.
#[must_use] pub const fn get_text_changeset(&self) -> Option<&PendingTextEdit> {
self.get_layout_window()
.text_input_manager
.get_pending_changeset()
}
/// Set/override the text changeset for the current text input operation
///
/// This allows you to modify what text will be inserted during text input events.
/// Typically used in combination with `prevent_default()` to transform user input.
///
/// # Arguments
/// * `changeset` - The modified text changeset to apply
pub fn set_text_changeset(&mut self, changeset: PendingTextEdit) {
self.push_change(CallbackChange::SetTextChangeset { changeset });
}
/// Create a synthetic text input event
///
/// This simulates receiving text input from the OS. Use this to programmatically
/// insert text into contenteditable elements, for example from the debug server
/// or from accessibility APIs.
///
/// The text input flow will:
/// 1. Record the text in `TextInputManager` (creating a `PendingTextEdit`)
/// 2. Generate synthetic `TextInput` events
/// 3. Invoke user callbacks (which can intercept/reject via preventDefault)
/// 4. Apply the changeset if not rejected
/// 5. Mark dirty nodes for re-render
///
/// # Arguments
/// * `text` - The text to insert at the current cursor position
pub fn create_text_input(&mut self, text: AzString) {
self.push_change(CallbackChange::CreateTextInput { text });
}
// DOM Mutation Api (for Debug API)
/// Insert a new child node into the DOM tree (applied after callback returns)
///
/// Creates a new node with the given type string and appends it as a child
/// of the specified parent node. The `node_type_str` can be:
/// - A tag name: "div", "p", "span", "button", etc.
/// - Text content: "text:Hello World"
///
/// # Arguments
/// * `dom_id` - The DOM to modify
/// * `parent_node_id` - The parent node to insert under
/// * `node_type_str` - The node type (tag name or "text:content")
/// * `position` - Optional child index (None = append at end)
/// * `classes` - CSS classes for the new node
/// * `id` - Optional ID for the new node
pub fn insert_child_node(
&mut self,
dom_id: DomId,
parent_node_id: NodeId,
node_type_str: AzString,
position: OptionUsize,
classes: StringVec,
id: OptionString,
) {
self.push_change(CallbackChange::InsertChildNode {
dom_id,
parent_node_id,
node_type_str,
position: position.into(),
classes: classes.into_library_owned_vec(),
id: id.into(),
});
}
/// Delete a node from the DOM tree (applied after callback returns)
///
/// Tombstones the node by setting it to an empty anonymous Div and
/// unlinking it from the hierarchy. This preserves node ID stability
/// (other node IDs don't shift).
///
/// # Arguments
/// * `dom_id` - The DOM containing the node
/// * `node_id` - The node to delete
pub fn delete_node(&mut self, dom_id: DomId, node_id: NodeId) {
self.push_change(CallbackChange::DeleteNode { dom_id, node_id });
}
/// Set the IDs and classes on an existing node (applied after callback returns)
///
/// Replaces the current IDs and classes of a node with the given set.
///
/// # Arguments
/// * `dom_id` - The DOM containing the node
/// * `node_id` - The node to modify
/// * `ids_and_classes` - The new set of IDs and classes
pub fn set_node_ids_and_classes(
&mut self,
dom_id: DomId,
node_id: NodeId,
ids_and_classes: azul_core::dom::IdOrClassVec,
) {
self.push_change(CallbackChange::SetNodeIdsAndClasses {
dom_id,
node_id,
ids_and_classes,
});
}
/// Prevent the default text input from being applied
///
/// When called in a `TextInput` callback, prevents the typed text from being inserted.
/// Useful for custom validation, filtering, or text transformation.
pub fn prevent_default(&mut self) {
self.push_change(CallbackChange::PreventDefault);
}
// Cursor Blinking Api (for system timer control)
/// Set cursor visibility state
///
/// This is primarily used internally by the cursor blink timer callback.
/// User code typically doesn't need to call this directly.
pub fn set_cursor_visibility(&mut self, visible: bool) {
self.push_change(CallbackChange::SetCursorVisibility { visible });
}
/// Reset cursor blink state on user input
///
/// This makes the cursor visible and records the current time, so the blink
/// timer knows to keep the cursor solid for a while before blinking.
/// Called automatically on keyboard input, but can be called manually.
pub fn reset_cursor_blink(&mut self) {
self.push_change(CallbackChange::ResetCursorBlink);
}
/// Start the cursor blink timer
///
/// Called automatically when focus lands on a contenteditable element.
/// The timer will toggle cursor visibility at ~530ms intervals.
pub fn start_cursor_blink_timer(&mut self) {
self.push_change(CallbackChange::StartCursorBlinkTimer);
}
/// Stop the cursor blink timer
///
/// Called automatically when focus leaves a contenteditable element.
pub fn stop_cursor_blink_timer(&mut self) {
self.push_change(CallbackChange::StopCursorBlinkTimer);
}
/// Scroll the active cursor into view
///
/// This scrolls the focused text element's cursor into the visible area
/// of any scrollable ancestor. Called automatically after text input.
pub fn scroll_active_cursor_into_view(&mut self) {
self.push_change(CallbackChange::ScrollActiveCursorIntoView);
}
/// Open a menu (context menu or dropdown)
///
/// The menu will be displayed either as a native menu or a fallback DOM-based menu
/// depending on the window's `use_native_context_menus` flag.
/// Uses the position specified in the menu itself.
///
/// # Arguments
/// * `menu` - The menu to display
pub fn open_menu(&mut self, menu: Menu) {
self.push_change(CallbackChange::OpenMenu {
menu,
position: None,
});
}
/// Open a menu at a specific position
///
/// # Arguments
/// * `menu` - The menu to display
/// * `position` - The position where the menu should appear (overrides menu's position)
pub fn open_menu_at(&mut self, menu: Menu, position: LogicalPosition) {
self.push_change(CallbackChange::OpenMenu {
menu,
position: Some(position),
});
}
// Tooltip Api
/// Show a tooltip at the current cursor position
///
/// Displays a simple text tooltip near the mouse cursor.
/// The tooltip will be shown using platform-specific native APIs where available.
///
/// Platform implementations:
/// - **Windows**: Uses `TOOLTIPS_CLASS` Win32 control
/// - **macOS**: Uses `NSPopover` or custom `NSWindow` with tooltip styling
/// - **X11**: Creates transient window with `_NET_WM_WINDOW_TYPE_TOOLTIP`
/// - **Wayland**: Uses `zwlr_layer_shell_v1` with overlay layer
///
/// # Arguments
/// * `text` - The tooltip text to display
pub fn show_tooltip(&mut self, text: AzString) {
let position = self
.get_cursor_relative_to_viewport()
.into_option()
.unwrap_or_else(LogicalPosition::zero);
self.push_change(CallbackChange::ShowTooltip { text, position });
}
/// Show a tooltip at a specific position
///
/// # Arguments
/// * `text` - The tooltip text to display
/// * `position` - The position where the tooltip should appear (in window coordinates)
pub fn show_tooltip_at(&mut self, text: AzString, position: LogicalPosition) {
self.push_change(CallbackChange::ShowTooltip { text, position });
}
/// Hide the currently displayed tooltip
pub fn hide_tooltip(&mut self) {
self.push_change(CallbackChange::HideTooltip);
}
// Text Editing Api (transactional)
/// Insert text at the current cursor position in a text node
///
/// This operation is transactional - the text will be inserted after the callback returns.
/// If there's a selection, it will be replaced with the inserted text.
///
/// # Arguments
/// * `dom_id` - The DOM containing the text node
/// * `node_id` - The node to insert text into
/// * `text` - The text to insert
pub fn insert_text(&mut self, dom_id: DomId, node_id: NodeId, text: AzString) {
self.push_change(CallbackChange::InsertText {
dom_id,
node_id,
text,
});
}
/// Move the text cursor to a specific position
///
/// # Arguments
/// * `dom_id` - The DOM containing the text node
/// * `node_id` - The node containing the cursor
/// * `cursor` - The new cursor position
pub fn move_cursor(&mut self, dom_id: DomId, node_id: NodeId, cursor: TextCursor) {
self.push_change(CallbackChange::MoveCursor {
dom_id,
node_id,
cursor,
});
}
/// Set the text selection range
///
/// # Arguments
/// * `dom_id` - The DOM containing the text node
/// * `node_id` - The node containing the selection
/// * `selection` - The new selection (can be a cursor or range)
pub fn set_selection(&mut self, dom_id: DomId, node_id: NodeId, selection: Selection) {
self.push_change(CallbackChange::SetSelection {
dom_id,
node_id,
selection,
});
}
// === Multi-Cursor Operations ===
/// Add an additional cursor at the specified position (for multi-cursor editing).
///
/// If a `MultiCursorState` already exists, the cursor is added and overlapping
/// selections are merged. If not, a new `MultiCursorState` is created.
///
/// Returns the `SelectionId` of the new cursor.
pub fn add_cursor(&mut self, dom_id: DomId, node_id: NodeId, cursor: TextCursor) -> azul_core::selection::SelectionId {
let id = azul_core::selection::SelectionId::new();
self.push_change(CallbackChange::AddCursor {
dom_id,
node_id,
cursor,
});
id
}
/// Add an additional selection range (for multi-cursor editing).
///
/// Returns the `SelectionId` of the new selection.
pub fn add_selection_range(&mut self, dom_id: DomId, node_id: NodeId, range: SelectionRange) -> azul_core::selection::SelectionId {
let id = azul_core::selection::SelectionId::new();
self.push_change(CallbackChange::AddSelectionRange {
dom_id,
node_id,
range,
});
id
}
/// Remove a specific selection/cursor by its stable ID.
///
/// Returns true if a selection with that ID existed and was removed.
pub fn remove_selection_by_id(&mut self, selection_id: azul_core::selection::SelectionId) -> bool {
self.push_change(CallbackChange::RemoveSelectionById {
selection_id,
});
true // Actual removal happens deferred; assume success
}
/// Get all selections for the given DOM (read-only).
///
/// Returns a Vec of `IdentifiedSelection` from the `MultiCursorState`, or empty
/// if no multi-cursor state exists.
#[must_use] pub fn get_multi_cursor_selections(&self, dom_id: &DomId) -> azul_core::selection::IdentifiedSelectionVec {
let lw = self.get_layout_window();
lw.text_edit_manager.multi_cursor.as_ref()
.map(|mc| mc.selections.clone())
.unwrap_or_default()
.into()
}
/// Get the primary (last-added) selection from the `MultiCursorState`.
#[must_use] pub fn get_primary_selection(&self, dom_id: &DomId) -> Option<azul_core::selection::IdentifiedSelection> {
let lw = self.get_layout_window();
lw.text_edit_manager.multi_cursor.as_ref()
.and_then(|mc| mc.get_primary().copied())
}
/// Get the number of active cursors/selections.
#[must_use] pub fn get_selection_count(&self, dom_id: &DomId) -> usize {
let lw = self.get_layout_window();
lw.text_edit_manager.multi_cursor.as_ref()
.map_or(0, azul_core::selection::MultiCursorState::len)
}
/// Open a menu positioned relative to a specific DOM node
///
/// This is useful for dropdowns, combo boxes, and context menus that should appear
/// near a specific UI element. The menu will be positioned below the node by default.
///
/// # Arguments
/// * `menu` - The menu to display
/// * `node_id` - The DOM node to position the menu relative to
///
/// # Returns
/// * `true` if the menu was queued for opening
/// * `false` if the node doesn't exist or has no layout information
pub fn open_menu_for_node(&mut self, menu: Menu, node_id: DomNodeId) -> bool {
// Position the menu at the hit node's bottom-left. Prefer the display-list
// hit-test bounds: they always carry the node's final rendered rect for an
// interactive (tagged) node, whereas get_node_rect (position + used_size)
// can be None for nodes whose used_size isn't recorded on the layout node.
let rect = self
.get_node_hit_test_bounds(node_id)
.or_else(|| self.get_node_rect(node_id));
rect.is_some_and(|rect| {
// Position menu at bottom-left of the node
let position = LogicalPosition::new(rect.origin.x, rect.origin.y + rect.size.height);
self.push_change(CallbackChange::OpenMenu {
menu,
position: Some(position),
});
true
})
}
/// Open a menu positioned relative to the currently hit node
///
/// Convenience method for opening a menu at the element that triggered the callback.
/// Equivalent to `open_menu_for_node(menu, info.get_hit_node())`.
///
/// # Arguments
/// * `menu` - The menu to display
///
/// # Returns
/// * `true` if the menu was queued for opening
/// * `false` if no node is currently hit or it has no layout information
pub fn open_menu_for_hit_node(&mut self, menu: Menu) -> bool {
let hit_node = self.get_hit_node();
self.open_menu_for_node(menu, hit_node)
}
// Internal accessors
/// Get reference to the underlying `LayoutWindow` for queries
///
/// This provides read-only access to layout data, node hierarchies, managers, etc.
/// All modifications should go through `CallbackChange` transactions via `push_change()`.
#[must_use] pub const fn get_layout_window(&self) -> &LayoutWindow {
unsafe { (*self.ref_data).layout_window }
}
/// Internal helper: Get the inline text layout for a given node
///
/// This efficiently looks up the text layout by following the chain:
/// `LayoutWindow` -> `layout_results` -> `LayoutTree` -> `dom_to_layout` -> `LayoutNode` ->
/// `inline_layout_result`
///
/// Returns None if:
/// - The DOM doesn't exist in `layout_results`
/// - The node doesn't have a layout node mapping
/// - The layout node doesn't have inline text layout
fn get_inline_layout_for_node(&self, node_id: &DomNodeId) -> Option<&Arc<UnifiedLayout>> {
let layout_window = self.get_layout_window();
// Get the layout result for this DOM
let layout_result = layout_window.layout_results.get(&node_id.dom)?;
// Convert NodeHierarchyItemId to NodeId
let dom_node_id = node_id.node.into_crate_internal()?;
// Look up the layout node index(es) for this DOM node
let layout_indices = layout_result.layout_tree.dom_to_layout.get(&dom_node_id)?;
// Get the first layout node (a DOM node can generate multiple layout nodes,
// but for text we typically only care about the first one)
let layout_index = *layout_indices.first()?;
// Get the layout node's inline layout result (warm data)
let warm_node = layout_result.layout_tree.warm(layout_index)?;
warm_node
.inline_layout_result
.as_ref()
.map(super::solver3::layout_tree::CachedInlineLayout::get_layout)
}
// Public query Api
// All methods below delegate to LayoutWindow for read-only access
/// Get the logical size of a node, or `None` if the node doesn't exist
#[must_use] pub fn get_node_size(&self, node_id: DomNodeId) -> Option<LogicalSize> {
self.get_layout_window().get_node_size(node_id)
}
/// Get the logical position of a node, or `None` if the node doesn't exist
#[must_use] pub fn get_node_position(&self, node_id: DomNodeId) -> Option<LogicalPosition> {
self.get_layout_window().get_node_position(node_id)
}
/// Get the hit test bounds of a node from the display list
///
/// This is more reliable than `get_node_rect` because the display list
/// always contains the correct final rendered positions.
#[must_use] pub fn get_node_hit_test_bounds(&self, node_id: DomNodeId) -> Option<LogicalRect> {
self.get_layout_window().get_node_hit_test_bounds(node_id)
}
/// Get the bounding rectangle of a node (position + size)
///
/// This is particularly useful for menu positioning, where you need
/// to know where a UI element is to popup a menu relative to it.
#[must_use] pub fn get_node_rect(&self, node_id: DomNodeId) -> Option<LogicalRect> {
let position = self.get_node_position(node_id)?;
let size = self.get_node_size(node_id)?;
Some(LogicalRect::new(position, size))
}
/// Get the bounding rectangle of the hit node
///
/// Convenience method that combines `get_hit_node()` and `get_node_rect()`.
/// Useful for menu positioning based on the clicked element.
#[must_use] pub fn get_hit_node_rect(&self) -> Option<LogicalRect> {
let hit_node = self.get_hit_node();
self.get_node_rect(hit_node)
}
// Timer Management (Query APIs)
/// Get a reference to a timer
#[must_use] pub fn get_timer(&self, timer_id: &TimerId) -> Option<&Timer> {
self.get_layout_window().get_timer(timer_id)
}
/// Get all timer IDs
#[must_use] pub fn get_timer_ids(&self) -> TimerIdVec {
self.get_layout_window().get_timer_ids()
}
// Thread Management (Query APIs)
/// Get a reference to a thread
#[must_use] pub fn get_thread(&self, thread_id: &ThreadId) -> Option<&Thread> {
self.get_layout_window().get_thread(thread_id)
}
/// Get all thread IDs
#[must_use] pub fn get_thread_ids(&self) -> ThreadIdVec {
self.get_layout_window().get_thread_ids()
}
// Gpu Value Cache Management (Query APIs)
/// Get the GPU value cache for a specific DOM
#[must_use] pub fn get_gpu_cache(&self, dom_id: &DomId) -> Option<&GpuValueCache> {
self.get_layout_window().get_gpu_cache(dom_id)
}
// Layout Result Access (Query APIs)
/// Get a layout result for a specific DOM
#[must_use] pub fn get_layout_result(&self, dom_id: &DomId) -> Option<&DomLayoutResult> {
self.get_layout_window().get_layout_result(dom_id)
}
/// Get all DOM IDs that have layout results
#[must_use] pub fn get_dom_ids(&self) -> DomIdVec {
self.get_layout_window().get_dom_ids()
}
// Node Hierarchy Navigation
/// Get the DOM node that was hit by the event that triggered this callback
#[must_use] pub const fn get_hit_node(&self) -> DomNodeId {
self.hit_dom_node
}
/// Check if a node is anonymous (generated for table layout)
#[allow(clippy::trivially_copy_pass_by_ref)] // <=8B Copy param kept by-ref intentionally (hot pixel/coord path or to avoid churning call sites for a perf-neutral change)
fn is_node_anonymous(&self, dom_id: &DomId, node_id: NodeId) -> bool {
let layout_window = self.get_layout_window();
let Some(layout_result) = layout_window.get_layout_result(dom_id) else {
return false;
};
let node_data_cont = layout_result.styled_dom.node_data.as_container();
let Some(node_data) = node_data_cont.get(node_id) else {
return false;
};
node_data.is_anonymous()
}
/// Get the parent of a node, skipping anonymous (table-generated) nodes
#[must_use] pub fn get_parent(&self, node_id: DomNodeId) -> Option<DomNodeId> {
let layout_window = self.get_layout_window();
let layout_result = layout_window.get_layout_result(&node_id.dom)?;
let node_id_internal = node_id.node.into_crate_internal()?;
let node_hierarchy = layout_result.styled_dom.node_hierarchy.as_container();
let hier_item = node_hierarchy.get(node_id_internal)?;
// Skip anonymous parent nodes - walk up the tree until we find a non-anonymous node
let mut current_parent_id = hier_item.parent_id()?;
loop {
if !self.is_node_anonymous(&node_id.dom, current_parent_id) {
return Some(DomNodeId {
dom: node_id.dom,
node: NodeHierarchyItemId::from_crate_internal(Some(current_parent_id)),
});
}
// This parent is anonymous, try its parent
let parent_hier_item = node_hierarchy.get(current_parent_id)?;
current_parent_id = parent_hier_item.parent_id()?;
}
}
/// Get the previous sibling of a node, skipping anonymous nodes
#[must_use] pub fn get_previous_sibling(&self, node_id: DomNodeId) -> Option<DomNodeId> {
let layout_window = self.get_layout_window();
let layout_result = layout_window.get_layout_result(&node_id.dom)?;
let node_id_internal = node_id.node.into_crate_internal()?;
let node_hierarchy = layout_result.styled_dom.node_hierarchy.as_container();
let hier_item = node_hierarchy.get(node_id_internal)?;
// Skip anonymous siblings - walk backwards until we find a non-anonymous node
let mut current_sibling_id = hier_item.previous_sibling_id()?;
loop {
if !self.is_node_anonymous(&node_id.dom, current_sibling_id) {
return Some(DomNodeId {
dom: node_id.dom,
node: NodeHierarchyItemId::from_crate_internal(Some(current_sibling_id)),
});
}
// This sibling is anonymous, try the previous one
let sibling_hier_item = node_hierarchy.get(current_sibling_id)?;
current_sibling_id = sibling_hier_item.previous_sibling_id()?;
}
}
/// Get the next sibling of a node, skipping anonymous nodes
#[must_use] pub fn get_next_sibling(&self, node_id: DomNodeId) -> Option<DomNodeId> {
let layout_window = self.get_layout_window();
let layout_result = layout_window.get_layout_result(&node_id.dom)?;
let node_id_internal = node_id.node.into_crate_internal()?;
let node_hierarchy = layout_result.styled_dom.node_hierarchy.as_container();
let hier_item = node_hierarchy.get(node_id_internal)?;
// Skip anonymous siblings - walk forwards until we find a non-anonymous node
let mut current_sibling_id = hier_item.next_sibling_id()?;
loop {
if !self.is_node_anonymous(&node_id.dom, current_sibling_id) {
return Some(DomNodeId {
dom: node_id.dom,
node: NodeHierarchyItemId::from_crate_internal(Some(current_sibling_id)),
});
}
// This sibling is anonymous, try the next one
let sibling_hier_item = node_hierarchy.get(current_sibling_id)?;
current_sibling_id = sibling_hier_item.next_sibling_id()?;
}
}
/// Get the first child of a node, skipping anonymous nodes
#[must_use] pub fn get_first_child(&self, node_id: DomNodeId) -> Option<DomNodeId> {
let layout_window = self.get_layout_window();
let layout_result = layout_window.get_layout_result(&node_id.dom)?;
let node_id_internal = node_id.node.into_crate_internal()?;
let node_hierarchy = layout_result.styled_dom.node_hierarchy.as_container();
let hier_item = node_hierarchy.get(node_id_internal)?;
// Get first child, then skip anonymous nodes
let mut current_child_id = hier_item.first_child_id(node_id_internal)?;
loop {
if !self.is_node_anonymous(&node_id.dom, current_child_id) {
return Some(DomNodeId {
dom: node_id.dom,
node: NodeHierarchyItemId::from_crate_internal(Some(current_child_id)),
});
}
// This child is anonymous, try the next sibling
let child_hier_item = node_hierarchy.get(current_child_id)?;
current_child_id = child_hier_item.next_sibling_id()?;
}
}
/// Get the last child of a node, skipping anonymous nodes
#[must_use] pub fn get_last_child(&self, node_id: DomNodeId) -> Option<DomNodeId> {
let layout_window = self.get_layout_window();
let layout_result = layout_window.get_layout_result(&node_id.dom)?;
let node_id_internal = node_id.node.into_crate_internal()?;
let node_hierarchy = layout_result.styled_dom.node_hierarchy.as_container();
let hier_item = node_hierarchy.get(node_id_internal)?;
// Get last child, then skip anonymous nodes by walking backwards
let mut current_child_id = hier_item.last_child_id()?;
loop {
if !self.is_node_anonymous(&node_id.dom, current_child_id) {
return Some(DomNodeId {
dom: node_id.dom,
node: NodeHierarchyItemId::from_crate_internal(Some(current_child_id)),
});
}
// This child is anonymous, try the previous sibling
let child_hier_item = node_hierarchy.get(current_child_id)?;
current_child_id = child_hier_item.previous_sibling_id()?;
}
}
// Node Data and State
/// Get the dataset (user-attached `RefAny`) of a node, or `None` if unset
pub fn get_dataset(&mut self, node_id: DomNodeId) -> Option<RefAny> {
let layout_window = self.get_layout_window();
let layout_result = layout_window.get_layout_result(&node_id.dom)?;
let node_id_internal = node_id.node.into_crate_internal()?;
let node_data_cont = layout_result.styled_dom.node_data.as_container();
let node_data = node_data_cont.get(node_id_internal)?;
node_data.get_dataset().cloned()
}
/// Find the root-level node whose dataset matches the type of `search_key`
// owned RefAny passed by value per the azul FFI / api.json convention.
#[allow(clippy::needless_pass_by_value)]
pub fn get_node_id_of_root_dataset(&mut self, search_key: RefAny) -> Option<DomNodeId> {
let mut found: Option<(u64, DomNodeId)> = None;
let search_type_id = search_key.get_type_id();
for dom_id in self.get_dom_ids().as_ref().iter().copied() {
let layout_window = self.get_layout_window();
let Some(layout_result) = layout_window.get_layout_result(&dom_id) else {
continue;
};
let node_data_cont = layout_result.styled_dom.node_data.as_container();
for (node_idx, node_data) in node_data_cont.iter().enumerate() {
if let Some(dataset) = node_data.get_dataset().cloned() {
if dataset.get_type_id() == search_type_id {
let node_id = DomNodeId {
dom: dom_id,
node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(
node_idx,
))),
};
let instance_id = dataset.instance_id;
match found {
None => found = Some((instance_id, node_id)),
Some((prev_instance, _)) => {
if instance_id < prev_instance {
found = Some((instance_id, node_id));
}
}
}
}
}
}
}
found.map(|s| s.1)
}
/// Get the text content of a text node, or `None` if the node is not a text node
#[must_use] pub fn get_string_contents(&self, node_id: DomNodeId) -> Option<AzString> {
let layout_window = self.get_layout_window();
let layout_result = layout_window.get_layout_result(&node_id.dom)?;
let node_id_internal = node_id.node.into_crate_internal()?;
let node_data_cont = layout_result.styled_dom.node_data.as_container();
let node_data = node_data_cont.get(node_id_internal)?;
if let NodeType::Text(text) = node_data.get_node_type() {
Some(text.clone_self())
} else {
None
}
}
/// Get the tag name of a node (e.g., "div", "p", "span")
///
/// Returns the HTML tag name as a string for the given node.
/// For text nodes, returns "text". For image nodes, returns "img".
#[must_use] pub fn get_node_tag_name(&self, node_id: DomNodeId) -> Option<AzString> {
let layout_window = self.get_layout_window();
let layout_result = layout_window.get_layout_result(&node_id.dom)?;
let node_id_internal = node_id.node.into_crate_internal()?;
let node_data_cont = layout_result.styled_dom.node_data.as_container();
let node_data = node_data_cont.get(node_id_internal)?;
let tag = node_data.get_node_type().get_path();
Some(tag.to_string().into())
}
/// Get an attribute value from a node by attribute name
///
/// # Arguments
/// * `node_id` - The node to query
/// * `attr_name` - The attribute name (e.g., "id", "class", "href", "data-custom", "aria-label")
///
/// Returns the attribute value if found, None otherwise.
/// This searches the strongly-typed `AttributeVec` on the node.
// Cross-type AttributeType payload dispatch: each `(attr_name, AttributeType::X(v))`
// arm binds a differently-typed `v`, so the same-bodied arms can't be merged into
// one or-pattern (won't type-check) — they are intentionally one-per-attribute.
#[allow(clippy::match_same_arms)]
#[must_use] pub fn get_node_attribute(&self, node_id: DomNodeId, attr_name: &str) -> Option<AzString> {
use azul_core::dom::AttributeType;
let layout_window = self.get_layout_window();
let layout_result = layout_window.get_layout_result(&node_id.dom)?;
let node_id_internal = node_id.node.into_crate_internal()?;
let node_data_cont = layout_result.styled_dom.node_data.as_container();
let node_data = node_data_cont.get(node_id_internal)?;
// Check the strongly-typed attributes vec
for attr in node_data.attributes().as_ref() {
match (attr_name, attr) {
("id", AttributeType::Id(v)) => return Some(v.clone()),
("class", AttributeType::Class(v)) => return Some(v.clone()),
("aria-label", AttributeType::AriaLabel(v)) => return Some(v.clone()),
("aria-labelledby", AttributeType::AriaLabelledBy(v)) => return Some(v.clone()),
("aria-describedby", AttributeType::AriaDescribedBy(v)) => return Some(v.clone()),
("role", AttributeType::AriaRole(v)) => return Some(v.clone()),
("href", AttributeType::Href(v)) => return Some(v.clone()),
("rel", AttributeType::Rel(v)) => return Some(v.clone()),
("target", AttributeType::Target(v)) => return Some(v.clone()),
("src", AttributeType::Src(v)) => return Some(v.clone()),
("alt", AttributeType::Alt(v)) => return Some(v.clone()),
("title", AttributeType::Title(v)) => return Some(v.clone()),
("name", AttributeType::Name(v)) => return Some(v.clone()),
("value", AttributeType::Value(v)) => return Some(v.clone()),
("type", AttributeType::InputType(v)) => return Some(v.clone()),
("placeholder", AttributeType::Placeholder(v)) => return Some(v.clone()),
("max", AttributeType::Max(v)) => return Some(v.clone()),
("min", AttributeType::Min(v)) => return Some(v.clone()),
("step", AttributeType::Step(v)) => return Some(v.clone()),
("pattern", AttributeType::Pattern(v)) => return Some(v.clone()),
("autocomplete", AttributeType::Autocomplete(v)) => return Some(v.clone()),
("scope", AttributeType::Scope(v)) => return Some(v.clone()),
("lang", AttributeType::Lang(v)) => return Some(v.clone()),
("dir", AttributeType::Dir(v)) => return Some(v.clone()),
("required", AttributeType::Required) => return Some("true".into()),
("disabled", AttributeType::Disabled) => return Some("true".into()),
("readonly", AttributeType::Readonly) => return Some("true".into()),
("checked", AttributeType::CheckedTrue) => return Some("true".into()),
("checked", AttributeType::CheckedFalse) => return Some("false".into()),
("selected", AttributeType::Selected) => return Some("true".into()),
("hidden", AttributeType::Hidden) => return Some("true".into()),
("focusable", AttributeType::Focusable) => return Some("true".into()),
("minlength", AttributeType::MinLength(v)) => return Some(v.to_string().into()),
("maxlength", AttributeType::MaxLength(v)) => return Some(v.to_string().into()),
("colspan", AttributeType::ColSpan(v)) => return Some(v.to_string().into()),
("rowspan", AttributeType::RowSpan(v)) => return Some(v.to_string().into()),
("tabindex", AttributeType::TabIndex(v)) => return Some(v.to_string().into()),
("contenteditable", AttributeType::ContentEditable(v)) => {
return Some(v.to_string().into())
}
("draggable", AttributeType::Draggable(v)) => return Some(v.to_string().into()),
// Handle data-* attributes
(name, AttributeType::Data(nv))
if name.starts_with("data-") && nv.attr_name.as_str() == &name[5..] =>
{
return Some(nv.value.clone());
}
// Handle aria-* state/property attributes
(name, AttributeType::AriaState(nv))
if name == format!("aria-{}", nv.attr_name.as_str()) =>
{
return Some(nv.value.clone());
}
(name, AttributeType::AriaProperty(nv))
if name == format!("aria-{}", nv.attr_name.as_str()) =>
{
return Some(nv.value.clone());
}
// Handle custom attributes
(name, AttributeType::Custom(nv)) if nv.attr_name.as_str() == name => {
return Some(nv.value.clone());
}
_ => {}
}
}
None
}
/// Get all classes of a node as a vector of strings
#[must_use] pub fn get_node_classes(&self, node_id: DomNodeId) -> StringVec {
let Some(layout_window) = self.get_layout_window().get_layout_result(&node_id.dom) else {
return StringVec::from_const_slice(&[]);
};
let Some(node_id_internal) = node_id.node.into_crate_internal() else {
return StringVec::from_const_slice(&[]);
};
let node_data_cont = layout_window.styled_dom.node_data.as_container();
let Some(node_data) = node_data_cont.get(node_id_internal) else {
return StringVec::from_const_slice(&[]);
};
let classes: Vec<AzString> = node_data
.attributes()
.as_ref()
.iter()
.filter_map(|attr| {
attr.as_class().map(|c| c.to_string().into())
})
.collect();
StringVec::from(classes)
}
/// Get the ID attribute of a node (if it has one)
#[must_use] pub fn get_node_id(&self, node_id: DomNodeId) -> Option<AzString> {
let layout_window = self.get_layout_window();
let layout_result = layout_window.get_layout_result(&node_id.dom)?;
let node_id_internal = node_id.node.into_crate_internal()?;
let node_data_cont = layout_result.styled_dom.node_data.as_container();
let node_data = node_data_cont.get(node_id_internal)?;
for attr in node_data.attributes().as_ref() {
if let Some(id) = attr.as_id() {
return Some(id.to_string().into());
}
}
None
}
// Text Selection Management
/// Get the current selection state for a DOM (via `multi_cursor`)
#[must_use] pub const fn get_selection(&self, _dom_id: &DomId) -> Option<&SelectionState> {
// SelectionManager removed; multi_cursor is the source of truth.
// SelectionState is a legacy type; return None.
None
}
/// Check if a DOM has any selection (via `multi_cursor`)
#[must_use] pub fn has_selection(&self, _dom_id: &DomId) -> bool {
self.get_layout_window()
.text_edit_manager.multi_cursor.as_ref()
.is_some_and(|mc| mc.selections.iter().any(|s| matches!(&s.selection, Selection::Range(_))))
}
/// Get the primary cursor for a DOM (via `multi_cursor`)
#[must_use] pub fn get_primary_cursor(&self, _dom_id: &DomId) -> Option<TextCursor> {
self.get_layout_window()
.text_edit_manager.multi_cursor.as_ref()
.and_then(azul_core::selection::MultiCursorState::get_primary_cursor)
}
/// Get all selection ranges (excludes plain cursors, via `multi_cursor`)
#[must_use] pub fn get_selection_ranges(&self, _dom_id: &DomId) -> SelectionRangeVec {
let ranges: Vec<SelectionRange> = self.get_layout_window()
.text_edit_manager.multi_cursor.as_ref()
.map(|mc| mc.selections.iter().filter_map(|s| match &s.selection {
Selection::Range(r) => Some(*r),
Selection::Cursor(_) => None,
}).collect()).unwrap_or_default();
ranges.into()
}
/// Get direct access to the text layout cache
///
/// Note: This provides direct read-only access to the text layout cache, but you need
/// to know the `CacheId` for the specific text node you want. Currently there's
/// no direct mapping from `NodeId` to `CacheId` exposed in the public API.
///
/// For text modifications, use `CallbackChange` transactions:
/// - `change_node_text()` for changing text content
/// - `set_selection()` for setting selections
/// - `get_selection()`, `get_primary_cursor()` for reading selections
///
/// Future: Add `NodeId` -> `CacheId` mapping to enable node-specific layout access
#[must_use] pub const fn get_text_cache(&self) -> &TextLayoutCache {
&self.get_layout_window().text_cache
}
// Window State Access
/// Get full current window state (immutable reference)
#[must_use] pub const fn get_current_window_state(&self) -> &FullWindowState {
// SAFETY: current_window_state is a valid pointer for the lifetime of CallbackInfo
unsafe { (*self.ref_data).current_window_state }
}
/// Get current window flags
#[must_use] pub const fn get_current_window_flags(&self) -> WindowFlags {
self.get_current_window_state().flags
}
/// Get current keyboard state
#[must_use] pub fn get_current_keyboard_state(&self) -> KeyboardState {
self.get_current_window_state().keyboard_state.clone()
}
/// Get current mouse state
#[must_use] pub const fn get_current_mouse_state(&self) -> MouseState {
self.get_current_window_state().mouse_state
}
/// Get full previous window state (immutable reference)
#[must_use] pub const fn get_previous_window_state(&self) -> &Option<FullWindowState> {
unsafe { (*self.ref_data).previous_window_state }
}
/// Get previous window flags
#[must_use] pub fn get_previous_window_flags(&self) -> Option<WindowFlags> {
Some(self.get_previous_window_state().as_ref()?.flags)
}
/// Get previous keyboard state
#[must_use] pub fn get_previous_keyboard_state(&self) -> Option<KeyboardState> {
Some(
self.get_previous_window_state()
.as_ref()?
.keyboard_state
.clone(),
)
}
/// Get previous mouse state
#[must_use] pub fn get_previous_mouse_state(&self) -> Option<MouseState> {
Some(
self.get_previous_window_state()
.as_ref()?
.mouse_state,
)
}
// Cursor and Input
#[must_use] pub const fn get_cursor_relative_to_node(&self) -> azul_core::geom::OptionCursorNodePosition {
use azul_core::geom::{CursorNodePosition, OptionCursorNodePosition};
match self.cursor_relative_to_item {
OptionLogicalPosition::Some(p) => OptionCursorNodePosition::Some(CursorNodePosition::from_logical(p)),
OptionLogicalPosition::None => OptionCursorNodePosition::None,
}
}
#[must_use] pub const fn get_cursor_relative_to_viewport(&self) -> OptionLogicalPosition {
self.cursor_in_viewport
}
/// Get cursor position in virtual screen coordinates (all monitors combined).
///
/// Computed as: `window_position + cursor_position_in_window`.
/// All coordinates are in logical pixels (HiDPI-independent on macOS; on Win32
/// this depends on DPI-awareness mode).
///
/// The origin (0, 0) is at the **top-left of the primary monitor**.
/// Y increases downward. On multi-monitor setups, coordinates may be negative
/// for monitors to the left of or above the primary monitor.
///
/// Returns `None` if the cursor is outside the window or the window position
/// is unknown.
///
/// ## Platform notes
///
/// | Platform | Accuracy |
/// |----------|----------|
/// | **macOS** | Exact (points = logical pixels) |
/// | **Win32** | Exact when DPI-aware; approximate otherwise |
/// | **X11** | Exact (pixels) |
/// | **Wayland** | Falls back to window-local (compositor hides global position) |
#[allow(clippy::cast_precision_loss)] // bounded graphics/coord/counter/fixed-point cast
#[must_use] pub fn get_cursor_position_screen(&self) -> azul_core::geom::OptionScreenPosition {
use azul_core::window::WindowPosition;
use azul_core::geom::{LogicalPosition, ScreenPosition, OptionScreenPosition};
let ws = self.get_current_window_state();
let Some(cursor_local) = ws.mouse_state.cursor_position.get_position() else {
return OptionScreenPosition::None;
};
match ws.position {
WindowPosition::Initialized(pos) => {
OptionScreenPosition::Some(ScreenPosition::new(
pos.x as f32 + cursor_local.x,
pos.y as f32 + cursor_local.y,
))
}
// Wayland / relative-to-parent: absolute screen position unknown here
// (relative needs the parent's screen pos), fall back to window-local.
WindowPosition::Uninitialized | WindowPosition::RelativeToParentWindow(_) => {
OptionScreenPosition::Some(ScreenPosition::new(cursor_local.x, cursor_local.y))
}
}
}
/// Get the drag delta in window-local coordinates.
///
/// Returns the offset from drag start to current cursor position in window-local
/// logical pixels. Returns `None` if no drag is active.
///
/// **Warning**: This is NOT stable during window moves (titlebar drag).
/// Use `get_drag_delta_screen()` for titlebar dragging.
#[must_use] pub fn get_drag_delta(&self) -> azul_core::geom::OptionDragDelta {
use azul_core::geom::{DragDelta, OptionDragDelta};
let gm = self.get_gesture_drag_manager();
match gm.get_drag_delta() {
Some((dx, dy)) => OptionDragDelta::Some(DragDelta::new(dx, dy)),
None => OptionDragDelta::None,
}
}
/// Get the drag delta in screen coordinates.
///
/// Unlike `get_drag_delta()`, this is stable even when the window moves
/// (e.g., during titlebar drag). Returns `None` if no drag is active.
/// On Wayland: falls back to window-local delta.
#[must_use] pub fn get_drag_delta_screen(&self) -> azul_core::geom::OptionDragDelta {
use azul_core::geom::{DragDelta, OptionDragDelta};
let gm = self.get_gesture_drag_manager();
match gm.get_drag_delta_screen() {
Some((dx, dy)) => OptionDragDelta::Some(DragDelta::new(dx, dy)),
None => OptionDragDelta::None,
}
}
/// Get the **incremental** (frame-to-frame) drag delta in screen coordinates.
///
/// Returns the screen-space delta between the current and previous sample
/// (not the total delta since drag start). Use this with the current window
/// position for robust titlebar drag:
///
/// ```text
/// new_pos = current_window_pos + incremental_delta
/// ```
///
/// This handles external position changes (DPI change, OS clamping, compositor
/// resize) that would make the initial position stale.
/// Returns `None` if no drag is active or fewer than 2 samples exist.
#[must_use] pub fn get_drag_delta_screen_incremental(&self) -> azul_core::geom::OptionDragDelta {
use azul_core::geom::{DragDelta, OptionDragDelta};
let gm = self.get_gesture_drag_manager();
match gm.get_drag_delta_screen_incremental() {
Some((dx, dy)) => OptionDragDelta::Some(DragDelta::new(dx, dy)),
None => OptionDragDelta::None,
}
}
#[must_use] pub const fn get_current_window_handle(&self) -> RawWindowHandle {
unsafe { *(*self.ref_data).current_window_handle }
}
/// Get the system style (for menu rendering, CSD, etc.)
/// This is useful for creating custom menus or other system-styled UI.
#[must_use] pub fn get_system_style(&self) -> Arc<SystemStyle> {
unsafe { (*self.ref_data).system_style.clone() }
}
/// Get a snapshot of all monitors available on the system.
///
/// The returned `MonitorVec` is cloned from the shared monitor cache.
/// The cache is initialized once at app start and updated by the platform
/// layer on monitor topology changes. No OS calls are made here.
#[must_use] pub fn get_monitors(&self) -> MonitorVec {
let monitors_arc = unsafe { &(*self.ref_data).monitors };
monitors_arc.lock().map_or_else(|_| MonitorVec::from_const_slice(&[]), |g| g.clone())
}
/// Get the monitor that the current window is on, if known.
///
/// Uses `FullWindowState::monitor_id` (set by the platform layer) to find
/// the matching monitor in the cached monitor list. Returns `None` if the
/// monitor ID is not set or no matching monitor is found.
#[must_use] pub fn get_current_monitor(&self) -> OptionMonitor {
let ws = self.get_current_window_state();
let monitor_index = match ws.monitor_id {
azul_css::corety::OptionU32::Some(idx) => idx as usize,
azul_css::corety::OptionU32::None => return OptionMonitor::None,
};
let monitors_arc = unsafe { &(*self.ref_data).monitors };
let Ok(guard) = monitors_arc.lock() else {
return OptionMonitor::None;
};
for m in guard.as_ref() {
if m.monitor_id.index == monitor_index {
return OptionMonitor::Some(m.clone());
}
}
OptionMonitor::None
}
// ==================== ICU4X Internationalization API ====================
//
// All formatting functions take a locale string (BCP 47 format) as the first
// parameter, allowing dynamic language switching per-call.
//
// For date/time construction, use the static methods on IcuDate, IcuTime, IcuDateTime:
// - IcuDate::now(), IcuDate::now_utc(), IcuDate::new(year, month, day)
// - IcuTime::now(), IcuTime::now_utc(), IcuTime::new(hour, minute, second)
// - IcuDateTime::now(), IcuDateTime::now_utc(), IcuDateTime::from_timestamp(secs)
/// Get the ICU localizer cache for internationalized formatting.
///
/// The cache stores localizers for multiple locales. Each locale's formatter
/// is lazily created on first use and cached for subsequent calls.
#[cfg(feature = "icu")]
pub fn get_icu_localizer(&self) -> &IcuLocalizerHandle {
unsafe { &(*self.ref_data).icu_localizer }
}
/// Format an integer with locale-appropriate grouping separators.
///
/// # Arguments
/// * `locale` - BCP 47 locale string (e.g., "en-US", "de-DE", "ja-JP")
/// * `value` - The integer to format
///
/// # Example
/// ```rust,ignore
/// info.format_integer("en-US", 1234567) // -> "1,234,567"
/// info.format_integer("de-DE", 1234567) // -> "1.234.567"
/// info.format_integer("fr-FR", 1234567) // -> "1 234 567"
/// ```
#[cfg(feature = "icu")]
pub fn format_integer(&self, locale: &str, value: i64) -> AzString {
self.get_icu_localizer().format_integer(locale, value)
}
/// Format a decimal number with locale-appropriate separators.
///
/// # Arguments
/// * `locale` - BCP 47 locale string
/// * `integer_part` - The full integer value (e.g., 123456 for 1234.56)
/// * `decimal_places` - Number of decimal places (e.g., 2 for 1234.56)
///
/// # Example
/// ```rust,ignore
/// info.format_decimal("en-US", 123456, 2) // -> "1,234.56"
/// info.format_decimal("de-DE", 123456, 2) // -> "1.234,56"
/// ```
#[cfg(feature = "icu")]
pub fn format_decimal(&self, locale: &str, integer_part: i64, decimal_places: i16) -> AzString {
self.get_icu_localizer().format_decimal(locale, integer_part, decimal_places)
}
/// Get the plural category for a number (cardinal: "1 item", "2 items").
///
/// # Arguments
/// * `locale` - BCP 47 locale string
/// * `value` - The number to get the plural category for
///
/// # Example
/// ```rust,ignore
/// info.get_plural_category("en", 1) // -> PluralCategory::One
/// info.get_plural_category("en", 2) // -> PluralCategory::Other
/// info.get_plural_category("pl", 2) // -> PluralCategory::Few
/// info.get_plural_category("pl", 5) // -> PluralCategory::Many
/// ```
#[cfg(feature = "icu")]
pub fn get_plural_category(&self, locale: &str, value: i64) -> PluralCategory {
self.get_icu_localizer().get_plural_category(locale, value)
}
/// Select the appropriate string based on plural rules.
///
/// # Arguments
/// * `locale` - BCP 47 locale string
/// * `value` - The number to pluralize
/// * `zero`, `one`, `two`, `few`, `many`, `other` - Strings for each category
///
/// # Example
/// ```rust,ignore
/// info.pluralize("en", count, "no items", "1 item", "2 items", "{} items", "{} items", "{} items")
/// info.pluralize("pl", count, "brak", "1 element", "2 elementy", "{} elementy", "{} elementów", "{} elementów")
/// ```
#[cfg(feature = "icu")]
pub fn pluralize(
&self,
locale: &str,
value: i64,
zero: &str,
one: &str,
two: &str,
few: &str,
many: &str,
other: &str,
) -> AzString {
self.get_icu_localizer().pluralize(locale, value, zero, one, two, few, many, other)
}
/// Format a list of items with locale-appropriate conjunctions.
///
/// # Arguments
/// * `locale` - BCP 47 locale string
/// * `items` - The items to format as a list
/// * `list_type` - And, Or, or Unit list type
///
/// # Example
/// ```rust,ignore
/// info.format_list("en-US", &items, ListType::And) // -> "A, B, and C"
/// info.format_list("es-ES", &items, ListType::And) // -> "A, B y C"
/// ```
#[cfg(feature = "icu")]
pub fn format_list(&self, locale: &str, items: StringVec, list_type: ListType) -> AzString {
self.get_icu_localizer()
.format_list(locale, items.as_ref(), list_type)
}
/// Format a date according to the specified locale.
///
/// # Arguments
/// * `locale` - BCP 47 locale string
/// * `date` - The date to format (use IcuDate::now() or IcuDate::new())
/// * `length` - Short, Medium, or Long format
///
/// # Example
/// ```rust,ignore
/// let today = IcuDate::now();
/// info.format_date("en-US", today, FormatLength::Medium) // -> "Jan 15, 2025"
/// info.format_date("de-DE", today, FormatLength::Medium) // -> "15.01.2025"
/// ```
#[cfg(feature = "icu")]
pub fn format_date(&self, locale: &str, date: IcuDate, length: FormatLength) -> IcuResult {
self.get_icu_localizer().format_date(locale, date, length)
}
/// Format a time according to the specified locale.
///
/// # Arguments
/// * `locale` - BCP 47 locale string
/// * `time` - The time to format (use IcuTime::now() or IcuTime::new())
/// * `include_seconds` - Whether to include seconds in the output
///
/// # Example
/// ```rust,ignore
/// let now = IcuTime::now();
/// info.format_time("en-US", now, false) // -> "4:30 PM"
/// info.format_time("de-DE", now, false) // -> "16:30"
/// ```
#[cfg(feature = "icu")]
pub fn format_time(&self, locale: &str, time: IcuTime, include_seconds: bool) -> IcuResult {
self.get_icu_localizer().format_time(locale, time, include_seconds)
}
/// Format a date and time according to the specified locale.
///
/// # Arguments
/// * `locale` - BCP 47 locale string
/// * `datetime` - The date and time to format (use IcuDateTime::now())
/// * `length` - Short, Medium, or Long format
#[cfg(feature = "icu")]
pub fn format_datetime(&self, locale: &str, datetime: IcuDateTime, length: FormatLength) -> IcuResult {
self.get_icu_localizer().format_datetime(locale, datetime, length)
}
/// Compare two strings according to locale-specific collation rules.
///
/// Returns -1 if a < b, 0 if a == b, 1 if a > b.
/// This is useful for locale-aware sorting where "Ä" should sort with "A" in German.
///
/// # Arguments
/// * `locale` - BCP 47 locale string
/// * `a` - First string to compare
/// * `b` - Second string to compare
///
/// # Example
/// ```rust,ignore
/// info.compare_strings("de-DE", "Äpfel", "Banane") // -> -1 (Ä sorts with A)
/// info.compare_strings("sv-SE", "Äpple", "Öl") // -> -1 (Swedish: Ä before Ö)
/// ```
#[cfg(feature = "icu")]
pub fn compare_strings(&self, locale: &str, a: &str, b: &str) -> i32 {
self.get_icu_localizer().compare_strings(locale, a, b)
}
/// Sort a list of strings using locale-aware collation.
///
/// This properly handles accented characters, case sensitivity, and
/// language-specific sorting rules.
///
/// # Arguments
/// * `locale` - BCP 47 locale string
/// * `strings` - The strings to sort
///
/// # Example
/// ```rust,ignore
/// let sorted = info.sort_strings("de-DE", &["Österreich", "Andorra", "Ägypten"]);
/// // Result: ["Ägypten", "Andorra", "Österreich"] (Ä sorts with A, Ö with O)
/// ```
#[cfg(feature = "icu")]
pub fn sort_strings(&self, locale: &str, strings: StringVec) -> IcuStringVec {
self.get_icu_localizer()
.sort_strings(locale, strings.as_ref())
}
/// Check if two strings are equal according to locale collation rules.
///
/// This may return `true` for strings that differ in case or accents,
/// depending on the collation strength.
///
/// # Arguments
/// * `locale` - BCP 47 locale string
/// * `a` - First string to compare
/// * `b` - Second string to compare
#[cfg(feature = "icu")]
pub fn strings_equal(&self, locale: &str, a: &str, b: &str) -> bool {
self.get_icu_localizer().strings_equal(locale, a, b)
}
/// Get the current cursor position in logical coordinates relative to the window
#[must_use] pub fn get_cursor_position(&self) -> Option<LogicalPosition> {
self.cursor_in_viewport.into_option()
}
/// Get the layout rectangle of the currently hit node (in logical coordinates)
#[must_use] pub fn get_hit_node_layout_rect(&self) -> Option<LogicalRect> {
self.get_layout_window()
.get_node_layout_rect(self.hit_dom_node)
}
// Css Property Access
/// Get the computed CSS property for a specific DOM node
///
/// This queries the CSS property cache and returns the resolved property value
/// for the given node, taking into account:
/// - User overrides (from callbacks)
/// - Node state (:hover, :active, :focus)
/// - CSS rules from stylesheets
/// - Cascaded properties from parents
/// - Inline styles
///
/// # Arguments
/// * `node_id` - The DOM node to query
/// * `property_type` - The CSS property type to retrieve
///
/// # Returns
/// * `Some(CssProperty)` if the property is set on this node
/// * `None` if the property is not set (will use default value)
#[must_use] pub fn get_computed_css_property(
&self,
node_id: DomNodeId,
property_type: CssPropertyType,
) -> Option<CssProperty> {
let layout_window = self.get_layout_window();
// Get the layout result for this DOM
let layout_result = layout_window.layout_results.get(&node_id.dom)?;
// Get the styled DOM
let styled_dom = &layout_result.styled_dom;
// Convert DomNodeId to NodeId using proper decoding
let internal_node_id = node_id.node.into_crate_internal()?;
// Get the node data
let node_data_container = styled_dom.node_data.as_container();
let node_data = node_data_container.get(internal_node_id)?;
// Get the styled node state
let styled_nodes_container = styled_dom.styled_nodes.as_container();
let styled_node = styled_nodes_container.get(internal_node_id)?;
let node_state = &styled_node.styled_node_state;
// Query the CSS property cache
let css_property_cache = &styled_dom.css_property_cache.ptr;
css_property_cache
.get_property(node_data, &internal_node_id, node_state, &property_type)
.cloned()
}
/// Get the computed width of a node from CSS
///
/// Convenience method for getting the CSS width property.
#[must_use] pub fn get_computed_width(&self, node_id: DomNodeId) -> Option<CssProperty> {
self.get_computed_css_property(node_id, CssPropertyType::Width)
}
/// Get the computed height of a node from CSS
///
/// Convenience method for getting the CSS height property.
#[must_use] pub fn get_computed_height(&self, node_id: DomNodeId) -> Option<CssProperty> {
self.get_computed_css_property(node_id, CssPropertyType::Height)
}
// System Callbacks
#[must_use] pub const fn get_system_time_fn(&self) -> GetSystemTimeCallback {
unsafe { (*self.ref_data).system_callbacks.get_system_time_fn }
}
#[must_use] pub fn get_current_time(&self) -> task::Instant {
let cb = self.get_system_time_fn();
(cb.cb)()
}
/// Get immutable reference to the renderer resources
///
/// This provides access to fonts, images, and other rendering resources.
/// Useful for custom rendering or screenshot functionality.
#[must_use] pub const fn get_renderer_resources(&self) -> &RendererResources {
unsafe { (*self.ref_data).renderer_resources }
}
// Font Cache Introspection
//
// These let a callback discover and retrieve the fonts the layout engine
// has actually loaded into its font cache, without having to pass them in
// up-front. The primary use case is "embed every font the layout actually
// used" from a callback (e.g. a printpdf consumer correlating
// `DisplayListItem::Text.font_hash` glyph runs with the loaded font bytes).
//
// IMAGE GAP (deferred): there is no analogous `get_loaded_image_*` here yet.
// Unlike fonts (whose cache lives in `LayoutWindow.font_manager`, reachable
// via `get_layout_window()`), the live image cache with the actual
// `ImageRef` bytes is owned by the windowing shell (`common.image_cache`)
// and is only passed *by reference* into the layout pass - it is not stored
// on the `LayoutWindow` (its `image_cache` field is initialised empty and
// never populated) and is not part of `CallbackInfoRefData`. Exposing image
// bytes here therefore requires threading `&ImageCache` into
// `CallbackInfoRefData` and through `invoke_single_callback` /
// `run_single_timer` / `run_all_threads` and all their per-platform callers
// (macOS / Wayland / X11 / Windows). `RendererResources.currently_registered_images`
// is reachable via `get_renderer_resources()` but only carries the WebRender
// key + `ImageDescriptor`, not the pixel bytes.
/// Enumerate every font the layout engine currently has loaded in its font
/// cache.
///
/// Returns one [`LoadedFont`](azul_core::resources::LoadedFont) descriptor
/// per loaded face. The `font_hash` field of each descriptor is identical
/// to the `font_hash` carried by `DisplayListItem::Text` glyph runs, so a
/// callback can correlate a loaded font with the text that uses it and then
/// pull the raw bytes via [`get_loaded_font_bytes`](Self::get_loaded_font_bytes).
///
/// The list includes fallback faces that were resolved during layout, not
/// just the families named in the source CSS.
#[cfg(feature = "text_layout")]
#[must_use] pub fn get_loaded_fonts(&self) -> LoadedFontVec {
let font_manager = &self.get_layout_window().font_manager;
let Ok(guard) = font_manager.parsed_fonts.lock() else {
return Vec::new().into();
};
// BTreeMap-style stable iteration is not guaranteed here (HashMap), so
// we collect then sort by font_hash for a deterministic order.
let mut out: Vec<LoadedFont> = guard
.values()
.map(|font_ref| {
let parsed = crate::font_ref_to_parsed_font(font_ref);
let family_name = parsed
.font_name
.as_ref()
.map(|s| AzString::from(s.clone()))
.unwrap_or_default();
LoadedFont {
font_hash: parsed.hash,
family_name,
num_glyphs: u32::from(parsed.num_glyphs),
has_bytes: parsed.source_bytes_for_subset().is_some(),
}
})
.collect();
out.sort_by(|a, b| a.font_hash.cmp(&b.font_hash));
out.into()
}
/// Retrieve the raw source bytes (TTF / OTF / TTC, etc.) for a loaded font,
/// looked up by the `font_hash` returned from
/// [`get_loaded_fonts`](Self::get_loaded_fonts) (or carried on a
/// `DisplayListItem::Text` glyph run).
///
/// Returns `None` if no loaded font matches `font_hash`, or if the matching
/// font did not retain its source bytes (e.g. a test-only font; production
/// fonts loaded from disk retain an mmap-backed handle and always succeed).
/// The returned bytes can be embedded directly into a generated document.
#[cfg(feature = "text_layout")]
#[must_use] pub fn get_loaded_font_bytes(&self, font_hash: u64) -> OptionU8Vec {
let font_manager = &self.get_layout_window().font_manager;
let Some(font_ref) = font_manager.get_font_by_hash(font_hash) else {
return OptionU8Vec::None;
};
let parsed = crate::font_ref_to_parsed_font(&font_ref);
parsed.source_bytes_for_subset().map_or_else(|| OptionU8Vec::None, |bytes| OptionU8Vec::Some(U8Vec::from_vec(bytes.as_slice().to_vec())))
}
// Screenshot API
/// Take a CPU-rendered screenshot of the current window content
///
/// This renders the current display list to a PNG image using CPU rendering.
/// The screenshot captures the window content as it would appear on screen,
/// without window decorations.
///
/// # Arguments
/// * `dom_id` - The DOM to screenshot (use the main DOM ID for the full window)
///
/// # Returns
/// * `Ok(Vec<u8>)` - PNG-encoded image data
/// * `Err(String)` - Error message if rendering failed
///
/// # Example
/// ```ignore
/// fn on_click(info: &mut CallbackInfo) -> Update {
/// let dom_id = info.get_hit_node().dom;
/// match info.take_screenshot(dom_id) {
/// Ok(png_data) => {
/// std::fs::write("screenshot.png", png_data).unwrap();
/// }
/// Err(e) => eprintln!("Screenshot failed: {}", e),
/// }
/// Update::DoNothing
/// }
/// ```
#[cfg(feature = "cpurender")]
/// # Errors
///
/// Returns an error message if the screenshot cannot be captured or encoded.
pub fn take_screenshot(&self, dom_id: DomId) -> Result<alloc::vec::Vec<u8>, AzString> {
use crate::cpurender::{render_with_font_manager_and_scroll, CpuRenderState, RenderOptions, ScrollOffsetMap};
let layout_window = self.get_layout_window();
let renderer_resources = &layout_window.renderer_resources;
// Get the layout result for this DOM
let layout_result = layout_window
.layout_results
.get(&dom_id)
.ok_or_else(|| AzString::from("DOM not found in layout results"))?;
// Use the current window state dimensions
let ws = self.get_current_window_state();
let width = ws.size.dimensions.width;
let height = ws.size.dimensions.height;
if width <= 0.0 || height <= 0.0 {
return Err(AzString::from("Invalid viewport dimensions"));
}
let display_list = &layout_result.display_list;
let dpi_factor = ws.size.get_hidpi_factor().inner.get();
// Build scroll offset map from the current ScrollManager state
let scroll_offsets = layout_window.scroll_manager
.build_scroll_offset_map(dom_id, &layout_result.scroll_ids);
// Build CPU render state from GpuValueCache - provides current
// transform values (scrollbar thumb positions) and opacity values
// (scrollbar visibility fading) that the GPU path animates dynamically.
let gpu_cache = layout_window.gpu_state_manager
.get_cache(dom_id);
let render_state = CpuRenderState::from_gpu_cache(
gpu_cache,
dom_id,
&scroll_offsets,
)
.with_system_style(layout_window.system_style.clone());
let opts = RenderOptions {
width,
height,
dpi_factor,
};
let mut glyph_cache = crate::glyph_cache::GlyphCache::new();
let pixmap = render_with_font_manager_and_scroll(
display_list,
renderer_resources,
&layout_window.font_manager,
opts,
&mut glyph_cache,
&render_state,
).map_err(AzString::from)?;
// Encode to PNG
let png_data = pixmap
.encode_png()
.map_err(|e| AzString::from(alloc::format!("PNG encoding failed: {e}")))?;
Ok(png_data)
}
/// Take a screenshot and save it directly to a file
///
/// Convenience method that combines `take_screenshot` with file writing.
///
/// # Arguments
/// * `dom_id` - The DOM to screenshot
/// * `path` - The file path to save the PNG to
///
/// # Returns
/// * `Ok(())` - Screenshot saved successfully
/// * `Err(String)` - Error message if rendering or saving failed
#[cfg(all(feature = "std", feature = "cpurender"))]
/// # Errors
///
/// Returns an error message if the screenshot cannot be captured or encoded.
pub fn take_screenshot_to_file(&self, dom_id: DomId, path: &str) -> Result<(), AzString> {
let png_data = self.take_screenshot(dom_id)?;
std::fs::write(path, png_data)
.map_err(|e| AzString::from(alloc::format!("Failed to write file: {e}")))?;
Ok(())
}
/// Take a native OS-level screenshot of the window including window decorations
///
/// **NOTE**: This is a stub implementation. For full native screenshot support,
/// use the `NativeScreenshotExt` trait from the `azul-dll` crate, which uses
/// runtime dynamic loading (dlopen) to avoid static linking dependencies.
///
/// # Returns
/// * `Err(String)` - Always returns an error directing to use the extension trait
#[cfg(feature = "std")]
/// # Errors
///
/// Returns an error message if the screenshot cannot be captured or encoded.
pub fn take_native_screenshot(&self, _path: &str) -> Result<(), AzString> {
Err(AzString::from(
"Native screenshot requires the NativeScreenshotExt trait from azul-dll crate. \
Import it with: use azul::desktop::NativeScreenshotExt;",
))
}
/// Take a native OS-level screenshot and return the PNG data as bytes
///
/// **NOTE**: This is a stub implementation. For full native screenshot support,
/// use the `NativeScreenshotExt` trait from the `azul-dll` crate.
///
/// # Returns
/// * `Ok(Vec<u8>)` - PNG-encoded image data
/// * `Err(String)` - Error message if screenshot failed
#[cfg(feature = "std")]
/// # Errors
///
/// Returns an error message if the screenshot cannot be captured or encoded.
pub fn take_native_screenshot_bytes(&self) -> Result<alloc::vec::Vec<u8>, AzString> {
// Create a temporary file, take screenshot, read bytes, delete file
let temp_path = std::env::temp_dir().join("azul_screenshot_temp.png");
let temp_path_str = temp_path.to_string_lossy().to_string();
self.take_native_screenshot(&temp_path_str)?;
let bytes = std::fs::read(&temp_path)
.map_err(|e| AzString::from(alloc::format!("Failed to read screenshot: {e}")))?;
drop(std::fs::remove_file(&temp_path));
Ok(bytes)
}
/// Take a native OS-level screenshot and return as a Base64 data URI
///
/// Returns the screenshot as a "data:image/png;base64,..." string that can
/// be directly used in HTML img tags or JSON responses.
///
/// # Returns
/// * `Ok(String)` - Base64 data URI string
/// * `Err(String)` - Error message if screenshot failed
///
#[cfg(feature = "std")]
/// # Errors
///
/// Returns an error message if the screenshot cannot be captured or encoded.
pub fn take_native_screenshot_base64(&self) -> Result<AzString, AzString> {
let png_bytes = self.take_native_screenshot_bytes()?;
let base64_str = base64_encode(&png_bytes);
Ok(AzString::from(alloc::format!(
"data:image/png;base64,{base64_str}"
)))
}
/// Take a CPU-rendered screenshot and return as a Base64 data URI
///
/// Returns the screenshot as a "data:image/png;base64,..." string.
/// This is the software-rendered version without window decorations.
///
/// # Returns
/// * `Ok(String)` - Base64 data URI string
/// * `Err(String)` - Error message if rendering failed
#[cfg(feature = "cpurender")]
/// # Errors
///
/// Returns an error message if the screenshot cannot be captured or encoded.
pub fn take_screenshot_base64(&self, dom_id: DomId) -> Result<AzString, AzString> {
let png_bytes = self.take_screenshot(dom_id)?;
let base64_str = base64_encode(&png_bytes);
Ok(AzString::from(alloc::format!(
"data:image/png;base64,{base64_str}"
)))
}
// Manager Access (Read-Only)
/// Get immutable reference to the scroll manager
///
/// Use this to query scroll state for nodes without modifying it.
/// To request programmatic scrolling, use `nodes_scrolled_in_callback`.
#[must_use] pub const fn get_scroll_manager(&self) -> &ScrollManager {
unsafe { &(*self.ref_data).layout_window.scroll_manager }
}
/// Get immutable reference to the gesture and drag manager
///
/// Use this to query current gesture/drag state (e.g., "is this node being dragged?",
/// "what files are being dropped?", "is a long-press active?").
///
/// The manager is updated by the event loop and provides read-only query access
/// to callbacks for gesture-aware UI behavior.
#[must_use] pub const fn get_gesture_drag_manager(&self) -> &GestureAndDragManager {
unsafe { &(*self.ref_data).layout_window.gesture_drag_manager }
}
/// Queue a platform-native gesture-recognizer result. Applied by
/// the event-loop after the callback returns, via
/// `CallbackChange::InjectNativeGesture` -> `GestureAndDragManager::
/// inject_native_gesture`. Used by the iOS / Android / macOS
/// platform backends from their gesture-recognizer callbacks and by
/// the e2e debug-server harness so JSON tests can drive every event
/// filter end-to-end.
pub fn inject_native_gesture(
&mut self,
gesture: crate::managers::gesture::NativeGestureEvent,
) {
self.push_change(CallbackChange::InjectNativeGesture { gesture });
}
/// Get immutable reference to the focus manager
///
/// Use this to query which node currently has focus and whether focus
/// is being moved to another node.
#[must_use] pub const fn get_focus_manager(&self) -> &FocusManager {
&self.get_layout_window().focus_manager
}
/// Get a reference to the undo/redo manager
///
/// This allows user callbacks to query the undo/redo state and intercept
/// undo/redo operations via `preventDefault()`.
#[must_use] pub const fn get_undo_redo_manager(&self) -> &UndoRedoManager {
&self.get_layout_window().undo_redo_manager
}
/// Get immutable reference to the hover manager
///
/// Use this to query which nodes are currently hovered at various input points
/// (mouse, touch points, pen).
#[must_use] pub const fn get_hover_manager(&self) -> &HoverManager {
&self.get_layout_window().hover_manager
}
/// Get immutable reference to the text input manager
///
/// Use this to query text selection state, cursor positions, and IME composition.
#[must_use] pub const fn get_text_input_manager(&self) -> &TextInputManager {
&self.get_layout_window().text_input_manager
}
/// Check if `multi_cursor` has any selection ranges.
///
/// Replaces the removed `get_selection_manager()`.
#[must_use] pub fn has_any_selection(&self) -> bool {
self.get_layout_window()
.text_edit_manager.multi_cursor.as_ref()
.is_some_and(|mc| mc.selections.iter().any(|s| matches!(&s.selection, Selection::Range(_))))
}
/// Check if a specific node is currently focused
#[must_use] pub fn is_node_focused(&self, node_id: DomNodeId) -> bool {
self.get_focus_manager().has_focus(&node_id)
}
/// Check if any node in a specific DOM is focused
#[must_use] pub fn is_dom_focused(&self, dom_id: DomId) -> bool {
self.get_focused_node()
.is_some_and(|n| n.dom == dom_id)
}
// Pen/Stylus Query Methods
/// Get current pen/stylus state if a pen is active
#[must_use] pub const fn get_pen_state(&self) -> Option<&PenState> {
self.get_gesture_drag_manager().get_pen_state()
}
/// Get the current Wacom tablet-**pad** state (`ExpressKeys` + touch-ring),
/// or `None` if no pad backend has delivered one. (The pen's own wacom
/// features - eraser / barrel button / barrel roll / tilt / pressure -
/// are in [`CallbackInfo::get_pen_state`].) Kept live by the platform pad
/// backend (Wintab / libwacom+libinput / macOS tablet `NSEvent`s).
#[must_use] pub const fn get_wacom_pad(&self) -> Option<crate::managers::gesture::WacomPadState> {
self.get_gesture_drag_manager().get_pad_state().copied()
}
/// Get the most recent geolocation fix, or `None` if no `GeolocationProbe`
/// is mounted or no platform backend has delivered a fix yet. The fix is
/// kept live by the platform backends (Android `FusedLocationProvider`,
/// iOS/macOS `CLLocationManager`) via the async fix channel that the
/// layout pass folds into the manager - so a callback can read the user's
/// position to, e.g., place a "you are here" marker on a map.
#[must_use] pub const fn get_location_fix(&self) -> Option<azul_core::geolocation::LocationFix> {
self.get_layout_window().geolocation_manager.latest_fix()
}
/// Get the latest motion-sensor reading for `kind` (Accelerometer /
/// Gyroscope / Magnetometer), or `None` if no platform backend has
/// delivered one. Kept live by the sensor backends (iOS `CoreMotion`,
/// Android `SensorManager`) via the async channel the layout pass folds
/// into the manager - so a callback can drive tilt / shake / compass UI.
#[must_use] pub const fn get_sensor_reading(
&self,
kind: azul_core::sensors::SensorKind,
) -> Option<azul_core::sensors::SensorReading> {
self.get_layout_window().sensor_manager.reading(kind)
}
/// The safe-area insets (notch / system-UI margins) for this window, in
/// logical px - lay out interactive content within them so it isn't hidden
/// by a notch / rounded corners / status bar. Zero where the platform or
/// window has no inset. Set by the platform shell (macOS `NSScreen` notch,
/// iOS `UIView.safeAreaInsets`, Android `WindowInsets`).
#[must_use] pub const fn get_safe_area_insets(&self) -> azul_css::system::SafeAreaInsets {
self.get_layout_window().safe_area_insets
}
/// Get the latest state of the gamepad `id` (button bitset + analog
/// axes), or `None` if no pad with that id has connected. Kept live by
/// the controller backend (gilrs / iOS `GCController` / Android
/// `InputDevice`) via the async channel the layout pass folds into the
/// manager - so a callback can drive movement / menu UI. For the common
/// single-controller case, [`CallbackInfo::get_primary_gamepad`] skips
/// the id bookkeeping.
#[must_use] pub fn get_gamepad_state(
&self,
id: azul_core::gamepad::GamepadId,
) -> Option<azul_core::gamepad::GamepadState> {
self.get_layout_window().gamepad_manager.state(id)
}
/// Get the first currently-connected gamepad, or `None` if none is
/// connected - the convenient single-controller accessor.
#[must_use] pub fn get_primary_gamepad(&self) -> Option<azul_core::gamepad::GamepadState> {
self.get_layout_window().gamepad_manager.primary()
}
/// Get the most recent biometric-auth result, or `None` if no
/// `request_biometric_auth` has completed yet. Kept live by the
/// platform backends (iOS/macOS `LAContext`, Android `BiometricPrompt`,
/// Windows `UserConsentVerifier`) via the async result channel the
/// layout pass folds into the manager - so a callback can unlock a
/// vault / settings panel once the user authenticates.
#[must_use] pub const fn get_biometric_result(&self) -> Option<azul_core::biometric::BiometricResult> {
self.get_layout_window().biometric_manager.last_result()
}
/// Get the device's biometric capability (sync probe): `Face`,
/// `Fingerprint`, `Iris`, or `NotAvailable`. Lets a callback decide
/// whether to even offer a biometric unlock before requesting one
/// (no OS prompt is shown - this just reads the cached probe).
#[must_use] pub const fn get_biometric_kind(&self) -> azul_core::biometric::BiometricKind {
self.get_layout_window().biometric_manager.availability()
}
/// Request a biometric-auth prompt (Face ID / Touch ID / Android
/// `BiometricPrompt` / Windows Hello). Returns immediately - the OS
/// draws its own modal asynchronously; the outcome arrives on a later
/// frame and is read via [`CallbackInfo::get_biometric_result`]. Call
/// this from, e.g., an unlock button's `on_click`. The `prompt`
/// configures the reason text, cancel label, and whether the OS
/// passcode fallback is allowed. (No platform backend reports a real
/// outcome yet - the request currently resolves to
/// `BiometricResult::Unavailable`; the iOS/macOS/Android backends land
/// in a later tick.)
pub fn request_biometric_auth(&mut self, prompt: azul_core::biometric::BiometricPrompt) {
crate::managers::biometric::push_biometric_request(prompt);
}
/// Store `secret` under `key` in the OS keyring (Keychain / `KeyStore` /
/// libsecret / `CredentialLocker`). When `require_biometry` is set, a
/// later `keyring_get` of this key triggers the OS biometric prompt.
/// Returns immediately; the outcome arrives via `get_keyring_result()`
/// on a later frame.
pub fn keyring_store(&mut self, key: AzString, secret: AzString, require_biometry: bool) {
crate::managers::keyring::push_keyring_request(
azul_core::keyring::KeyringRequest::Store {
key,
secret,
require_biometry,
},
);
}
/// Read the secret stored under `key`. A biometry-bound item shows the
/// OS prompt first; the secret (or a denial) arrives via
/// `get_keyring_result()` on a later frame.
pub fn keyring_get(&mut self, key: AzString) {
crate::managers::keyring::push_keyring_request(azul_core::keyring::KeyringRequest::Get {
key,
});
}
/// Remove the item stored under `key` from the OS keyring (no-op if
/// absent). The outcome arrives via `get_keyring_result()`.
pub fn keyring_delete(&mut self, key: AzString) {
crate::managers::keyring::push_keyring_request(
azul_core::keyring::KeyringRequest::Delete { key },
);
}
/// Get the most recent keyring outcome, or `None` until the first op
/// completes. Read after a `keyring_store/get/delete` to observe the
/// result - e.g. the revealed secret from a `keyring_get`
/// (`KeyringResult::Retrieved`).
#[must_use] pub fn get_keyring_result(&self) -> Option<azul_core::keyring::KeyringResult> {
self.get_layout_window().keyring_manager.last_result().cloned()
}
/// Read the most recently observed permission state for `capability`
/// (Camera / Microphone / Geolocation / Sensors / Notifications / …) - e.g.
/// so a callback can check a capability is `Granted` before using it (show
/// a camera preview only once granted). Kept live by the platform
/// permission backend; a capability is subscribed by mounting its probe
/// node (`CameraProbe` / `GeolocationProbe` / …) into the DOM.
#[must_use] pub fn get_permission_status(
&self,
capability: crate::managers::permission::Capability,
) -> crate::managers::permission::PermissionState {
self.get_layout_window()
.permission_manager
.get_status(capability)
}
/// Get current pen pressure (0.0 to 1.0)
/// Returns None if no pen is active, Some(0.5) for mouse
#[must_use] pub fn get_pen_pressure(&self) -> Option<f32> {
self.get_pen_state().map(|pen| pen.pressure)
}
/// Get current pen tilt angles (`x_tilt`, `y_tilt`) in degrees
/// Returns None if no pen is active
#[must_use] pub fn get_pen_tilt(&self) -> Option<PenTilt> {
self.get_pen_state().map(|pen| pen.tilt)
}
/// Check if pen is currently in contact with surface
#[must_use] pub fn is_pen_in_contact(&self) -> bool {
self.get_pen_state()
.is_some_and(|pen| pen.in_contact)
}
/// Check if pen is in eraser mode
#[must_use] pub fn is_pen_eraser(&self) -> bool {
self.get_pen_state()
.is_some_and(|pen| pen.is_eraser)
}
/// Check if pen barrel button is pressed
#[must_use] pub fn is_pen_barrel_button_pressed(&self) -> bool {
self.get_pen_state()
.is_some_and(|pen| pen.barrel_button_pressed)
}
/// Get the last recorded input sample (for `event_id` and detailed input data)
#[must_use] pub fn get_last_input_sample(&self) -> Option<&InputSample> {
let manager = self.get_gesture_drag_manager();
manager
.get_current_session()
.and_then(|session| session.last_sample())
}
/// Get the event ID of the current event
#[must_use] pub fn get_current_event_id(&self) -> Option<u64> {
self.get_last_input_sample().map(|sample| sample.event_id)
}
// Gesture Query Methods
//
// These read whatever the in-process `GestureAndDragManager` has detected
// from the touch / mouse stream. On platforms with native gesture
// recognizers (iOS UIKit, Android `GestureDetector`), the platform
// backend may inject pre-detected gestures via
// `GestureAndDragManager::inject_native_gesture(...)` - accessors below
// see the same data regardless of source, fulfilling Azul's
// "superset of every platform" guarantee for gesture handlers.
/// Returns the dominant direction of the current swipe gesture, if any.
/// Detection uses the touch / pointer trajectory and a velocity
/// threshold; on iOS / Android the platform backend may override the
/// in-process detector with a native gesture-recognizer result.
#[must_use] pub fn get_swipe_direction(&self) -> crate::managers::gesture::OptionGestureDirection {
self.get_gesture_drag_manager().detect_swipe_direction().into()
}
/// Returns the active pinch gesture (scale + center + distances), if any.
#[must_use] pub fn get_pinch(&self) -> crate::managers::gesture::OptionDetectedPinch {
self.get_gesture_drag_manager().detect_pinch().into()
}
/// Returns the active rotation gesture (radians + center), if any.
#[must_use] pub fn get_rotation(&self) -> crate::managers::gesture::OptionDetectedRotation {
self.get_gesture_drag_manager().detect_rotation().into()
}
/// Returns the active long-press, if the user is currently holding a
/// pointer in place beyond the configured threshold.
#[must_use] pub fn get_long_press(&self) -> crate::managers::gesture::OptionDetectedLongPress {
self.get_gesture_drag_manager().detect_long_press().into()
}
/// True iff the gesture manager classified the current event sequence
/// as a double-click / double-tap.
#[must_use] pub fn was_double_clicked(&self) -> bool {
self.get_gesture_drag_manager().detect_double_click()
}
// Focus Management Methods
/// Set focus to a specific DOM node by ID
pub fn set_focus_to_node(&mut self, dom_id: DomId, node_id: NodeId) {
self.set_focus(FocusTarget::Id(DomNodeId {
dom: dom_id,
node: NodeHierarchyItemId::from_crate_internal(Some(node_id)),
}));
}
/// Set focus to a node matching a CSS path
pub fn set_focus_to_path(&mut self, dom_id: DomId, css_path: CssPath) {
self.set_focus(FocusTarget::Path(FocusTargetPath {
dom: dom_id,
css_path,
}));
}
/// Move focus to next focusable element in tab order
pub fn focus_next(&mut self) {
self.set_focus(FocusTarget::Next);
}
/// Move focus to previous focusable element in tab order
pub fn focus_previous(&mut self) {
self.set_focus(FocusTarget::Previous);
}
/// Move focus to first focusable element
pub fn focus_first(&mut self) {
self.set_focus(FocusTarget::First);
}
/// Move focus to last focusable element
pub fn focus_last(&mut self) {
self.set_focus(FocusTarget::Last);
}
/// Remove focus from all elements
pub fn clear_focus(&mut self) {
self.set_focus(FocusTarget::NoFocus);
}
// Manager Access Methods
/// Check if a drag gesture is currently active
///
/// Convenience method that queries the gesture manager.
#[must_use] pub const fn is_dragging(&self) -> bool {
self.get_gesture_drag_manager().is_dragging()
}
/// Get the currently focused node (if any)
///
/// Returns None if no node has focus.
#[must_use] pub const fn get_focused_node(&self) -> Option<DomNodeId> {
self.get_layout_window()
.focus_manager
.get_focused_node()
.copied()
}
/// Check if a specific node has focus
#[must_use] pub fn has_focus(&self, node_id: DomNodeId) -> bool {
self.get_layout_window().focus_manager.has_focus(&node_id)
}
/// Get the currently hovered file (if drag-drop is in progress)
///
/// Returns None if no file is being hovered over the window.
/// (First file only - use [`get_hovered_files`](Self::get_hovered_files)
/// for multi-file drags; no longer `const` since MWA-B7 made the manager
/// store a Vec.)
#[must_use] pub fn get_hovered_file(&self) -> Option<&AzString> {
self.get_layout_window()
.file_drop_manager
.get_hovered_file()
}
/// ALL files of the current drag hover (MWA-B7 - multi-file drags were
/// previously truncated to the first path before they reached callbacks).
#[must_use] pub fn get_hovered_files(&self) -> StringVec {
self.get_layout_window()
.file_drop_manager
.get_hovered_files()
.to_vec()
.into()
}
/// Get the currently dropped file (if a file was just dropped)
///
/// This is a one-shot value that is cleared after event processing.
/// Returns None if no file was dropped this frame. (First file only -
/// use [`get_dropped_files`](Self::get_dropped_files) for the full list.)
#[must_use] pub fn get_dropped_file(&self) -> Option<&AzString> {
self.get_layout_window()
.file_drop_manager
.get_dropped_file()
}
/// ALL files of this frame's drop (MWA-B7; one-shot).
#[must_use] pub fn get_dropped_files(&self) -> StringVec {
self.get_layout_window()
.file_drop_manager
.get_dropped_files()
.to_vec()
.into()
}
/// Measure a DOM headlessly: style + lay it out against `available`
/// constraints (this window's fonts / system style) without touching the
/// live layout. Returns the union of all node bounds - use a very tall
/// `available.height` (e.g. `1_000_000.0`) to get a DOM's natural height
/// at a given width. Primary use: sizing `VirtualView` items to compute
/// the virtual scroll extent. A full cold layout pass per call - cache
/// per item template.
#[cfg(feature = "std")]
#[must_use] pub fn measure_dom(
&self,
dom: azul_core::dom::Dom,
available: LogicalSize,
) -> LogicalSize {
self.get_layout_window().measure_dom(dom, available)
}
/// Deepest node currently under the mouse pointer (MWA-B8). Anchor for
/// drag auto-scroll when there is no focused node - node drags and OS
/// file hovers scroll the container under the pointer, not the focused
/// text field.
#[must_use] pub fn get_deepest_hovered_node(&self) -> Option<DomNodeId> {
let hit = self
.get_layout_window()
.hover_manager
.get_current(&InputPointId::Mouse)?;
hit.hovered_nodes.iter().next().and_then(|(dom_id, entry)| {
entry.regular_hit_test_nodes.keys().next_back().map(|nid| DomNodeId {
dom: *dom_id,
node: NodeHierarchyItemId::from_crate_internal(Some(*nid)),
})
})
}
/// Check if a node or file drag is currently active
///
/// Returns true if either a node drag or file drag is in progress.
/// `gesture_drag_manager` is the single source of truth (the old
/// `drag_drop_manager` mirror has been deleted — see `managers/drag_drop.rs`).
#[must_use] pub const fn is_drag_active(&self) -> bool {
self.get_layout_window().gesture_drag_manager.is_dragging()
}
/// Check if a node drag is specifically active
#[must_use] pub fn is_node_drag_active(&self) -> bool {
self.get_layout_window().gesture_drag_manager.is_node_drag_active()
}
/// Check if a file drag is specifically active
#[must_use] pub fn is_file_drag_active(&self) -> bool {
let lw = self.get_layout_window();
// MWA-C-file_drop: an EXTERNAL OS drag (Finder/Explorer hovering
// files over the window) lives in file_drop_manager, not in the
// intra-app drag managers — without this arm the query answered
// false during exactly the drag it is most often asked about.
lw.gesture_drag_manager.is_file_dropping()
|| !lw.file_drop_manager.get_hovered_files().is_empty()
}
/// Get the current drag/drop state (if any)
///
/// Returns None if no drag is active, or Some with drag state.
#[must_use] pub fn get_drag_state(&self) -> Option<crate::managers::drag_drop::DragState> {
let ctx = self.get_layout_window().gesture_drag_manager.get_drag_context()?;
crate::managers::drag_drop::DragState::from_context(ctx)
}
/// Get the current drag context (if any)
///
/// Returns None if no drag is active, or Some with drag context.
/// Prefer this over `get_drag_state` for new code.
#[must_use] pub const fn get_drag_context(&self) -> Option<&azul_core::drag::DragContext> {
// The gesture manager holds the LIVE context and is the ONLY source of
// truth. (The `drag_drop_manager` mirror was a frozen clone taken at
// drag start whose drop-target/position went stale for the whole drag;
// it has been deleted.)
self.get_layout_window().gesture_drag_manager.get_drag_context()
}
// Hover Manager Access
/// Get the current mouse cursor hit test result (most recent frame)
#[must_use] pub fn get_current_hit_test(&self) -> Option<&FullHitTest> {
self.get_hover_manager().get_current(&InputPointId::Mouse)
}
/// Get mouse cursor hit test from N frames ago (0 = current, 1 = previous, etc.)
#[must_use] pub fn get_hit_test_frame(&self, frames_ago: usize) -> Option<&FullHitTest> {
self.get_hover_manager()
.get_frame(&InputPointId::Mouse, frames_ago)
}
/// Get the full mouse cursor hit test history (up to 5 frames)
///
/// Returns None if no mouse history exists yet
#[must_use] pub fn get_hit_test_history(&self) -> Option<&VecDeque<FullHitTest>> {
self.get_hover_manager().get_history(&InputPointId::Mouse)
}
/// Check if there's sufficient mouse history for gesture detection (at least 2 frames)
#[must_use] pub fn has_sufficient_history_for_gestures(&self) -> bool {
self.get_hover_manager()
.has_sufficient_history_for_gestures(&InputPointId::Mouse)
}
// File Drop Manager Access
/// Get immutable reference to the file drop manager
#[must_use] pub const fn get_file_drop_manager(&self) -> &FileDropManager {
&self.get_layout_window().file_drop_manager
}
// Drag-Drop Manager Access
/// Get the node being dragged (if any)
#[must_use] pub fn get_dragged_node(&self) -> Option<DomNodeId> {
self.get_drag_context()
.and_then(|ctx| {
ctx.as_node_drag().map(|node_drag| {
DomNodeId {
dom: node_drag.dom_id,
node: NodeHierarchyItemId::from_crate_internal(Some(node_drag.node_id)),
}
})
})
}
/// Get the file path being dragged (if any)
#[must_use] pub fn get_dragged_file(&self) -> Option<&AzString> {
// Gesture context first (intra-app file drags), then the
// FileDropManager's hovered/dropped state (external OS drags).
self.get_drag_context()
.and_then(|ctx| {
ctx.as_file_drop().and_then(|file_drop| {
file_drop.files.as_ref().first()
})
})
.or_else(|| {
let lw = self.get_layout_window();
lw.file_drop_manager
.get_hovered_files()
.first()
.or_else(|| lw.file_drop_manager.get_dropped_files().first())
})
}
/// Get the MIME types available in the current drag data.
///
/// W3C equivalent: `dataTransfer.types`
/// Returns an empty vec if no drag is active or no data is set.
#[must_use] pub fn get_drag_types(&self) -> StringVec {
let lw = self.get_layout_window();
// Try gesture manager first
if let Some(ctx) = lw.gesture_drag_manager.get_drag_context() {
if let Some(node_drag) = ctx.as_node_drag() {
return node_drag
.drag_data
.data
.as_ref()
.iter()
.map(|e| e.mime_type.clone())
.collect();
}
}
StringVec::from_const_slice(&[])
}
/// Get drag data for a specific MIME type.
///
/// W3C equivalent: `dataTransfer.getData(type)`
/// Returns None if no drag is active or the MIME type is not set.
#[must_use] pub fn get_drag_data(&self, mime_type: &str) -> OptionU8Vec {
let lw = self.get_layout_window();
if let Some(ctx) = lw.gesture_drag_manager.get_drag_context() {
if let Some(node_drag) = ctx.as_node_drag() {
return node_drag.drag_data.get_data(mime_type).map(|d| U8Vec::from(d.to_vec())).into();
}
}
OptionU8Vec::None
}
/// Set drag data for a MIME type on the active drag operation.
///
/// W3C equivalent: `dataTransfer.setData(type, data)`
/// Should be called from a `DragStart` callback to populate the drag data.
pub fn set_drag_data(&mut self, mime_type: AzString, data: Vec<u8>) {
self.push_change(CallbackChange::SetDragData { mime_type, data });
}
/// Accept the current drop operation on this node.
///
/// W3C equivalent: calling `event.preventDefault()` in a `DragOver` handler.
/// This signals that the current drop target can accept the dragged data.
/// Must be called from a `DragOver` or `DragEnter` callback for the Drop event
/// to fire on this node.
pub fn accept_drop(&mut self) {
self.push_change(CallbackChange::AcceptDrop);
}
/// Set the drop effect for the current drag operation.
///
/// W3C equivalent: `dataTransfer.dropEffect = "move"|"copy"|"link"`
/// Should be called from a `DragOver` or `DragEnter` callback.
pub fn set_drop_effect(&mut self, effect: azul_core::drag::DropEffect) {
self.push_change(CallbackChange::SetDropEffect { effect });
}
// Scroll Manager Query Methods
/// Get the current scroll offset for the hit node (if it's scrollable)
///
/// Convenience method that uses the `hit_dom_node` from this callback.
/// Use `get_scroll_offset_for_node` if you need to query a specific node.
#[must_use] pub fn get_scroll_offset(&self) -> Option<LogicalPosition> {
self.get_scroll_offset_for_node(
self.hit_dom_node.dom,
self.hit_dom_node.node.into_crate_internal()?,
)
}
/// Get the current scroll offset for a specific node (if it's scrollable)
#[must_use] pub fn get_scroll_offset_for_node(
&self,
dom_id: DomId,
node_id: NodeId,
) -> Option<LogicalPosition> {
self.get_scroll_manager()
.get_current_offset(dom_id, node_id)
}
/// Get the scroll state (container rect, content rect, current offset) for a node
#[must_use] pub fn get_scroll_state(&self, dom_id: DomId, node_id: NodeId) -> Option<&AnimatedScrollState> {
self.get_scroll_manager().get_scroll_state(dom_id, node_id)
}
/// Get a read-only snapshot of a scroll node's bounds and position.
///
/// This is the recommended API for timer callbacks that need to compute
/// scroll physics. Returns container/content rects and max scroll bounds.
#[must_use] pub fn get_scroll_node_info(
&self,
dom_id: DomId,
node_id: NodeId,
) -> Option<crate::managers::scroll_state::ScrollNodeInfo> {
self.get_scroll_manager()
.get_scroll_node_info(dom_id, node_id)
}
/// Deprecated: Returns None. Scroll deltas are no longer tracked per-frame.
/// Kept for FFI backward compatibility.
/// The raw wheel / trackpad delta that triggered the current `Scroll`
/// callback, or `None` outside a scroll dispatch. The value is the per-pass
/// delta recorded by the platform scroll handler (see
/// `ScrollManager::pending_wheel_event`); it is global to the pass, so the
/// `dom_id` / `node_id` arguments are advisory - a `Scroll` callback only
/// fires on the hovered node, which is what they identify. Wheel-as-zoom
/// widgets (the map) read `.y` here instead of consuming the scroll-physics
/// input queue (which only carries deltas for actual scroll containers).
#[must_use] pub const fn get_scroll_delta(
&self,
_dom_id: DomId,
_node_id: NodeId,
) -> Option<LogicalPosition> {
self.get_scroll_manager().pending_wheel_event
}
/// Deprecated: Returns false. Scroll activity flags were removed.
/// Kept for FFI backward compatibility.
#[must_use] pub const fn had_scroll_activity(
&self,
_dom_id: DomId,
_node_id: NodeId,
) -> bool {
false
}
/// Find the closest scrollable ancestor of a node.
///
/// Walks up the node hierarchy to find a node registered in the `ScrollManager`.
/// Used by auto-scroll timer to find which container to scroll.
#[must_use] pub fn find_scroll_parent(
&self,
dom_id: DomId,
node_id: NodeId,
) -> Option<NodeId> {
let layout_window = self.get_layout_window();
let layout_results = &layout_window.layout_results;
let lr = layout_results.get(&dom_id)?;
let node_hierarchy: &[azul_core::styled_dom::NodeHierarchyItem] =
lr.styled_dom.node_hierarchy.as_ref();
self.get_scroll_manager()
.find_scroll_parent(dom_id, node_id, node_hierarchy)
}
/// Get a clone of the scroll input queue for consuming pending inputs.
///
/// Timer callbacks use this to drain pending scroll inputs recorded by
/// platform event handlers. The queue is thread-safe (Arc<Mutex>), so
/// the timer can call `take_all()` with only `&self`.
#[cfg(feature = "std")]
#[must_use] pub fn get_scroll_input_queue(
&self,
) -> crate::managers::scroll_state::ScrollInputQueue {
self.get_scroll_manager().scroll_input_queue.clone()
}
// Gpu State Manager Access
/// Get immutable reference to the GPU state manager
#[must_use] pub const fn get_gpu_state_manager(&self) -> &GpuStateManager {
&self.get_layout_window().gpu_state_manager
}
// VirtualView Manager Access
/// Get immutable reference to the `VirtualView` manager
#[must_use] pub const fn get_virtual_view_manager(&self) -> &VirtualViewManager {
&self.get_layout_window().virtual_view_manager
}
// Changeset Inspection/Modification Methods
// These methods allow callbacks to inspect pending operations and modify them before execution
/// Inspect a pending copy operation
///
/// Returns the clipboard content that would be copied if the operation proceeds.
/// Use this to validate or transform clipboard content before copying.
#[must_use] pub fn inspect_copy_changeset(&self, target: DomNodeId) -> Option<ClipboardContent> {
let layout_window = self.get_layout_window();
let dom_id = &target.dom;
layout_window.get_selected_content_for_clipboard(dom_id)
}
/// Inspect a pending cut operation
///
/// Returns the clipboard content that would be cut (copied + deleted).
/// Use this to validate or transform content before cutting.
#[must_use] pub fn inspect_cut_changeset(&self, target: DomNodeId) -> Option<ClipboardContent> {
// Cut uses same content extraction as copy
self.inspect_copy_changeset(target)
}
/// Inspect the current selection range that would be affected by paste
///
/// Returns the selection range that will be replaced when pasting.
/// Returns None if no selection exists (paste will insert at cursor).
#[must_use] pub fn inspect_paste_target_range(&self, _target: DomNodeId) -> Option<SelectionRange> {
let layout_window = self.get_layout_window();
layout_window
.text_edit_manager.multi_cursor.as_ref()
.and_then(|mc| mc.selections.iter().find_map(|s| match &s.selection {
Selection::Range(r) => Some(*r),
Selection::Cursor(_) => None,
}))
}
/// Inspect what text would be selected by Select All operation
///
/// Returns the full text content and the range that would be selected.
#[must_use] pub fn inspect_select_all_changeset(&self, target: DomNodeId) -> Option<SelectAllResult> {
use azul_core::selection::{CursorAffinity, GraphemeClusterId, TextCursor};
let layout_window = self.get_layout_window();
let node_id = target.node.into_crate_internal()?;
// Get text content
let content = layout_window.get_text_before_textinput(target.dom, node_id);
let text = layout_window.extract_text_from_inline_content(&content);
// Create selection range from start to end
let start_cursor = TextCursor {
cluster_id: GraphemeClusterId {
source_run: 0,
start_byte_in_run: 0,
},
affinity: CursorAffinity::Leading,
};
let end_cursor = TextCursor {
cluster_id: GraphemeClusterId {
source_run: 0,
start_byte_in_run: u32::try_from(text.len()).unwrap_or(u32::MAX),
},
affinity: CursorAffinity::Leading,
};
let range = SelectionRange {
start: start_cursor,
end: end_cursor,
};
Some(SelectAllResult {
full_text: text.into(),
selection_range: range,
})
}
/// Inspect what would be deleted by a backspace/delete operation
///
/// Uses the pure functions from `text3::edit::inspect_delete()` to determine
/// what would be deleted without actually performing the deletion.
///
/// Returns (`range_to_delete`, `deleted_text`).
/// - forward=true: Delete key (delete character after cursor)
/// - forward=false: Backspace key (delete character before cursor)
#[must_use] pub fn inspect_delete_changeset(
&self,
target: DomNodeId,
forward: bool,
) -> Option<DeleteResult> {
let layout_window = self.get_layout_window();
let dom_id = &target.dom;
let node_id = target.node.into_crate_internal()?;
// Get the inline content for this node
let content = layout_window.get_text_before_textinput(target.dom, node_id);
// Get current selection state from multi_cursor
let selection = if let Some(mc) = layout_window.text_edit_manager.multi_cursor.as_ref() {
if let Some(range) = mc.selections.iter().find_map(|s| match &s.selection {
Selection::Range(r) => Some(*r),
Selection::Cursor(_) => None,
}) {
Selection::Range(range)
} else if let Some(cursor) = mc.get_primary_cursor() {
Selection::Cursor(cursor)
} else {
return None;
}
} else {
return None; // No multi_cursor active
};
// Use text3::edit::inspect_delete to determine what would be deleted
crate::text3::edit::inspect_delete(&content, &selection, forward).map(|(range, text)| {
DeleteResult {
range_to_delete: range,
deleted_text: text.into(),
}
})
}
/// Inspect a pending undo operation
///
/// Returns the operation that would be undone, allowing inspection
/// of what state will be restored.
#[must_use] pub fn inspect_undo_operation(&self, node_id: NodeId) -> Option<&UndoableOperation> {
self.get_undo_redo_manager().peek_undo(node_id)
}
/// Inspect a pending redo operation
///
/// Returns the operation that would be reapplied.
#[must_use] pub fn inspect_redo_operation(&self, node_id: NodeId) -> Option<&UndoableOperation> {
self.get_undo_redo_manager().peek_redo(node_id)
}
/// Check if undo is available for a specific node
///
/// Returns true if there is at least one undoable operation in the stack.
#[must_use] pub fn can_undo(&self, node_id: NodeId) -> bool {
self.get_undo_redo_manager()
.get_stack(node_id)
.is_some_and(super::managers::undo_redo::NodeUndoRedoStack::can_undo)
}
/// Check if redo is available for a specific node
///
/// Returns true if there is at least one redoable operation in the stack.
#[must_use] pub fn can_redo(&self, node_id: NodeId) -> bool {
self.get_undo_redo_manager()
.get_stack(node_id)
.is_some_and(super::managers::undo_redo::NodeUndoRedoStack::can_redo)
}
/// Get the text that would be restored by undo for a specific node
///
/// Returns the pre-state text content that would be restored if undo is performed.
/// Returns None if no undo operation is available.
#[must_use] pub fn get_undo_text(&self, node_id: NodeId) -> Option<AzString> {
self.get_undo_redo_manager()
.peek_undo(node_id)
.map(|op| op.pre_state.text_content.clone())
}
/// Get the text that would be restored by redo for a specific node
///
/// Returns the pre-state text content that would be restored if redo is performed.
/// Returns None if no redo operation is available.
#[must_use] pub fn get_redo_text(&self, node_id: NodeId) -> Option<AzString> {
self.get_undo_redo_manager()
.peek_redo(node_id)
.map(|op| op.pre_state.text_content.clone())
}
// Clipboard Helper Methods
/// Get clipboard content from system clipboard (available during paste operations)
///
/// This returns content that was read from the system clipboard when Ctrl+V was pressed.
/// It's only available in `On::Paste` callbacks or similar clipboard-related callbacks.
///
/// Use this to inspect what will be pasted before allowing or modifying the paste operation.
///
/// # Returns
/// * `Some(&ClipboardContent)` - If paste is in progress and clipboard has content
/// * `None` - If no paste operation is active or clipboard is empty
#[must_use] pub const fn get_clipboard_content(&self) -> Option<&ClipboardContent> {
unsafe {
(*self.ref_data)
.layout_window
.clipboard_manager
.get_paste_content()
}
}
/// Override clipboard content for copy/cut operations
///
/// This sets custom content that will be written to the system clipboard.
/// Use this in `On::Copy` or `On::Cut` callbacks to modify what gets copied.
///
/// # Arguments
/// * `content` - The clipboard content to write to system clipboard
pub fn set_clipboard_content(&mut self, content: ClipboardContent) {
self.set_copy_content(self.hit_dom_node, content);
}
/// Set/modify the clipboard content before a copy operation
///
/// Use this to transform clipboard content before copying.
/// The change is queued and will be applied after the callback returns,
/// if `preventDefault()` was not called.
pub fn set_copy_content(&mut self, target: DomNodeId, content: ClipboardContent) {
self.push_change(CallbackChange::SetCopyContent { target, content });
}
/// Set/modify the clipboard content before a cut operation
///
/// Similar to `set_copy_content` but for cut operations.
/// The change is queued and will be applied after the callback returns.
pub fn set_cut_content(&mut self, target: DomNodeId, content: ClipboardContent) {
self.push_change(CallbackChange::SetCutContent { target, content });
}
/// Override the selection range for select-all operation
///
/// Use this to limit what gets selected (e.g., only select visible text).
/// The change is queued and will be applied after the callback returns.
pub fn set_select_all_range(&mut self, target: DomNodeId, range: SelectionRange) {
self.push_change(CallbackChange::SetSelectAllRange { target, range });
}
/// Request a hit test update at a specific position
///
/// This is used by the Debug API to update the hover manager's hit test
/// data after modifying the mouse position. This ensures that mouse event
/// callbacks can find the correct nodes under the cursor.
///
/// The hit test is performed during the next frame update.
pub fn request_hit_test_update(&mut self, position: LogicalPosition) {
self.push_change(CallbackChange::RequestHitTestUpdate { position });
}
/// Process a text selection click at a specific position
///
/// This is used by the Debug API to trigger text selection directly,
/// bypassing the normal event pipeline which generates `PreCallbackSystemEvent::TextClick`.
///
/// The selection processing is deferred until the `CallbackChange` is processed,
/// at which point the `LayoutWindow` can be mutably accessed.
pub fn process_text_selection_click(&mut self, position: LogicalPosition, time_ms: u64) {
self.push_change(CallbackChange::ProcessTextSelectionClick { position, time_ms });
}
/// Get the current text content of a node
///
/// Helper for inspecting text before operations.
#[must_use] pub fn get_node_text_content(&self, target: DomNodeId) -> Option<String> {
let layout_window = self.get_layout_window();
let node_id = target.node.into_crate_internal()?;
// Some("") must mean "the node exists and its text is empty" — an empty string is
// valid text content. get_text_before_textinput returns an empty Vec for BOTH a
// missing node and an existing-but-empty one, so verify the node actually exists
// (committed layout or a pending edit) before returning Some; otherwise None,
// like the sibling selection/undo queries.
let exists = layout_window.dirty_text_nodes.contains_key(&(target.dom, node_id))
|| layout_window
.layout_results
.get(&target.dom)
.is_some_and(|lr| node_id.index() < lr.styled_dom.node_data.as_ref().len());
if !exists {
return None;
}
let content = layout_window.get_text_before_textinput(target.dom, node_id);
Some(layout_window.extract_text_from_inline_content(&content))
}
/// Get the current cursor position in a node
///
/// Returns the text cursor position if the node is focused.
#[must_use] pub fn get_node_cursor_position(&self, target: DomNodeId) -> Option<TextCursor> {
let layout_window = self.get_layout_window();
// Check if this node is focused
if !layout_window.focus_manager.has_focus(&target) {
return None;
}
layout_window.text_edit_manager.get_primary_cursor()
}
/// Get the current selection ranges in a node
///
/// Returns all active selection ranges for the specified DOM.
#[must_use] pub fn get_node_selection_ranges(&self, _target: DomNodeId) -> SelectionRangeVec {
let layout_window = self.get_layout_window();
let ranges: Vec<SelectionRange> = layout_window
.text_edit_manager.multi_cursor.as_ref()
.map(|mc| mc.selections.iter().filter_map(|s| match &s.selection {
Selection::Range(r) => Some(*r),
Selection::Cursor(_) => None,
}).collect()).unwrap_or_default();
ranges.into()
}
/// Check if a specific node has an active selection
///
/// This checks if the specific node (identified by `DomNodeId`) has a selection,
/// as opposed to `has_selection(DomId)` which checks the entire DOM.
#[must_use] pub fn node_has_selection(&self, target: DomNodeId) -> bool {
!self.get_node_selection_ranges(target).as_ref().is_empty()
}
/// Get the length of text in a node
///
/// Useful for bounds checking in custom operations.
#[must_use] pub fn get_node_text_length(&self, target: DomNodeId) -> Option<usize> {
self.get_node_text_content(target).map(|text| text.len())
}
// Cursor Movement Inspection/Override Methods
/// Inspect where the cursor would move when pressing left arrow
///
/// Returns the new cursor position that would result from moving left.
/// Returns None if the cursor is already at the start of the document.
///
/// # Arguments
/// * `target` - The node containing the cursor
pub fn inspect_move_cursor_left(&self, target: DomNodeId) -> Option<TextCursor> {
let layout_window = self.get_layout_window();
let cursor = layout_window.text_edit_manager.get_primary_cursor()?;
// Get the text layout directly via layout_results -> LayoutTree -> LayoutNode ->
// inline_layout_result
let layout = self.get_inline_layout_for_node(&target)?;
// Use the text3::cache cursor movement logic
let new_cursor = layout.move_cursor_left(cursor, &mut None);
// Only return if cursor actually moved
if new_cursor == cursor {
None
} else {
Some(new_cursor)
}
}
/// Inspect where the cursor would move when pressing right arrow
///
/// Returns the new cursor position that would result from moving right.
/// Returns None if the cursor is already at the end of the document.
pub fn inspect_move_cursor_right(&self, target: DomNodeId) -> Option<TextCursor> {
let layout_window = self.get_layout_window();
let cursor = layout_window.text_edit_manager.get_primary_cursor()?;
// Get the text layout directly via layout_results -> LayoutTree -> LayoutNode ->
// inline_layout_result
let layout = self.get_inline_layout_for_node(&target)?;
// Use the text3::cache cursor movement logic
let new_cursor = layout.move_cursor_right(cursor, &mut None);
// Only return if cursor actually moved
if new_cursor == cursor {
None
} else {
Some(new_cursor)
}
}
/// Inspect where the cursor would move when pressing up arrow
///
/// Returns the new cursor position that would result from moving up one line.
/// Returns None if the cursor is already on the first line.
pub fn inspect_move_cursor_up(&self, target: DomNodeId) -> Option<TextCursor> {
let layout_window = self.get_layout_window();
let cursor = layout_window.text_edit_manager.get_primary_cursor()?;
// Get the text layout directly via layout_results -> LayoutTree -> LayoutNode ->
// inline_layout_result
let layout = self.get_inline_layout_for_node(&target)?;
// Use the text3::cache cursor movement logic
// goal_x maintains horizontal position when moving vertically
let new_cursor = layout.move_cursor_up(cursor, &mut None, &mut None);
// Only return if cursor actually moved
if new_cursor == cursor {
None
} else {
Some(new_cursor)
}
}
/// Inspect where the cursor would move when pressing down arrow
///
/// Returns the new cursor position that would result from moving down one line.
/// Returns None if the cursor is already on the last line.
pub fn inspect_move_cursor_down(&self, target: DomNodeId) -> Option<TextCursor> {
let layout_window = self.get_layout_window();
let cursor = layout_window.text_edit_manager.get_primary_cursor()?;
// Get the text layout directly via layout_results -> LayoutTree -> LayoutNode ->
// inline_layout_result
let layout = self.get_inline_layout_for_node(&target)?;
// Use the text3::cache cursor movement logic
// goal_x maintains horizontal position when moving vertically
let new_cursor = layout.move_cursor_down(cursor, &mut None, &mut None);
// Only return if cursor actually moved
if new_cursor == cursor {
None
} else {
Some(new_cursor)
}
}
/// Inspect where the cursor would move when pressing Home key
///
/// Returns the cursor position at the start of the current line.
pub fn inspect_move_cursor_to_line_start(&self, target: DomNodeId) -> Option<TextCursor> {
let layout_window = self.get_layout_window();
let cursor = layout_window.text_edit_manager.get_primary_cursor()?;
// Get the text layout directly via layout_results -> LayoutTree -> LayoutNode ->
// inline_layout_result
let layout = self.get_inline_layout_for_node(&target)?;
// Use the text3::cache cursor movement logic
let new_cursor = layout.move_cursor_to_line_start(cursor, &mut None);
// Always return the result (might be same as input if already at line start)
Some(new_cursor)
}
/// Inspect where the cursor would move when pressing End key
///
/// Returns the cursor position at the end of the current line.
pub fn inspect_move_cursor_to_line_end(&self, target: DomNodeId) -> Option<TextCursor> {
let layout_window = self.get_layout_window();
let cursor = layout_window.text_edit_manager.get_primary_cursor()?;
// Get the text layout directly via layout_results -> LayoutTree -> LayoutNode ->
// inline_layout_result
let layout = self.get_inline_layout_for_node(&target)?;
// Use the text3::cache cursor movement logic
let new_cursor = layout.move_cursor_to_line_end(cursor, &mut None);
// Always return the result (might be same as input if already at line end)
Some(new_cursor)
}
/// Inspect where the cursor would move when pressing Ctrl+Home
///
/// Returns the cursor position at the start of the document.
#[must_use] pub const fn inspect_move_cursor_to_document_start(&self, target: DomNodeId) -> Option<TextCursor> {
use azul_core::selection::{CursorAffinity, GraphemeClusterId};
Some(TextCursor {
cluster_id: GraphemeClusterId {
source_run: 0,
start_byte_in_run: 0,
},
affinity: CursorAffinity::Leading,
})
}
/// Inspect where the cursor would move when pressing Ctrl+End
///
/// Returns the cursor position at the end of the document.
#[must_use] pub fn inspect_move_cursor_to_document_end(&self, target: DomNodeId) -> Option<TextCursor> {
use azul_core::selection::{CursorAffinity, GraphemeClusterId};
let text_len = self.get_node_text_length(target)?;
Some(TextCursor {
cluster_id: GraphemeClusterId {
source_run: 0,
start_byte_in_run: u32::try_from(text_len).unwrap_or(u32::MAX),
},
affinity: CursorAffinity::Leading,
})
}
/// Inspect what text would be deleted by backspace (including Shift+Backspace)
///
/// Returns (`range_to_delete`, `deleted_text`).
/// This is a convenience wrapper around `inspect_delete_changeset(target`, false).
#[must_use] pub fn inspect_backspace(&self, target: DomNodeId) -> Option<DeleteResult> {
self.inspect_delete_changeset(target, false)
}
/// Inspect what text would be deleted by delete key
///
/// Returns (`range_to_delete`, `deleted_text`).
/// This is a convenience wrapper around `inspect_delete_changeset(target`, true).
#[must_use] pub fn inspect_delete(&self, target: DomNodeId) -> Option<DeleteResult> {
self.inspect_delete_changeset(target, true)
}
// Cursor Movement Override Methods
// These methods queue cursor movement operations to be applied after the callback
/// Move cursor left (arrow left key)
///
/// # Arguments
/// * `target` - The node containing the cursor
/// * `extend_selection` - If true, extends selection (Shift+Left); if false, moves cursor
pub fn move_cursor_left(&mut self, target: DomNodeId, extend_selection: bool) {
self.push_change(CallbackChange::MoveCursorLeft {
dom_id: target.dom,
node_id: target.node.into_crate_internal().unwrap_or(NodeId::ZERO),
extend_selection,
});
}
/// Move cursor right (arrow right key)
pub fn move_cursor_right(&mut self, target: DomNodeId, extend_selection: bool) {
self.push_change(CallbackChange::MoveCursorRight {
dom_id: target.dom,
node_id: target.node.into_crate_internal().unwrap_or(NodeId::ZERO),
extend_selection,
});
}
/// Move cursor up (arrow up key)
pub fn move_cursor_up(&mut self, target: DomNodeId, extend_selection: bool) {
self.push_change(CallbackChange::MoveCursorUp {
dom_id: target.dom,
node_id: target.node.into_crate_internal().unwrap_or(NodeId::ZERO),
extend_selection,
});
}
/// Move cursor down (arrow down key)
pub fn move_cursor_down(&mut self, target: DomNodeId, extend_selection: bool) {
self.push_change(CallbackChange::MoveCursorDown {
dom_id: target.dom,
node_id: target.node.into_crate_internal().unwrap_or(NodeId::ZERO),
extend_selection,
});
}
/// Move cursor to line start (Home key)
pub fn move_cursor_to_line_start(&mut self, target: DomNodeId, extend_selection: bool) {
self.push_change(CallbackChange::MoveCursorToLineStart {
dom_id: target.dom,
node_id: target.node.into_crate_internal().unwrap_or(NodeId::ZERO),
extend_selection,
});
}
/// Move cursor to line end (End key)
pub fn move_cursor_to_line_end(&mut self, target: DomNodeId, extend_selection: bool) {
self.push_change(CallbackChange::MoveCursorToLineEnd {
dom_id: target.dom,
node_id: target.node.into_crate_internal().unwrap_or(NodeId::ZERO),
extend_selection,
});
}
/// Move cursor to document start (Ctrl+Home)
pub fn move_cursor_to_document_start(&mut self, target: DomNodeId, extend_selection: bool) {
self.push_change(CallbackChange::MoveCursorToDocumentStart {
dom_id: target.dom,
node_id: target.node.into_crate_internal().unwrap_or(NodeId::ZERO),
extend_selection,
});
}
/// Move cursor to document end (Ctrl+End)
pub fn move_cursor_to_document_end(&mut self, target: DomNodeId, extend_selection: bool) {
self.push_change(CallbackChange::MoveCursorToDocumentEnd {
dom_id: target.dom,
node_id: target.node.into_crate_internal().unwrap_or(NodeId::ZERO),
extend_selection,
});
}
/// Delete text backward (backspace or Shift+Backspace)
///
/// Queues a backspace operation to be applied after the callback.
/// Use `inspect_backspace()` to see what would be deleted.
pub fn delete_backward(&mut self, target: DomNodeId) {
self.push_change(CallbackChange::DeleteBackward {
dom_id: target.dom,
node_id: target.node.into_crate_internal().unwrap_or(NodeId::ZERO),
});
}
/// Delete text forward (delete key)
///
/// Queues a delete operation to be applied after the callback.
/// Use `inspect_delete()` to see what would be deleted.
pub fn delete_forward(&mut self, target: DomNodeId) {
self.push_change(CallbackChange::DeleteForward {
dom_id: target.dom,
node_id: target.node.into_crate_internal().unwrap_or(NodeId::ZERO),
});
}
}
/// Config necessary for threading + animations to work in `no_std` environments
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(C)]
pub struct ExternalSystemCallbacks {
pub create_thread_fn: CreateThreadCallback,
pub get_system_time_fn: GetSystemTimeCallback,
}
impl ExternalSystemCallbacks {
#[must_use] pub fn rust_internal() -> Self {
use crate::thread::create_thread_libstd;
Self {
create_thread_fn: CreateThreadCallback {
cb: create_thread_libstd,
},
get_system_time_fn: GetSystemTimeCallback {
cb: task::get_system_time_libstd,
},
}
}
}
/// Request to change focus, returned from callbacks
#[derive(Copy, Debug, Clone, PartialEq, Eq)]
pub enum FocusUpdateRequest {
/// Focus a specific node
FocusNode(DomNodeId),
/// Clear focus (no node has focus)
ClearFocus,
/// No focus change requested
NoChange,
}
impl FocusUpdateRequest {
/// Check if this represents a focus change
#[must_use] pub const fn is_change(&self) -> bool {
!matches!(self, Self::NoChange)
}
/// Convert to the new focused node (Some(node) or None for clear)
#[must_use] pub const fn to_focused_node(&self) -> Option<Option<DomNodeId>> {
match self {
Self::FocusNode(node) => Some(Some(*node)),
Self::ClearFocus => Some(None),
Self::NoChange => None,
}
}
/// Create from Option<Option<DomNodeId>> (legacy format)
#[must_use] pub const fn from_optional(opt: Option<Option<DomNodeId>>) -> Self {
match opt {
Some(Some(node)) => Self::FocusNode(node),
Some(None) => Self::ClearFocus,
None => Self::NoChange,
}
}
}
/// Menu callback: What data / function pointer should
/// be called when the menu item is clicked?
#[derive(Debug, Clone, PartialEq, PartialOrd, Hash, Eq, Ord)]
#[repr(C)]
pub struct MenuCallback {
pub callback: Callback,
pub refany: RefAny,
}
#[allow(variant_size_differences)] // repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size disparity accepted
/// Optional `MenuCallback`
#[derive(Debug, Clone, PartialEq, PartialOrd, Hash, Eq, Ord)]
#[repr(C, u8)]
pub enum OptionMenuCallback {
None,
Some(MenuCallback),
}
impl OptionMenuCallback {
#[must_use] pub fn into_option(self) -> Option<MenuCallback> {
match self {
Self::None => None,
Self::Some(c) => Some(c),
}
}
#[must_use] pub const fn is_some(&self) -> bool {
matches!(self, Self::Some(_))
}
#[must_use] pub const fn is_none(&self) -> bool {
matches!(self, Self::None)
}
}
impl From<Option<MenuCallback>> for OptionMenuCallback {
fn from(o: Option<MenuCallback>) -> Self {
o.map_or_else(|| Self::None, Self::Some)
}
}
impl From<OptionMenuCallback> for Option<MenuCallback> {
fn from(o: OptionMenuCallback) -> Self {
o.into_option()
}
}
// -- RenderImage callbacks
/// Callback type that renders an OpenGL texture
///
/// **IMPORTANT**: In azul-core, this is stored as `CoreRenderImageCallbackType = usize`
/// to avoid circular dependencies. The actual function pointer is cast to usize for
/// storage in the data model, then unsafely cast back to this type when invoked.
pub type RenderImageCallbackType = extern "C" fn(RefAny, RenderImageCallbackInfo) -> ImageRef;
/// Callback that returns a rendered OpenGL texture
///
/// **IMPORTANT**: In azul-core, this is stored as `CoreRenderImageCallback` with
/// a `cb: usize` field. When creating callbacks in the data model, function pointers
/// are cast to usize. This type is used in azul-layout where we can safely work
/// with the actual function pointer type.
#[repr(C)]
pub struct RenderImageCallback {
pub cb: RenderImageCallbackType,
/// For FFI: stores the foreign callable (e.g., `PyFunction`)
/// Native Rust code sets this to None
pub ctx: OptionRefAny,
}
impl_callback!(RenderImageCallback, RenderImageCallbackType);
impl RenderImageCallback {
/// Create a new callback with just a function pointer (for native Rust code)
pub fn create(cb: RenderImageCallbackType) -> Self {
Self {
cb,
ctx: OptionRefAny::None,
}
}
/// Convert from the core crate's `CoreRenderImageCallback` (which stores cb as usize)
/// back to the layout crate's typed function pointer.
///
/// # Safety
///
/// This is safe because we ensure that the usize in `CoreRenderImageCallback`
/// was originally created from a valid `RenderImageCallbackType` function pointer.
#[must_use] pub fn from_core(core_callback: &azul_core::callbacks::CoreRenderImageCallback) -> Self {
debug_assert!(core_callback.cb != 0, "CoreRenderImageCallback.cb is null");
Self {
cb: unsafe { core::mem::transmute::<usize, RenderImageCallbackType>(core_callback.cb) },
ctx: core_callback.ctx.clone(),
}
}
/// Convert to `CoreRenderImageCallback` (function pointer stored as usize)
///
/// This is always safe - we're just casting the function pointer to usize for storage.
#[must_use] pub fn to_core(self) -> azul_core::callbacks::CoreRenderImageCallback {
azul_core::callbacks::CoreRenderImageCallback {
cb: self.cb as usize,
ctx: self.ctx,
}
}
}
/// Allow `RenderImageCallback` to be passed to functions expecting `C: Into<CoreRenderImageCallback>`
impl From<RenderImageCallback> for azul_core::callbacks::CoreRenderImageCallback {
fn from(callback: RenderImageCallback) -> Self {
callback.to_core()
}
}
/// Information passed to image rendering callbacks
#[derive(Debug)]
#[repr(C)]
pub struct RenderImageCallbackInfo {
/// The ID of the DOM node that the `ImageCallback` was attached to
callback_node_id: DomNodeId,
/// Bounds of the laid-out node
bounds: HidpiAdjustedBounds,
/// Optional OpenGL context pointer
gl_context: *const OptionGlContextPtr,
/// Image cache for looking up images
image_cache: *const ImageCache,
/// System font cache
system_fonts: *const FcFontCache,
/// Pointer to callable (Python/FFI callback function)
callable_ptr: *const OptionRefAny,
/// Extension for future ABI stability (mutable data)
_abi_mut: *mut core::ffi::c_void,
}
impl Clone for RenderImageCallbackInfo {
// `_abi_mut` is an intentional FFI/api.json ABI-stability placeholder field.
#[allow(clippy::used_underscore_binding)]
fn clone(&self) -> Self {
Self {
callback_node_id: self.callback_node_id,
bounds: self.bounds,
gl_context: self.gl_context,
image_cache: self.image_cache,
system_fonts: self.system_fonts,
callable_ptr: self.callable_ptr,
_abi_mut: self._abi_mut,
}
}
}
impl RenderImageCallbackInfo {
#[must_use] pub const fn new<'a>(
callback_node_id: DomNodeId,
bounds: HidpiAdjustedBounds,
gl_context: &'a OptionGlContextPtr,
image_cache: &'a ImageCache,
system_fonts: &'a FcFontCache,
) -> Self {
Self {
callback_node_id,
bounds,
gl_context: std::ptr::from_ref::<OptionGlContextPtr>(gl_context),
image_cache: std::ptr::from_ref::<ImageCache>(image_cache),
system_fonts: std::ptr::from_ref::<FcFontCache>(system_fonts),
callable_ptr: core::ptr::null(),
_abi_mut: core::ptr::null_mut(),
}
}
/// Get the callable for FFI language bindings (Python, etc.)
#[must_use] pub fn get_ctx(&self) -> OptionRefAny {
if self.callable_ptr.is_null() {
OptionRefAny::None
} else {
unsafe { (*self.callable_ptr).clone() }
}
}
/// Set the callable pointer (called before invoking callback)
///
/// # Safety
///
/// `ptr` must either be null or point to an `OptionRefAny` that stays valid
/// for as long as this `CallbackInfo` may read it (i.e. until the pointer is
/// replaced or the callback returns). The pointee is read by [`get_ctx`]; a
/// dangling or misaligned `ptr` is undefined behavior.
///
/// [`get_ctx`]: Self::get_ctx
pub const unsafe fn set_callable_ptr(&mut self, ptr: *const OptionRefAny) {
self.callable_ptr = ptr;
}
#[must_use] pub const fn get_callback_node_id(&self) -> DomNodeId {
self.callback_node_id
}
#[must_use] pub const fn get_bounds(&self) -> HidpiAdjustedBounds {
self.bounds
}
const fn internal_get_gl_context(&self) -> &OptionGlContextPtr {
unsafe { &*self.gl_context }
}
const fn internal_get_image_cache(&self) -> &ImageCache {
unsafe { &*self.image_cache }
}
const fn internal_get_system_fonts(&self) -> &FcFontCache {
unsafe { &*self.system_fonts }
}
#[must_use] pub fn get_gl_context(&self) -> OptionGlContextPtr {
self.internal_get_gl_context().clone()
}
}
// ============================================================================
// Result types for FFI
// ============================================================================
/// Result type for functions returning `U8Vec` or a String error
#[derive(Debug, Clone)]
#[repr(C, u8)]
pub enum ResultU8VecString {
Ok(U8Vec),
Err(AzString),
}
impl From<Result<alloc::vec::Vec<u8>, AzString>> for ResultU8VecString {
fn from(result: Result<alloc::vec::Vec<u8>, AzString>) -> Self {
match result {
Ok(v) => Self::Ok(v.into()),
Err(e) => Self::Err(e),
}
}
}
#[allow(variant_size_differences)] // repr(C,u8) FFI enum: boxing the large variant would change the C ABI (api.json bindings); size disparity accepted
/// Result type for functions returning () or a String error
#[derive(Debug, Clone)]
#[repr(C, u8)]
pub enum ResultVoidString {
Ok,
Err(AzString),
}
impl From<Result<(), AzString>> for ResultVoidString {
fn from(result: Result<(), AzString>) -> Self {
match result {
Ok(()) => Self::Ok,
Err(e) => Self::Err(e),
}
}
}
/// Result type for functions returning String or a String error
#[derive(Debug, Clone)]
#[repr(C, u8)]
pub enum ResultStringString {
Ok(AzString),
Err(AzString),
}
impl From<Result<AzString, AzString>> for ResultStringString {
fn from(result: Result<AzString, AzString>) -> Self {
match result {
Ok(s) => Self::Ok(s),
Err(e) => Self::Err(e),
}
}
}
// ============================================================================
// Base64 encoding helper
// ============================================================================
const BASE64_ALPHABET: &[u8; 64] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// Encode bytes to Base64 string
#[must_use] pub fn base64_encode(input: &[u8]) -> String {
let mut output = String::with_capacity(input.len().div_ceil(3) * 4);
for chunk in input.chunks(3) {
let b0 = chunk[0] as usize;
let b1 = chunk.get(1).copied().unwrap_or(0) as usize;
let b2 = chunk.get(2).copied().unwrap_or(0) as usize;
let n = (b0 << 16) | (b1 << 8) | b2;
output.push(BASE64_ALPHABET[(n >> 18) & 0x3F] as char);
output.push(BASE64_ALPHABET[(n >> 12) & 0x3F] as char);
if chunk.len() > 1 {
output.push(BASE64_ALPHABET[(n >> 6) & 0x3F] as char);
} else {
output.push('=');
}
if chunk.len() > 2 {
output.push(BASE64_ALPHABET[n & 0x3F] as char);
} else {
output.push('=');
}
}
output
}
#[cfg(all(test, feature = "std"))]
#[allow(clippy::float_cmp, clippy::cast_possible_truncation)]
mod autotest_generated {
use super::*;
// ------------------------------------------------------------------
// Harness
// ------------------------------------------------------------------
/// Runs `f` with a fully-constructed `CallbackInfo` backed by an *empty*
/// `LayoutWindow` (no layout results, no timers, no threads, no routes).
/// Every query API therefore hits its "nothing there" path — which is
/// exactly the path adversarial tests need to exercise.
fn with_info<R>(hit: DomNodeId, f: impl FnOnce(&mut CallbackInfo) -> R) -> R {
let layout_window =
LayoutWindow::new(FcFontCache::default()).expect("LayoutWindow::new failed");
let renderer_resources = RendererResources::default();
let previous_window_state: Option<FullWindowState> = None;
let current_window_state = FullWindowState::default();
let gl_context = OptionGlContextPtr::None;
let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
BTreeMap::new();
let window_handle = RawWindowHandle::Unsupported;
let system_callbacks = ExternalSystemCallbacks::rust_internal();
let ref_data = CallbackInfoRefData {
layout_window: &layout_window,
renderer_resources: &renderer_resources,
previous_window_state: &previous_window_state,
current_window_state: ¤t_window_state,
gl_context: &gl_context,
current_scroll_manager: &scroll_states,
current_window_handle: &window_handle,
system_callbacks: &system_callbacks,
system_style: Arc::new(SystemStyle::default()),
monitors: Arc::new(std::sync::Mutex::new(MonitorVec::from_const_slice(&[]))),
#[cfg(feature = "icu")]
icu_localizer: IcuLocalizerHandle::default(),
ctx: OptionRefAny::None,
};
let changes: Arc<std::sync::Mutex<Vec<CallbackChange>>> =
Arc::new(std::sync::Mutex::new(Vec::new()));
let mut info = CallbackInfo::new(
&ref_data,
&changes,
hit,
OptionLogicalPosition::None,
OptionLogicalPosition::None,
);
f(&mut info)
}
/// `DomNodeId` pointing at node 0 of the root DOM.
fn node0() -> DomNodeId {
DomNodeId {
dom: DomId::ROOT_ID,
node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(0))),
}
}
/// `DomNodeId` whose node component is `None` (the "no concrete node" case).
fn node_none() -> DomNodeId {
DomNodeId {
dom: DomId::ROOT_ID,
node: NodeHierarchyItemId::NONE,
}
}
extern "C" fn cb_do_nothing(_: RefAny, _: CallbackInfo) -> Update {
Update::DoNothing
}
extern "C" fn cb_refresh_dom(_: RefAny, _: CallbackInfo) -> Update {
Update::RefreshDom
}
/// Pushes a change, so we can prove `invoke` really reaches the transaction log.
extern "C" fn cb_pushes_change(_: RefAny, mut info: CallbackInfo) -> Update {
info.stop_propagation();
Update::RefreshDomAllWindows
}
extern "C" fn img_cb(_: RefAny, _: RenderImageCallbackInfo) -> ImageRef {
ImageRef::null_image(0, 0, azul_core::resources::RawImageFormat::RGBA8, Vec::new())
}
fn a_css_property() -> CssProperty {
use azul_css::props::{basic::PixelValue, layout::dimensions::LayoutWidth};
CssProperty::const_width(LayoutWidth::Px(PixelValue::px(123.0)))
}
fn a_cursor() -> TextCursor {
use azul_core::selection::{CursorAffinity, GraphemeClusterId};
TextCursor {
cluster_id: GraphemeClusterId {
source_run: 0,
start_byte_in_run: 0,
},
affinity: CursorAffinity::Leading,
}
}
// ------------------------------------------------------------------
// base64_encode - round-trip, boundary, huge, unicode
// ------------------------------------------------------------------
/// Strict RFC-4648 decoder, written independently of the encoder so that
/// `decode(encode(x)) == x` is a real round-trip and not a tautology.
fn base64_decode(s: &str) -> Option<Vec<u8>> {
fn val(c: u8) -> Option<u32> {
match c {
b'A'..=b'Z' => Some((c - b'A') as u32),
b'a'..=b'z' => Some((c - b'a') as u32 + 26),
b'0'..=b'9' => Some((c - b'0') as u32 + 52),
b'+' => Some(62),
b'/' => Some(63),
_ => None,
}
}
let bytes = s.as_bytes();
if bytes.len() % 4 != 0 {
return None;
}
let mut out = Vec::with_capacity(bytes.len() / 4 * 3);
for chunk in bytes.chunks(4) {
let pad = chunk.iter().filter(|&&c| c == b'=').count();
if pad > 2 {
return None;
}
let mut n: u32 = 0;
for (i, &c) in chunk.iter().enumerate() {
let v = if c == b'=' { 0 } else { val(c)? };
n |= v << (18 - 6 * i as u32);
}
out.push(((n >> 16) & 0xFF) as u8);
if pad < 2 {
out.push(((n >> 8) & 0xFF) as u8);
}
if pad < 1 {
out.push((n & 0xFF) as u8);
}
}
Some(out)
}
#[test]
fn base64_encode_rfc4648_test_vectors() {
assert_eq!(base64_encode(b""), "");
assert_eq!(base64_encode(b"f"), "Zg==");
assert_eq!(base64_encode(b"fo"), "Zm8=");
assert_eq!(base64_encode(b"foo"), "Zm9v");
assert_eq!(base64_encode(b"foob"), "Zm9vYg==");
assert_eq!(base64_encode(b"fooba"), "Zm9vYmE=");
assert_eq!(base64_encode(b"foobar"), "Zm9vYmFy");
}
#[test]
fn base64_encode_extreme_bytes() {
// All-zero and all-ones map to the first / last alphabet entries.
assert_eq!(base64_encode(&[0x00, 0x00, 0x00]), "AAAA");
assert_eq!(base64_encode(&[0xFF, 0xFF, 0xFF]), "////");
// Single 0xFF byte: two significant chars + two pad chars.
assert_eq!(base64_encode(&[0xFF]), "/w==");
assert_eq!(base64_encode(&[0xFF, 0xFF]), "//8=");
// Every 6-bit value 0..63 appears exactly once in the alphabet.
let all: Vec<u8> = (0u8..=255).collect();
let enc = base64_encode(&all);
assert_eq!(base64_decode(&enc).as_deref(), Some(all.as_slice()));
}
#[test]
fn base64_encode_output_length_is_ceil_div_3_times_4() {
for n in 0usize..=64 {
let input = vec![0xABu8; n];
let enc = base64_encode(&input);
assert_eq!(
enc.len(),
n.div_ceil(3) * 4,
"unexpected encoded length for {n} input bytes"
);
// Padding is only ever at the very end, and never more than 2 chars.
let pad = enc.bytes().filter(|&c| c == b'=').count();
assert!(pad <= 2, "too much padding for n = {n}");
assert_eq!(pad, (3 - n % 3) % 3, "wrong padding count for n = {n}");
if pad > 0 {
assert!(enc.ends_with(&"=".repeat(pad)));
}
}
}
#[test]
fn base64_encode_emits_only_alphabet_characters() {
let input: Vec<u8> = (0u8..=255).chain(0u8..=255).collect();
let enc = base64_encode(&input);
for c in enc.bytes() {
assert!(
c == b'=' || BASE64_ALPHABET.contains(&c),
"non-base64 char {c:?} in output"
);
}
}
#[test]
fn base64_encode_round_trips_for_every_length_remainder() {
// 0, 1, 2 mod 3 all exercise a different padding branch.
for n in 0usize..=130 {
let input: Vec<u8> = (0..n).map(|i| (i * 7 + 13) as u8).collect();
let enc = base64_encode(&input);
let dec = base64_decode(&enc).unwrap_or_else(|| panic!("failed to decode {enc:?}"));
assert_eq!(dec, input, "round-trip failed at length {n}");
}
}
#[test]
fn base64_encode_unicode_bytes_round_trip() {
for s in [
"\u{1F600}", // emoji (4-byte UTF-8)
"e\u{301}", // combining acute accent
"\u{0}\u{7F}\u{80}\u{FFFF}", // control + boundary code points
"тест 日本語 🌍",
] {
let enc = base64_encode(s.as_bytes());
assert_eq!(base64_decode(&enc).as_deref(), Some(s.as_bytes()));
}
// Known-good positive control: base64("😀") == "8J+YgA=="
assert_eq!(base64_encode("\u{1F600}".as_bytes()), "8J+YgA==");
}
#[test]
fn base64_encode_one_megabyte_does_not_panic_or_hang() {
let input = vec![0x5Au8; 1_000_000];
let enc = base64_encode(&input);
assert_eq!(enc.len(), 1_000_000usize.div_ceil(3) * 4);
// 1_000_000 % 3 == 1 -> exactly two padding chars.
assert!(enc.ends_with("=="));
assert_eq!(base64_decode(&enc).map(|v| v.len()), Some(1_000_000));
}
// ------------------------------------------------------------------
// PenTilt / SelectAllResult / DeleteResult (From conversions)
// ------------------------------------------------------------------
#[test]
fn pen_tilt_from_tuple_preserves_extreme_floats() {
let t = PenTilt::from((0.0, -0.0));
assert_eq!(t.x_tilt, 0.0);
assert!(t.y_tilt.is_sign_negative());
let t = PenTilt::from((f32::MAX, f32::MIN));
assert_eq!(t.x_tilt, f32::MAX);
assert_eq!(t.y_tilt, f32::MIN);
let t = PenTilt::from((f32::INFINITY, f32::NEG_INFINITY));
assert!(t.x_tilt.is_infinite() && t.x_tilt.is_sign_positive());
assert!(t.y_tilt.is_infinite() && t.y_tilt.is_sign_negative());
// NaN is passed through unchanged (no sanitisation) - and, being NaN,
// makes the derived PartialEq report "not equal to itself".
let t = PenTilt::from((f32::NAN, 90.0));
assert!(t.x_tilt.is_nan());
assert_eq!(t.y_tilt, 90.0);
assert_ne!(t, t);
}
#[test]
fn option_pen_tilt_is_some_is_none_are_exclusive() {
let some = OptionPenTilt::Some(PenTilt::from((1.0, 2.0)));
let none = OptionPenTilt::None;
assert!(some.is_some() && !some.is_none());
assert!(none.is_none() && !none.is_some());
}
#[test]
fn select_all_result_from_tuple_keeps_fields_including_empty_and_huge() {
let range = SelectionRange {
start: a_cursor(),
end: a_cursor(),
};
let empty = SelectAllResult::from((String::new(), range));
assert_eq!(empty.full_text.as_str(), "");
assert_eq!(empty.selection_range, range);
let huge = SelectAllResult::from(("x".repeat(100_000), range));
assert_eq!(huge.full_text.as_str().len(), 100_000);
let unicode = SelectAllResult::from(("🌍\u{0}é".to_string(), range));
assert_eq!(unicode.full_text.as_str(), "🌍\u{0}é");
}
#[test]
fn delete_result_from_tuple_keeps_fields() {
let range = SelectionRange {
start: a_cursor(),
end: a_cursor(),
};
let d = DeleteResult::from((range, String::new()));
assert_eq!(d.range_to_delete, range);
assert_eq!(d.deleted_text.as_str(), "");
let d = DeleteResult::from((range, "\u{1F600}".to_string()));
assert_eq!(d.deleted_text.as_str(), "\u{1F600}");
}
// ------------------------------------------------------------------
// Callback: constructors, core round-trip, invoke, eq/hash invariants
// ------------------------------------------------------------------
#[test]
fn callback_from_ptr_and_create_and_from_agree() {
let a = Callback::from_ptr(cb_do_nothing);
let b = Callback::create(cb_do_nothing as CallbackType);
let c = Callback::from(cb_do_nothing as CallbackType);
assert_eq!(a, b);
assert_eq!(b, c);
// Constructed from a bare fn pointer => no FFI ctx attached.
assert!(a.ctx.is_none());
assert!(b.ctx.is_none());
assert!(c.ctx.is_none());
assert_ne!(a.cb as usize, 0);
}
#[test]
fn callback_to_core_from_core_round_trips_pointer_and_ctx() {
let original = Callback {
cb: cb_refresh_dom,
ctx: OptionRefAny::Some(RefAny::new(0xDEAD_BEEFu32)),
};
let ptr = original.cb as usize;
let core = original.to_core();
assert_eq!(core.cb, ptr);
assert!(core.ctx.is_some(), "to_core must not drop the FFI ctx");
let back = Callback::from_core(core);
assert_eq!(back.cb as usize, ptr, "encode == decode for the fn pointer");
assert!(
back.ctx.is_some(),
"from_core must preserve ctx (managed-FFI handlers rely on it)"
);
}
#[test]
fn callback_to_core_of_ctxless_callback_keeps_ctx_none() {
let core = Callback::from_ptr(cb_do_nothing).to_core();
assert!(core.ctx.is_none());
assert_eq!(Callback::from_core(core).cb as usize, cb_do_nothing as usize);
}
#[test]
#[cfg(debug_assertions)]
#[should_panic(expected = "CoreCallback.cb is null")]
fn callback_from_core_null_pointer_trips_debug_assert() {
// A null fn pointer would be UB to call; from_core must not silently
// hand one back in a debug build.
let _ = Callback::from_core(CoreCallback {
cb: 0,
ctx: OptionRefAny::None,
});
}
#[test]
fn callback_invoke_returns_the_functions_update() {
let update = with_info(node_none(), |info| {
Callback::from_ptr(cb_refresh_dom).invoke(RefAny::new(1u8), *info)
});
assert!(matches!(update, Update::RefreshDom));
let update = with_info(node_none(), |info| {
Callback::from_ptr(cb_do_nothing).invoke(RefAny::new(1u8), *info)
});
assert!(matches!(update, Update::DoNothing));
}
#[test]
fn callback_invoke_changes_reach_the_callers_transaction_log() {
// CallbackInfo is Copy; a change pushed through the *copy* handed to the
// callback must still land in the original's change vector.
let changes = with_info(node_none(), |info| {
let update = Callback::from_ptr(cb_pushes_change).invoke(RefAny::new(0u8), *info);
assert!(matches!(update, Update::RefreshDomAllWindows));
info.take_changes()
});
assert_eq!(changes.len(), 1);
assert!(matches!(changes[0], CallbackChange::StopPropagation));
}
#[test]
fn callback_eq_and_hash_ignore_ctx_but_stay_consistent() {
use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
let plain = Callback::from_ptr(cb_do_nothing);
let with_ctx = Callback {
cb: cb_do_nothing,
ctx: OptionRefAny::Some(RefAny::new(7u64)),
};
let other_fn = Callback::from_ptr(cb_refresh_dom);
// Documented macro behaviour: identity is the fn pointer alone.
assert_eq!(plain, with_ctx);
assert_ne!(plain, other_fn);
// Eq/Hash must agree, or these end up as duplicate keys in a HashMap.
let hash = |c: &Callback| {
let mut h = DefaultHasher::new();
c.hash(&mut h);
h.finish()
};
assert_eq!(hash(&plain), hash(&with_ctx));
}
// ------------------------------------------------------------------
// OptionCallback / OptionMenuCallback predicates + round-trips
// ------------------------------------------------------------------
#[test]
fn option_callback_predicates_are_exclusive_and_total() {
let none = OptionCallback::None;
let some = OptionCallback::Some(Callback::from_ptr(cb_do_nothing));
assert!(none.is_none() && !none.is_some());
assert!(some.is_some() && !some.is_none());
// Exactly one of the two predicates holds, for every value.
for v in [&none, &some] {
assert!(v.is_some() ^ v.is_none());
}
}
#[test]
fn option_callback_round_trips_through_std_option() {
let cb = Callback::from_ptr(cb_do_nothing);
let round = OptionCallback::from(Some(cb.clone())).into_option();
assert_eq!(round, Some(cb.clone()));
let round = OptionCallback::from(None).into_option();
assert_eq!(round, None);
// and the other direction of the From impls
let ffi: OptionCallback = Some(cb.clone()).into();
let back: Option<Callback> = ffi.into();
assert_eq!(back, Some(cb));
let ffi: OptionCallback = None.into();
let back: Option<Callback> = ffi.into();
assert_eq!(back, None);
}
#[test]
fn option_menu_callback_predicates_and_round_trip() {
let mc = MenuCallback {
callback: Callback::from_ptr(cb_do_nothing),
refany: RefAny::new(5i32),
};
let none = OptionMenuCallback::None;
assert!(none.is_none() && !none.is_some());
assert_eq!(none.into_option(), None);
let some = OptionMenuCallback::from(Some(mc.clone()));
assert!(some.is_some() && !some.is_none());
assert_eq!(some.into_option(), Some(mc));
let back: Option<MenuCallback> = OptionMenuCallback::None.into();
assert!(back.is_none());
}
// ------------------------------------------------------------------
// RenderImageCallback + RenderImageCallbackInfo
// ------------------------------------------------------------------
#[test]
fn render_image_callback_core_round_trip() {
let cb = RenderImageCallback::create(img_cb);
assert!(cb.ctx.is_none());
let ptr = cb.cb as usize;
let core = cb.to_core();
assert_eq!(core.cb, ptr);
let back = RenderImageCallback::from_core(&core);
assert_eq!(back.cb as usize, ptr);
assert!(back.ctx.is_none());
}
#[test]
#[cfg(debug_assertions)]
#[should_panic(expected = "CoreRenderImageCallback.cb is null")]
fn render_image_callback_from_core_null_pointer_trips_debug_assert() {
let core = azul_core::callbacks::CoreRenderImageCallback {
cb: 0,
ctx: OptionRefAny::None,
};
let _ = RenderImageCallback::from_core(&core);
}
#[test]
fn render_image_callback_info_getters_and_null_ctx() {
let gl = OptionGlContextPtr::None;
let image_cache = ImageCache::default();
let fonts = FcFontCache::default();
let bounds = HidpiAdjustedBounds {
logical_size: LogicalSize::new(640.0, 480.0),
hidpi_factor: azul_core::resources::DpiScaleFactor::new(2.0),
};
let info = RenderImageCallbackInfo::new(node0(), bounds, &gl, &image_cache, &fonts);
assert_eq!(info.get_callback_node_id(), node0());
assert_eq!(info.get_bounds().logical_size, LogicalSize::new(640.0, 480.0));
// callable_ptr is null for native Rust callbacks: get_ctx must return
// None rather than dereferencing the null pointer.
assert!(info.get_ctx().is_none());
assert!(info.get_gl_context().is_none());
// Clone is a field-wise pointer copy - the getters must still work.
let cloned = info.clone();
assert_eq!(cloned.get_callback_node_id(), node0());
assert!(cloned.get_ctx().is_none());
}
#[test]
fn render_image_callback_info_accepts_degenerate_and_nan_bounds() {
let gl = OptionGlContextPtr::None;
let image_cache = ImageCache::default();
let fonts = FcFontCache::default();
for (w, h, dpi) in [
(0.0f32, 0.0f32, 0.0f32),
(-1.0, -1.0, 1.0),
(f32::MAX, f32::MAX, f32::MAX),
(f32::INFINITY, f32::NAN, 1.0),
] {
let bounds = HidpiAdjustedBounds {
logical_size: LogicalSize::new(w, h),
hidpi_factor: azul_core::resources::DpiScaleFactor::new(dpi),
};
let info = RenderImageCallbackInfo::new(node_none(), bounds, &gl, &image_cache, &fonts);
let got = info.get_bounds().logical_size;
assert_eq!(got.width.is_nan(), w.is_nan());
assert_eq!(got.height.is_nan(), h.is_nan());
}
}
#[test]
fn render_image_callback_info_set_callable_ptr_makes_ctx_visible() {
let gl = OptionGlContextPtr::None;
let image_cache = ImageCache::default();
let fonts = FcFontCache::default();
let bounds = HidpiAdjustedBounds {
logical_size: LogicalSize::new(1.0, 1.0),
hidpi_factor: azul_core::resources::DpiScaleFactor::new(1.0),
};
let mut info = RenderImageCallbackInfo::new(node0(), bounds, &gl, &image_cache, &fonts);
let ctx = OptionRefAny::Some(RefAny::new(99u32));
// SAFETY: `ctx` outlives `info` (both are dropped at the end of this fn).
unsafe { info.set_callable_ptr(core::ptr::from_ref(&ctx)) };
assert!(info.get_ctx().is_some());
// Resetting to null must go back to the safe "no ctx" answer.
unsafe { info.set_callable_ptr(core::ptr::null()) };
assert!(info.get_ctx().is_none());
}
// ------------------------------------------------------------------
// FocusUpdateRequest - predicate + round-trip laws
// ------------------------------------------------------------------
#[test]
fn focus_update_request_is_change_matches_variant() {
assert!(FocusUpdateRequest::FocusNode(node0()).is_change());
assert!(FocusUpdateRequest::ClearFocus.is_change());
assert!(!FocusUpdateRequest::NoChange.is_change());
}
#[test]
fn focus_update_request_optional_round_trip_is_lossless() {
for req in [
FocusUpdateRequest::FocusNode(node0()),
FocusUpdateRequest::FocusNode(node_none()),
FocusUpdateRequest::ClearFocus,
FocusUpdateRequest::NoChange,
] {
assert_eq!(
FocusUpdateRequest::from_optional(req.to_focused_node()),
req,
"from_optional . to_focused_node must be the identity"
);
}
// ... and in the other direction, for the legacy Option<Option<_>> form.
for opt in [Some(Some(node0())), Some(None), None] {
assert_eq!(FocusUpdateRequest::from_optional(opt).to_focused_node(), opt);
}
// is_change agrees with "to_focused_node produced something"
for req in [
FocusUpdateRequest::FocusNode(node0()),
FocusUpdateRequest::ClearFocus,
FocusUpdateRequest::NoChange,
] {
assert_eq!(req.is_change(), req.to_focused_node().is_some());
}
}
// ------------------------------------------------------------------
// FFI Result enums
// ------------------------------------------------------------------
#[test]
fn result_u8vec_string_from_maps_ok_and_err() {
let ok = ResultU8VecString::from(Ok(Vec::new()));
assert!(matches!(&ok, ResultU8VecString::Ok(v) if v.is_empty()));
let ok = ResultU8VecString::from(Ok(vec![0u8; 100_000]));
assert!(matches!(&ok, ResultU8VecString::Ok(v) if v.len() == 100_000));
let err = ResultU8VecString::from(Err(AzString::from("boom")));
assert!(matches!(&err, ResultU8VecString::Err(e) if e.as_str() == "boom"));
}
#[test]
fn result_void_string_from_maps_ok_and_err() {
assert!(matches!(ResultVoidString::from(Ok(())), ResultVoidString::Ok));
let err = ResultVoidString::from(Err(AzString::from("")));
assert!(matches!(&err, ResultVoidString::Err(e) if e.as_str().is_empty()));
}
#[test]
fn result_string_string_from_keeps_both_sides_distinct() {
let ok = ResultStringString::from(Ok(AzString::from("x")));
assert!(matches!(&ok, ResultStringString::Ok(s) if s.as_str() == "x"));
// Same payload type on both sides - the discriminant is what carries meaning.
let err = ResultStringString::from(Err(AzString::from("x")));
assert!(matches!(&err, ResultStringString::Err(s) if s.as_str() == "x"));
}
// ------------------------------------------------------------------
// ExternalSystemCallbacks
// ------------------------------------------------------------------
#[test]
fn external_system_callbacks_time_fn_is_callable_and_monotonic() {
let cbs = ExternalSystemCallbacks::rust_internal();
let t0 = (cbs.get_system_time_fn.cb)();
let t1 = (cbs.get_system_time_fn.cb)();
// Both calls must succeed; we only assert they produce a value (the
// clock resolution makes strict ordering flaky).
let _ = (t0, t1);
}
// ------------------------------------------------------------------
// CallbackInfo: transaction log (push / take / relayout predicate)
// ------------------------------------------------------------------
#[test]
fn callback_info_starts_with_an_empty_change_log() {
with_info(node_none(), |info| {
assert!(info.take_changes().is_empty());
assert!(!info.has_pending_relayout_change());
assert!(!info.get_changes_ptr().is_null());
});
}
#[test]
fn callback_info_take_changes_drains_the_log() {
with_info(node_none(), |info| {
info.stop_propagation();
info.prevent_default();
let first = info.take_changes();
assert_eq!(first.len(), 2);
// Second take must not hand out the same changes again.
assert!(
info.take_changes().is_empty(),
"take_changes must consume the log"
);
});
}
#[test]
fn callback_info_is_copy_and_copies_share_one_change_log() {
with_info(node_none(), |info| {
let mut copy = *info;
copy.stop_immediate_propagation();
assert_eq!(
info.get_changes_ptr(),
copy.get_changes_ptr(),
"a Copy of CallbackInfo must alias the same Arc<Mutex<..>>"
);
let changes = info.take_changes();
assert_eq!(changes.len(), 1);
assert!(matches!(changes[0], CallbackChange::StopImmediatePropagation));
});
}
#[test]
fn has_pending_relayout_change_is_true_only_for_relayout_changes() {
// Known-false: a propagation change needs no relayout.
with_info(node_none(), |info| {
info.stop_propagation();
assert!(!info.has_pending_relayout_change());
});
// Known-true: window resize.
with_info(node_none(), |info| {
info.modify_window_state(FullWindowState::default());
assert!(info.has_pending_relayout_change());
});
// Known-true: scroll.
with_info(node_none(), |info| {
info.scroll_to(
DomId::ROOT_ID,
NodeHierarchyItemId::NONE,
LogicalPosition::new(0.0, 0.0),
);
assert!(info.has_pending_relayout_change());
});
// Known-true: queued synthetic input sequence.
with_info(node_none(), |info| {
info.queue_window_state_sequence(FullWindowStateVec::from_vec(vec![
FullWindowState::default(),
]));
assert!(info.has_pending_relayout_change());
});
// A relayout change anywhere in the log counts, not just at the head.
with_info(node_none(), |info| {
info.prevent_default();
info.hide_tooltip();
info.close_window();
assert!(!info.has_pending_relayout_change());
info.modify_window_state(FullWindowState::default());
assert!(info.has_pending_relayout_change());
// Querying must not consume the log.
assert!(info.has_pending_relayout_change());
assert_eq!(info.take_changes().len(), 4);
});
}
#[test]
fn callback_info_flag_mutators_queue_exactly_one_matching_change() {
macro_rules! assert_queues {
($call:expr, $pat:pat) => {{
with_info(node_none(), |info| {
let f: &dyn Fn(&mut CallbackInfo) = &$call;
f(info);
let changes = info.take_changes();
assert_eq!(changes.len(), 1, "expected exactly one queued change");
assert!(
matches!(changes[0], $pat),
"queued the wrong CallbackChange: {:?}",
changes[0]
);
});
}};
}
assert_queues!(
|i: &mut CallbackInfo| i.stop_propagation(),
CallbackChange::StopPropagation
);
assert_queues!(
|i: &mut CallbackInfo| i.stop_immediate_propagation(),
CallbackChange::StopImmediatePropagation
);
assert_queues!(
|i: &mut CallbackInfo| i.prevent_default(),
CallbackChange::PreventDefault
);
assert_queues!(
|i: &mut CallbackInfo| i.close_window(),
CallbackChange::CloseWindow
);
assert_queues!(
|i: &mut CallbackInfo| i.begin_interactive_move(),
CallbackChange::BeginInteractiveMove
);
assert_queues!(
|i: &mut CallbackInfo| i.commit_undo_snapshot(),
CallbackChange::CommitUndoSnapshot
);
assert_queues!(
|i: &mut CallbackInfo| i.undo_app_state(),
CallbackChange::UndoAppState
);
assert_queues!(
|i: &mut CallbackInfo| i.redo_app_state(),
CallbackChange::RedoAppState
);
assert_queues!(
|i: &mut CallbackInfo| i.update_all_image_callbacks(),
CallbackChange::UpdateAllImageCallbacks
);
assert_queues!(
|i: &mut CallbackInfo| i.trigger_all_virtual_view_rerender(),
CallbackChange::UpdateAllVirtualViews
);
assert_queues!(
|i: &mut CallbackInfo| i.reload_system_fonts(),
CallbackChange::ReloadSystemFonts
);
assert_queues!(
|i: &mut CallbackInfo| i.hide_tooltip(),
CallbackChange::HideTooltip
);
}
#[test]
fn callback_info_timer_and_thread_ids_survive_boundary_values() {
with_info(node_none(), |info| {
info.add_timer(TimerId { id: 0 }, Timer::default());
info.add_timer(TimerId { id: usize::MAX }, Timer::default());
info.remove_timer(TimerId { id: usize::MAX });
info.remove_thread(ThreadId::unique());
let changes = info.take_changes();
assert_eq!(changes.len(), 4);
assert!(
matches!(&changes[1], CallbackChange::AddTimer { timer_id, .. } if timer_id.id == usize::MAX)
);
assert!(
matches!(&changes[2], CallbackChange::RemoveTimer { timer_id } if timer_id.id == usize::MAX)
);
assert!(matches!(&changes[3], CallbackChange::RemoveThread { .. }));
});
}
// ------------------------------------------------------------------
// CallbackInfo: numeric edges (scroll / menu / tooltip positions)
// ------------------------------------------------------------------
#[test]
fn scroll_to_records_position_verbatim_at_numeric_extremes() {
let positions = [
LogicalPosition::new(0.0, 0.0),
LogicalPosition::new(-0.0, -1_000_000.0),
LogicalPosition::new(f32::MIN, f32::MAX),
LogicalPosition::new(f32::INFINITY, f32::NEG_INFINITY),
LogicalPosition::new(f32::NAN, f32::NAN),
];
with_info(node_none(), |info| {
for p in positions {
info.scroll_to(DomId::ROOT_ID, NodeHierarchyItemId::NONE, p);
}
let changes = info.take_changes();
assert_eq!(changes.len(), positions.len());
for (change, expected) in changes.iter().zip(positions) {
let CallbackChange::ScrollTo {
position, unclamped, ..
} = change
else {
panic!("expected ScrollTo, got {change:?}");
};
assert!(!*unclamped, "scroll_to must request clamping");
// No sanitisation happens here - NaN/inf reach the change log
// unchanged, and clamping is the change-processor's job.
assert_eq!(position.x.is_nan(), expected.x.is_nan());
if !expected.x.is_nan() {
assert_eq!(position.x, expected.x);
assert_eq!(position.y, expected.y);
}
}
});
}
#[test]
fn scroll_to_unclamped_sets_the_unclamped_flag() {
with_info(node_none(), |info| {
info.scroll_to_unclamped(
DomId { inner: usize::MAX },
NodeHierarchyItemId::from_raw(usize::MAX),
LogicalPosition::new(-99999.0, 99999.0),
);
let changes = info.take_changes();
assert_eq!(changes.len(), 1);
let CallbackChange::ScrollTo {
unclamped,
dom_id,
position,
..
} = &changes[0]
else {
panic!("expected ScrollTo");
};
assert!(*unclamped, "scroll_to_unclamped must skip clamping");
assert_eq!(dom_id.inner, usize::MAX, "an unknown DomId is not rejected here");
assert_eq!(position.x, -99999.0);
});
}
#[test]
fn scroll_node_into_view_queues_the_options_verbatim() {
use crate::managers::scroll_into_view::ScrollIntoViewOptions;
with_info(node_none(), |info| {
info.scroll_node_into_view(node_none(), ScrollIntoViewOptions::nearest());
let changes = info.take_changes();
assert_eq!(changes.len(), 1);
assert!(matches!(changes[0], CallbackChange::ScrollIntoView { .. }));
});
}
#[test]
fn open_menu_at_and_show_tooltip_at_accept_extreme_positions() {
let menu = || Menu::create(azul_core::menu::MenuItemVec::from_const_slice(&[]));
with_info(node_none(), |info| {
info.open_menu(menu());
info.open_menu_at(menu(), LogicalPosition::new(0.0, 0.0));
info.open_menu_at(menu(), LogicalPosition::new(f32::MIN, f32::MAX));
info.open_menu_at(menu(), LogicalPosition::new(f32::NAN, f32::INFINITY));
let changes = info.take_changes();
assert_eq!(changes.len(), 4);
// open_menu keeps the menu's own position (None override) ...
assert!(matches!(
&changes[0],
CallbackChange::OpenMenu { position: None, .. }
));
// ... open_menu_at always overrides it.
for change in &changes[1..] {
assert!(matches!(
change,
CallbackChange::OpenMenu {
position: Some(_),
..
}
));
}
});
with_info(node_none(), |info| {
info.show_tooltip(AzString::from(""));
info.show_tooltip_at(AzString::from("🌍"), LogicalPosition::new(f32::NAN, -0.0));
info.show_tooltip_at(
AzString::from("x".repeat(100_000)),
LogicalPosition::new(f32::MAX, f32::MIN),
);
let changes = info.take_changes();
assert_eq!(changes.len(), 3);
assert!(matches!(&changes[0], CallbackChange::ShowTooltip { text, .. } if text.as_str().is_empty()));
assert!(matches!(&changes[1], CallbackChange::ShowTooltip { text, position } if text.as_str() == "🌍" && position.x.is_nan()));
assert!(matches!(&changes[2], CallbackChange::ShowTooltip { text, .. } if text.as_str().len() == 100_000));
});
}
// ------------------------------------------------------------------
// CallbackInfo: CSS property helpers (documented panics)
// ------------------------------------------------------------------
#[test]
fn set_css_property_wraps_a_single_property() {
with_info(node_none(), |info| {
info.set_css_property(node0(), a_css_property());
let changes = info.take_changes();
assert_eq!(changes.len(), 1);
let CallbackChange::ChangeNodeCssProperties {
dom_id,
node_id,
properties,
} = &changes[0]
else {
panic!("expected ChangeNodeCssProperties");
};
assert_eq!(*dom_id, DomId::ROOT_ID);
assert_eq!(node_id.index(), 0);
assert_eq!(properties.len(), 1);
});
}
#[test]
fn override_css_property_uses_the_override_channel_not_the_cascade() {
with_info(node_none(), |info| {
info.override_css_property(node0(), a_css_property());
let changes = info.take_changes();
assert_eq!(changes.len(), 1);
assert!(
matches!(changes[0], CallbackChange::OverrideNodeCssProperties { .. }),
"must not fall back to the invalidating ChangeNodeCssProperties path"
);
});
}
#[test]
#[should_panic(expected = "DomNodeId node should not be None")]
fn set_css_property_panics_on_a_none_node_as_documented() {
with_info(node_none(), |info| {
info.set_css_property(node_none(), a_css_property());
});
}
#[test]
#[should_panic(expected = "DomNodeId node should not be None")]
fn override_css_property_panics_on_a_none_node_as_documented() {
with_info(node_none(), |info| {
info.override_css_property(node_none(), a_css_property());
});
}
#[test]
fn change_node_css_properties_accepts_an_empty_property_vec() {
with_info(node_none(), |info| {
info.change_node_css_properties(
DomId::ROOT_ID,
NodeId::new(usize::MAX),
CssPropertyVec::from_const_slice(&[]),
);
let changes = info.take_changes();
assert_eq!(changes.len(), 1);
assert!(
matches!(&changes[0], CallbackChange::ChangeNodeCssProperties { properties, .. } if properties.is_empty())
);
});
}
// ------------------------------------------------------------------
// CallbackInfo: text / DOM mutation payloads (malformed + unicode + huge)
// ------------------------------------------------------------------
#[test]
fn change_node_text_passes_hostile_strings_through_unchanged() {
let inputs = [
String::new(),
" \t\n ".to_string(),
"\u{0}embedded nul".to_string(),
"🌍é\u{301}\u{200B}".to_string(),
"x".repeat(1_000_000),
];
with_info(node_none(), |info| {
for s in &inputs {
info.change_node_text(node0(), AzString::from(s.clone()));
}
let changes = info.take_changes();
assert_eq!(changes.len(), inputs.len());
for (change, expected) in changes.iter().zip(&inputs) {
let CallbackChange::ChangeNodeText { text, .. } = change else {
panic!("expected ChangeNodeText");
};
assert_eq!(text.as_str(), expected.as_str());
}
});
}
#[test]
fn insert_child_node_accepts_empty_and_garbage_type_strings() {
with_info(node_none(), |info| {
// Neither an empty tag nor a garbage tag is validated at queue time.
info.insert_child_node(
DomId::ROOT_ID,
NodeId::new(0),
AzString::from(""),
OptionUsize::None,
StringVec::from_const_slice(&[]),
OptionString::None,
);
info.insert_child_node(
DomId { inner: usize::MAX },
NodeId::new(usize::MAX),
AzString::from("\u{0}<<not a tag>>"),
OptionUsize::Some(usize::MAX),
StringVec::from_const_slice(&[]),
OptionString::None,
);
assert_eq!(info.take_changes().len(), 2);
});
}
#[test]
fn text_editing_mutators_queue_their_changes() {
with_info(node_none(), |info| {
info.insert_text(DomId::ROOT_ID, NodeId::new(0), AzString::from("🌍"));
info.move_cursor(DomId::ROOT_ID, NodeId::new(0), a_cursor());
info.set_selection(
DomId::ROOT_ID,
NodeId::new(0),
Selection::Cursor(a_cursor()),
);
info.set_text_changeset(PendingTextEdit {
node: node0(),
inserted_text: AzString::from(""),
old_text: AzString::from(""),
});
info.create_text_input(AzString::from("\u{0}"));
info.delete_node(DomId::ROOT_ID, NodeId::new(usize::MAX));
info.set_node_ids_and_classes(
DomId::ROOT_ID,
NodeId::new(0),
azul_core::dom::IdOrClassVec::from_const_slice(&[]),
);
let changes = info.take_changes();
assert_eq!(changes.len(), 7);
assert!(matches!(&changes[0], CallbackChange::InsertText { text, .. } if text.as_str() == "🌍"));
assert!(matches!(changes[1], CallbackChange::MoveCursor { .. }));
assert!(matches!(changes[2], CallbackChange::SetSelection { .. }));
assert!(matches!(changes[3], CallbackChange::SetTextChangeset { .. }));
assert!(matches!(changes[5], CallbackChange::DeleteNode { .. }));
});
}
#[test]
fn image_cache_mutators_accept_empty_ids_and_null_images() {
with_info(node_none(), |info| {
let img = || {
ImageRef::null_image(0, 0, azul_core::resources::RawImageFormat::RGBA8, Vec::new())
};
info.add_image_to_cache(AzString::from(""), img());
info.remove_image_from_cache(AzString::from(""));
info.change_node_image(
DomId::ROOT_ID,
NodeId::new(0),
img(),
UpdateImageType::Content,
);
info.update_image_callback(DomId { inner: usize::MAX }, NodeId::new(usize::MAX));
info.trigger_virtual_view_rerender(DomId::ROOT_ID, NodeId::new(usize::MAX));
assert_eq!(info.take_changes().len(), 5);
});
}
#[test]
fn focus_mutators_queue_set_focus_target() {
with_info(node_none(), |info| {
info.set_focus(FocusTarget::NoFocus);
// usize::MAX is the ONE index NodeId's 1-based encoding cannot represent
// (into_raw does `inner + 1`); the repo pins usize::MAX - 1 as
// MAX_ENCODABLE_NODE for exactly this. Still an out-of-range node.
info.set_focus_to_node(DomId::ROOT_ID, NodeId::new(usize::MAX - 1));
info.focus_next();
info.focus_previous();
info.focus_first();
info.focus_last();
info.clear_focus();
let changes = info.take_changes();
assert_eq!(changes.len(), 7);
for change in &changes {
assert!(matches!(change, CallbackChange::SetFocusTarget { .. }));
}
assert!(matches!(
&changes[2],
CallbackChange::SetFocusTarget {
target: FocusTarget::Next
}
));
assert!(matches!(
&changes[6],
CallbackChange::SetFocusTarget {
target: FocusTarget::NoFocus
}
));
});
}
#[test]
fn create_window_queues_window_creation() {
with_info(node_none(), |info| {
info.create_window(WindowCreateOptions::default());
let changes = info.take_changes();
assert_eq!(changes.len(), 1);
assert!(matches!(changes[0], CallbackChange::CreateNewWindow { .. }));
});
}
// ------------------------------------------------------------------
// CallbackInfo: routing
// ------------------------------------------------------------------
#[test]
fn route_getters_return_empty_strings_when_no_route_is_active() {
with_info(node_none(), |info| {
assert_eq!(info.get_route_pattern().as_str(), "");
assert_eq!(info.get_route_param(AzString::from("id")).as_str(), "");
// Malformed / hostile keys must not panic either.
assert_eq!(info.get_route_param(AzString::from("")).as_str(), "");
assert_eq!(info.get_route_param(AzString::from("\u{0}🌍")).as_str(), "");
assert_eq!(
info.get_route_param(AzString::from("k".repeat(100_000)))
.as_str(),
""
);
});
}
#[test]
fn set_route_param_without_an_active_route_queues_nothing() {
with_info(node_none(), |info| {
info.set_route_param(AzString::from("id"), AzString::from("42"));
assert!(
info.take_changes().is_empty(),
"no active route => no SwitchRoute change may be queued"
);
});
}
#[test]
fn switch_route_queues_the_pattern_verbatim() {
with_info(node_none(), |info| {
info.switch_route(
AzString::from("/user/:id"),
azul_core::window::StringPairVec::from_vec(vec![azul_core::window::AzStringPair {
key: AzString::from("id"),
value: AzString::from("42"),
}]),
);
let changes = info.take_changes();
assert_eq!(changes.len(), 1);
assert!(
matches!(&changes[0], CallbackChange::SwitchRoute { pattern, params } if pattern.as_str() == "/user/:id" && params.len() == 1)
);
});
}
// ------------------------------------------------------------------
// CallbackInfo: query APIs against an EMPTY layout window
// ------------------------------------------------------------------
#[test]
fn get_node_id_by_id_attribute_returns_none_for_hostile_ids() {
let long = "a".repeat(1_000_000);
let nested = "[".repeat(10_000);
let ids: [&str; 12] = [
"",
" ",
"\t\n",
"\u{0}",
"!@#$%^&*()",
"0",
"-0",
"9223372036854775807",
"NaN",
"inf",
" valid ",
"valid;garbage",
];
with_info(node_none(), |info| {
for id in ids {
assert_eq!(
info.get_node_id_by_id_attribute(DomId::ROOT_ID, id),
None,
"id {id:?} must not resolve in an empty layout tree"
);
}
// Unicode / combining marks / emoji.
for id in ["\u{1F600}", "e\u{301}", "🌍🌍🌍"] {
assert_eq!(info.get_node_id_by_id_attribute(DomId::ROOT_ID, id), None);
}
// Extremely long + deeply "nested" input must not hang or overflow.
assert_eq!(
info.get_node_id_by_id_attribute(DomId::ROOT_ID, &long),
None
);
assert_eq!(
info.get_node_id_by_id_attribute(DomId::ROOT_ID, &nested),
None
);
// An out-of-range DomId is a miss, not a panic.
assert_eq!(
info.get_node_id_by_id_attribute(DomId { inner: usize::MAX }, "x"),
None
);
});
}
#[test]
fn hierarchy_navigation_is_none_and_zero_on_an_empty_layout_tree() {
with_info(node_none(), |info| {
for dom in [DomId::ROOT_ID, DomId { inner: usize::MAX }] {
for node in [NodeId::new(0), NodeId::new(usize::MAX)] {
assert_eq!(info.get_parent_node(dom, node), None);
assert_eq!(info.get_next_sibling_node(dom, node), None);
assert_eq!(info.get_previous_sibling_node(dom, node), None);
assert_eq!(info.get_first_child_node(dom, node), None);
assert_eq!(info.get_last_child_node(dom, node), None);
assert_eq!(info.get_children_count(dom, node), 0);
assert_eq!(info.get_all_children_nodes(dom, node).len(), 0);
}
}
// The DomNodeId-flavoured navigation must agree.
assert_eq!(info.get_parent(node0()), None);
assert_eq!(info.get_first_child(node0()), None);
assert_eq!(info.get_last_child(node0()), None);
assert_eq!(info.get_next_sibling(node_none()), None);
assert_eq!(info.get_previous_sibling(node_none()), None);
});
}
#[test]
fn geometry_and_css_queries_are_none_on_an_empty_layout_tree() {
with_info(node0(), |info| {
assert_eq!(info.get_node_size(node0()), None);
assert_eq!(info.get_node_position(node0()), None);
assert_eq!(info.get_node_rect(node0()), None);
assert_eq!(info.get_node_hit_test_bounds(node0()), None);
assert_eq!(info.get_hit_node_rect(), None);
assert!(info.get_computed_width(node0()).is_none());
assert!(info.get_computed_height(node0()).is_none());
assert!(info
.get_computed_css_property(node_none(), CssPropertyType::Width)
.is_none());
assert!(info.get_layout_result(&DomId::ROOT_ID).is_none());
assert!(info.get_gpu_cache(&DomId::ROOT_ID).is_none());
assert_eq!(info.get_dom_ids().len(), 0);
});
}
#[test]
fn state_getters_reflect_the_construction_arguments() {
let hit = node0();
with_info(hit, |info| {
assert_eq!(info.get_hit_node(), hit);
// No cursor was supplied at construction.
assert!(info.get_cursor_relative_to_viewport().is_none());
assert!(info.get_cursor_relative_to_node().is_none());
// Native Rust callback => no FFI ctx, no GL context.
assert!(info.get_ctx().is_none());
assert!(info.get_gl_context().is_none());
// No previous frame yet.
assert!(info.get_previous_window_state().is_none());
assert!(info.get_previous_window_flags().is_none());
assert!(info.get_previous_mouse_state().is_none());
assert!(info.get_previous_keyboard_state().is_none());
assert!(matches!(
info.get_current_window_handle(),
RawWindowHandle::Unsupported
));
assert_eq!(info.get_monitors().len(), 0);
assert!(info.get_current_monitor().is_none());
assert_eq!(info.get_timer_ids().len(), 0);
assert_eq!(info.get_thread_ids().len(), 0);
assert!(info.get_timer(&TimerId { id: 0 }).is_none());
assert!(info.get_thread(&ThreadId::unique()).is_none());
// The system-time callback must be wired up and callable.
let _now = info.get_current_time();
});
}
#[test]
fn selection_and_undo_queries_are_empty_for_unknown_nodes() {
with_info(node_none(), |info| {
assert!(!info.has_any_selection());
assert_eq!(info.get_selection_count(&DomId::ROOT_ID), 0);
assert!(info.get_primary_selection(&DomId::ROOT_ID).is_none());
assert!(!info.node_has_selection(node0()));
for node in [NodeId::new(0), NodeId::new(usize::MAX)] {
assert!(!info.can_undo(node));
assert!(!info.can_redo(node));
assert!(info.get_undo_text(node).is_none());
assert!(info.get_redo_text(node).is_none());
assert!(info.inspect_undo_operation(node).is_none());
assert!(info.inspect_redo_operation(node).is_none());
}
assert!(info.get_node_text_content(node0()).is_none());
assert_eq!(info.get_node_text_length(node0()), None);
assert!(info.get_text_changeset().is_none());
assert!(!info.is_node_focused(node0()));
assert!(!info.has_focus(node0()));
assert!(info.get_focused_node().is_none());
});
}
#[test]
fn cursor_inspection_is_none_without_a_text_layout() {
with_info(node_none(), |info| {
assert!(info.inspect_move_cursor_left(node0()).is_none());
assert!(info.inspect_move_cursor_right(node0()).is_none());
assert!(info.inspect_move_cursor_up(node0()).is_none());
assert!(info.inspect_move_cursor_down(node0()).is_none());
assert!(info.inspect_move_cursor_to_line_start(node0()).is_none());
assert!(info.inspect_move_cursor_to_line_end(node0()).is_none());
assert!(info.inspect_backspace(node0()).is_none());
assert!(info.inspect_delete(node0()).is_none());
// ... and the same for a node id that does not decode at all.
assert!(info.inspect_move_cursor_left(node_none()).is_none());
assert!(info.inspect_backspace(node_none()).is_none());
});
}
#[test]
fn drag_and_gesture_queries_are_inactive_by_default() {
with_info(node_none(), |info| {
assert!(!info.is_dragging());
assert!(!info.is_drag_active());
assert!(!info.is_node_drag_active());
assert!(!info.is_file_drag_active());
assert!(info.get_drag_delta().is_none());
assert!(info.get_drag_delta_screen().is_none());
assert!(info.get_drag_delta_screen_incremental().is_none());
assert!(!info.was_double_clicked());
assert!(info.get_pen_pressure().is_none());
assert!(info.get_pen_tilt().is_none());
assert!(!info.is_pen_in_contact());
assert!(!info.is_pen_eraser());
assert!(!info.is_pen_barrel_button_pressed());
assert_eq!(info.get_drag_types().len(), 0);
assert!(info.get_drag_data("text/plain").is_none());
assert!(info.get_drag_data("").is_none());
});
}
#[test]
#[cfg(feature = "text_layout")]
fn get_loaded_font_bytes_returns_none_for_boundary_hashes() {
with_info(node_none(), |info| {
// No fonts are loaded, so every hash - including the numeric
// boundaries - must miss rather than index out of bounds.
for hash in [0u64, 1, u64::MAX, u64::MAX / 2] {
assert!(info.get_loaded_font_bytes(hash).is_none());
}
assert_eq!(info.get_loaded_fonts().len(), 0);
});
}
#[test]
#[cfg(feature = "cpurender")]
fn take_screenshot_of_a_missing_dom_is_an_error_not_a_panic() {
with_info(node_none(), |info| {
let err = info
.take_screenshot(DomId::ROOT_ID)
.expect_err("an empty layout window has no DOM to screenshot");
assert_eq!(err.as_str(), "DOM not found in layout results");
let err = info
.take_screenshot(DomId { inner: usize::MAX })
.expect_err("an out-of-range DomId must be rejected");
assert_eq!(err.as_str(), "DOM not found in layout results");
assert!(info.take_screenshot_base64(DomId::ROOT_ID).is_err());
});
}
// ------------------------------------------------------------------
// CallbackChange payload smoke test
// ------------------------------------------------------------------
#[test]
fn callback_change_is_debug_and_clone() {
let change = CallbackChange::ScrollTo {
dom_id: DomId::ROOT_ID,
node_id: NodeHierarchyItemId::NONE,
position: LogicalPosition::new(f32::NAN, 0.0),
unclamped: true,
};
let cloned = change.clone();
assert!(matches!(
cloned,
CallbackChange::ScrollTo { unclamped: true, .. }
));
assert!(!format!("{change:?}").is_empty());
}
}