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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech
use std::any::{Any, TypeId};
use std::collections::HashMap;
use std::rc::Rc;
use std::time::{Duration, Instant};
use teksilo_canvas::SizeProposal;
use teksilo_core::Theme;
use teksilo_core::app_event::AppEvent;
use teksilo_core::event::WidgetEvent;
use teksilo_core::event_source::{
AppEventPoster, EventSource, EventSourceAdapter, SubscriptionId, TreeAppContext,
};
use teksilo_core::modal::{ModalCloseBehavior, ModalContent, ModalPresentation, ModalRequest};
use teksilo_core::{DismissBehavior, OverlayLayer, OverlayPlacement, OverlayRequest};
use teksilo_core::{WidgetId, WidgetTree};
use teksilo_i18n::{I18nConfig, I18nManager, LanguageIdentifier};
use teksilo_platform::event_translation;
use winit::application::ApplicationHandler;
use winit::event::{StartCause, WindowEvent};
use winit::event_loop::{ActiveEventLoop, ControlFlow};
#[allow(unused_imports)]
use winit::raw_window_handle::HasWindowHandle;
use winit::window::WindowId;
/// How the application resolves its theme.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ThemeMode {
/// Use a specific fixed theme (current behavior, default).
#[default]
Manual,
/// Follow the OS light/dark preference using Teksilo's built-in themes.
FollowSystem,
/// Adopt colors read directly from the OS/DE config files (GNOME/KDE/Cinnamon).
/// Falls back to `FollowSystem` on unsupported platforms or DEs.
Native,
}
#[cfg(feature = "text")]
use teksilo_text::SharedTypesetter;
use crate::window_config::{SizeToContent, TeksiloWindowId, WindowConfig};
use crate::window_manager::WindowManager;
use teksilo_core::WindowPlacement;
/// Interrogate the winit window for its current placement so an
/// `OS-initiated` state change can be mirrored into the corresponding
/// `WindowState::placement` signal without the observer pushing it
/// back out as a `WindowCommand` (re-entrancy guard on `from_os`).
fn query_window_placement(win: &winit::window::Window) -> WindowPlacement {
if win.is_minimized() == Some(true) {
WindowPlacement::Minimized
} else if win.fullscreen().is_some() {
WindowPlacement::Fullscreen
} else if win.is_maximized() {
WindowPlacement::Maximized
} else {
WindowPlacement::Floating
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ResolvedModalPresentation {
InTree,
NativeWindow,
}
/// Generate a per-process random session id for telemetry.
///
/// Not persisted across restarts — by design (a stable id would be
/// pseudonymous tracking, distinct from `InstallId`'s 13-month UUID).
/// The first 16 hex chars of a fresh UUID are sufficient for grouping
/// events within one process lifetime.
#[cfg(feature = "telemetry")]
fn generate_session_id() -> String {
let uuid = uuid::Uuid::new_v4().simple().to_string();
uuid[..16].to_string()
}
fn resolve_modal_presentation(
requested: ModalPresentation,
content: &ModalContent,
native_supported: bool,
) -> ResolvedModalPresentation {
let can_use_native = native_supported && matches!(content, ModalContent::Deferred(_));
match requested {
ModalPresentation::InTree => ResolvedModalPresentation::InTree,
ModalPresentation::NativeWindow => {
if can_use_native {
ResolvedModalPresentation::NativeWindow
} else {
ResolvedModalPresentation::InTree
}
}
ModalPresentation::Auto => {
if can_use_native {
ResolvedModalPresentation::NativeWindow
} else {
ResolvedModalPresentation::InTree
}
}
}
}
fn modal_close_behavior_to_overlay_dismiss(behavior: ModalCloseBehavior) -> DismissBehavior {
match behavior {
ModalCloseBehavior::ClickOutside => DismissBehavior::ClickOutside,
ModalCloseBehavior::EscapeKey => DismissBehavior::EscapeKey,
ModalCloseBehavior::EscapeOrClickOutside => DismissBehavior::EscapeOrClickOutside,
ModalCloseBehavior::Manual => DismissBehavior::Manual,
}
}
fn present_in_tree_modal_request(
tree: &mut WidgetTree,
source_widget: WidgetId,
request: ModalRequest,
) {
let dismiss = modal_close_behavior_to_overlay_dismiss(request.close_behavior);
let requested_focus = request.focus_target;
let user_on_dismiss = request.on_dismiss;
let close_behavior = request.close_behavior;
// Capture the focus owner BEFORE the modal moves focus into itself
// (below). Recorded as the modal overlay's `focus_restore` so that
// dismissing the dialog returns keyboard focus to the trigger — e.g.
// tabbing to a "Rename…" button, opening the InputDialog, then
// accepting/cancelling lands back on that button. Without this, the
// modal shows via `show_overlay` (which, unlike
// `show_overlay_from_source`, records no restore target) and focus is
// dropped on dismiss.
let focus_before_modal = tree.focused();
// Capture the `:focus-visible` input modality at the same instant. A
// modal is a transient interruption: when it closes and focus snaps
// back to the trigger, the trigger's focus ring should look exactly as
// it did before the modal opened — NOT inherit keyboard modality from
// input directed *at the dialog* (typing a name, pressing Enter to
// accept). Without restoring this, mouse-clicking the trigger then
// pressing Enter inside the dialog leaves the global modality "keyboard"
// and the trigger sprouts a focus ring it never had. We restore it on
// dismiss alongside focus. (`focus_ops` itself never touches this
// signal, so the value we restore is the value that sticks.)
let focus_visible_before = tree.focus_visible_signal().get();
let focus_visible_signal = tree.focus_visible_signal();
let content_id = match request.content {
ModalContent::ExistingWidget(id) => id,
ModalContent::Deferred(builder) => {
let id = builder(tree);
tree.set_dormant(id);
id
}
};
// Mount the dialog scrim FIRST so it z-orders below the modal
// panel in the overlay stack. The scrim chrome (a full-viewport
// dim) comes from the active `DialogStyle::make_scrim`; clicks on
// it dismiss the modal when its `ModalCloseBehavior` permits
// click-outside dismissal. The framework patches the scrim's
// `parent_overlay` after the modal is pushed so that dismissing
// the modal cascades through and also dismisses the scrim.
let click_to_dismiss = matches!(
close_behavior,
ModalCloseBehavior::ClickOutside | ModalCloseBehavior::EscapeOrClickOutside,
);
let dismiss_target: std::rc::Rc<std::cell::Cell<Option<teksilo_core::overlay::OverlayId>>> =
std::rc::Rc::new(std::cell::Cell::new(None));
let scrim_id = tree.add(
teksilo_widgets::ModalScrim::new()
.dismiss_target(dismiss_target.clone())
.click_to_dismiss(click_to_dismiss),
);
let scrim_overlay = tree.show_overlay(OverlayRequest {
content_id: scrim_id,
anchor: source_widget,
placement: OverlayPlacement::FullViewport,
dismiss: DismissBehavior::Manual,
layer: OverlayLayer::InTree,
parent_overlay: None,
on_dismiss: None,
fade_duration: None,
});
tree.activate(content_id);
// Wrap the caller's `on_dismiss` so the framework also restores the
// pre-modal `:focus-visible` modality when the dialog closes (by any
// path: OK, Cancel, Escape, click-outside). Only when a focus owner
// was captured — if nothing was focused before, there's no prior state
// to return to. The overlay fires `on_dismiss` during dismissal, just
// before focus is restored to the trigger, so the value we set here is
// the one the trigger paints with.
let restore_modality = focus_before_modal.is_some();
let on_dismiss: Option<teksilo_core::overlay::OverlayDismissCallback> =
if restore_modality || user_on_dismiss.is_some() {
Some(std::rc::Rc::new(move || {
if restore_modality {
focus_visible_signal.set(focus_visible_before);
}
if let Some(cb) = &user_on_dismiss {
cb();
}
}))
} else {
None
};
// Present the modal as a WINDOW-LEVEL overlay via `show_overlay` rather than
// `show_overlay_from_source`: the latter re-parents the overlay to the source
// widget's overlay ancestor, so a modal opened from a menu item would be
// trapped in (and positioned relative to) the transient menu overlay instead
// of centering on the window. `Centered` already ignores the anchor; keeping
// `parent_overlay: None` makes it center on the viewport.
let modal_overlay = tree.show_overlay(OverlayRequest {
content_id,
anchor: source_widget,
placement: OverlayPlacement::Centered,
dismiss,
layer: OverlayLayer::InTree,
parent_overlay: None,
on_dismiss,
fade_duration: None,
});
// The modal is now the topmost overlay; record where focus should
// return when it dismisses. Mirrors `show_overlay_from_source`'s
// capture-then-set-top pattern. The `is_active` guard on the restore
// side makes a stale id (e.g. a menu trigger that went dormant) a
// graceful no-op.
if let Some(restore) = focus_before_modal {
tree.overlay_manager_mut().set_top_focus_restore(restore);
}
// Cascade-dismiss the scrim when the modal is dismissed (by any
// path: Escape, click-outside, manual). The scrim is below the
// modal in the stack but counts as its "child" in the parent-
// overlay graph, so `dismiss_immediate` walks the descendants and
// dismisses it too.
tree.overlay_manager_mut()
.set_parent_overlay(scrim_overlay, Some(modal_overlay));
// Fill in the dismiss target NOW that the modal id is known. The
// scrim's on-tap reads through this `Cell` at click time.
dismiss_target.set(Some(modal_overlay));
let focus_target = requested_focus
.filter(|id| tree.is_active(*id) && tree.is_descendant_of(*id, content_id))
.or_else(|| tree.widget_initial_focus_hint(content_id))
.or_else(|| tree.first_focusable_descendant(content_id));
if let Some(id) = focus_target {
tree.focus(id);
}
}
fn apply_cursor_to_window(
platform_window: &teksilo_platform::PlatformWindow,
cursor: teksilo_core::CursorIcon,
) {
let winit_cursor = match cursor {
teksilo_core::CursorIcon::Default => winit::window::CursorIcon::Default,
teksilo_core::CursorIcon::Pointer => winit::window::CursorIcon::Pointer,
teksilo_core::CursorIcon::Text => winit::window::CursorIcon::Text,
teksilo_core::CursorIcon::Crosshair => winit::window::CursorIcon::Crosshair,
teksilo_core::CursorIcon::Move => winit::window::CursorIcon::Move,
teksilo_core::CursorIcon::NotAllowed => winit::window::CursorIcon::NotAllowed,
teksilo_core::CursorIcon::Grab => winit::window::CursorIcon::Grab,
teksilo_core::CursorIcon::Grabbing => winit::window::CursorIcon::Grabbing,
teksilo_core::CursorIcon::ColResize => winit::window::CursorIcon::ColResize,
teksilo_core::CursorIcon::RowResize => winit::window::CursorIcon::RowResize,
teksilo_core::CursorIcon::NeswResize => winit::window::CursorIcon::NeswResize,
teksilo_core::CursorIcon::NwseResize => winit::window::CursorIcon::NwseResize,
};
platform_window.window().set_cursor(winit_cursor);
}
#[derive(Debug)]
struct IdleTrace {
last_report: Instant,
resume_time_reached: u64,
redraw_requested: u64,
rendered_frames: u64,
request_redraw_all: u64,
cursor_redraw_requests: u64,
mouse_input_redraw_requests: u64,
mouse_wheel_redraw_requests: u64,
keyboard_redraw_requests: u64,
resize_redraw_requests: u64,
/// Post-render redraw requests caused by `tree.frame_requested()`
/// (a widget asked for another frame from a `frame_tick` effect or
/// similar). Surfaces the only redraw source that was previously
/// invisible to the trace.
frame_request_redraws: u64,
/// Windows poked by `WindowManager::request_redraw_needing_render`
/// (a sibling window dirtied by another window's `Signal` mutation),
/// distinct from `request_redraw_all` — surfaces how often the
/// targeted cross-window path actually fires versus the blanket one.
cross_window_redraws: u64,
idle_callbacks_run: u64,
control_flow_wait: u64,
control_flow_wait_until: u64,
timer_windows: usize,
animation_timers: usize,
tooltip_timers: usize,
}
impl IdleTrace {
fn from_env() -> Option<Self> {
match std::env::var("TEKSILO_IDLE_TRACE") {
Ok(value) if value != "0" && !value.is_empty() => Some(Self {
last_report: Instant::now(),
resume_time_reached: 0,
redraw_requested: 0,
rendered_frames: 0,
request_redraw_all: 0,
cursor_redraw_requests: 0,
mouse_input_redraw_requests: 0,
mouse_wheel_redraw_requests: 0,
keyboard_redraw_requests: 0,
resize_redraw_requests: 0,
frame_request_redraws: 0,
cross_window_redraws: 0,
idle_callbacks_run: 0,
control_flow_wait: 0,
control_flow_wait_until: 0,
timer_windows: 0,
animation_timers: 0,
tooltip_timers: 0,
}),
_ => None,
}
}
fn note_control_flow(
&mut self,
has_deadline: bool,
timer_windows: usize,
animation_timers: usize,
tooltip_timers: usize,
) {
if has_deadline {
self.control_flow_wait_until += 1;
} else {
self.control_flow_wait += 1;
}
self.timer_windows = timer_windows;
self.animation_timers = animation_timers;
self.tooltip_timers = tooltip_timers;
self.maybe_report();
}
fn note_request_redraw_all(&mut self) {
self.request_redraw_all += 1;
self.maybe_report();
}
fn note_redraw_request(&mut self, reason: &'static str) {
match reason {
"cursor" => self.cursor_redraw_requests += 1,
"mouse_input" => self.mouse_input_redraw_requests += 1,
"mouse_wheel" => self.mouse_wheel_redraw_requests += 1,
"keyboard" => self.keyboard_redraw_requests += 1,
"resize" => self.resize_redraw_requests += 1,
_ => {}
}
self.maybe_report();
}
fn note_cross_window_redraw(&mut self, windows: usize) {
self.cross_window_redraws += windows as u64;
self.maybe_report();
}
fn note_resume_time_reached(&mut self) {
self.resume_time_reached += 1;
self.maybe_report();
}
fn note_redraw_requested(&mut self) {
self.redraw_requested += 1;
self.maybe_report();
}
fn note_rendered_frame(&mut self) {
self.rendered_frames += 1;
self.maybe_report();
}
fn note_idle_callbacks_run(&mut self) {
self.idle_callbacks_run += 1;
self.maybe_report();
}
fn maybe_report(&mut self) {
if self.last_report.elapsed() < Duration::from_secs(1) {
return;
}
eprintln!(
"teksilo_idle_trace redraw_requested={} rendered_frames={} resume_time_reached={} request_redraw_all={} cross_window_redraws={} input_redraws={{cursor:{},mouse_input:{},mouse_wheel:{},keyboard:{},resize:{},frame_request:{}}} idle_callbacks={} control_flow={{wait:{},wait_until:{}}} timers={{windows:{},animations:{},tooltips:{}}}",
self.redraw_requested,
self.rendered_frames,
self.resume_time_reached,
self.request_redraw_all,
self.cross_window_redraws,
self.cursor_redraw_requests,
self.mouse_input_redraw_requests,
self.mouse_wheel_redraw_requests,
self.keyboard_redraw_requests,
self.resize_redraw_requests,
self.frame_request_redraws,
self.idle_callbacks_run,
self.control_flow_wait,
self.control_flow_wait_until,
self.timer_windows,
self.animation_timers,
self.tooltip_timers,
);
self.last_report = Instant::now();
self.resume_time_reached = 0;
self.redraw_requested = 0;
self.rendered_frames = 0;
self.request_redraw_all = 0;
self.cross_window_redraws = 0;
self.cursor_redraw_requests = 0;
self.mouse_input_redraw_requests = 0;
self.mouse_wheel_redraw_requests = 0;
self.keyboard_redraw_requests = 0;
self.resize_redraw_requests = 0;
self.frame_request_redraws = 0;
self.idle_callbacks_run = 0;
self.control_flow_wait = 0;
self.control_flow_wait_until = 0;
}
}
/// An app-supplied router for [`AppEvent::External`] payloads that need to
/// perform **window operations** — open a window, focus one, look one up by its
/// string id.
///
/// Registered with [`TeksiloAppBuilder::on_external_with_ctx`]. Returns `true`
/// to say "this payload was mine"; `false` leaves it unclaimed.
///
/// The plain [`on_app_event`](TeksiloAppBuilder::on_app_event) hook receives only
/// `&AppEvent` — no tree, no [`WindowOps`](teksilo_core::WindowOps) — so a handler
/// there cannot call `open_window` at all: `EventContext::open_window` panics on a
/// standalone context. This one runs against a real window's tree with a real ops
/// sink, which is what makes the multi-window recipes in `docs/multi-window.md`
/// reachable from a background thread (a single-instance app's IPC listener being
/// the motivating case: a second launch forwards its command line and the running
/// process opens the document window).
pub type ExternalCtxHandler =
Box<dyn FnMut(&(dyn std::any::Any + Send), &mut teksilo_core::widget::EventContext) -> bool>;
struct TeksiloAppHandler {
wm: WindowManager,
app_event_handler: Option<Box<dyn FnMut(&AppEvent)>>,
/// App-supplied `AppEvent::External` router with window ops — see
/// [`ExternalCtxHandler`]. Consulted only for payloads no framework router
/// and no built-in downcast arm claimed.
external_ctx_handler: Option<ExternalCtxHandler>,
initial_window: Option<WindowConfig>,
initial_created: bool,
idle_budget: Duration,
idle_trace: Option<IdleTrace>,
#[cfg(feature = "text")]
typesetter: SharedTypesetter,
/// Kept alive for the lifetime of the event loop so that the
/// `notify::RecommendedWatcher` background thread keeps running.
/// Created in `TeksiloAppBuilder::run` when the `I18nConfig` registers
/// any `runtime_override`s; otherwise `None`.
_i18n_watcher: Option<teksilo_i18n::FtlFileWatcher>,
/// Kept alive for the lifetime of the event loop so that the
/// settings directory watcher's background thread keeps running.
/// Created in `TeksiloAppBuilder::run` when a settings bundle was
/// opened and live-reload was not disabled; otherwise `None`.
_settings_watcher: Option<teksilo_settings::SettingsWatcher>,
/// Optional per-loop-turn closure (e.g. an async executor poll) installed
/// via [`TeksiloAppBuilder::on_loop_tick`]. Runs at the top of
/// `about_to_wait`; returning `true` means tasks advanced and a repaint is
/// needed. Async-agnostic — the loop only ever sees `FnMut`.
loop_tick: Option<Box<dyn FnMut() -> bool>>,
/// Shared flag a `loop_tick` owner sets while it wants continuous polling.
/// Read in `update_control_flow` to force `ControlFlow::Poll`; when clear,
/// the loop sleeps until the next event (off-thread wakes via the proxy).
loop_tick_poll: Option<std::rc::Rc<std::cell::Cell<bool>>>,
}
impl TeksiloAppHandler {
fn new(
theme: Theme,
theme_mode: ThemeMode,
app_event_handler: Option<Box<dyn FnMut(&AppEvent)>>,
initial_window: WindowConfig,
app_context_template: Option<std::rc::Rc<TreeAppContext>>,
#[cfg(feature = "text")] typesetter: SharedTypesetter,
i18n_watcher: Option<teksilo_i18n::FtlFileWatcher>,
settings_watcher: Option<teksilo_settings::SettingsWatcher>,
event_proxy: AppEventProxy,
) -> Self {
let mut wm = WindowManager::new(theme);
wm.set_theme_mode(theme_mode);
wm.set_event_proxy(event_proxy);
if let Some(template) = app_context_template {
// Seed the persisted user text-scale factor (if settings are
// installed) so every initially-created window opens at the saved
// scale. No per-app boilerplate: apps without settings stay at 1.0.
if let Some(store) = template.app_state::<teksilo_settings::SettingsStore>() {
let scale = store.signal_for(&teksilo_settings::TEXT_SCALE_KEY).get();
wm.set_initial_text_scale(scale);
}
wm.set_app_context_template(template);
}
#[cfg(feature = "text")]
{
wm.set_typesetter(typesetter.clone());
}
Self {
wm,
app_event_handler,
external_ctx_handler: None,
initial_window: Some(initial_window),
initial_created: false,
idle_budget: Duration::from_millis(4),
idle_trace: IdleTrace::from_env(),
#[cfg(feature = "text")]
typesetter,
_i18n_watcher: i18n_watcher,
_settings_watcher: settings_watcher,
loop_tick: None,
loop_tick_poll: None,
}
}
fn process_pending(&mut self, event_loop: &ActiveEventLoop) {
self.wm.process_pending(event_loop);
}
fn process_modal_requests(&mut self, event_loop: &ActiveEventLoop) -> bool {
let native_supported = teksilo_platform::supports_native_modal_windows();
let requests = self.wm.drain_pending_modal_requests();
let had_requests = !requests.is_empty();
for (source_window, requests) in requests {
for queued in requests {
let resolved = resolve_modal_presentation(
queued.request.presentation,
&queued.request.content,
native_supported,
);
match resolved {
ResolvedModalPresentation::InTree => {
if let Some(managed) = self.wm.get_by_teksilo_mut(source_window) {
present_in_tree_modal_request(
&mut managed.tree,
queued.source_widget,
queued.request,
);
}
}
ResolvedModalPresentation::NativeWindow => {
let ModalRequest {
content,
title,
size,
focus_target,
..
} = queued.request;
let ModalContent::Deferred(builder) = content else {
continue;
};
let mut config =
WindowConfig::new().modal(crate::window_config::ModalConfig {
parent: source_window,
focus_target,
});
if let Some(title) = title {
config = config.title(title);
}
if let Some((width, height)) = size {
// Native modals size their height to content: the
// requested (width, height) is the floor and the OS
// window grows to fit taller content (e.g. a
// MessageBox "Show details" expander). Without this
// the fixed height clips content that exceeds it —
// the footer buttons fall below the client edge and
// stop receiving clicks. NOTE: deliberately NOT
// `resizable(false)` — winit encodes that as
// min==max size hints on X11, which would clamp away
// the programmatic growth this relies on.
config = config
.size(width, height)
.min_size(width, height)
.size_to_content(SizeToContent::Height);
}
self.wm.create_window(
config.root(move |tree, _state| builder(tree)),
event_loop,
);
}
}
}
}
had_requests
}
fn process_modal_dismissals(&mut self) -> bool {
let windows_to_close = self.wm.drain_pending_modal_dismissals();
let had_dismissals = !windows_to_close.is_empty();
for window_id in windows_to_close {
self.wm.queue_close(window_id);
}
had_dismissals
}
fn maybe_exit(&self, event_loop: &ActiveEventLoop) {
if self.wm.is_empty() {
event_loop.exit();
}
}
fn update_control_flow(&mut self, event_loop: &ActiveEventLoop) {
// Tick time-driven gesture recognizers (long-press) on every tree
// before computing the next deadline. Without this, a long-press
// that expired between frames would never fire until the next
// unrelated pointer event. Handlers that run may emit commands
// and mark nodes dirty — request a redraw on those windows.
let now = Instant::now();
// Collect winit ids up front so we can safely iterate without
// holding a borrow on `self.wm.windows` across the
// `tick_gestures_in_window` calls (each of which briefly
// takes a window out of the map).
let winit_ids: Vec<_> = self.wm.windows_map().keys().copied().collect();
for winit_id in winit_ids {
let before = self
.wm
.get_by_winit_mut(winit_id)
.map(|m| m.tree.has_idle_work())
.unwrap_or(false);
self.tick_gestures_in_window(winit_id, now, event_loop);
if let Some(managed) = self.wm.get_by_winit_mut(winit_id)
&& managed.tree.has_idle_work() != before
{
managed.platform_window.request_redraw();
}
}
let mut earliest_deadline: Option<Instant> = None;
let mut timer_windows = 0_usize;
let mut animation_timers = 0_usize;
let mut tooltip_timers = 0_usize;
for managed in self.wm.iter() {
let animation_count = managed.tree.active_animation_count();
let tooltip_count = managed.tree.pending_tooltip_count();
if animation_count > 0 || tooltip_count > 0 {
timer_windows += 1;
}
animation_timers += animation_count;
tooltip_timers += tooltip_count;
// `next_timer_deadline` now folds in the per-frame-effect
// path's fixed 60 Hz deadline (Pulse / Cycle / caret blink /
// drag auto-scroll) alongside the tween + shader schedulers,
// so continuous animations pace through `WaitUntil` below
// instead of forcing `ControlFlow::Poll` (which free-ran at
// the display's refresh rate — 300 fps on a 300 Hz panel).
if let Some(deadline) = managed.tree.next_timer_deadline() {
earliest_deadline = Some(match earliest_deadline {
Some(current) => current.min(deadline),
None => deadline,
});
}
}
// The ONLY remaining consumer that forces true `ControlFlow::Poll`:
// an installed loop-tick owner (e.g. the `teksilo-async` executor)
// with runnable work. Async task processing wants to run as fast as
// possible and is not an animation, so it is deliberately *not*
// 60 Hz-capped. Every per-frame *animation* effect now paces through
// the `WaitUntil` deadline instead.
let force_poll = self.loop_tick_poll.as_ref().is_some_and(|poll| poll.get());
if force_poll {
event_loop.set_control_flow(ControlFlow::Poll);
} else if let Some(deadline) = earliest_deadline {
event_loop.set_control_flow(ControlFlow::WaitUntil(deadline));
} else {
event_loop.set_control_flow(ControlFlow::Wait);
}
if let Some(trace) = &mut self.idle_trace {
trace.note_control_flow(
earliest_deadline.is_some(),
timer_windows,
animation_timers,
tooltip_timers,
);
}
}
fn post_event(&mut self, event_loop: &ActiveEventLoop) {
// App-wide environment changes (theme / locale) raised by a handler
// in one window fan out to every window's tree, marking the
// non-originating windows dirty. Those windows never received the
// triggering event, so they would otherwise stay un-repainted —
// `request_redraw_all()` below (gated on these flags) fixes that.
let had_locale = self.wm.drain_pending_locale_requests();
let had_theme = self.wm.drain_pending_theme_requests();
let had_follow_system = self.wm.drain_pending_follow_system_requests();
let had_text_scale = self.wm.drain_pending_text_scale_requests();
let had_commands = self.wm.drain_close_window_requests();
let had_modal_requests = self.process_modal_requests(event_loop);
let had_modal_dismissals = self.process_modal_dismissals();
self.process_pending(event_loop);
// Drain post-mount actions (e.g. a WebView opening its native engine
// subview, which needs the OS parent handle only reachable here).
self.process_pending_mount_actions(event_loop);
// Drain per-window command queues: app-side writes to
// WindowState signals emitted WindowCommand values that the
// registry routes through the per-window queue. Translate each
// into the appropriate winit call.
self.wm.drain_window_commands();
if had_locale
|| had_theme
|| had_follow_system
|| had_text_scale
|| had_commands
|| had_modal_requests
|| had_modal_dismissals
{
if let Some(trace) = &mut self.idle_trace {
trace.note_request_redraw_all();
}
self.wm.request_redraw_all();
}
// Targeted counterpart to the blanket call above: a handler may have
// mutated an app-level `Signal` that sibling windows also read,
// dirtying their trees without those windows ever seeing the
// triggering event. See `WindowManager::request_redraw_needing_render`
// for why this is filtered rather than another `request_redraw_all()`.
let cross_window_redraws = self.wm.request_redraw_needing_render();
if cross_window_redraws > 0
&& let Some(trace) = &mut self.idle_trace
{
trace.note_cross_window_redraw(cross_window_redraws);
}
self.maybe_exit(event_loop);
self.update_control_flow(event_loop);
}
/// Dispatch a widget event into the named window's `WidgetTree`
/// with a real [`teksilo_core::WindowOps`] sink so handlers can
/// synchronously `open_window`, `focus_window`, etc.
///
/// Re-entry pattern: the current `ManagedWindow` is temporarily
/// removed from `WindowManager::windows` before dispatch and put
/// back afterwards. The removed tree is borrowed mutably for the
/// handler run; the `WindowOpsImpl` holds `&mut WindowManager`
/// (with the tree out of the way) plus `&ActiveEventLoop`. Opening
/// a new window from a handler therefore goes straight into
/// `wm.create_window` without borrow-checker conflicts.
fn dispatch_in_window(
&mut self,
window_id: WindowId,
event: WidgetEvent,
event_loop: &ActiveEventLoop,
) {
let Some(mut current) = self.wm.take_managed(window_id) else {
return;
};
let current_id = current.teksilo_id;
#[cfg(not(target_os = "macos"))]
let current_handle = current
.platform_window
.window()
.window_handle()
.ok()
.map(|h| h.as_raw());
let current_arc = Some(current.platform_window.window_arc());
{
let mut ops = crate::window_manager::WindowOpsImpl::new(
&mut self.wm,
event_loop,
current_id,
#[cfg(not(target_os = "macos"))]
current_handle,
current_arc,
);
current.tree.dispatch_event_with_ops(event, &mut ops);
}
Self::reconcile_ime(&mut current);
self.wm.reinsert_managed(window_id, current);
}
/// Apply a [`MenubarAction`](teksilo_core::window::MenubarAction)
/// decision from a window-level menubar dispatcher. Takes the
/// managed window aside the same way
/// [`Self::dispatch_in_window`] does so the action runs with
/// `WindowOps` wired up (focus changes need to repaint, etc.).
///
/// - `OpenMenu`: focus the trigger and synthesise a primary click
/// on it. The MenuBarTrigger's `on_tap` handler then runs the
/// normal `MenuContext::open_at` path.
/// - `FocusTrigger`: focus the trigger and stop. Matches Win32
/// F10 behaviour (menubar mode, no menu).
/// - `Intercept`: do nothing — the key was swallowed.
fn apply_menubar_action(
&mut self,
window_id: WindowId,
action: teksilo_core::window::MenubarAction,
event_loop: &ActiveEventLoop,
) {
use teksilo_core::window::MenubarAction;
let Some(mut current) = self.wm.take_managed(window_id) else {
return;
};
let current_id = current.teksilo_id;
#[cfg(not(target_os = "macos"))]
let current_handle = current
.platform_window
.window()
.window_handle()
.ok()
.map(|h| h.as_raw());
let current_arc = Some(current.platform_window.window_arc());
// For a collapsed (hamburger) MenuBar, the action carries a
// `reveal` closure. We must run it (it shows the bar as a
// floating overlay) and then re-layout synchronously, so the
// trigger has valid bounds before we focus / synthesise the
// click on it. Compute the same layout proposal the redraw
// path uses.
let proposal = {
let size = current.platform_window.surface_size();
let sf = current.platform_window.scale_factor() as f32;
SizeProposal::exact(size.0 as f32 / sf, size.1 as f32 / sf)
};
{
let mut ops = crate::window_manager::WindowOpsImpl::new(
&mut self.wm,
event_loop,
current_id,
#[cfg(not(target_os = "macos"))]
current_handle,
current_arc,
);
match action {
MenubarAction::Intercept => {}
MenubarAction::FocusTrigger { trigger_id, reveal } => {
if let Some(reveal) = reveal {
current
.tree
.run_with_event_context(&mut ops, |ctx| reveal(ctx));
current.tree.layout_with_ops(proposal, &mut ops);
}
current.tree.focus_ops(trigger_id, &mut ops);
}
MenubarAction::OpenMenu { trigger_id, reveal } => {
if let Some(reveal) = reveal {
current
.tree
.run_with_event_context(&mut ops, |ctx| reveal(ctx));
current.tree.layout_with_ops(proposal, &mut ops);
}
current.tree.focus_ops(trigger_id, &mut ops);
let pointer = current.tree.bounds(trigger_id).center();
current.tree.dispatch_event_with_ops(
WidgetEvent::PointerDown {
position: pointer,
button: teksilo_core::event::PointerButton::Primary,
modifiers: teksilo_core::event::Modifiers::NONE,
},
&mut ops,
);
current.tree.dispatch_event_with_ops(
WidgetEvent::PointerUp {
position: pointer,
button: teksilo_core::event::PointerButton::Primary,
modifiers: teksilo_core::event::Modifiers::NONE,
},
&mut ops,
);
}
}
}
Self::reconcile_ime(&mut current);
self.wm.reinsert_managed(window_id, current);
}
/// Bring the winit window's OS-IME state in line with the focused
/// widget's descriptor. Enablement + purpose are declarative: a focused
/// text widget carries `Some(ImeContext { purpose })`, everything else
/// `None`. Applied only on change vs. the per-window cache — repeated
/// `set_ime_allowed(true)` can cancel an active composition. The caret
/// area is reported separately (and idempotently) by the focused widget
/// via `WindowOps::set_ime_cursor_area`.
fn reconcile_ime(managed: &mut crate::window_manager::ManagedWindow) {
match managed.tree.ime_context_for_focused() {
Some(ctx) => {
if managed.ime_purpose != Some(ctx.purpose) {
managed
.platform_window
.window()
.set_ime_purpose(Self::map_ime_purpose(ctx.purpose));
managed.ime_purpose = Some(ctx.purpose);
}
if managed.ime_allowed != Some(true) {
managed.platform_window.window().set_ime_allowed(true);
managed.ime_allowed = Some(true);
}
}
None => {
if managed.ime_allowed != Some(false) {
managed.platform_window.window().set_ime_allowed(false);
managed.ime_allowed = Some(false);
// Force the purpose to re-apply when IME is next enabled.
managed.ime_purpose = None;
}
}
}
}
/// Map the core `ImePurpose` onto winit's enum at the platform boundary.
fn map_ime_purpose(purpose: teksilo_core::ImePurpose) -> winit::window::ImePurpose {
match purpose {
teksilo_core::ImePurpose::Normal => winit::window::ImePurpose::Normal,
teksilo_core::ImePurpose::Password => winit::window::ImePurpose::Password,
teksilo_core::ImePurpose::Terminal => winit::window::ImePurpose::Terminal,
}
}
/// Run `f` against window `winit_id`'s tree with a real
/// [`WindowOps`](teksilo_core::WindowOps) sink (so `open_window`,
/// `parent_window_handle`, etc. work). Encapsulates the take-out /
/// build-`WindowOpsImpl` / reinsert dance that the `AppEvent::External`
/// routers and the mount-action drain all share — keeping the reinsert
/// (whose omission silently freezes a window) in exactly one place.
/// No-op if `winit_id` is not a managed window.
/// Route a debug-bridge [`AutomationPayload`](crate::automation_bridge::AutomationPayload):
/// resolve the target window, then run the op against the live tree
/// (and, for screenshots, the live `PlatformWindow`). `list_windows` and
/// `screenshot` are served here (they need the window manager / platform
/// window); everything else goes through [`teksilo_automation::execute`]
/// with a real `WindowOps`. The settle runs synchronously on this (the
/// main) thread, never across a frame boundary.
#[cfg(all(feature = "automation", debug_assertions))]
fn try_route_automation_payload(
&mut self,
payload: Box<dyn std::any::Any + Send>,
event_loop: &ActiveEventLoop,
) -> Result<(), Box<dyn std::any::Any + Send>> {
use teksilo_automation::dto::{AutomationOp, AutomationReply, WindowInfo, codes};
let payload = *payload.downcast::<crate::automation_bridge::AutomationPayload>()?;
// Resolve target window: explicit id, else focused, else primary.
let bid = match payload.window_id {
Some(raw) => crate::window_config::TeksiloWindowId::new(raw),
None => self
.wm
.iter()
.find(|m| m.focused)
.map(|m| m.teksilo_id)
.unwrap_or_else(|| self.wm.primary_window_id()),
};
let Some(winit_id) = self.wm.winit_id_for_teksilo(bid) else {
let _ = payload
.reply_tx
.send(AutomationReply::err(codes::NOT_FOUND, "no such window"));
return Ok(());
};
// `list_windows` is served straight from the window manager.
if matches!(payload.op, AutomationOp::ListWindows) {
let windows: Vec<WindowInfo> = self
.wm
.iter()
.map(|m| WindowInfo {
id: m.teksilo_id.raw(),
label: m.string_id.clone(),
title: Some(m.state.title().get()),
focused: m.focused,
})
.collect();
let _ = payload.reply_tx.send(AutomationReply::ok_json(&windows));
return Ok(());
}
// Screenshots reach the `ManagedWindow` (tree + platform window).
if matches!(payload.op, AutomationOp::Screenshot { .. }) {
self.automation_screenshot(winit_id, event_loop, &payload);
return Ok(());
}
// Everything else: a per-tree op with a real `WindowOps`.
let crate::automation_bridge::AutomationPayload {
op,
settle,
reply_tx,
..
} = payload;
// Clamp the settle: this runs on the winit main thread, so an
// unbounded wait/settle would freeze the live UI (see Risk 1).
let settle = crate::automation_bridge::clamp_live_settle(&settle);
self.run_in_window(winit_id, event_loop, move |tree, ops| {
let reply = teksilo_automation::execute(tree, ops, &op, &settle);
let _ = reply_tx.send(reply);
});
if let Some(m) = self.wm.windows_map().get(&winit_id) {
m.platform_window.request_redraw();
}
Ok(())
}
/// The screenshot arm of the automation bridge: take the window out of
/// the manager (so we can borrow both its tree and its platform window),
/// settle, render, capture offscreen, reinsert, then reply with a
/// base64-PNG.
#[cfg(all(feature = "automation", debug_assertions))]
fn automation_screenshot(
&mut self,
winit_id: winit::window::WindowId,
event_loop: &ActiveEventLoop,
payload: &crate::automation_bridge::AutomationPayload,
) {
use teksilo_automation::dto::{AutomationOp, AutomationReply, codes};
let node = match &payload.op {
AutomationOp::Screenshot { node } => *node,
_ => None,
};
let Some(mut current) = self.wm.take_managed(winit_id) else {
let _ = payload
.reply_tx
.send(AutomationReply::err(codes::NOT_FOUND, "window vanished"));
return;
};
let current_id = current.teksilo_id;
#[cfg(not(target_os = "macos"))]
let current_handle = current
.platform_window
.window()
.window_handle()
.ok()
.map(|h| h.as_raw());
let current_arc = Some(current.platform_window.window_arc());
// Settle synchronously on the main thread with a real `WindowOps`.
{
let mut ops = crate::window_manager::WindowOpsImpl::new(
&mut self.wm,
event_loop,
current_id,
#[cfg(not(target_os = "macos"))]
current_handle,
current_arc,
);
let settle = crate::automation_bridge::clamp_live_settle(&payload.settle);
let _ = teksilo_automation::run_settle(&mut current.tree, &mut ops, &settle);
}
// Optional crop rect in physical pixels (logical bounds × scale).
let scale = current.tree.device_scale_factor();
let crop = node.and_then(|n| {
let nid = teksilo_core::accesskit::NodeId(n);
let wid = teksilo_core::accessibility::node_id_to_widget_id_maybe(nid)
.or_else(|| current.tree.widget_for_synthetic(nid))?;
let b = current.tree.bounds(wid);
Some(teksilo_canvas::Rect {
x: b.x * scale,
y: b.y * scale,
width: b.width * scale,
height: b.height * scale,
})
});
// WebView blind-spot warning.
let warnings = {
let update = current.tree.sync_accessibility();
if update
.nodes
.iter()
.any(|(_, nd)| nd.role() == teksilo_core::accesskit::Role::WebView)
{
vec!["webview_hole_possible".to_string()]
} else {
Vec::new()
}
};
let clear = teksilo_render::vertex::srgb_to_linear_rgba(
current.tree.theme().colors.surface_main.to_array(),
);
let frame = current.tree.render();
// The GPU readback inside `capture_offscreen` can `.expect()`-panic on
// device loss (compositor restart, driver crash, memory pressure).
// Catch it so the window is still reinserted (no zombie) and the app
// survives — a screenshot failure must not abort a live session.
let captured = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
current
.platform_window
.capture_offscreen(&frame, clear, crop)
}));
current.platform_window.request_redraw();
self.wm.reinsert_managed(winit_id, current);
let reply = match captured {
Ok((rgba, w, h)) if w != 0 && h != 0 => {
crate::automation_bridge::screenshot_reply(&rgba, w, h, warnings)
}
Ok(_) => {
AutomationReply::err(codes::BAD_ARGUMENT, "crop region empty / outside window")
}
Err(_) => AutomationReply::err(
"GPU_READBACK_FAILED",
"offscreen capture failed (GPU device lost?)",
),
};
let _ = payload.reply_tx.send(reply);
}
fn run_in_window(
&mut self,
winit_id: winit::window::WindowId,
event_loop: &ActiveEventLoop,
f: impl FnOnce(&mut WidgetTree, &mut crate::window_manager::WindowOpsImpl),
) {
let Some(mut current) = self.wm.take_managed(winit_id) else {
return;
};
let current_id = current.teksilo_id;
#[cfg(not(target_os = "macos"))]
let current_handle = current
.platform_window
.window()
.window_handle()
.ok()
.map(|h| h.as_raw());
let current_arc = Some(current.platform_window.window_arc());
{
let mut ops = crate::window_manager::WindowOpsImpl::new(
&mut self.wm,
event_loop,
current_id,
#[cfg(not(target_os = "macos"))]
current_handle,
current_arc,
);
f(&mut current.tree, &mut ops);
}
self.wm.reinsert_managed(winit_id, current);
}
/// Last stop for an `AppEvent::External` payload: hand it to the app's own
/// [`ExternalCtxHandler`] (if one was registered) with a live
/// [`EventContext`](teksilo_core::widget::EventContext), so it can open,
/// find and focus windows.
///
/// **Target window** = the focused one, else the primary — the same
/// resolution [`try_route_automation_payload`](Self::try_route_automation_payload)
/// uses. The handler is about *application*-level intent ("open this
/// document"), so which window hosts the context is an implementation
/// detail; it just has to be a real one, because `open_window` on a
/// standalone context panics.
///
/// The handler is `take`n for the duration of the call and put back
/// afterwards: [`run_in_window`](Self::run_in_window) needs `&mut self`, and
/// the handler lives on `self`. Re-entrancy (a handler whose body somehow
/// pumps another external event) therefore sees `None` and is a no-op rather
/// than a double borrow.
///
/// No window open (the instant between the last close and loop exit) is a
/// silent no-op — there is nowhere to mint a context from.
fn route_external_with_ctx(
&mut self,
payload: &(dyn std::any::Any + Send),
event_loop: &ActiveEventLoop,
) {
let Some(mut handler) = self.external_ctx_handler.take() else {
return;
};
let target = self
.wm
.iter()
.find(|m| m.focused)
.map(|m| m.teksilo_id)
.unwrap_or_else(|| self.wm.primary_window_id());
if let Some(winit_id) = self.wm.winit_id_for_teksilo(target) {
let handler = &mut handler;
self.run_in_window(winit_id, event_loop, move |tree, ops| {
tree.run_with_event_context(ops, |ctx| {
handler(payload, ctx);
});
});
}
self.external_ctx_handler = Some(handler);
}
/// Try to route an `AppEvent::External` payload as a
/// [`FileDialogEventPayload`](teksilo_platform::file_dialog::FileDialogEventPayload).
/// Returns `Ok(())` if the payload matched and was delivered to
/// the originating window's tree, `Err(payload)` to hand the
/// box back for fallthrough to other downcast attempts.
///
/// Routing details:
/// - Resolves `payload.window_id_owner` to the matching winit
/// `WindowId` via `WindowManager::teksilo_to_winit_map`.
/// - Temporarily takes the window out of `WindowManager::windows`
/// (matches the `dispatch_in_window` re-entry pattern) so
/// `open_window` / other ops calls inside the result callback
/// can run.
/// - Builds a `WidgetTree::run_with_event_context` closure that
/// pops the pending callback from `FileDialogHandle` and
/// invokes it.
/// - On any miss (no matching window, no handle in app-state,
/// already-purged callback) the result is silently dropped —
/// no panic, no leaked callback.
#[cfg_attr(not(feature = "file-dialog"), allow(unused_variables))]
fn try_route_file_dialog_payload(
&mut self,
payload: Box<dyn std::any::Any + Send>,
event_loop: &ActiveEventLoop,
) -> Result<(), Box<dyn std::any::Any + Send>> {
#[cfg(feature = "file-dialog")]
{
use teksilo_platform::file_dialog::{FileDialogEventPayload, FileDialogHandle};
let payload = *payload.downcast::<FileDialogEventPayload>()?;
// Find the originating window.
let target_winit = self
.wm
.teksilo_to_winit_map()
.get(&payload.window_id_owner)
.copied();
let Some(winit_id) = target_winit else {
// Window already torn down — drop silently.
return Ok(());
};
// Pull the FileDialogHandle out of the shared app context
// template. Same Rc held by every window's tree, so this
// does not fight take_managed below.
let handle = self
.wm
.app_context_template()
.and_then(|t| t.app_state::<FileDialogHandle>().cloned());
let Some(handle) = handle else {
// Application did not install a FileDialogHandle —
// shouldn't happen if a payload was dispatched, but
// drop silently rather than panic.
return Ok(());
};
let Some(mut current) = self.wm.take_managed(winit_id) else {
return Ok(());
};
let current_id = current.teksilo_id;
#[cfg(not(target_os = "macos"))]
let current_handle = current
.platform_window
.window()
.window_handle()
.ok()
.map(|h| h.as_raw());
let current_arc = Some(current.platform_window.window_arc());
{
let mut ops = crate::window_manager::WindowOpsImpl::new(
&mut self.wm,
event_loop,
current_id,
#[cfg(not(target_os = "macos"))]
current_handle,
current_arc,
);
current
.tree
.run_with_event_context(&mut ops, |ctx| handle.deliver(payload, ctx));
}
self.wm.reinsert_managed(winit_id, current);
Ok(())
}
#[cfg(not(feature = "file-dialog"))]
{
Err(payload)
}
}
/// Drain queued post-mount actions for every window that has any, each
/// with a real [`EventContext`](teksilo_core::widget::EventContext) (so `ctx.parent_window_handle()` resolves).
/// Modal-blocked windows are skipped — their actions (e.g. a WebView
/// opening its native engine subview) stay queued until the modal closes,
/// so a native surface can't appear over a modal. Cheap when nothing is
/// queued (the common case): one map scan, the returned Vec is empty and
/// unallocated.
fn process_pending_mount_actions(&mut self, event_loop: &ActiveEventLoop) {
let winit_ids = self.wm.winit_ids_with_pending_mount_actions();
for winit_id in winit_ids {
self.run_in_window(winit_id, event_loop, |tree, ops| {
tree.run_mount_actions(ops)
});
}
}
/// Try to route an `AppEvent::External` payload as a
/// [`WebViewEventPayload`](teksilo_webview::WebViewEventPayload) posted by a
/// web-view engine backend, delivering it to the originating window's tree
/// via [`WebViewRegistry::deliver`](teksilo_webview::WebViewRegistry::deliver).
/// Returns `Ok(())` if matched and delivered, `Err(payload)` to hand the
/// box back for fallthrough. Same take/run-with-context/reinsert dance as
/// [`Self::try_route_file_dialog_payload`].
#[cfg_attr(not(feature = "web-view"), allow(unused_variables))]
fn try_route_web_view_payload(
&mut self,
payload: Box<dyn std::any::Any + Send>,
event_loop: &ActiveEventLoop,
) -> Result<(), Box<dyn std::any::Any + Send>> {
#[cfg(feature = "web-view")]
{
use teksilo_webview::{WebViewEventPayload, WebViewRegistry};
let payload = *payload.downcast::<WebViewEventPayload>()?;
let target_winit = self
.wm
.teksilo_to_winit_map()
.get(&payload.window_id_owner)
.copied();
let Some(winit_id) = target_winit else {
return Ok(());
};
let registry = self
.wm
.app_context_template()
.and_then(|t| t.app_state::<WebViewRegistry>().cloned());
let Some(registry) = registry else {
return Ok(());
};
self.run_in_window(winit_id, event_loop, move |tree, ops| {
tree.run_with_event_context(ops, |ctx| registry.deliver(payload, ctx));
});
Ok(())
}
#[cfg(not(feature = "web-view"))]
{
Err(payload)
}
}
/// Try to route an `AppEvent::External` payload as an
/// [`AsyncCompletionPayload`](teksilo_core::AsyncCompletionPayload) posted
/// by the `teksilo-async` executor when a `spawn_local_with` future
/// resolves. Returns `Ok(())` if matched and delivered, `Err(payload)` to
/// hand the box back for fallthrough.
///
/// Uses only teksilo-core types ([`AsyncCompletionHandle`](teksilo_core::AsyncCompletionHandle)),
/// so `teksilo-async` (which depends on `teksilo-app`) never has to be a
/// dependency here — the same take/run-with-context/reinsert pattern as
/// the file-dialog path. On any miss (window gone, runtime not installed,
/// already-purged completion) the result is dropped silently.
fn try_route_async_completion_payload(
&mut self,
payload: Box<dyn std::any::Any + Send>,
event_loop: &ActiveEventLoop,
) -> Result<(), Box<dyn std::any::Any + Send>> {
use teksilo_core::{AsyncCompletionHandle, AsyncCompletionPayload};
let payload = *payload.downcast::<AsyncCompletionPayload>()?;
let target_winit = self
.wm
.teksilo_to_winit_map()
.get(&payload.window_id)
.copied();
let Some(winit_id) = target_winit else {
// Window already torn down — drop silently.
return Ok(());
};
let handle = self
.wm
.app_context_template()
.and_then(|t| t.app_state::<AsyncCompletionHandle>().cloned());
let Some(handle) = handle else {
// No async runtime installed — drop silently.
return Ok(());
};
let Some(mut current) = self.wm.take_managed(winit_id) else {
return Ok(());
};
let current_id = current.teksilo_id;
#[cfg(not(target_os = "macos"))]
let current_handle = current
.platform_window
.window()
.window_handle()
.ok()
.map(|h| h.as_raw());
let current_arc = Some(current.platform_window.window_arc());
{
let mut ops = crate::window_manager::WindowOpsImpl::new(
&mut self.wm,
event_loop,
current_id,
#[cfg(not(target_os = "macos"))]
current_handle,
current_arc,
);
current.tree.run_with_event_context(&mut ops, |ctx| {
handle.deliver(payload.id, payload.window_id, ctx)
});
}
self.wm.reinsert_managed(winit_id, current);
Ok(())
}
/// Deliver a backend `AppEvent::SubscriptionEvent` to a *context-bearing*
/// subscription registered via
/// [`BuildContext::subscribe_event_with_ctx`](teksilo_core::BuildContext::subscribe_event_with_ctx):
/// mint a fresh [`EventContext`](teksilo_core::EventContext) from the
/// subscriber's window tree and invoke the stored callback inside it.
///
/// Returns `true` iff `sub_id` names a context-bearing subscription — the
/// caller then skips the plain, context-free dispatch (a `sub_id` lives in
/// exactly one callback map). A `true` return with the window torn down (or
/// mid-teardown) drops the event, exactly like the async-completion path;
/// it still returns `true` so the stale event never falls through to the
/// plain map.
///
/// Mirrors [`try_route_async_completion_payload`](Self::try_route_async_completion_payload)'s
/// take / run-with-context / reinsert dance — the one supported way to run
/// application code with a fresh `EventContext` from the event loop.
fn try_dispatch_subscription_with_ctx(
&mut self,
sub_id: SubscriptionId,
event: &dyn std::any::Any,
event_loop: &ActiveEventLoop,
) -> bool {
let Some(template) = self.wm.app_context_template().cloned() else {
return false;
};
let Some(window_id) = template.ctx_subscription_window(sub_id) else {
return false;
};
// From here `sub_id` IS a context-bearing subscription: consume it
// (return `true`) even if the window is gone, so a late event never
// falls back to the plain, context-free map.
let Some(winit_id) = self.wm.teksilo_to_winit_map().get(&window_id).copied() else {
return true;
};
let Some(mut current) = self.wm.take_managed(winit_id) else {
return true;
};
let current_id = current.teksilo_id;
#[cfg(not(target_os = "macos"))]
let current_handle = current
.platform_window
.window()
.window_handle()
.ok()
.map(|h| h.as_raw());
let current_arc = Some(current.platform_window.window_arc());
{
let mut ops = crate::window_manager::WindowOpsImpl::new(
&mut self.wm,
event_loop,
current_id,
#[cfg(not(target_os = "macos"))]
current_handle,
current_arc,
);
current.tree.run_with_event_context(&mut ops, |ctx| {
template.dispatch_subscription_event_with_ctx(sub_id, event, ctx);
});
}
self.wm.reinsert_managed(winit_id, current);
true
}
/// Try to route an `AppEvent::External` payload as a
/// [`NativeMenuEventPayload`](teksilo_platform::native_menu::NativeMenuEventPayload)
/// posted when the user chose an item in the platform's native menu bar.
/// Resolves the item's [`MenuItemId`](teksilo_core::MenuItemId) to its
/// recorded intent / action via the [`NativeMenuHandle`](teksilo_platform::native_menu::NativeMenuHandle)
/// and fires it inside the originating window's `EventContext` with
/// `IntentSource::Menu` — the same pipeline an in-window `MenuItem` uses.
/// Same take/run-with-context/reinsert shape as the file-dialog router; any
/// miss is dropped silently.
fn try_route_native_menu_payload(
&mut self,
payload: Box<dyn std::any::Any + Send>,
event_loop: &ActiveEventLoop,
) -> Result<(), Box<dyn std::any::Any + Send>> {
use teksilo_core::Intent;
use teksilo_core::telemetry::IntentSource;
use teksilo_platform::native_menu::{NativeMenuEventPayload, NativeMenuHandle};
let payload = *payload.downcast::<NativeMenuEventPayload>()?;
let target_winit = self
.wm
.teksilo_to_winit_map()
.get(&payload.window_id_owner)
.copied();
let Some(winit_id) = target_winit else {
return Ok(());
};
let handle = self
.wm
.app_context_template()
.and_then(|t| t.app_state::<NativeMenuHandle>().cloned());
let Some(handle) = handle else {
return Ok(());
};
let Some(activation) = handle.activation(payload.window_id_owner, payload.item_id) else {
// Item not found (menu replaced / window torn down) — drop.
return Ok(());
};
let Some(mut current) = self.wm.take_managed(winit_id) else {
return Ok(());
};
let current_id = current.teksilo_id;
#[cfg(not(target_os = "macos"))]
let current_handle = current
.platform_window
.window()
.window_handle()
.ok()
.map(|h| h.as_raw());
let current_arc = Some(current.platform_window.window_arc());
{
let mut ops = crate::window_manager::WindowOpsImpl::new(
&mut self.wm,
event_loop,
current_id,
#[cfg(not(target_os = "macos"))]
current_handle,
current_arc,
);
current.tree.run_with_event_context(&mut ops, |ctx| {
ctx.with_intent_source(IntentSource::Menu, |ctx| {
if let Some(name) = activation.intent {
ctx.send_intent(Intent::new(name));
}
if let Some(action) = &activation.action {
action(ctx);
}
});
});
}
self.wm.reinsert_managed(winit_id, current);
Ok(())
}
/// Try to interpret an `AppEvent::External` payload as an
/// [`ExternalDndEventPayload`](teksilo_platform::external_dnd::ExternalDndEventPayload)
/// posted by a platform drag backend and route it to the originating
/// window's tree, driving the matching `*_external_drag` method.
///
/// Returns `Ok(())` if the payload was an external-drag event (consumed),
/// or `Err(payload)` to hand it back for other downcast attempts. Mirrors
/// [`Self::try_route_file_dialog_payload`]'s take/dispatch/reinsert dance.
fn try_route_external_dnd_payload(
&mut self,
payload: Box<dyn std::any::Any + Send>,
event_loop: &ActiveEventLoop,
) -> Result<(), Box<dyn std::any::Any + Send>> {
use teksilo_platform::external_dnd::{
ExternalDndEventPayload, ExternalDndHandle, ExternalDragEvent, OutboundOsDragRequest,
};
// Deferred blocking outbound (app → OS) drag: run OLE DoDragDrop here,
// outside the in-app dispatch that started it (Windows). No window is
// taken out of the manager at this point, so the drag's modal message
// loop can't strand a borrowed window.
let payload = match payload.downcast::<OutboundOsDragRequest>() {
Ok(req) => {
if let Some(handle) = self
.wm
.app_context_template()
.and_then(|t| t.app_state::<ExternalDndHandle>().cloned())
{
handle.run_pending_outbound_drag(req.window_id);
}
return Ok(());
}
Err(other) => other,
};
let payload = *payload.downcast::<ExternalDndEventPayload>()?;
let Some(winit_id) = self
.wm
.teksilo_to_winit_map()
.get(&payload.window_id_owner)
.copied()
else {
// Window already torn down — drop silently.
return Ok(());
};
let Some(mut current) = self.wm.take_managed(winit_id) else {
return Ok(());
};
let current_id = current.teksilo_id;
#[cfg(not(target_os = "macos"))]
let current_handle = current
.platform_window
.window()
.window_handle()
.ok()
.map(|h| h.as_raw());
let current_arc = Some(current.platform_window.window_arc());
{
let mut ops = crate::window_manager::WindowOpsImpl::new(
&mut self.wm,
event_loop,
current_id,
#[cfg(not(target_os = "macos"))]
current_handle,
current_arc,
);
match payload.event {
ExternalDragEvent::Entered { data, position } => {
current.tree.begin_external_drag(position, data, &mut ops);
}
ExternalDragEvent::Moved { position } => {
current.tree.update_external_drag(position, &mut ops);
}
ExternalDragEvent::Left => {
current.tree.cancel_external_drag(&mut ops);
}
ExternalDragEvent::Dropped { data, position } => {
current.tree.end_external_drag(position, data, &mut ops);
}
ExternalDragEvent::DragEnded { outcome } => {
current.tree.handle_os_drag_ended(outcome, &mut ops);
}
}
}
// Repaint so hover feedback / drop results show promptly.
current.platform_window.request_redraw();
self.wm.reinsert_managed(winit_id, current);
Ok(())
}
/// Tick gestures on every window with a real `WindowOps` sink so
/// long-press / drag-tick handlers can open windows.
fn tick_gestures_in_window(
&mut self,
window_id: WindowId,
now: Instant,
event_loop: &ActiveEventLoop,
) {
let Some(mut current) = self.wm.take_managed(window_id) else {
return;
};
let current_id = current.teksilo_id;
#[cfg(not(target_os = "macos"))]
let current_handle = current
.platform_window
.window()
.window_handle()
.ok()
.map(|h| h.as_raw());
let current_arc = Some(current.platform_window.window_arc());
{
let mut ops = crate::window_manager::WindowOpsImpl::new(
&mut self.wm,
event_loop,
current_id,
#[cfg(not(target_os = "macos"))]
current_handle,
current_arc,
);
current.tree.tick_gestures_with_ops(now, &mut ops);
}
self.wm.reinsert_managed(window_id, current);
}
fn handle_accessibility_actions(
&mut self,
window_id: WindowId,
event: &WindowEvent,
event_loop: &ActiveEventLoop,
) {
// Collect events while holding the `ManagedWindow` borrow;
// dispatch them below through `dispatch_in_window`, which
// needs the borrow to be released first.
let mut a11y_events: Vec<WidgetEvent> = Vec::new();
if let Some(managed) = self.wm.get_by_winit_mut(window_id) {
managed.platform_window.process_accessibility_event(event);
let actions = managed.platform_window.drain_accessibility_actions();
for req in actions {
// Synthetic NodeIds (TextRun children emitted by the
// rich text editor) can't be decoded back to a
// WidgetId by value alone — look them up via the
// tree's reverse-map. For plain widget NodeIds the
// infallible converter is fine.
let target_widget = if teksilo_core::accessibility::is_synthetic(req.target_node) {
managed.tree.widget_for_synthetic(req.target_node)
} else {
Some(teksilo_core::accessibility::node_id_to_widget_id(
req.target_node,
))
};
let evt = WidgetEvent::AccessAction {
action: req.action,
target: target_widget,
target_node: req.target_node,
data: req.data,
};
a11y_events.push(evt);
}
}
for evt in a11y_events {
self.dispatch_in_window(window_id, evt, event_loop);
}
}
fn handle_redraw_requested(&mut self, window_id: WindowId, event_loop: &ActiveEventLoop) {
// Pre-render: take the window out so we can construct a real
// WindowOpsImpl and pass it into layout + render. This lets
// rebuild-triggered handlers (data-driven state changes,
// delayed-overlay activation, drag-tick) open windows.
let Some(mut current) = self.wm.take_managed(window_id) else {
return;
};
let current_id = current.teksilo_id;
#[cfg(not(target_os = "macos"))]
let current_handle = current
.platform_window
.window()
.window_handle()
.ok()
.map(|h| h.as_raw());
let current_arc = Some(current.platform_window.window_arc());
if let Some(trace) = &mut self.idle_trace {
trace.note_redraw_requested();
}
if current.tree.has_idle_work() {
if let Some(trace) = &mut self.idle_trace {
trace.note_idle_callbacks_run();
}
current.tree.run_idle_callbacks(self.idle_budget);
}
let size = current.platform_window.surface_size();
let sf = current.platform_window.scale_factor() as f32;
let proposal = SizeProposal::exact(size.0 as f32 / sf, size.1 as f32 / sf);
{
let mut ops = crate::window_manager::WindowOpsImpl::new(
&mut self.wm,
event_loop,
current_id,
#[cfg(not(target_os = "macos"))]
current_handle,
current_arc.clone(),
);
current.tree.layout_with_ops(proposal, &mut ops);
}
// Size-to-content: after layout, measure the content's intrinsic height
// at the fixed width and grow/shrink the OS window to fit. The native-
// window modal path lays the tree out at the window's *exact* size, so
// (unlike the in-tree overlay) the content's natural height never
// reaches the OS window on its own — a `MessageBox` taller than its
// fixed height clips, dropping the footer buttons below the client edge.
// Drive the size through the reactive `WindowState::size()` → `SetSize`
// path (drained in `post_event`); `last_autosize_height` guards against
// a measure → resize → re-measure oscillation.
if current.size_to_content.sizes_height() {
let width_logical = size.0 as f32 / sf;
if let Some(intrinsic) = current.tree.measure_root_intrinsic(SizeProposal {
width: Some(width_logical),
height: None,
}) {
let target_h = intrinsic.height.ceil().max(1.0) as u32;
let cur_h = (size.1 as f32 / sf).round() as u32;
if target_h != cur_h && current.last_autosize_height != Some(target_h) {
current.last_autosize_height = Some(target_h);
current
.state
.size()
.set((width_logical.round() as u32, target_h));
}
}
}
let a11y_update = current.tree.sync_accessibility();
current.platform_window.update_accessibility(a11y_update);
// Catch-all IME reconcile: covers focus changes from any source
// (access actions, programmatic focus, rebuild) that didn't go
// through `dispatch_in_window`. Layout has settled, so the focused
// node's descriptor is current. Cheap + deduped, safe every frame.
Self::reconcile_ime(&mut current);
let mut frame = {
let mut ops = crate::window_manager::WindowOpsImpl::new(
&mut self.wm,
event_loop,
current_id,
#[cfg(not(target_os = "macos"))]
current_handle,
current_arc.clone(),
);
current.tree.render_with_ops(&mut ops)
};
let managed = &mut current;
#[cfg(feature = "text")]
{
let atlas = self
.typesetter
.bridge()
.borrow_mut()
.atlas_info(managed.atlas_uploaded_version);
if atlas.version != managed.atlas_uploaded_version
&& atlas.width > 0
&& atlas.height > 0
{
managed.platform_window.renderer_mut().upload_atlas(
atlas.width,
atlas.height,
&atlas.pixels,
);
managed.atlas_uploaded_version = atlas.version;
}
if atlas.glyphs_evicted {
// Glyphs were evicted since the previous atlas_info call
// (any path: snapshot scan, rich-text render scan, or
// scale-factor reset). Every retained paint frame in
// EVERY window may hold quads whose atlas UVs now point
// at recycled slots — and invalidate_cache() below clears
// the bridge's layout/glyph caches, which also kills the
// touch_layout keep-alive for frames baked before the
// clear. Invalidate all windows, not just the current
// one; the others re-render at their own requested
// redraw with fresh layouts and pull the current atlas
// pixels through the version comparison above.
self.typesetter.bridge().borrow_mut().invalidate_cache();
managed.tree.invalidate_all_paints();
for other in self.wm.iter_mut() {
other.tree.invalidate_all_paints();
other.platform_window.request_redraw();
}
// Re-render after atlas invalidation with a real ops
// sink so rebuild-triggered handlers on this recovery
// path can still open windows.
let mut ops = crate::window_manager::WindowOpsImpl::new(
&mut self.wm,
event_loop,
current_id,
#[cfg(not(target_os = "macos"))]
current_handle,
current_arc.clone(),
);
frame = managed.tree.render_with_ops(&mut ops);
let atlas2 = self
.typesetter
.bridge()
.borrow_mut()
.atlas_info(managed.atlas_uploaded_version);
// The recovery re-render cannot legitimately evict again
// (the eviction scan's generation-cadence gate just
// reset), but atlas_info consumes the epoch delta — a
// report here would be silently lost, so check the
// assumption instead of assuming it.
debug_assert!(
!atlas2.glyphs_evicted,
"glyph eviction during eviction recovery — epoch delta would be lost"
);
if atlas2.version != managed.atlas_uploaded_version
&& atlas2.width > 0
&& atlas2.height > 0
{
managed.platform_window.renderer_mut().upload_atlas(
atlas2.width,
atlas2.height,
&atlas2.pixels,
);
managed.atlas_uploaded_version = atlas2.version;
}
}
}
// The wgpu surface is Rgba8UnormSrgb: it expects linear-light color
// values and applies sRGB encoding on write. Our Color stores sRGB-
// encoded bytes (as designers specify them), so we must linearize
// the clear color here the same way we do for vertex colors.
let clear = teksilo_render::vertex::srgb_to_linear_rgba(
managed.tree.theme().colors.surface_main.to_array(),
);
match managed.platform_window.render_frame(&frame, clear) {
teksilo_platform::FrameOutcome::Rendered => {
if let Some(trace) = &mut self.idle_trace {
trace.note_rendered_frame();
}
}
teksilo_platform::FrameOutcome::Skipped => {
if !managed.occluded {
managed.platform_window.request_redraw();
}
self.wm.reinsert_managed(window_id, current);
return;
}
teksilo_platform::FrameOutcome::NeedsReconfigure => {
managed.platform_window.reconfigure_surface();
managed.platform_window.request_redraw();
self.wm.reinsert_managed(window_id, current);
return;
}
teksilo_platform::FrameOutcome::Error(e) => {
eprintln!("teksilo-app: {e}, reconfiguring surface");
managed.platform_window.reconfigure_surface();
managed.platform_window.request_redraw();
self.wm.reinsert_managed(window_id, current);
return;
}
}
// A live per-frame effect (Pulse / Cycle / caret blink / drag
// auto-scroll) leaves `frame_requested()` armed after this render.
// We deliberately do NOT `request_redraw()` here: an immediate
// redraw request makes winit skip the `WaitUntil` sleep and
// free-run at the display's refresh rate — the exact 300 fps
// uncapped behaviour we're removing. Instead the fixed 60 Hz
// deadline published by `WidgetTree::frame_tick_deadline` (folded
// into `next_timer_deadline`) drives the next frame: at the
// deadline, `new_events(ResumeTimeReached)` calls
// `request_redraw_all()`. This mirrors how the shader-quad
// animation path has always paced itself, so per-frame animations
// now show in the idle trace as `resume_time_reached` /
// `request_redraw_all` rather than `frame_request`.
self.wm.reinsert_managed(window_id, current);
}
fn handle_window_event_inner(
&mut self,
event_loop: &ActiveEventLoop,
window_id: WindowId,
event: WindowEvent,
) {
let teksilo_id = self.wm.teksilo_id_for_winit(window_id);
if let Some(fid) = teksilo_id
&& self.wm.is_blocked(fid)
&& !matches!(
event,
WindowEvent::CloseRequested | WindowEvent::ActivationTokenDone { .. }
)
{
self.wm.refocus_modal_child(fid);
self.update_control_flow(event_loop);
return;
}
self.handle_accessibility_actions(window_id, &event, event_loop);
match event {
WindowEvent::CloseRequested => {
if let Some(fid) = teksilo_id {
// Guarded close: the OS close button / Alt+F4 / Cmd+W
// is an interactive gesture, so it runs through the
// window's close guard (if any) on the next
// `process_pending` tick and may be vetoed.
self.wm.request_close(fid);
}
}
WindowEvent::Resized(new_size) => {
if let Some(managed) = self.wm.get_by_winit_mut(window_id) {
managed.platform_window.resize(new_size);
// Mirror OS-initiated geometry / placement changes
// into WindowState so widgets bound to those signals
// re-render. The `*_from_os` setters flip the
// re-entrancy guard so observers on the signal do
// not push the change back out as a WindowCommand.
// Covers OS-initiated maximize (drag-to-top-snap on
// Wayland/Windows, green-light zoom on macOS) —
// query_window_placement reads the winit state and
// the Switcher glyph swap on `TitleBar`'s maximize
// button (bound to `WindowState::placement`) stays
// in sync.
let sf = managed.platform_window.scale_factor();
let logical_w = (new_size.width as f64 / sf).round().max(0.0) as u32;
let logical_h = (new_size.height as f64 / sf).round().max(0.0) as u32;
managed.state.set_size_from_os((logical_w, logical_h));
let placement = query_window_placement(managed.platform_window.window());
managed.state.set_placement_from_os(placement);
if let Some(trace) = &mut self.idle_trace {
trace.note_redraw_request("resize");
}
managed.platform_window.request_redraw();
}
}
WindowEvent::Moved(pos) => {
if let Some(managed) = self.wm.get_by_winit_mut(window_id) {
let sf = managed.platform_window.scale_factor();
let lx = (pos.x as f64 / sf).round() as i32;
let ly = (pos.y as f64 / sf).round() as i32;
managed.state.set_position_from_os((lx, ly));
}
}
WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
let mut teksilo_id = None;
if let Some(managed) = self.wm.get_by_winit_mut(window_id) {
managed.translation_state.set_scale_factor(scale_factor);
managed.platform_window.set_scale_factor(scale_factor);
managed.tree.set_device_scale_factor(scale_factor as f32);
teksilo_id = Some(managed.teksilo_id);
}
// Keep the external-DnD backend's idea of the scale current:
// dragging the window onto a monitor with a different scale
// mid-drag would otherwise start reporting drops at the wrong
// place (X11 only — see `ExternalDndGuard::set_scale_factor`).
if let Some(teksilo_id) = teksilo_id
&& let Some(handle) = self
.wm
.app_context_template()
.and_then(|t| {
t.app_state::<teksilo_platform::external_dnd::ExternalDndHandle>()
})
.cloned()
{
handle.set_scale_factor(teksilo_id, scale_factor);
}
#[cfg(feature = "text")]
{
self.typesetter.set_scale_factor(scale_factor as f32);
}
}
WindowEvent::CursorMoved { position, .. } => {
let maybe_evt = if let Some(managed) = self.wm.get_by_winit_mut(window_id) {
event_translation::translate_cursor_moved(
position.x,
position.y,
&mut managed.translation_state,
)
} else {
None
};
if let Some(evt) = maybe_evt {
self.dispatch_in_window(window_id, evt, event_loop);
}
if let Some(managed) = self.wm.get_by_winit_mut(window_id) {
apply_cursor_to_window(&managed.platform_window, managed.tree.current_cursor());
if managed.tree.needs_redraw() {
if let Some(trace) = &mut self.idle_trace {
trace.note_redraw_request("cursor");
}
managed.platform_window.request_redraw();
}
}
}
WindowEvent::MouseInput { state, button, .. } => {
let maybe_evt = if let Some(managed) = self.wm.get_by_winit_mut(window_id) {
event_translation::translate_mouse_input(
state,
button,
&managed.translation_state,
)
} else {
None
};
if let Some(evt) = maybe_evt {
self.dispatch_in_window(window_id, evt, event_loop);
}
if let Some(managed) = self.wm.get_by_winit_mut(window_id) {
apply_cursor_to_window(&managed.platform_window, managed.tree.current_cursor());
if let Some(trace) = &mut self.idle_trace {
trace.note_redraw_request("mouse_input");
}
managed.platform_window.request_redraw();
}
}
WindowEvent::MouseWheel { delta, phase, .. } => {
let maybe_evt = if let Some(managed) = self.wm.get_by_winit_mut(window_id) {
event_translation::translate_mouse_wheel(
delta,
phase,
&managed.translation_state,
)
} else {
None
};
if let Some(evt) = maybe_evt {
self.dispatch_in_window(window_id, evt, event_loop);
}
if let Some(managed) = self.wm.get_by_winit_mut(window_id) {
if let Some(trace) = &mut self.idle_trace {
trace.note_redraw_request("mouse_wheel");
}
managed.platform_window.request_redraw();
}
}
WindowEvent::ModifiersChanged(mods) => {
// Capture state before the alt_down write so we can
// detect the falling edge without re-reading after.
let alt_tap_action = if let Some(managed) = self.wm.get_by_winit_mut(window_id) {
managed.current_modifiers = mods.state();
managed
.translation_state
.set_modifiers(event_translation::translate_modifiers(mods.state()));
let new_alt = mods.state().alt_key();
let prev_alt = managed.state.alt_down().get();
let other_pressed = managed.state.other_key_pressed_during_alt();
// Alt-tap tracking: surface the OS Alt-held edge on
// the window's `alt_down` signal so `MenuLabel` can
// gate mnemonic underlines and `MenuBar` can detect
// bare-Alt-tap on the falling edge. winit reports
// Alt presses through `ModifiersChanged` (not as a
// `Key::Alt` KeyDown, which doesn't exist in our
// Key enum), so this is the only correct hook.
managed.state.set_alt_from_os(new_alt);
// Detect the bare-Alt-tap pattern: true → false
// with no non-Alt KeyDowns during the hold.
if prev_alt && !new_alt && !other_pressed {
managed
.state
.menubar_dispatcher()
.and_then(|d| d.on_alt_tap())
} else {
None
}
} else {
None
};
if let Some(action) = alt_tap_action {
self.apply_menubar_action(window_id, action, event_loop);
}
}
WindowEvent::KeyboardInput {
event: key_event, ..
} => {
// Track Caps Lock from the discrete key press — winit's
// `ModifiersState` carries no lock state — toggling on
// each key-down edge and pushing the result to
// `WindowState::caps_lock` for the password-field warning.
if key_event.state == winit::event::ElementState::Pressed
&& matches!(
event_translation::translate_key(&key_event.logical_key),
Some(teksilo_core::event::Key::CapsLock)
)
&& let Some(managed) = self.wm.get_by_winit_mut(window_id)
{
managed.caps_lock_active = !managed.caps_lock_active;
managed
.state
.set_caps_lock_from_os(managed.caps_lock_active);
}
// Bare-Alt-tap detection: every non-Alt KeyDown while
// Alt is held flips the sticky flag, so the falling
// edge of `alt_down` only counts as a tap when no
// chord was composed. winit fires modifier keys
// through `ModifiersChanged`, not `KeyboardInput`, so
// every KeyDown we see here is a non-modifier and
// qualifies as an "other key" press.
if key_event.state == winit::event::ElementState::Pressed
&& event_translation::translate_key(&key_event.logical_key).is_some()
&& let Some(managed) = self.wm.get_by_winit_mut(window_id)
{
managed.state.note_non_alt_keydown_during_alt();
}
let maybe_evt = if let Some(managed) = self.wm.get_by_winit_mut(window_id) {
event_translation::translate_key(&key_event.logical_key).map(|key| {
let modifiers =
event_translation::translate_modifiers(managed.current_modifiers);
let text = key_event.text.as_ref().map(|t| t.to_string());
match key_event.state {
winit::event::ElementState::Pressed => WidgetEvent::KeyDown {
key,
modifiers,
text,
},
winit::event::ElementState::Released => {
WidgetEvent::KeyUp { key, modifiers }
}
}
})
} else {
None
};
if let Some(evt) = maybe_evt {
// Window-level menubar pre-dispatch (F10 / Alt+letter):
// intercepts BEFORE the normal focus-based path so the
// event reaches the menubar even when focus is in a
// TextInput or some other unrelated widget. Matches
// Win32's `WM_SYSKEYDOWN` → `DefWindowProc` route.
let intercept = if let WidgetEvent::KeyDown { key, modifiers, .. } = &evt {
self.wm
.get_by_winit_mut(window_id)
.and_then(|m| {
m.state.menubar_dispatcher().map(|d| {
d.try_handle(&teksilo_core::window::MenubarKeyEvent {
key: *key,
modifiers: *modifiers,
})
})
})
.flatten()
} else {
None
};
if let Some(action) = intercept {
self.apply_menubar_action(window_id, action, event_loop);
} else {
self.dispatch_in_window(window_id, evt, event_loop);
}
}
if let Some(managed) = self.wm.get_by_winit_mut(window_id) {
if let Some(trace) = &mut self.idle_trace {
trace.note_redraw_request("keyboard");
}
managed.platform_window.request_redraw();
}
}
WindowEvent::Ime(ime) => {
// Dedup consecutive empty preedits at the funnel. Some Linux IME
// backends (ibus / fcitx via winit) flood empty `Ime::Preedit("")`
// events while a field is focused. The first is meaningful (it
// clears any active composition); every consecutive repeat is a
// no-op that would still translate + dispatch through the tree AND
// wake a full unconditional layout+render pass here. Skip the
// repeats entirely — neither dispatch nor redraw. Any non-empty
// preedit (or a Commit / Enabled / Disabled) resets the flag so
// the next empty preedit is again treated as meaningful.
let empty_preedit =
matches!(&ime, winit::event::Ime::Preedit(t, _) if t.is_empty());
let skip = if let Some(managed) = self.wm.get_by_winit_mut(window_id) {
crate::window_manager::ime_should_skip_empty_preedit(
&mut managed.last_ime_preedit_empty,
empty_preedit,
)
} else {
false
};
if !skip {
let maybe_evt = if self.wm.get_by_winit_mut(window_id).is_some() {
event_translation::translate_ime(ime)
} else {
None
};
if let Some(evt) = maybe_evt {
self.dispatch_in_window(window_id, evt, event_loop);
}
if let Some(managed) = self.wm.get_by_winit_mut(window_id) {
if let Some(trace) = &mut self.idle_trace {
trace.note_redraw_request("ime");
}
managed.platform_window.request_redraw();
}
}
}
WindowEvent::RedrawRequested => {
self.handle_redraw_requested(window_id, event_loop);
}
WindowEvent::ThemeChanged(winit_theme) => {
self.handle_theme_changed(winit_theme);
if let Some(managed) = self.wm.get_by_winit_mut(window_id) {
managed.platform_window.request_redraw();
}
}
// Pause all looping animations on the unfocused window so it
// stops waking the event loop at the animation frame
// interval. The scheduler rebases start_time on resume so
// the animation phase is continuous — a half-swept
// indeterminate bar picks up at exactly the same position,
// not snapped forward by the elapsed unfocused time.
//
// On Linux/Windows (winit 0.30) minimize fires `Focused(false)`
// — no separate minimize event — so this path covers it.
WindowEvent::Focused(focused) => {
let mut newly_focused = None;
if let Some(managed) = self.wm.get_by_winit_mut(window_id) {
managed.focused = focused;
let active = managed.focused && !managed.occluded;
managed.tree.set_window_active(active);
managed.state.set_focused_from_os(focused);
// Drive a redraw on every focus transition so the
// window-active observers (caret hide/restore, selection
// desaturation, DimWhenInactive) reach a paint pass
// promptly — the OS does not reliably emit RedrawRequested
// on focus change across all platforms.
managed.platform_window.request_redraw();
if focused {
newly_focused = Some(managed.teksilo_id);
}
}
// A window regaining focus is the natural, zero-idle-cost moment
// to re-check the OS accessibility preferences (WCAG / EN 301
// 549 §11.7): the user may have toggled "increase contrast" /
// "reduce motion" / text scale in System Settings and switched
// back. `refresh_accessibility_preferences` applies any change
// to every window (marking them dirty for repaint).
if focused {
self.wm.refresh_accessibility_preferences();
}
// The global native menu (macOS) follows window focus: make the
// focused window's installed menu the visible one.
if let Some(teksilo_id) = newly_focused
&& let Some(handle) = self.wm.app_context_template().and_then(|t| {
t.app_state::<teksilo_platform::native_menu::NativeMenuHandle>()
.cloned()
})
{
handle.activate_window(teksilo_id);
}
}
// macOS-only in winit 0.30 (X11/Wayland/Windows never emit
// this). Handled for parity with Focused so a macOS app
// that is hidden behind another window — still focused —
// also parks its animations.
WindowEvent::Occluded(occluded) => {
if let Some(managed) = self.wm.get_by_winit_mut(window_id) {
managed.occluded = occluded;
let active = managed.focused && !managed.occluded;
managed.tree.set_window_active(active);
// Drive a redraw on both directions. On reveal
// (`!occluded`) the render loop stopped pinging while we
// were occluded, so without this nudge the window stays
// frozen until the user moves the mouse or hits a key. On
// occlusion (`occluded`) the active-state flip must reach a
// paint pass so the caret hides / selection desaturates
// before the window is hidden behind another.
managed.platform_window.request_redraw();
}
}
WindowEvent::ActivationTokenDone { token, .. } => {
// A `request_activation_token` we issued resolved — hand the
// freshly-minted token to whoever asked (child-process spawn or
// an IPC peer). One request outstanding per window, so key by
// window id and ignore the serial.
if let Some(cb) = self.wm.take_activation_token_callback(window_id) {
cb(Some(token.into_raw()));
}
}
_ => {}
}
self.post_event(event_loop);
}
fn handle_theme_changed(&mut self, winit_theme: winit::window::Theme) {
// Read the mode from the WindowManager (the live owner) so a runtime
// switch to "follow system" via `EventContext::follow_system_theme`
// is honoured here too. OS-following results carry the id "system".
match self.wm.theme_mode() {
ThemeMode::Manual => {} // ignore OS theme changes
ThemeMode::FollowSystem => {
// Trust winit's per-window signal (authoritative on
// macOS/Windows where OS-colour querying is unimplemented).
let theme = match winit_theme {
winit::window::Theme::Dark => teksilo_core::presets::intui::dark(),
winit::window::Theme::Light => teksilo_core::presets::intui::light(),
}
.with_id("system");
self.wm.set_theme(theme);
}
// Native adopts the OS's actual colours on Linux; on macOS/Windows
// (no OS-colour query) it follows winit's authoritative light/dark
// hint. The shared helper stamps the "system" id.
ThemeMode::Native => self
.wm
.apply_os_theme(Some(matches!(winit_theme, winit::window::Theme::Dark))),
}
}
}
impl ApplicationHandler<AppEvent> for TeksiloAppHandler {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
if !self.initial_created
&& let Some(config) = self.initial_window.take()
{
self.wm.create_window(config, event_loop);
self.initial_created = true;
}
self.process_pending(event_loop);
self.update_control_flow(event_loop);
}
fn new_events(&mut self, event_loop: &ActiveEventLoop, cause: StartCause) {
if matches!(cause, StartCause::ResumeTimeReached { .. }) {
if let Some(trace) = &mut self.idle_trace {
trace.note_resume_time_reached();
trace.note_request_redraw_all();
}
// Redraw only the windows whose frame deadline is actually due —
// NOT every window. A blanket redraw here pins non-animating
// windows at the animation frame rate and, on Windows (one
// RedrawRequested serviced per loop iteration), starves an inactive
// window's own pending repaint so it freezes. See
// `WindowManager::request_redraw_due`.
self.wm.request_redraw_due(Instant::now());
}
self.update_control_flow(event_loop);
}
fn user_event(&mut self, event_loop: &ActiveEventLoop, event: AppEvent) {
if let Some(handler) = &mut self.app_event_handler {
handler(&event);
}
// Composed framework observers (see `AppEventObservers` /
// `TeksiloAppBuilder::register_app_event_observer`) run in
// addition to the app's own `on_app_event` handler above — this
// is what lets `teksilo::install_toast` react to
// `AppEvent::SettingsWriteFailed` without clobbering (or being
// clobbered by) an app that also called `on_app_event`.
if let Some(template) = self.wm.app_context_template()
&& let Some(observers) =
template.app_state::<crate::app_event_observers::AppEventObservers>()
{
(observers.0)(&event);
}
match event {
// Backend-event subscription delivery (architecture §9.4): look
// up the UI-side callback in the shared app context and invoke
// it with the downcast event payload. The shared template is
// the same Rc held by every window's tree, so we don't need to
// route by window.
AppEvent::SubscriptionEvent { sub_id, event } => {
// A context-bearing subscription (`subscribe_event_with_ctx`)
// needs a fresh `EventContext` minted from its window's tree;
// a plain one dispatches against the shared template with no
// context. `try_dispatch_subscription_with_ctx` returns `true`
// when `sub_id` names a context-bearing subscription (so we
// skip the plain path — a sub_id lives in exactly one map).
if !self.try_dispatch_subscription_with_ctx(sub_id, &*event, event_loop)
&& let Some(template) = self.wm.app_context_template()
{
template.dispatch_subscription_event(sub_id, &*event);
}
}
// Hot-reload of an `.ftl` file registered via
// `I18nConfig::runtime_override(...)`. Architecture §12.7:
// the reload must *not* trigger a composite rebuild — only
// the version signal is bumped, and the existing binding
// system propagates the change to every `LocalizedString`
// observer. Direction and active locale are unchanged.
AppEvent::I18nReload { locale, path } => {
let parsed: Result<teksilo_i18n::LanguageIdentifier, _> = locale.parse();
match parsed {
Ok(loc) => {
let reloaded = teksilo_i18n::thread_local::with_active(|mgr| {
mgr.reload_from_path(&loc, &path)
});
match reloaded {
Some(Ok(())) => {}
Some(Err(e)) => eprintln!(
"teksilo-app: hot-reload failed for {loc} ({}): {e}",
path.display()
),
None => eprintln!(
"teksilo-app: hot-reload event for {loc} but no i18n manager installed"
),
}
}
Err(e) => {
eprintln!(
"teksilo-app: hot-reload event with invalid locale `{locale}`: {e}"
)
}
}
}
// Live cross-process settings sync: a `teksilo-settings`
// managed file changed on disk (a peer process's write, or
// harmlessly this process's own write being noticed by its
// own watcher). Look the path up in the app's
// `SettingsRegistry` and let it dispatch to whichever
// `Reloadable` owns it. This must *not* trigger a composite
// rebuild — `reload_from_disk` only mutates signals/models
// in place, and the existing reactive binding system
// propagates the change to every observer, exactly like
// `I18nReload` above.
AppEvent::SettingsReload { path } => {
if let Some(template) = self.wm.app_context_template()
&& let Some(registry) =
template.app_state::<teksilo_settings::SettingsRegistry>()
&& let Err(e) = registry.dispatch(&path)
{
eprintln!(
"teksilo-app: settings reload failed for {}: {e}",
path.display()
);
}
}
// F3: a `teksilo-settings` `DebouncedWriter` permanently gave
// up on a queued write (retry cap reached, or a still-failing
// write forced by process teardown) — the patches for `path`
// were discarded. `teksilo-app` itself stays widget-agnostic
// (it cannot depend on `teksilo-widgets`' `Toast` /
// `NotificationArchive`), so this log is only half the
// story: the composed `AppEventObservers` dispatched just
// above also sees this event, and `teksilo::install_toast`
// (the umbrella crate, which sees both `AppEvent` and
// `Toast`) registers an observer that turns it into a
// persistent error toast — see
// `ToastRegistry::show_settings_write_failed`. This log
// stays too: a headless/CI app with no toast host installed
// still needs *some* signal that a write was lost.
AppEvent::SettingsWriteFailed {
path,
attempts,
dropped_patches,
message,
} => {
eprintln!(
"teksilo-app: settings write permanently failed for {} after {} attempts ({} patches dropped): {}",
path.display(),
attempts,
dropped_patches,
message
);
}
// Title-bar hosts route their `close()` through this variant so
// the operation hops back onto the main thread before touching
// `WindowManager` (see `title_bar_host.rs`). File-dialog
// backends post their results through the same variant. The
// arm tries each known payload type in turn; unrecognized
// payloads are ignored — application-authored `send_external`
// payloads can coexist with framework-internal ones.
AppEvent::External(payload) => {
// Try each framework-internal payload type in turn; the first
// that consumes it wins. Unrecognized payloads fall through to
// the title-bar / close-request downcast chain.
let payload = self
.try_route_file_dialog_payload(payload, event_loop)
.err();
let payload = match payload {
None => None,
Some(payload) => self
.try_route_external_dnd_payload(payload, event_loop)
.err(),
};
let payload = match payload {
None => None,
Some(payload) => self
.try_route_async_completion_payload(payload, event_loop)
.err(),
};
let payload = match payload {
None => None,
Some(payload) => self
.try_route_native_menu_payload(payload, event_loop)
.err(),
};
let payload = match payload {
None => None,
Some(payload) => self.try_route_web_view_payload(payload, event_loop).err(),
};
#[cfg(all(feature = "automation", debug_assertions))]
let payload = match payload {
None => None,
Some(payload) => self.try_route_automation_payload(payload, event_loop).err(),
};
if let Some(payload) = payload {
// Did one of the framework's own built-in arms below claim
// it? Only what is left over is offered to the app's
// `on_external_with_ctx` router (see
// `route_external_with_ctx`). The framework arms run FIRST,
// so an app router that returns `true` too eagerly can never
// swallow a `CloseWindowRequest` or a title-bar synthetic
// event; and because the answer is the chain's own trailing
// `else`, a built-in arm added later is withheld from the
// app router automatically — there is no second list of
// "framework-owned types" to keep in step.
let mut consumed = true;
{
if let Some(req) = payload.downcast_ref::<CloseWindowRequest>() {
// Custom-chrome (Teksilo-drawn) title-bar close
// button — an interactive gesture, so it runs
// through the window's close guard (guarded
// close), matching the OS close button.
self.wm.request_close(req.teksilo_id);
} else if let Some(evt) = payload.downcast_ref::<TitleBarSyntheticEvent>() {
// Windows custom-chrome wndproc sends this when
// `WM_NCLBUTTONUP` fires over a control-button
// hit-region. The button's pixels are owned by
// the OS so the widget tree never saw the click;
// re-issue it as a synthetic tap on the
// matching `ControlButton`.
self.wm
.route_title_bar_synthetic_tap(evt.teksilo_id, evt.target);
} else if let Some(evt) = payload.downcast_ref::<TitleBarHoverEvent>() {
// Same idea for hover: `WM_NCMOUSEMOVE` over a
// control-button hit-region delivers an
// entered/leave event the widget tree never
// sees, so we drive the matching button's
// hover signal explicitly.
self.wm.route_title_bar_synthetic_hover(
evt.teksilo_id,
evt.target,
evt.entered,
);
} else if let Some(inject) = payload.downcast_ref::<SyntheticImeInject>() {
// Test / demo hook: replay a scripted IME
// sequence into the focused window's focused
// widget through the real dispatch path — no OS
// IME needed. Mirrors exactly what the
// `WindowEvent::Ime` arm produces.
let target = self
.wm
.windows_map()
.iter()
.find(|(_, m)| m.focused)
.or_else(|| self.wm.windows_map().iter().next())
.map(|(id, _)| *id);
if let Some(winit_id) = target {
for evt in inject.events.clone() {
self.dispatch_in_window(winit_id, evt, event_loop);
}
}
} else if let Some(req) =
payload.downcast_ref::<teksilo_core::RepaintWindowRequest>()
{
// Off-thread "repaint this window" — e.g. a
// terminal's PTY-reader thread whose bytes changed a
// widget's content outside the UI thread. A bare
// redraw re-presents the cached frame, so mark the
// window's tree paint-dirty; the unconditional
// `request_redraw_all()` below then re-runs the
// changed widget's `paint()`.
let winit_id =
self.wm.teksilo_to_winit_map().get(&req.window_id).copied();
if let Some(winit_id) = winit_id
&& let Some(managed) = self.wm.get_by_winit_mut(winit_id)
{
managed.tree.mark_all_needs_paint_only();
}
} else {
consumed = false;
}
}
if !consumed {
self.route_external_with_ctx(&*payload, event_loop);
}
}
}
_ => {}
}
if let Some(trace) = &mut self.idle_trace {
trace.note_request_redraw_all();
}
self.wm.request_redraw_all();
self.post_event(event_loop);
}
fn window_event(
&mut self,
event_loop: &ActiveEventLoop,
window_id: WindowId,
event: WindowEvent,
) {
self.handle_window_event_inner(event_loop, window_id, event);
}
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
// Drive any registered per-turn closure (the async executor poll when
// `teksilo-async` is installed) before computing the next control
// flow. A `true` return means tasks advanced and may have mutated
// reactive state, so repaint the open windows — mirroring the
// subscription-delivery redraw in `user_event`.
if let Some(tick) = &mut self.loop_tick
&& tick()
{
self.wm.request_redraw_all();
}
self.process_pending(event_loop);
self.maybe_exit(event_loop);
self.update_control_flow(event_loop);
}
}
/// Payload used by `TitleBarHostCallbacks::request_close` to route a
/// host-initiated close back to the main event loop. The host's
/// close callback boxes one of these through `AppEventProxy::send_external`;
/// `TeksiloAppHandler::user_event` downcasts the payload and calls
/// `WindowManager::queue_close` so the window tears down on the next tick
/// (matching the `WindowEvent::CloseRequested` path).
#[derive(Debug, Clone, Copy)]
pub struct CloseWindowRequest {
pub teksilo_id: TeksiloWindowId,
}
/// Test / demo payload that replays a scripted IME sequence into the
/// focused window's focused widget, through the same dispatch path the
/// real `WindowEvent::Ime` arm uses — so the full preedit pipeline
/// (document mutation, underline, caret-area reporting, AT selection) can
/// be exercised without an OS input method installed.
///
/// Post it via [`AppEventPoster::post_external`](teksilo_core::AppEventPoster)
/// (reachable from a handler with `ctx.poster()`).
#[derive(Debug, Clone)]
pub struct SyntheticImeInject {
pub events: Vec<teksilo_core::event::WidgetEvent>,
}
// `TitleBarSyntheticEvent` and `TitleBarHoverEvent` live in
// `teksilo_core::window_chrome` so teksilo-platform (which posts them from
// the Windows wndproc subclass) and teksilo-app (which routes them) can
// both name the type without teksilo-platform depending on teksilo-app.
pub use teksilo_core::{TitleBarHoverEvent, TitleBarSyntheticEvent};
/// A thread-safe handle for posting `AppEvent`s to the UI thread.
///
/// Clone and send to background threads. The event loop wakes up
/// and processes the event like any other input.
#[derive(Clone)]
pub struct AppEventProxy {
inner: winit::event_loop::EventLoopProxy<AppEvent>,
}
impl AppEventProxy {
/// Post a background completion event.
pub fn send_background_complete(&self, operation_id: String) {
let _ = self
.inner
.send_event(AppEvent::BackgroundComplete { operation_id });
}
/// Post a background progress event.
pub fn send_background_progress(&self, operation_id: String, percent: f32, message: String) {
let _ = self.inner.send_event(AppEvent::BackgroundProgress {
operation_id,
percent,
message,
});
}
/// Post an arbitrary external event.
pub fn send_external(&self, payload: impl std::any::Any + Send + 'static) {
let _ = self.inner.send_event(AppEvent::External(Box::new(payload)));
}
/// Post a pre-boxed external event. Used by callers that already
/// hold a `Box<dyn Any + Send>` (notably
/// `TitleBarHostCallbacks::post_external`, which abstracts the
/// posting mechanism behind a closure that teksilo-core can hold
/// without depending on winit).
pub fn send_external_boxed(&self, payload: Box<dyn std::any::Any + Send>) {
let _ = self.inner.send_event(AppEvent::External(payload));
}
/// Post a backend-event delivery for the given subscription id. Called
/// by the framework's event-source wrapper from the publisher thread.
pub fn post_subscription_event(
&self,
sub_id: SubscriptionId,
event: Box<dyn std::any::Any + Send>,
) {
let _ = self
.inner
.send_event(AppEvent::SubscriptionEvent { sub_id, event });
}
}
/// `AppEventProxy` implements [`AppEventPoster`] directly so it can be both the
/// `Arc<dyn AppEventPoster>` every widget tree holds AND handed to background
/// integrations (e.g. the `teksilo-async` executor's cross-thread waker, wired
/// via [`TeksiloAppBuilder::on_ready`]). teksilo-core cannot import winit, so
/// this trait implementation lives here.
impl AppEventPoster for AppEventProxy {
fn post_subscription_event(
&self,
sub_id: SubscriptionId,
event: Box<dyn std::any::Any + Send>,
) {
let _ = self
.inner
.send_event(AppEvent::SubscriptionEvent { sub_id, event });
}
fn post_external(&self, payload: Box<dyn std::any::Any + Send>) {
let _ = self.inner.send_event(AppEvent::External(payload));
}
}
/// Builder for a Teksilo application.
pub struct TeksiloAppBuilder {
theme: Theme,
theme_mode: ThemeMode,
#[cfg(feature = "text")]
typesetter: Option<SharedTypesetter>,
#[cfg(feature = "text")]
font_registrars: Vec<Box<dyn teksilo_text::FontRegistrar>>,
app_event_handler: Option<Box<dyn FnMut(&AppEvent)>>,
external_ctx_handler: Option<ExternalCtxHandler>,
on_ready: Vec<Box<dyn FnOnce(AppEventProxy)>>,
initial_window: Option<WindowConfig>,
/// Type-erased adapter for the application's backend event source.
/// Installed via `event_source<S>(source)`.
event_source: Option<EventSourceAdapter>,
/// Application-scoped values keyed by `TypeId`.
/// Installed via `app_state::<T>(value)` and reachable from any
/// `BuildContext` via `ctx.app_state::<T>()`.
app_state_registry: HashMap<TypeId, Box<dyn Any>>,
/// Internationalization configuration. Installed
/// via `i18n(I18nConfig)`. When present, an `I18nManager` is built at
/// `build_headless` / `run` time and registered on the thread-local so
/// `tr!`-expanded code can resolve translations.
i18n: Option<I18nConfig>,
/// Tooltip content entries registered via
/// [`register_tooltips`](Self::register_tooltips). Frozen into a
/// thread-local registry in `run` / `build_headless` before the
/// first frame builds.
tooltip_contents: Vec<teksilo_widgets::tooltip::TooltipContent>,
/// OS-correct application paths (config / data dirs). Set via
/// [`application`](Self::application) or [`app_paths`](Self::app_paths).
/// Required when `settings_bundle` is set.
app_paths: Option<teksilo_settings::AppPaths>,
/// Persistence configuration. When present, the bundle is opened
/// at startup and each enabled service is registered into the
/// `app_state` registry under its concrete type.
settings_bundle: Option<teksilo_settings::SettingsBundle>,
/// Whether `run()` should start a `SettingsWatcher` over the settings
/// directories so a peer process's write is picked up live. On by
/// default whenever a settings bundle is configured — this is the
/// entire point of `SettingsBundle`'s cross-process-safe writes.
/// Toggle off via [`settings_watch`](Self::settings_watch) for tests
/// or environments without a usable filesystem watcher.
settings_watch_enabled: bool,
/// Telemetry configuration. When present, the bundle is opened
/// after `settings_bundle` (it depends on `SettingsStore`) and the
/// resulting `OpenedTelemetry` + `TelemetryContext` are registered
/// into the `app_state` registry. The `TelemetryContext` is the
/// hook the dispatch tap in
/// [`teksilo_core::widget_tree::WidgetTree::dispatch_intent`] uses to
/// emit `intent.dispatched` events.
#[cfg(feature = "telemetry")]
telemetry_bundle: Option<teksilo_telemetry::TelemetryBundle>,
/// Per-loop-turn closure + poll flag installed via
/// [`on_loop_tick`](Self::on_loop_tick). Async-agnostic; moved into the
/// handler at `run`.
loop_tick: Option<Box<dyn FnMut() -> bool>>,
loop_tick_poll: Option<std::rc::Rc<std::cell::Cell<bool>>>,
}
impl TeksiloAppBuilder {
pub fn new() -> Self {
Self {
theme: teksilo_core::presets::intui::light(),
theme_mode: ThemeMode::Manual,
#[cfg(feature = "text")]
typesetter: None,
#[cfg(feature = "text")]
font_registrars: Vec::new(),
app_event_handler: None,
external_ctx_handler: None,
on_ready: Vec::new(),
initial_window: None,
event_source: None,
app_state_registry: HashMap::new(),
i18n: None,
tooltip_contents: Vec::new(),
app_paths: None,
settings_bundle: None,
settings_watch_enabled: true,
#[cfg(feature = "telemetry")]
telemetry_bundle: None,
loop_tick: None,
loop_tick_poll: None,
}
}
/// Identify the application for OS-correct path resolution. The
/// `(qualifier, organization, application)` triple follows the
/// `directories` convention (e.g. `("eu", "FernTech", "Skribisto")`).
/// Required when [`settings`](Self::settings) is used.
///
/// # Panics
///
/// Panics if the OS does not expose a usable home directory
/// (typically a sandboxed environment with `HOME` unset). Use
/// [`app_paths`](Self::app_paths) to supply an explicit path
/// in that situation.
pub fn application(mut self, qualifier: &str, organization: &str, application: &str) -> Self {
let paths = teksilo_settings::AppPaths::new(qualifier, organization, application)
.unwrap_or_else(|| {
panic!(
"TeksiloAppBuilder::application(\"{qualifier}\", \"{organization}\", \
\"{application}\"): could not resolve a usable OS config directory. \
This typically happens in sandboxed environments with no HOME set. \
Use TeksiloAppBuilder::app_paths(AppPaths::for_testing(...) or \
AppPaths::from_dirs(...)) to supply an explicit location.",
)
});
self.app_paths = Some(paths);
self
}
/// Provide an explicit [`AppPaths`](teksilo_settings::AppPaths). Used
/// for portable-mode apps and tests.
pub fn app_paths(mut self, paths: teksilo_settings::AppPaths) -> Self {
self.app_paths = Some(paths);
self
}
/// Read the currently-configured `AppPaths`, if any. Used by
/// builder-extension traits (e.g. `install_toast` in `teksilo`)
/// that need to open persistent files at install time before
/// `run` fires.
pub fn configured_app_paths(&self) -> Option<&teksilo_settings::AppPaths> {
self.app_paths.as_ref()
}
/// Configure the persistence bundle. When `run`/`build_headless`
/// fires, the bundle is opened against the configured `AppPaths`
/// and every active service is registered in `app_state`, where
/// it becomes reachable via the
/// [`SettingsExt`](teksilo_settings::SettingsExt) trait.
///
/// # Panics
///
/// Panics during `run` / `build_headless` if no `AppPaths` was
/// configured first via [`application`](Self::application) or
/// [`app_paths`](Self::app_paths).
pub fn settings(mut self, bundle: teksilo_settings::SettingsBundle) -> Self {
self.settings_bundle = Some(bundle);
self
}
/// Enable or disable the live cross-process settings-reload watcher
/// started in [`run`](Self::run) (windowed apps only —
/// [`build_headless`](Self::build_headless) never starts one, since
/// there is no event loop to post the reload event through).
///
/// **On by default** whenever [`settings`](Self::settings) is
/// configured: this is what makes a peer process's write to a
/// shared settings file (Skribisto's one-process-per-project model
/// shares `general.toml` / `recents.toml` / `window_state.toml`
/// across every open project) show up in this process's UI with no
/// restart and no polling. Pass `false` to opt out — e.g. a
/// sandboxed test environment with no usable filesystem watcher, or
/// an app that wants to poll `Reloadable::reload_from_disk` on its
/// own schedule instead.
pub fn settings_watch(mut self, enabled: bool) -> Self {
self.settings_watch_enabled = enabled;
self
}
/// Configure the telemetry stack (`teksilo-telemetry`). Mirrors
/// [`settings`](Self::settings): the bundle is opened during
/// `run` / `build_headless` against the configured `AppPaths`
/// **and** the live `SettingsStore`, and the resulting handles
/// (`OpenedTelemetry`, `TelemetryContext`, `DynamicReporter`) are
/// registered into `app_state`. Apps reach them via
/// [`teksilo_telemetry::TelemetryExt`] (`use teksilo_telemetry::TelemetryExt;`).
///
/// # Panics
///
/// Panics during `run` / `build_headless` if no `AppPaths` was
/// configured first via [`application`](Self::application) or
/// [`app_paths`](Self::app_paths), or if no
/// [`settings`](Self::settings) bundle was registered (the
/// telemetry consent file is opened via the same `AppPaths` and
/// the endpoint-override key is read from the `SettingsStore`).
#[cfg(feature = "telemetry")]
pub fn telemetry(mut self, bundle: teksilo_telemetry::TelemetryBundle) -> Self {
self.telemetry_bundle = Some(bundle);
self
}
/// Register the application's tooltip string catalog.
///
/// Each [`TooltipContent`](teksilo_widgets::tooltip::TooltipContent)
/// in the list maps a short stable key (referenced from inline
/// markup as `[label](:key)`) to a translatable body, an optional
/// long-form "more" body revealed by the Accordion disclosure
/// inside a sticky rich tooltip, and an optional keyboard shortcut
/// (literal label — registry-backed auto-lookup is a follow-up).
///
/// This is a **single-call registration**: the list is the
/// application's complete tooltip catalog. Call once at app boot,
/// before `run()`. Calling multiple times panics in debug builds.
///
/// ```ignore
/// use teksilo_widgets::tooltip::TooltipContent;
///
/// TeksiloAppBuilder::new()
/// .register_tooltips(vec![
/// TooltipContent::new("save-as", tr!(save_as_tooltip))
/// .for_shortcut("app.save_as"),
/// TooltipContent::new("autosave", tr!(autosave_tooltip))
/// .with_more(tr!(autosave_tooltip_more)),
/// ])
/// // …
/// ```
///
/// **Multiple calls accumulate**, like [`Self::register_fonts`] and
/// [`I18nConfig::compile_in`](teksilo_i18n::I18nConfig::compile_in), so an
/// application can compose its own catalogue with catalogues shipped by
/// plugins, extensions or sibling crates. Assigning here instead would mean
/// a contributor registering one tooltip silently deleted every tooltip the
/// application had — the failure has no error and no warning, it just makes
/// rich tooltips stop resolving their `[label](:key)` links.
///
/// On a duplicate key the **first** registration wins; see
/// [`install_tooltip_registry`](teksilo_widgets::tooltip::install_tooltip_registry).
pub fn register_tooltips(
mut self,
contents: Vec<teksilo_widgets::tooltip::TooltipContent>,
) -> Self {
self.tooltip_contents.extend(contents);
self
}
/// Register a backend event source. Widgets can
/// then call `BuildContext::subscribe_event(origin, callback)` from
/// inside their `build()` method to receive events on the UI thread.
///
/// Only one source per application is supported. Subsequent calls
/// replace the previously registered source.
pub fn event_source<S: EventSource>(mut self, source: S) -> Self {
self.event_source = Some(EventSourceAdapter::new(source));
self
}
/// Register an application-defined value of type `T` that any widget
/// can retrieve via `BuildContext::app_state::<T>()`.
///
/// Each type `T` may be registered at most once; a subsequent call
/// with the same type replaces the previous value. To share multiple
/// values of the same logical kind, wrap each in a distinct newtype.
pub fn app_state<T: 'static>(mut self, value: T) -> Self {
self.app_state_registry
.insert(TypeId::of::<T>(), Box::new(value));
self
}
/// Register an app-wide [`DefaultPostRoot`](crate::DefaultPostRoot) hook that wraps every
/// window's root after its `root_builder` runs.
///
/// Unlike `app_state(DefaultPostRoot::new(..))` — which stores a single
/// type-keyed value and so silently replaces any previously-registered
/// hook — this **composes**: each registered hook runs in call order,
/// each wrapping the previous one's result. So an app that installs the
/// debug inspector AND the toast host (or any other post-root chrome)
/// gets both wrappers, not just whichever was installed last. The
/// earlier-registered hook is the innermost wrapper (it sees the raw
/// user root); the latest is outermost.
///
/// All framework installers that splice window-level chrome
/// (`install_inspector_in_debug`, `install_toast*`) route through this,
/// so their order of installation no longer matters for correctness.
pub fn register_post_root(mut self, hook: crate::DefaultPostRoot) -> Self {
use crate::DefaultPostRoot;
let key = TypeId::of::<DefaultPostRoot>();
let composed = match self.app_state_registry.remove(&key) {
Some(existing) => {
let existing = *existing
.downcast::<DefaultPostRoot>()
.expect("DefaultPostRoot slot held a non-DefaultPostRoot value");
let prev = existing.0;
let next = hook.0;
DefaultPostRoot(std::rc::Rc::new(move |tree, root_id| {
let inner = prev(tree, root_id);
next(tree, inner)
}))
}
None => hook,
};
self.app_state_registry.insert(key, Box::new(composed));
self
}
/// Register a composable observer that runs on every `AppEvent`,
/// in addition to (never instead of) the single
/// [`on_app_event`](Self::on_app_event) handler.
///
/// Unlike `on_app_event` — which stores a single `Option<Box<dyn
/// FnMut(&AppEvent)>>` and so silently replaces any previously
/// registered handler — this **composes**: each registered observer
/// runs, in call order, on every `AppEvent` delivered to the UI
/// thread. So a framework extension that needs to react to
/// `AppEvent`s (e.g. `teksilo::install_toast` turning
/// `AppEvent::SettingsWriteFailed` into a toast) can register its
/// own observer without clobbering the application's own
/// `on_app_event` handler, or being clobbered by it, regardless of
/// install order. Mirrors [`register_post_root`](Self::register_post_root)'s
/// type-keyed `app_state` composition pattern exactly, but for
/// event observation instead of post-root window chrome.
///
/// See `TeksiloAppHandler::user_event` for the dispatch order: the
/// `on_app_event` handler runs first, then every composed observer.
pub fn register_app_event_observer(mut self, observer: impl Fn(&AppEvent) + 'static) -> Self {
use crate::app_event_observers::AppEventObservers;
let key = TypeId::of::<AppEventObservers>();
let observer = AppEventObservers::new(observer);
let composed = match self.app_state_registry.remove(&key) {
Some(existing) => {
let existing = *existing
.downcast::<AppEventObservers>()
.expect("AppEventObservers slot held a non-AppEventObservers value");
let prev = existing.0;
let next = observer.0;
AppEventObservers(std::rc::Rc::new(move |event: &AppEvent| {
prev(event);
next(event);
}))
}
None => observer,
};
self.app_state_registry.insert(key, Box::new(composed));
self
}
/// Install the rfd-backed native file-dialog service. Registers a
/// [`FileDialogHandle`](teksilo_platform::file_dialog::FileDialogHandle)
/// wrapping an
/// [`RfdAsyncBackend`](teksilo_platform::file_dialog::RfdAsyncBackend)
/// into the app-state registry. Reachable from any handler via
/// `ctx.app_state::<FileDialogHandle>()`, or — with
/// `use teksilo_platform::file_dialog::EventContextFileDialogExt;` —
/// directly via `ctx.pick_file(req, |result, ctx| ...)`.
///
/// Apps that ship a custom or mock backend bypass this and call
/// `.app_state(FileDialogHandle::new(my_backend))` directly.
#[cfg(feature = "rfd-backend")]
pub fn install_file_dialog(mut self) -> Self {
use teksilo_platform::file_dialog::{FileDialogHandle, RfdAsyncBackend};
let handle = FileDialogHandle::new(RfdAsyncBackend::new());
self.app_state_registry
.insert(TypeId::of::<FileDialogHandle>(), Box::new(handle));
self
}
/// Install the external (OS) drag-and-drop service. Registers an
/// [`ExternalDndHandle`](teksilo_platform::external_dnd::ExternalDndHandle)
/// wrapping the platform's default backend
/// ([`default_backend`](teksilo_platform::external_dnd::default_backend) —
/// raw `NSDraggingDestination` on macOS, OLE on Windows, `wl_data_device`
/// on Wayland, a no-op on X11) into the app-state registry.
///
/// Once installed, every window is registered as an OS drop target on
/// creation (and detached on close) by the window manager. Drops surface
/// to widgets through the normal drag handlers (`on_drag_hover` /
/// `on_drag_leave` / `on_drop`) with `payload.is_external()` true — the
/// ready-made `DropZone` widget consumes them.
///
/// Apps that ship a custom backend bypass this and call
/// `.app_state(ExternalDndHandle::new(my_backend))` directly.
pub fn install_external_dnd(mut self) -> Self {
use teksilo_platform::external_dnd::{ExternalDndHandle, default_backend};
let handle = ExternalDndHandle::new(default_backend());
self.app_state_registry
.insert(TypeId::of::<ExternalDndHandle>(), Box::new(handle));
self
}
/// Install the native (OS) menu service. Registers a
/// [`NativeMenuHandle`](teksilo_platform::native_menu::NativeMenuHandle)
/// wrapping the platform's default backend (a real `NSMenu` on macOS, a
/// no-op elsewhere) into the app-state registry.
///
/// Once installed, a [`MenuBar`](teksilo_widgets::MenuBar) built with
/// `from_model(..).native_on_macos(..)` mirrors its [`MenuModel`](teksilo_widgets::MenuModel) into the
/// global menu bar on macOS, and item activations route back through the
/// usual `Intent`/`Action` pipeline. The global menu follows window focus
/// automatically (see the `WindowEvent::Focused` arm).
///
/// Apps that ship a custom backend bypass this and call
/// `.app_state(NativeMenuHandle::new(my_backend))` directly.
pub fn install_native_menu(mut self) -> Self {
use teksilo_platform::native_menu::{NativeMenuHandle, default_backend};
let handle = NativeMenuHandle::new(default_backend());
self.app_state_registry
.insert(TypeId::of::<NativeMenuHandle>(), Box::new(handle));
self
}
/// Register an `I18nConfig`. Constructs an
/// `I18nManager` at startup, installs it on the thread-local, and
/// seeds the widget tree with the resolved initial locale and layout
/// direction. Without this call, `tr!`-expanded code falls back to
/// returning the literal key as a placeholder.
pub fn i18n(mut self, config: I18nConfig) -> Self {
self.i18n = Some(config);
self
}
/// Set a fixed theme (implies `ThemeMode::Manual`).
pub fn theme(mut self, theme: Theme) -> Self {
self.theme = theme;
self.theme_mode = ThemeMode::Manual;
self
}
/// Set how the application resolves its theme.
///
/// - `ThemeMode::Manual` — use the theme set via `.theme()` (default).
/// - `ThemeMode::FollowSystem` — auto-switch between light/dark built-in themes.
/// - `ThemeMode::Native` — read colors from OS desktop environment config.
pub fn theme_mode(mut self, mode: ThemeMode) -> Self {
self.theme_mode = mode;
self
}
#[cfg(feature = "text")]
pub fn typesetter(mut self, typesetter: SharedTypesetter) -> Self {
self.typesetter = Some(typesetter);
self
}
/// Register additional fonts (e.g. a theme's font family) into the
/// shared typesetter at startup, *before* any text is shaped — so a
/// theme that sets `typography.body.family = "Roboto"` resolves
/// correctly instead of silently falling back to the bundled Inter.
///
/// A theme preset typically exposes a `FontRegistrar` the app passes
/// here:
/// ```ignore
/// TeksiloAppBuilder::new()
/// .theme(material3::light())
/// .register_fonts(material3::font_registrar())
/// .run();
/// ```
#[cfg(feature = "text")]
pub fn register_fonts(mut self, registrar: impl teksilo_text::FontRegistrar + 'static) -> Self {
self.font_registrars.push(Box::new(registrar));
self
}
/// Register a handler for `AppEvent`s received from background threads.
pub fn on_app_event(mut self, handler: impl FnMut(&AppEvent) + 'static) -> Self {
self.app_event_handler = Some(Box::new(handler));
self
}
/// Register a router for [`AppEvent::External`] payloads that needs to
/// **open, find or focus windows** — see [`ExternalCtxHandler`].
///
/// [`on_app_event`](Self::on_app_event) is the hook for reacting to an event;
/// this is the hook for *acting on the window set* because of one. The
/// difference is not stylistic: `on_app_event` receives `&AppEvent` and
/// nothing else, and `EventContext::open_window` panics on a standalone
/// context, so there is no way to open a window from there at all.
///
/// The handler runs against the focused window's tree (or the primary
/// window's) with a real [`WindowOps`](teksilo_core::WindowOps) sink, and is
/// consulted **only** for payloads that no framework router and no built-in
/// downcast arm claimed — so it never has to defend against
/// `CloseWindowRequest` and friends. Return `true` when the payload was
/// yours.
///
/// Unlike [`register_app_event_observer`](Self::register_app_event_observer),
/// this is a single slot: calling it twice replaces the first router, the
/// same way `on_app_event` does.
///
/// ```ignore
/// // A single-instance app: a second launch forwards its argv over a socket,
/// // the listener posts it with `AppEventProxy::send_external`, and this
/// // opens (or raises) the document window — the "document window" recipe in
/// // docs/multi-window.md, driven from off the UI thread.
/// .on_external_with_ctx(move |payload, ctx| {
/// let Some(req) = payload.downcast_ref::<OpenDocument>() else {
/// return false;
/// };
/// let wid = window_id_for(&req.path);
/// match ctx.find_window(&wid) {
/// Some(id) => ctx.focus_window(id),
/// None => { ctx.open_window(document_window_config(&req.path)); }
/// }
/// true
/// })
/// ```
pub fn on_external_with_ctx(
mut self,
handler: impl FnMut(
&(dyn std::any::Any + Send),
&mut teksilo_core::widget::EventContext,
) -> bool
+ 'static,
) -> Self {
self.external_ctx_handler = Some(Box::new(handler));
self
}
/// Register a callback that receives an `AppEventProxy` once the event loop is ready.
/// Use this to hand the proxy to background threads that need to post commands.
/// May be called more than once; all registered callbacks fire in order
/// (e.g. `install_async` registers one to wire the executor's waker).
pub fn on_ready(mut self, handler: impl FnOnce(AppEventProxy) + 'static) -> Self {
self.on_ready.push(Box::new(handler));
self
}
/// Register a closure run once per event-loop turn (at the top of
/// `about_to_wait`) plus a shared poll flag. Returning `true` from the
/// closure means it advanced work that may have mutated UI state, which
/// triggers a repaint of all windows. While `poll_source` is set the loop
/// stays in [`ControlFlow::Poll`] so the closure keeps running; when it
/// clears, the loop sleeps until the next event (off-thread wakes arrive
/// via [`AppEventProxy`]).
///
/// General-purpose and async-agnostic — `teksilo-app` only ever sees
/// `FnMut`. The optional `teksilo-async` crate uses this to drive a
/// main-thread executor; nothing in the core loop depends on a runtime.
pub fn on_loop_tick(
mut self,
poll_source: std::rc::Rc<std::cell::Cell<bool>>,
tick: impl FnMut() -> bool + 'static,
) -> Self {
self.loop_tick = Some(Box::new(tick));
self.loop_tick_poll = Some(poll_source);
self
}
/// Configure the initial window. Required — every app must open at
/// least one window at startup. The single canonical entry point:
/// build a [`WindowConfig`] and pass it here.
///
/// ```ignore
/// TeksiloAppBuilder::new()
/// .theme(teksilo_core::presets::intui::light())
/// .initial_window(
/// WindowConfig::new()
/// .title("My App")
/// .size(800, 600)
/// .root(|tree, _state| tree.add(MyRoot::new())),
/// )
/// .run();
/// ```
pub fn initial_window(mut self, config: WindowConfig) -> Self {
self.initial_window = Some(config);
self
}
/// Open the configured settings bundle (if any) and register
/// each service in the app-state registry.
fn install_settings(&mut self) -> Option<teksilo_settings::OpenedSettings> {
let bundle = self.settings_bundle.take()?;
let paths = self.app_paths.clone().expect(
"TeksiloAppBuilder::settings(...) requires .application(...) or .app_paths(...) \
to be set first so persistence has a target directory.",
);
match bundle.open(&paths) {
Ok(opened) => {
self.app_state_registry.insert(
TypeId::of::<teksilo_settings::SettingsStore>(),
Box::new(opened.store.clone()),
);
if let Some(w) = &opened.window_state {
self.app_state_registry.insert(
TypeId::of::<teksilo_settings::WindowStateService>(),
Box::new(w.clone()),
);
}
// Reachable from any handler via
// `ctx.app_state::<teksilo_settings::SettingsRegistry>()`,
// so application code can register its own ad hoc
// `SettingsFile` / `PersistedListModel` / `MruList`
// handles into the very same registry a `SettingsWatcher`
// event gets dispatched through — not just the two
// services the bundle itself opens.
self.app_state_registry.insert(
TypeId::of::<teksilo_settings::SettingsRegistry>(),
Box::new(opened.registry.clone()),
);
Some(opened)
}
Err(e) => {
eprintln!("teksilo-app: failed to open settings bundle: {e}");
None
}
}
}
/// Open the configured telemetry bundle (if any) and register the
/// resulting handles into `app_state` so the dispatch tap and the
/// `TelemetryExt` accessors can reach them. Must be called *after*
/// `install_settings`, because `TelemetryBundle::open` reads the
/// endpoint-override key from the live `SettingsStore`.
///
/// # Panics
///
/// Panics if `.telemetry(...)` was called without prior
/// `.application(...)` / `.app_paths(...)`, or without a
/// `.settings(...)` bundle. Both are hard requirements: the
/// consent file needs an `AppPaths` target, and the runtime
/// endpoint-override key lives in the `SettingsStore`.
/// Fail-closed by design — a misconfigured app must not silently
/// skip telemetry installation.
#[cfg(feature = "telemetry")]
fn install_telemetry(&mut self, settings: Option<&teksilo_settings::SettingsStore>) {
let Some(bundle) = self.telemetry_bundle.take() else {
return;
};
let paths = self.app_paths.clone().expect(
"TeksiloAppBuilder::telemetry(...) requires .application(...) or .app_paths(...) \
to be set first so the consent file has a target directory.",
);
let store = settings.expect(
"TeksiloAppBuilder::telemetry(...) requires .settings(...) so the runtime \
endpoint-override key can be read from the SettingsStore. \
Add .settings(SettingsBundle::new()) before .telemetry(...).",
);
match bundle.open(&paths, store) {
Ok(opened) => {
// Register the OpenedTelemetry under its concrete type
// so widgets can access it via TelemetryExt::telemetry().
self.app_state_registry.insert(
TypeId::of::<teksilo_telemetry::OpenedTelemetry>(),
Box::new(opened.clone()),
);
// Register the dispatch hook under the teksilo-core type.
// The dispatch tap looks this up by TypeId.
let session_id = generate_session_id();
let tcx = teksilo_core::telemetry::TelemetryContext {
reporter: opened.reporter.clone()
as std::rc::Rc<dyn teksilo_core::telemetry::UsageReporter>,
session_id,
schema_version: opened.event_schema_version,
};
self.app_state_registry.insert(
TypeId::of::<teksilo_core::telemetry::TelemetryContext>(),
Box::new(tcx),
);
}
Err(e) => {
eprintln!("teksilo-app: failed to open telemetry bundle: {e}");
}
}
}
/// Build a headless app for testing (no window, no GPU).
pub fn build_headless(mut self) -> HeadlessApp {
// Install the tooltip registry before anything else — widgets
// that read from it during their first build (e.g. rich
// tooltips looking up their :key) need it available.
if !self.tooltip_contents.is_empty() {
teksilo_widgets::tooltip::install_tooltip_registry(std::mem::take(
&mut self.tooltip_contents,
));
}
// Open settings (if a bundle was configured) and register the
// services into `app_state_registry` so they're reachable from
// any handler via the SettingsExt trait.
let opened_settings = self.install_settings();
// Open telemetry (if a bundle was configured). Must come after
// install_settings — TelemetryBundle reads the endpoint-override
// key from the SettingsStore.
#[cfg(feature = "telemetry")]
self.install_telemetry(opened_settings.as_ref().map(|s| &s.store));
let mut tree = WidgetTree::new().with_theme(self.theme.clone());
#[cfg(feature = "text")]
let typesetter = {
let ts = self
.typesetter
.take()
.unwrap_or_else(SharedTypesetter::new_with_default_font);
// Install app/theme fonts before any text is shaped, so a
// theme's `typography.*.family` resolves instead of falling
// back to the bundled default.
for registrar in &self.font_registrars {
ts.apply_font_registrar(registrar.as_ref());
}
tree = tree.with_text_backend(ts.as_text_backend());
// Auto-register so rich-text widgets can reach the shared
// typesetter via `ctx.app_state::<SharedTypesetter>()` in
// headless tests too.
use std::any::TypeId;
self.app_state_registry
.insert(TypeId::of::<SharedTypesetter>(), Box::new(ts.clone()));
ts
};
#[cfg(not(feature = "text"))]
let _ = &mut self;
// Install the i18n manager (if any) and seed the tree with the
// resolved initial locale and layout direction. Must happen before
// the root builder runs so that any `tr!` calls inside `build()`
// resolve against the correct locale on first build.
let i18n_manager = self.i18n.as_ref().map(|cfg| install_i18n(&mut tree, cfg));
// Install the app-state registry (if any) before running the root
// builder so that widgets' `build()` methods can call
// `ctx.app_state::<T>()`.
if !self.app_state_registry.is_empty() {
let ctx = TreeAppContext::empty().with_app_state(self.app_state_registry);
tree.set_app_context(std::rc::Rc::new(ctx));
}
#[cfg(feature = "text")]
let _ = &typesetter;
// Build the root from the `initial_window`'s builder if one was
// provided. Headless apps without an `initial_window` run with an
// empty tree — tests add widgets via `tree.add(...)` directly.
if let Some(mut config) = self.initial_window.take()
&& let Some(root_builder) = config.take_root_builder()
{
// Headless has no real WindowState; construct a stub so
// widgets that bind against their own window signals
// still get a valid handle.
let stub_state = teksilo_core::WindowState::new(teksilo_core::WindowStateInit {
id: crate::TeksiloWindowId::new(0),
string_id: config.string_id.clone(),
placement: config.initial_placement,
title: config.title.clone(),
size: config.size,
position: config.position.unwrap_or((0, 0)),
focused: true,
resizable: config.resizable,
always_on_top: config.always_on_top,
});
tree.set_window_state(stub_state.clone());
root_builder(&mut tree, stub_state);
}
HeadlessApp {
tree,
theme: self.theme,
i18n_manager,
settings: opened_settings,
}
}
/// Build and run the application with windowed rendering.
pub fn run(mut self) {
// Install the tooltip registry before the window manager
// starts building trees — rich tooltips read from it during
// their first build.
if !self.tooltip_contents.is_empty() {
teksilo_widgets::tooltip::install_tooltip_registry(std::mem::take(
&mut self.tooltip_contents,
));
}
// Open settings (if a bundle was configured) so the services
// are present in the app_state registry when window trees
// start being built. The `OpenedSettings` handle is kept on
// the stack so its inner `SettingsFile` clones live long
// enough to flush on shutdown.
let opened_settings = self.install_settings();
// Open telemetry (if a bundle was configured). Must come after
// install_settings — TelemetryBundle reads the endpoint-override
// key from the SettingsStore.
#[cfg(feature = "telemetry")]
self.install_telemetry(opened_settings.as_ref().map(|s| &s.store));
// Construct the i18n manager (if configured) and install it on
// the thread-local before any window or widget tree is created.
// `WindowManager::create_window` seeds every new tree from the
// thread-local, so each window inherits the manager's active
// locale and layout direction on construction — no separate
// post-create seeding step needed here.
//
// `runtime_override` entries are collected before the install
// so the hot-reload watcher can be spun up after the winit
// event loop exists (we need the `EventLoopProxy` as the sink
// target) without a second borrow of `self.i18n`.
let runtime_overrides: Vec<(LanguageIdentifier, std::path::PathBuf)> = self
.i18n
.as_ref()
.map(|cfg| cfg.runtime_overrides().to_vec())
.unwrap_or_default();
if let Some(cfg) = self.i18n.as_ref() {
install_i18n_manager(cfg);
}
let event_loop = winit::event_loop::EventLoop::<AppEvent>::with_user_event()
.build()
.expect("winit event loop creation failed");
event_loop.set_control_flow(ControlFlow::Wait);
// Always create a proxy: it's needed by both `on_ready` (if set)
// and by the event-source poster (if a source is registered). The
// proxy is cheap to clone.
let proxy = AppEventProxy {
inner: event_loop.create_proxy(),
};
// Register the process-wide sink for permanently-discarded
// `teksilo-settings` writes (F3): a `DebouncedWriter` gave up
// after `MAX_WRITE_ATTEMPTS` retries, or was dropped at teardown
// with a write still failing. Previously this only reached an
// `eprintln!` on the settings crate's own background I/O thread
// and was otherwise invisible; this posts a typed `AppEvent`
// through the event loop proxy so it reaches the UI thread like
// every other backend->UI channel (see `user_event` above).
let proxy_for_write_failure = proxy.inner.clone();
teksilo_settings::set_write_failure_sink(std::sync::Arc::new(
move |path, attempts, dropped_patches, message| {
let _ = proxy_for_write_failure.send_event(AppEvent::SettingsWriteFailed {
path,
attempts,
dropped_patches,
message,
});
},
));
// Build the i18n hot-reload watcher if any `runtime_override`s
// were registered. The sink posts `AppEvent::I18nReload` through
// the event loop proxy; the watcher's background thread converts
// file-change events into these messages. The watcher handle is
// handed to `TeksiloAppHandler` which keeps it alive for the loop
// lifetime. Construction failures log and fall back to no
// hot-reload (the rest of i18n still works).
let i18n_watcher = if runtime_overrides.is_empty() {
None
} else {
let proxy_for_sink = proxy.inner.clone();
let sink: teksilo_i18n::ReloadSink = std::sync::Arc::new(move |locale, path| {
let _ = proxy_for_sink.send_event(AppEvent::I18nReload {
locale: locale.to_string(),
path,
});
});
match teksilo_i18n::FtlFileWatcher::new(runtime_overrides, sink) {
Ok(watcher) => Some(watcher),
Err(e) => {
eprintln!("teksilo-app: failed to start i18n file watcher: {e}");
None
}
}
};
// Build the live cross-process settings-reload watcher, mirroring
// the i18n watcher immediately above: on by default whenever a
// settings bundle was actually opened (`opened_settings.is_some()`),
// opt-out via `.settings_watch(false)`. The sink posts
// `AppEvent::SettingsReload` through the event loop proxy; the
// handler (see `user_event` above) dispatches the changed path
// through the app's `SettingsRegistry` (installed into `app_state`
// by `install_settings`). Construction failures log and fall back
// to no live reload — the rest of settings persistence still
// works, peers just won't be noticed until this process happens
// to touch the same key itself.
let settings_watcher = if self.settings_watch_enabled && opened_settings.is_some() {
self.app_paths.as_ref().and_then(|paths| {
let proxy_for_sink = proxy.inner.clone();
let sink: teksilo_settings::SettingsReloadSink = std::sync::Arc::new(move |path| {
let _ = proxy_for_sink.send_event(AppEvent::SettingsReload { path });
});
let dirs = vec![
paths.config_dir().to_path_buf(),
paths.data_dir().to_path_buf(),
];
match teksilo_settings::SettingsWatcher::new(dirs, sink) {
Ok(watcher) => Some(watcher),
Err(e) => {
eprintln!("teksilo-app: failed to start settings file watcher: {e}");
None
}
}
})
} else {
None
};
// Build the typesetter first so we can auto-register it into
// the per-tree app-state registry below. This gives rich-text
// widgets (and anything else that needs direct typesetter
// access) a reachable handle via `ctx.app_state::<SharedTypesetter>()`
// without forcing the application author to wire it manually.
#[cfg(feature = "text")]
let typesetter = self
.typesetter
.unwrap_or_else(SharedTypesetter::new_with_default_font);
#[cfg(feature = "text")]
// Install app/theme fonts before any text is shaped.
for registrar in &self.font_registrars {
typesetter.apply_font_registrar(registrar.as_ref());
}
#[cfg(feature = "text")]
{
use std::any::TypeId;
self.app_state_registry.insert(
TypeId::of::<SharedTypesetter>(),
Box::new(typesetter.clone()),
);
}
// Auto-install a system clipboard handle so `RichTextEditor::editor`
// (and any future clipboard-aware widget) can reach it via
// `EventContext::app_state::<ClipboardHandle>()`. Behind the
// `clipboard` feature because it pulls `arboard` into the build.
// Falls back to `MemoryClipboard` if the OS backend fails to
// initialize (headless CI, missing display, …) so the editor
// still works in-process.
#[cfg(feature = "clipboard")]
{
use std::any::TypeId;
use teksilo_platform::clipboard::{ArboardClipboard, ClipboardHandle, MemoryClipboard};
let handle = match ArboardClipboard::new() {
Ok(backend) => ClipboardHandle::new(backend),
Err(_) => ClipboardHandle::new(MemoryClipboard::new()),
};
self.app_state_registry
.insert(TypeId::of::<ClipboardHandle>(), Box::new(handle));
}
// Always build the per-tree app context — the poster is cheap
// and lets background-work integrations (file dialogs, future
// async-result features) reach the event loop without forcing
// an event-source registration. Apps without an event source,
// app-state registry, or background-work feature simply pay an
// unused Arc<AppEventPoster> per tree.
let poster: std::sync::Arc<dyn AppEventPoster> = std::sync::Arc::new(proxy.clone());
let base = match self.event_source {
Some(adapter) => TreeAppContext::with_source_and_poster(adapter, poster.clone()),
None => TreeAppContext::empty(),
};
let app_context_template = Some(std::rc::Rc::new(
base.with_app_state(self.app_state_registry)
.with_poster(poster),
));
for on_ready in self.on_ready {
on_ready(proxy.clone());
}
let initial_config = self
.initial_window
.expect("TeksiloAppBuilder::initial_window(WindowConfig) is required");
let mut app = TeksiloAppHandler::new(
self.theme,
self.theme_mode,
self.app_event_handler,
initial_config,
app_context_template,
#[cfg(feature = "text")]
typesetter,
i18n_watcher,
settings_watcher,
proxy.clone(),
);
// Hand over the app's own ops-bearing external-event router, if any —
// moved onto the handler after construction (like `loop_tick` below)
// rather than threaded through `TeksiloAppHandler::new`'s already long
// parameter list.
app.external_ctx_handler = self.external_ctx_handler;
// Hand over any registered loop-tick hook (e.g. the `teksilo-async`
// executor poll). Async-agnostic: just a closure + a poll flag.
app.loop_tick = self.loop_tick;
app.loop_tick_poll = self.loop_tick_poll;
event_loop
.run_app(&mut app)
.expect("winit event loop exited with error");
// Flush any pending settings writes synchronously before the
// process exits. The `DebouncedWriter` background threads also
// flush on Drop, but doing it synchronously here also surfaces
// any I/O errors to stderr before the binding goes out of
// scope.
if let Some(opened) = opened_settings
&& let Err(e) = opened.flush_all()
{
eprintln!("teksilo-app: settings flush on exit failed: {e}");
}
}
}
impl Default for TeksiloAppBuilder {
fn default() -> Self {
Self::new()
}
}
/// Build an `I18nManager` from `cfg`, pre-resolve its initial locale,
/// and install it on the thread-local. Shared by `build_headless` and
/// `run` so both paths use identical setup. Returns the manager so the
/// headless caller can hand it to `HeadlessApp`; in the windowed `run`
/// path the thread-local owns it for the process lifetime.
fn install_i18n_manager(cfg: &I18nConfig) -> Rc<I18nManager> {
let mgr = I18nManager::from_config(cfg);
let initial_loc = I18nManager::resolve_initial_locale(cfg);
mgr.set_locale(initial_loc);
teksilo_i18n::thread_local::install(mgr.clone());
mgr
}
/// Headless-only helper: install the i18n manager AND seed the single
/// `WidgetTree` with the resolved locale and direction. The windowed
/// path doesn't need this because `WindowManager::create_window` reads
/// the thread-local and seeds each new tree at construction time; the
/// headless path has no WindowManager so it seeds its one tree here.
fn install_i18n(tree: &mut WidgetTree, cfg: &I18nConfig) -> Rc<I18nManager> {
let mgr = install_i18n_manager(cfg);
tree.set_locale(mgr.locale_signal().get().to_string());
tree.set_layout_direction(mgr.direction_signal().get());
mgr
}
/// A headless app for testing (no window, no GPU).
pub struct HeadlessApp {
pub tree: WidgetTree,
pub theme: Theme,
/// Active i18n manager, if `TeksiloAppBuilder::i18n(...)` was used. Tests
/// can reach the bundles, version signal, and locale signal directly
/// through this handle.
pub i18n_manager: Option<Rc<I18nManager>>,
/// Active persistence services, if `TeksiloAppBuilder::settings(...)`
/// was used. Held here so the underlying `SettingsFile` clones
/// (and their I/O threads) live as long as the headless app.
pub settings: Option<teksilo_settings::OpenedSettings>,
}
impl HeadlessApp {
pub fn theme(&self) -> &Theme {
&self.theme
}
/// The active i18n manager, if `i18n(...)` was registered on the
/// builder.
pub fn i18n_manager(&self) -> Option<&Rc<I18nManager>> {
self.i18n_manager.as_ref()
}
/// Switch the active locale. Updates the manager (which increments the
/// version signal so any `LocalizedString::to_signal()` observers
/// re-resolve), then seeds the tree with the new direction (only when
/// it actually changed) and triggers a composite rebuild via
/// `WidgetTree::set_locale`. No-op if no `I18nConfig` was registered.
pub fn set_locale(&mut self, locale: LanguageIdentifier) {
let Some(mgr) = self.i18n_manager.clone() else {
return;
};
let outcome = mgr.set_locale(locale.clone());
if outcome.direction_changed {
self.tree.set_layout_direction(mgr.direction_signal().get());
}
self.tree.set_locale(locale.to_string());
}
}
#[cfg(test)]
mod tests {
use super::*;
use teksilo_i18n::lit;
use teksilo_tokens::Color;
use teksilo_widgets::{Button, ModalContainer};
#[test]
fn builder_accepts_theme() {
let app = TeksiloAppBuilder::new()
.theme(teksilo_core::presets::intui::light())
.build_headless();
assert_ne!(app.theme().colors.accent, Color::TRANSPARENT);
}
#[test]
fn register_post_root_composes_instead_of_clobbering() {
// Regression: installing two post-root chrome wrappers (e.g. the
// debug inspector AND the toast host) must run BOTH, not just the
// last-installed one — `app_state(DefaultPostRoot)` is type-keyed
// and silently overwrote the earlier hook, killing F12 / overflow
// stripes in any app that also installed toast.
use crate::DefaultPostRoot;
use std::cell::RefCell;
use std::rc::Rc;
let order: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
let (o1, o2) = (order.clone(), order.clone());
let builder = TeksiloAppBuilder::new()
.register_post_root(DefaultPostRoot::new(move |_t, id| {
o1.borrow_mut().push("inspector");
id
}))
.register_post_root(DefaultPostRoot::new(move |_t, id| {
o2.borrow_mut().push("toast");
id
}));
let composed = builder
.app_state_registry
.get(&TypeId::of::<DefaultPostRoot>())
.and_then(|b| b.downcast_ref::<DefaultPostRoot>())
.expect("composed DefaultPostRoot must be present")
.clone();
let mut tree = WidgetTree::new();
let root = tree.add(Button::new(lit!("root")));
let out = (composed.0)(&mut tree, root);
assert_eq!(
*order.borrow(),
vec!["inspector", "toast"],
"both hooks run, earliest-registered innermost (first)"
);
assert_eq!(out, root, "passthrough hooks return the same root id");
}
#[test]
fn register_app_event_observer_composes_instead_of_clobbering() {
// Mirrors `register_post_root_composes_instead_of_clobbering`
// above: two extensions each registering their own `AppEvent`
// observer (e.g. a future telemetry hook AND
// `teksilo::install_toast`'s settings-write-failure toast) must
// both fire, not just the last-installed one.
use crate::app_event_observers::AppEventObservers;
use std::cell::RefCell;
use std::rc::Rc;
use teksilo_core::app_event::AppEvent;
let order: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
let (o1, o2) = (order.clone(), order.clone());
let builder = TeksiloAppBuilder::new()
.register_app_event_observer(move |_event| {
o1.borrow_mut().push("first");
})
.register_app_event_observer(move |_event| {
o2.borrow_mut().push("second");
});
let composed = builder
.app_state_registry
.get(&TypeId::of::<AppEventObservers>())
.and_then(|b| b.downcast_ref::<AppEventObservers>())
.expect("composed AppEventObservers must be present")
.clone();
let event = AppEvent::BackgroundComplete {
operation_id: "op".to_string(),
};
(composed.0)(&event);
assert_eq!(
*order.borrow(),
vec!["first", "second"],
"both observers run, in registration order"
);
}
#[test]
fn register_app_event_observer_does_not_suppress_on_app_event_handler() {
// The composable observer slot and the single `on_app_event`
// handler slot are independent storage (`app_state_registry` vs
// `app_event_handler`), so registering one must never clear or
// shadow the other. `TeksiloAppHandler::user_event` dispatches
// both (handler first, then composed observers) — this test
// proves the two slots coexist and mirrors that dispatch order
// directly, since driving the real `ApplicationHandler::user_event`
// requires a live winit event loop unavailable in a unit test.
use crate::app_event_observers::AppEventObservers;
use std::cell::RefCell;
use std::rc::Rc;
use teksilo_core::app_event::AppEvent;
let handler_fired = Rc::new(RefCell::new(false));
let observer_fired = Rc::new(RefCell::new(false));
let (h1, h2) = (handler_fired.clone(), observer_fired.clone());
let mut builder = TeksiloAppBuilder::new()
.on_app_event(move |_event| {
*h1.borrow_mut() = true;
})
.register_app_event_observer(move |_event| {
*h2.borrow_mut() = true;
});
let mut handler = builder
.app_event_handler
.take()
.expect("on_app_event handler must survive register_app_event_observer");
let observers = builder
.app_state_registry
.get(&TypeId::of::<AppEventObservers>())
.and_then(|b| b.downcast_ref::<AppEventObservers>())
.expect("registered observer must survive on_app_event")
.clone();
let event = AppEvent::BackgroundComplete {
operation_id: "op".to_string(),
};
// Mirrors the dispatch order in `user_event`: handler first, then
// composed observers.
handler(&event);
(observers.0)(&event);
assert!(
*handler_fired.borrow(),
"on_app_event's handler must still fire"
);
assert!(
*observer_fired.borrow(),
"the registered observer must also fire"
);
}
/// `on_external_with_ctx` is a third, independent slot: registering it must
/// not disturb `on_app_event`'s handler or the composable observers, and
/// they must not disturb it. Same shape (and same limitation) as the test
/// above — driving the real `ApplicationHandler::user_event` needs a live
/// winit event loop, so this proves slot independence and the router's own
/// claim contract; that it truly receives a window-capable `EventContext`
/// is proven end-to-end by Skribisto's `scripts/automation_single_instance.py`.
#[test]
fn on_external_with_ctx_is_a_slot_of_its_own() {
use crate::app_event_observers::AppEventObservers;
let builder = TeksiloAppBuilder::new()
.on_external_with_ctx(|_payload, _ctx| true)
.on_app_event(|_event| {})
.register_app_event_observer(|_event| {});
assert!(
builder.external_ctx_handler.is_some(),
"the external router must survive a later on_app_event/observer registration"
);
assert!(
builder.app_event_handler.is_some(),
"on_app_event must survive on_external_with_ctx"
);
assert!(
builder
.app_state_registry
.contains_key(&TypeId::of::<AppEventObservers>()),
"observers must survive on_external_with_ctx"
);
// Single slot, like `on_app_event`: registering twice replaces.
let builder = builder.on_external_with_ctx(|_payload, _ctx| false);
let mut router = builder
.external_ctx_handler
.expect("the second registration is the live one");
// Exercise the claim contract — the `bool` `user_event` branches on to
// decide whether the payload was the app's — through a real, headless
// `EventContext`. `NoopWindowOps` is the same sink `window_manager`'s
// own close-guard tests use; the live `WindowOpsImpl` only arrives with
// a winit event loop.
let mut tree = teksilo_core::WidgetTree::new();
let mut claimed = true;
tree.run_with_event_context(
&mut teksilo_core::NoopWindowOps,
|ctx: &mut teksilo_core::widget::EventContext| {
claimed = router(&42i32, ctx);
},
);
assert!(
!claimed,
"the replacing router's answer is the one that decides"
);
}
#[test]
fn builder_with_root() {
use teksilo_widgets::RectWidget;
let app = TeksiloAppBuilder::new()
.initial_window(
WindowConfig::new()
.root(|tree, _state| tree.add(RectWidget::new().background(Color::RED))),
)
.build_headless();
let mut tree = app.tree;
tree.layout(SizeProposal::exact(200.0, 100.0));
let frame = tree.render();
assert!(!frame.is_empty());
}
#[test]
fn app_state_flows_through_headless_builder() {
use std::rc::Rc;
use teksilo_core::build_context::BuildContext;
use teksilo_core::signal::Signal;
use teksilo_core::widget::{LayoutContext, Widget};
struct AppGlobals {
label: Signal<String>,
}
#[derive(Debug)]
struct GlobalsReader {
observed: Signal<String>,
}
impl Widget for GlobalsReader {
fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
let globals = ctx
.app_state::<Rc<AppGlobals>>()
.expect("AppGlobals not registered");
self.observed.set(globals.label.get());
Vec::new()
}
fn layout_response(
&self,
proposal: SizeProposal,
_ctx: &LayoutContext,
) -> teksilo_core::widget::LayoutResponse {
proposal.resolve(0.0, 0.0).into()
}
}
let globals = Rc::new(AppGlobals {
label: Signal::new("headless works".to_string()),
});
let observed = Signal::new(String::new());
let observed_for_root = observed.clone();
let _app = TeksiloAppBuilder::new()
.app_state(globals.clone())
.initial_window(WindowConfig::new().root(move |tree, _state| {
tree.add(GlobalsReader {
observed: observed_for_root.clone(),
})
}))
.build_headless();
assert_eq!(observed.get(), "headless works");
}
#[test]
fn auto_prefers_native_for_deferred_content_when_supported() {
let request = ModalRequest::deferred(|tree| tree.add(Button::new(lit!("Deferred"))));
assert_eq!(
resolve_modal_presentation(request.presentation, &request.content, true),
ResolvedModalPresentation::NativeWindow
);
}
#[test]
fn existing_widget_forces_in_tree_even_if_native_requested() {
let mut tree = WidgetTree::new();
let content = tree.add(Button::new(lit!("Existing")));
let request = ModalRequest::in_tree(content).presentation(ModalPresentation::NativeWindow);
assert_eq!(
resolve_modal_presentation(request.presentation, &request.content, true),
ResolvedModalPresentation::InTree
);
}
#[test]
fn present_in_tree_modal_request_shows_centered_overlay() {
let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
let source = tree.add(Button::new(lit!("Trigger")));
let content = tree.add(Button::new(lit!("Modal content")));
tree.set_dormant(content);
tree.layout(SizeProposal::exact(800.0, 600.0));
present_in_tree_modal_request(
&mut tree,
source,
ModalRequest::in_tree(content).presentation(ModalPresentation::InTree),
);
tree.layout(SizeProposal::exact(800.0, 600.0));
// Two overlays: the modal-panel overlay AND the dialog scrim
// pushed below it by the modal-presentation pipeline.
assert_eq!(tree.active_overlays().len(), 2);
assert!(tree.find_by_label("Modal content").is_some());
}
#[test]
fn present_in_tree_modal_request_builds_deferred_content() {
let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
let source = tree.add(Button::new(lit!("Trigger")));
tree.layout(SizeProposal::exact(800.0, 600.0));
present_in_tree_modal_request(
&mut tree,
source,
ModalRequest::deferred(|tree| tree.add(Button::new(lit!("Deferred modal"))))
.presentation(ModalPresentation::InTree),
);
tree.layout(SizeProposal::exact(800.0, 600.0));
// Two overlays: the modal-panel overlay AND the dialog scrim
// pushed below it by the modal-presentation pipeline.
assert_eq!(tree.active_overlays().len(), 2);
assert!(tree.find_by_label("Deferred modal").is_some());
}
#[test]
fn present_in_tree_modal_request_mounts_scrim_below_modal() {
// The scrim must be pushed BEFORE the modal so it z-orders
// below the panel. `active_content_ids()` returns ids in
// stack order (oldest → newest), so the first id is the
// scrim and the second is the modal content.
let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
let source = tree.add(Button::new(lit!("Trigger")));
let content = tree.add(Button::new(lit!("Modal content")));
tree.set_dormant(content);
tree.layout(SizeProposal::exact(800.0, 600.0));
present_in_tree_modal_request(
&mut tree,
source,
ModalRequest::in_tree(content).presentation(ModalPresentation::InTree),
);
let stack = tree.overlay_manager().active_content_ids();
assert_eq!(stack.len(), 2, "scrim + modal");
// Scrim is the first one; modal content the second.
assert_eq!(stack[1], content, "modal content sits above scrim");
}
#[test]
fn dismissing_modal_cascades_to_scrim() {
// The scrim's `parent_overlay` is patched to the modal id
// after both are pushed. Dismissing the modal must therefore
// also dismiss the scrim through the cascade walk in
// `dismiss_immediate`.
let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
let source = tree.add(Button::new(lit!("Trigger")));
let content = tree.add(Button::new(lit!("Modal content")));
tree.set_dormant(content);
tree.layout(SizeProposal::exact(800.0, 600.0));
present_in_tree_modal_request(
&mut tree,
source,
ModalRequest::in_tree(content).presentation(ModalPresentation::InTree),
);
assert_eq!(tree.active_overlays().len(), 2);
// Find the modal's overlay id (the one whose content is the
// modal content widget) and dismiss it.
let modal_overlay = tree
.overlay_manager()
.find_by_content(content)
.expect("modal overlay registered");
tree.overlay_manager_mut().dismiss(modal_overlay);
assert!(
tree.active_overlays().is_empty(),
"scrim must cascade away with the modal",
);
}
#[test]
fn scrim_uses_full_viewport_placement() {
// The scrim's overlay placement determines its bounds during
// `position_overlays`. It must be `FullViewport` so the dim
// covers the entire window regardless of the modal's size or
// position.
let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
let source = tree.add(Button::new(lit!("Trigger")));
let content = tree.add(Button::new(lit!("Modal content")));
tree.set_dormant(content);
tree.layout(SizeProposal::exact(800.0, 600.0));
present_in_tree_modal_request(
&mut tree,
source,
ModalRequest::in_tree(content).presentation(ModalPresentation::InTree),
);
tree.layout(SizeProposal::exact(800.0, 600.0));
// The scrim is at the bottom of the stack — first content id.
let scrim_content_id = tree.overlay_manager().active_content_ids()[0];
let scrim_bounds = tree.bounds(scrim_content_id);
assert!(
(scrim_bounds.width - 800.0).abs() < 0.01,
"scrim spans the viewport width",
);
assert!(
(scrim_bounds.height - 600.0).abs() < 0.01,
"scrim spans the viewport height",
);
}
#[test]
fn present_in_tree_modal_request_moves_focus_into_modal() {
let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
let source = tree.add(Button::new(lit!("Trigger")));
tree.layout(SizeProposal::exact(800.0, 600.0));
tree.focus(source);
present_in_tree_modal_request(
&mut tree,
source,
ModalRequest::deferred(|tree| {
tree.add(ModalContainer::new(Button::new(lit!("Continue"))))
})
.presentation(ModalPresentation::InTree),
);
let continue_button = tree.find_by_label("Continue").unwrap();
assert_eq!(tree.focused(), Some(continue_button));
}
/// **A modal whose content is a text editor opens with the caret in it.**
///
/// The editors are the one focusable widget family that carries no label,
/// so `first_focusable_descendant` is the only thing that can find them —
/// and a modal that fails to focus one opens with no caret at all, which
/// reads as a broken surface rather than an unfocused one.
#[test]
fn present_in_tree_modal_focuses_a_rich_text_editor() {
use teksilo_widgets::rich_text::RichTextEditor;
let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
let source = tree.add(Button::new(lit!("Trigger")));
tree.layout(SizeProposal::exact(800.0, 600.0));
tree.focus(source);
let doc = teksilo_text::text_document::TextDocument::new();
doc.set_plain_text("hello").unwrap();
present_in_tree_modal_request(
&mut tree,
source,
ModalRequest::deferred(move |tree| {
tree.add(ModalContainer::new(RichTextEditor::editor(doc)))
})
.presentation(ModalPresentation::InTree),
);
let focused = tree.focused().expect("the modal moved focus into itself");
assert_ne!(
focused, source,
"focus must leave the trigger and land inside the modal"
);
let name = tree.widget_type_name(focused).unwrap_or("<none>");
assert!(
name.contains("RichTextEditor"),
"focus landed on {name}, not the editor — the modal opens caretless"
);
}
/// **A modal that opens over a text editor shows its caret.**
///
/// Focus landing on the editor is not enough: the caret is gated on the
/// editor's *own* `has_focus`, and `present_in_tree_modal_request` parks
/// the content dormant and re-activates it in the same batch, before
/// moving focus in. Those two activation edges used to be replayed in
/// order *after* the focus dispatch, so the superseded `false` arrived
/// last and the editor's dormancy handler wiped the focus it had just
/// been granted — the dialog opened with the text visible and no caret,
/// which reads as a dead surface rather than an unfocused one.
///
/// Asserted on the painted frame rather than on any internal flag,
/// because the caret is the whole point: a thin, full-line-height rect
/// in the theme's `editor_caret` colour, at the editor's origin.
#[test]
fn present_in_tree_modal_paints_the_editor_caret() {
use teksilo_widgets::rich_text::RichTextEditor;
let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
let source = tree.add(Button::new(lit!("Trigger")));
tree.layout(SizeProposal::exact(800.0, 600.0));
tree.focus(source);
let doc = teksilo_text::text_document::TextDocument::new();
doc.set_plain_text("hello").unwrap();
present_in_tree_modal_request(
&mut tree,
source,
ModalRequest::deferred(move |tree| {
tree.add(ModalContainer::new(RichTextEditor::editor(doc)))
})
.presentation(ModalPresentation::InTree),
);
tree.layout(SizeProposal::exact(800.0, 600.0));
let editor = tree.focused().expect("the modal moved focus into itself");
let editor_bounds = tree.bounds(editor);
let frame = tree.render();
// The caret is emitted through `Canvas::fill_rect`, which lands in the
// frame as a `WidgetBackground` decoration — so identify it by shape
// and colour rather than by kind.
let caret_color = teksilo_core::presets::intui::light()
.colors
.editor_caret
.to_array();
let caret = frame.decorations.iter().find(|d| {
d.color == caret_color && d.rect[2] > 0.0 && d.rect[2] <= 4.0 && d.rect[3] > 4.0
});
let caret = caret.unwrap_or_else(|| {
panic!(
"the modal painted no caret — {} glyphs and {} decorations, none caret-shaped: {:?}",
frame.glyphs.len(),
frame.decorations.len(),
frame.decorations,
)
});
// ...and it sits inside the editor, not stranded at the viewport origin.
assert!(
caret.rect[0] >= editor_bounds.x
&& caret.rect[0] <= editor_bounds.x + editor_bounds.width
&& caret.rect[1] >= editor_bounds.y
&& caret.rect[1] <= editor_bounds.y + editor_bounds.height,
"caret at {:?} must fall inside the editor's bounds {editor_bounds:?}",
caret.rect,
);
}
/// Same, but with the editor buried under the chrome a real dialog wraps it
/// in — a titled panel, a column, a fixed-size box, padding. The walk has to
/// reach through all of it.
#[test]
fn present_in_tree_modal_focuses_an_editor_under_chrome() {
use teksilo_widgets::rich_text::RichTextEditor;
use teksilo_widgets::{Divider, FixedSize, Padding, Panel, TextWidget, VStack};
let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
let source = tree.add(Button::new(lit!("Trigger")));
tree.layout(SizeProposal::exact(900.0, 700.0));
tree.focus(source);
let doc = teksilo_text::text_document::TextDocument::new();
doc.set_plain_text("hello").unwrap();
present_in_tree_modal_request(
&mut tree,
source,
ModalRequest::deferred(move |tree| {
tree.add(ModalContainer::new(
Panel::new().corner_radius(10.0).padding(0.0).child(
VStack::new()
.spacing(0.0)
.child(
Padding::symmetric(8.0, 14.0)
.child(TextWidget::new(lit!("Synopsis"))),
)
.child(Divider::new())
.child(
FixedSize::new().width(600.0).height(400.0).child(
Padding::uniform(16.0).child(RichTextEditor::editor(doc)),
),
),
),
))
})
.presentation(ModalPresentation::InTree),
);
let focused = tree.focused().expect("the modal moved focus into itself");
let name = tree.widget_type_name(focused).unwrap_or("<none>");
assert!(
name.contains("RichTextEditor"),
"focus landed on {name}, not the editor — chrome between the modal root \
and the editor is hiding it from the focus walk"
);
}
/// And with **no `ModalContainer`** — the shape an app takes when its dialog
/// owns its own chrome (Skribisto's synopsis / picker panels do). The focus
/// walk starts at whatever the deferred builder returned.
#[test]
fn present_in_tree_modal_focuses_an_editor_without_a_modal_container() {
use teksilo_widgets::rich_text::RichTextEditor;
use teksilo_widgets::{FixedSize, Padding, Panel, VStack};
let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
let source = tree.add(Button::new(lit!("Trigger")));
tree.layout(SizeProposal::exact(900.0, 700.0));
tree.focus(source);
let doc = teksilo_text::text_document::TextDocument::new();
doc.set_plain_text("hello").unwrap();
present_in_tree_modal_request(
&mut tree,
source,
ModalRequest::deferred(move |tree| {
tree.add(
Panel::new().corner_radius(10.0).padding(0.0).child(
VStack::new().spacing(0.0).child(
FixedSize::new()
.width(600.0)
.height(400.0)
.child(Padding::uniform(16.0).child(RichTextEditor::editor(doc))),
),
),
)
})
.presentation(ModalPresentation::InTree),
);
let focused = tree.focused().expect("the modal moved focus into itself");
let name = tree.widget_type_name(focused).unwrap_or("<none>");
assert!(
name.contains("RichTextEditor"),
"focus landed on {name}, not the editor"
);
}
#[test]
fn present_in_tree_modal_restores_focus_to_trigger_on_dismiss() {
// Regression: tabbing to a trigger, opening a modal, then
// dismissing it must return keyboard focus to the trigger. The
// modal overlay carries the pre-modal focus owner as its
// `focus_restore`, which every dismiss path replays.
let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
let source = tree.add(Button::new(lit!("Rename")));
tree.layout(SizeProposal::exact(800.0, 600.0));
tree.focus(source);
assert_eq!(
tree.focused(),
Some(source),
"precondition: trigger focused"
);
present_in_tree_modal_request(
&mut tree,
source,
ModalRequest::deferred(|tree| {
tree.add(ModalContainer::new(Button::new(lit!("Continue"))))
})
.presentation(ModalPresentation::InTree),
);
// Focus moved into the modal (existing behavior).
let continue_button = tree.find_by_label("Continue").unwrap();
assert_eq!(tree.focused(), Some(continue_button));
// The modal overlay is the topmost; dismissing it must surface
// the trigger as the focus_restore target.
let modal_overlay = *tree
.active_overlays()
.last()
.expect("modal overlay registered");
let (_dismissed, focus_restore) = tree
.overlay_manager_mut()
.dismiss_with_focus_restore(modal_overlay);
assert_eq!(
focus_restore,
Some(source),
"dismissing the modal must restore focus to the trigger that opened it",
);
}
#[test]
fn mouse_opened_modal_restores_pointer_modality_on_dismiss() {
// Regression: a modal opened by mouse (focus_visible = false) must
// not leave the trigger sporting a keyboard `:focus-visible` ring
// after the user types / presses Enter inside the dialog — which
// flips the global modality to keyboard. The pre-modal modality is
// captured and replayed when the overlay dismisses.
let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
let source = tree.add(Button::new(lit!("Rename")));
tree.layout(SizeProposal::exact(800.0, 600.0));
// Mouse-style entry: pointer modality, trigger focused.
let focus_visible = tree.focus_visible_signal();
focus_visible.set(false);
tree.focus(source);
present_in_tree_modal_request(
&mut tree,
source,
ModalRequest::deferred(|tree| {
tree.add(ModalContainer::new(Button::new(lit!("Continue"))))
})
.presentation(ModalPresentation::InTree),
);
// Keyboard input *inside* the dialog (typing the name, Enter to
// accept) flips the global modality to keyboard.
focus_visible.set(true);
// Dismiss fires the overlay's on_dismiss, which restores modality.
let modal_overlay = *tree
.active_overlays()
.last()
.expect("modal overlay registered");
tree.overlay_manager_mut()
.dismiss_with_focus_restore(modal_overlay);
assert!(
!focus_visible.get(),
"a mouse-opened modal must restore pointer modality on dismiss, \
not leave a keyboard focus ring on the trigger",
);
}
#[test]
fn keyboard_opened_modal_keeps_focus_visible_on_dismiss() {
// Invariant guard for the fix above: a modal opened while in
// keyboard modality must KEEP the focus ring on the trigger when it
// closes — restoring the captured modality must not blanket-clear it.
let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
let source = tree.add(Button::new(lit!("Rename")));
tree.layout(SizeProposal::exact(800.0, 600.0));
// Keyboard-style entry: keyboard modality, trigger focused.
let focus_visible = tree.focus_visible_signal();
focus_visible.set(true);
tree.focus(source);
present_in_tree_modal_request(
&mut tree,
source,
ModalRequest::deferred(|tree| {
tree.add(ModalContainer::new(Button::new(lit!("Continue"))))
})
.presentation(ModalPresentation::InTree),
);
// Even if a pointer event flipped modality off inside the dialog,
// dismiss restores the captured (keyboard) modality.
focus_visible.set(false);
let modal_overlay = *tree
.active_overlays()
.last()
.expect("modal overlay registered");
tree.overlay_manager_mut()
.dismiss_with_focus_restore(modal_overlay);
assert!(
focus_visible.get(),
"a keyboard-opened modal must restore keyboard modality on dismiss",
);
}
/// Test content widget: a focusable container with two focusable
/// button descendants. `hint` controls which (if any) the widget
/// reports as its `initial_focus_hint`.
#[derive(Debug)]
struct TwoButtonContent {
root: Option<WidgetId>,
second: Option<WidgetId>,
hint_to_second: bool,
}
impl teksilo_core::Widget for TwoButtonContent {
fn build(&mut self, ctx: &mut teksilo_core::BuildContext) -> Vec<WidgetId> {
let first = ctx.add(Button::new(lit!("First")));
let second = ctx.add(Button::new(lit!("Second")));
let row = ctx.add(
teksilo_widgets::HStack::new()
.add_child(first)
.add_child(second),
);
self.root = Some(row);
self.second = Some(second);
vec![row]
}
fn layout_response(
&self,
proposal: teksilo_canvas::SizeProposal,
ctx: &teksilo_core::LayoutContext,
) -> teksilo_core::widget::LayoutResponse {
self.root
.and_then(|id| ctx.child_size(id, proposal))
.unwrap_or_else(|| proposal.resolve(0.0, 0.0))
.into()
}
fn initial_focus_hint(&self) -> Option<WidgetId> {
if self.hint_to_second {
self.second
} else {
None
}
}
fn children(&self) -> Vec<WidgetId> {
self.root.into_iter().collect()
}
}
#[test]
fn present_in_tree_modal_consults_initial_focus_hint() {
// When `focus_target` is None, the framework must consult the
// content widget's `initial_focus_hint` before falling back to
// `first_focusable_descendant`.
let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
let source = tree.add(Button::new(lit!("Trigger")));
tree.layout(SizeProposal::exact(800.0, 600.0));
present_in_tree_modal_request(
&mut tree,
source,
ModalRequest::deferred(|tree| {
tree.add(TwoButtonContent {
root: None,
second: None,
hint_to_second: true,
})
})
.presentation(ModalPresentation::InTree),
);
tree.layout(SizeProposal::exact(800.0, 600.0));
// Two "Second" labels may exist globally (source isn't one), so
// find_by_label is unambiguous here.
let second = tree.find_by_label("Second").unwrap();
assert_eq!(
tree.focused(),
Some(second),
"initial_focus_hint must redirect focus away from first focusable",
);
}
#[test]
fn present_in_tree_modal_falls_back_to_first_focusable_without_hint() {
// Baseline: content without an initial_focus_hint gets the first
// focusable descendant, matching prior behavior.
let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
let source = tree.add(Button::new(lit!("Trigger")));
tree.layout(SizeProposal::exact(800.0, 600.0));
present_in_tree_modal_request(
&mut tree,
source,
ModalRequest::deferred(|tree| {
tree.add(TwoButtonContent {
root: None,
second: None,
hint_to_second: false,
})
})
.presentation(ModalPresentation::InTree),
);
tree.layout(SizeProposal::exact(800.0, 600.0));
let first = tree.find_by_label("First").unwrap();
assert_eq!(
tree.focused(),
Some(first),
"without focus_target or initial_focus_hint, first focusable wins",
);
}
#[test]
fn present_in_tree_modal_rejects_focus_target_outside_content_subtree() {
// A focus_target pointing at a widget that exists but is NOT a
// descendant of content_id must be rejected. The framework falls
// back to initial_focus_hint → first_focusable_descendant.
let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
let source = tree.add(Button::new(lit!("Trigger")));
tree.layout(SizeProposal::exact(800.0, 600.0));
present_in_tree_modal_request(
&mut tree,
source,
ModalRequest::deferred(|tree| {
tree.add(TwoButtonContent {
root: None,
second: None,
hint_to_second: false,
})
})
.presentation(ModalPresentation::InTree)
.focus_target(source), // active but outside modal subtree
);
tree.layout(SizeProposal::exact(800.0, 600.0));
let first = tree.find_by_label("First").unwrap();
assert_eq!(
tree.focused(),
Some(first),
"focus_target outside content subtree must be rejected",
);
}
}