1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
#[cfg(feature = "profiler")]
use crate::DebugFrameOverlayMode;
#[cfg(any(feature = "inspector", debug_assertions))]
use crate::Inspector;
#[cfg(feature = "profiler")]
use crate::profiler;
use crate::subscription::SingleSubscriberSet;
use crate::taffy::TaffyLayoutEngine;
use crate::{
Action, AnyDrag, AnyElement, AnyImageCache, AnyTooltip, AnyView, App, AppContext, Arena, Asset,
AsyncWindowContext, AtlasKey, AtlasStats, AtlasTile, AvailableSpace, BackdropBlurRect, Background, BorderStyle,
EffectQuad, EffectSpec,
Bounds, BoxShadow,
Capslock, Context, CornerShape, CornerShapes, Corners, CursorHideMode, CursorStyle, Decorations, DevicePixels,
DispatchActionListener, DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity,
EntityId, EventEmitter, FileDropEvent, FontId, Global, GlobalElementId, GlyphId, GpuSpecs,
GlyphShadowParams, GpuTextureHandle,
Hsla, InputHandler, InputPreference, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeyEvent,
Keystroke, KeystrokeEvent, LayoutId, LineLayoutIndex, Modifiers, ModifiersChangedEvent,
MonochromeSprite, MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, PaintedPath, Path,
Pixels, PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow,
Point, PolychromeSprite, Priority, PromptButton, PromptLevel, Quad, Render, RenderGlyphParams,
RenderImage, RenderImageParams, RenderSvgParams, Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR,
SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y, ScaledPixels, Scene, Shadow, SharedString, Size,
SpriteAnimation, SpriteAnimationId, StrikethroughStyle, Style, SubpixelSprite, Subscription,
SystemWindowTab, SystemWindowTabController, TabStopMap, Task, TextInputConfiguration,
TextInputStateChange, TextRenderingMode, TextStyle, TextStyleRefinement, ThermalState,
TileSource, TileWrite, TransformationMatrix, Underline, UnderlineStyle, WindowAppearance,
WindowBackgroundAppearance, WindowBounds, WindowControls, WindowDecorations, WindowInsets,
WindowOptions, WindowParams, WindowTextSystem, WindowVisibility, blur_glyph_coverage, point,
prelude::*, px, rems, size, transparent_black,
};
use crate::gestures::{GestureTuning, RecognizedTouchGesture, TouchGestureRecognizer};
use crate::interactive::TouchEvent;
use crate::util::impl_deref;
use anyhow::{Context as _, Result, anyhow};
use collections::{FxHashMap, FxHashSet};
use futures::channel::oneshot;
use gpui_util::post_inc;
use gpui_util::{ResultExt, measure};
use itertools::FoldWhile::{Continue, Done};
use itertools::Itertools;
#[cfg(any(target_os = "macos", target_os = "ios"))]
use objc2_core_foundation::CFRetained;
#[cfg(any(target_os = "macos", target_os = "ios"))]
use objc2_core_video::CVPixelBuffer;
use parking_lot::{RwLock, RwLockUpgradableReadGuard};
use raw_window_handle::{HandleError, HasDisplayHandle, HasWindowHandle};
use refineable::Refineable;
use scheduler::Instant;
use slotmap::SlotMap;
use smallvec::SmallVec;
use std::{
any::{Any, TypeId},
borrow::Cow,
cell::{Cell, RefCell},
cmp,
fmt::{Debug, Display},
hash::{Hash, Hasher},
marker::PhantomData,
mem,
ops::{Add, Div, Range, Sub},
rc::Rc,
sync::{
Arc, Weak,
atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
},
thread::AccessError,
time::Duration,
};
use uuid::Uuid;
pub(crate) mod a11y;
mod prompts;
pub use a11y::A11ySubtreeBuilder;
use self::a11y::A11y;
#[cfg(not(target_family = "wasm"))]
use self::a11y::ROOT_NODE_ID;
use crate::util::{
atomic_incr_if_not_zero, ceil_to_device_pixel, floor_to_device_pixel, round_half_toward_zero,
round_half_toward_zero_f64, round_stroke_to_device_pixel, round_to_device_pixel,
};
pub use prompts::*;
/// Default window size used when no explicit size is provided.
pub const DEFAULT_WINDOW_SIZE: Size<Pixels> = size(px(1536.), px(1095.));
/// A 6:5 aspect ratio minimum window size to be used for functional,
/// additional-to-main-Zed windows, like the settings and rules library windows.
pub const DEFAULT_ADDITIONAL_WINDOW_SIZE: Size<Pixels> = Size {
width: Pixels(900.),
height: Pixels(750.),
};
/// Represents the two different phases when dispatching events.
#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
pub enum DispatchPhase {
/// After the capture phase comes the bubble phase, in which mouse event listeners are
/// invoked front to back and keyboard event listeners are invoked from the focused element
/// to the root of the element tree. This is the phase you'll most commonly want to use when
/// registering event listeners.
#[default]
Bubble,
/// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
/// listeners are invoked from the root of the tree downward toward the focused element. This phase
/// is used for special purposes such as clearing the "pressed" state for click events. If
/// you stop event propagation during this phase, you need to know what you're doing. Handlers
/// outside of the immediate region may rely on detecting non-local events during this phase.
Capture,
}
impl DispatchPhase {
/// Returns true if this represents the "bubble" phase.
#[inline]
pub fn bubble(self) -> bool {
self == DispatchPhase::Bubble
}
/// Returns true if this represents the "capture" phase.
#[inline]
pub fn capture(self) -> bool {
self == DispatchPhase::Capture
}
}
struct WindowInvalidatorInner {
#[cfg(feature = "profiler")]
pub window_id: WindowId,
pub dirty: bool,
pub draw_phase: DrawPhase,
pub dirty_views: FxHashSet<EntityId>,
pub update_count: usize,
#[cfg(feature = "profiler")]
pub frame_dirty: FrameDirtyAccumulator,
pub platform_waker: Option<Rc<dyn Fn()>>,
}
/// Per-frame invalidation bookkeeping, drained at draw time and emitted to the
/// frame profiler. Tracks when the current frame first became dirty and how
/// many invalidations were coalesced into it, whenever the profiler is
/// compiled in. Retention of the resulting per-frame records is what
/// `profiler::trace_enabled()` controls, not this measurement.
#[cfg(feature = "profiler")]
#[derive(Default)]
struct FrameDirtyAccumulator {
dirty_at: Option<Instant>,
invalidations: u64,
}
#[derive(Clone)]
pub(crate) struct WindowInvalidator {
inner: Rc<RefCell<WindowInvalidatorInner>>,
}
impl WindowInvalidator {
pub fn new(#[allow(unused_variables)] window_id: WindowId) -> Self {
WindowInvalidator {
inner: Rc::new(RefCell::new(WindowInvalidatorInner {
#[cfg(feature = "profiler")]
window_id,
dirty: true,
draw_phase: DrawPhase::None,
dirty_views: FxHashSet::default(),
update_count: 0,
#[cfg(feature = "profiler")]
frame_dirty: FrameDirtyAccumulator::default(),
platform_waker: None,
})),
}
}
pub fn invalidate_view(&self, entity: EntityId, cx: &mut App) -> bool {
let mut inner = self.inner.borrow_mut();
inner.update_count += 1;
inner.dirty_views.insert(entity);
if inner.draw_phase == DrawPhase::None {
#[cfg(feature = "profiler")]
let dirty_at = Self::record_frame_dirty(&mut inner);
let became_dirty = !inner.dirty;
inner.dirty = true;
let waker = became_dirty.then(|| inner.platform_waker.clone()).flatten();
#[cfg(feature = "profiler")]
let window_id = inner.window_id;
drop(inner);
#[cfg(feature = "profiler")]
if became_dirty {
profiler::journal::record_frame_pending(window_id, dirty_at);
}
cx.push_effect(Effect::Notify { emitter: entity });
if let Some(waker) = waker {
waker();
}
true
} else {
false
}
}
pub fn is_dirty(&self) -> bool {
self.inner.borrow().dirty
}
pub fn set_dirty(&self, dirty: bool) {
let mut inner = self.inner.borrow_mut();
let became_dirty = dirty && !inner.dirty;
inner.dirty = dirty;
if dirty {
inner.update_count += 1;
}
#[cfg(feature = "profiler")]
let dirty_at = dirty.then(|| Self::record_frame_dirty(&mut inner));
let waker = became_dirty.then(|| inner.platform_waker.clone()).flatten();
#[cfg(feature = "profiler")]
let window_id = inner.window_id;
drop(inner);
#[cfg(feature = "profiler")]
if became_dirty && let Some(dirty_at) = dirty_at {
profiler::journal::record_frame_pending(window_id, dirty_at);
}
if let Some(waker) = waker {
waker();
}
}
pub fn set_platform_waker(&self, waker: Option<Rc<dyn Fn()>>) {
let mut inner = self.inner.borrow_mut();
inner.platform_waker = waker;
let waker = inner.dirty.then(|| inner.platform_waker.clone()).flatten();
drop(inner);
if let Some(waker) = waker {
waker();
}
}
/// Wakes the platform's frame-request source so a frame request is
/// delivered even if the platform stops requesting frames for idle
/// windows. No-op on platforms without a frame waker.
pub fn wake_platform(&self) {
let waker = self.inner.borrow().platform_waker.clone();
if let Some(waker) = waker {
waker();
}
}
pub fn set_phase(&self, phase: DrawPhase) {
self.inner.borrow_mut().draw_phase = phase
}
pub fn update_count(&self) -> usize {
self.inner.borrow().update_count
}
#[cfg(feature = "profiler")]
fn record_frame_dirty(inner: &mut WindowInvalidatorInner) -> Instant {
let dirty_at = *inner.frame_dirty.dirty_at.get_or_insert_with(Instant::now);
inner.frame_dirty.invalidations += 1;
dirty_at
}
#[cfg(feature = "profiler")]
fn take_frame_dirty(&self) -> FrameDirtyAccumulator {
mem::take(&mut self.inner.borrow_mut().frame_dirty)
}
pub fn take_views(&self) -> FxHashSet<EntityId> {
mem::take(&mut self.inner.borrow_mut().dirty_views)
}
pub fn replace_views(&self, views: FxHashSet<EntityId>) {
self.inner.borrow_mut().dirty_views = views;
}
pub fn not_drawing(&self) -> bool {
self.inner.borrow().draw_phase == DrawPhase::None
}
/// vue-native fork: whether the window is in its paint phase.
pub fn is_painting(&self) -> bool {
self.inner.borrow().draw_phase == DrawPhase::Paint
}
#[track_caller]
pub fn debug_assert_paint(&self) {
debug_assert!(
matches!(self.inner.borrow().draw_phase, DrawPhase::Paint),
"this method can only be called during paint"
);
}
#[track_caller]
pub fn debug_assert_prepaint(&self) {
debug_assert!(
matches!(self.inner.borrow().draw_phase, DrawPhase::Prepaint),
"this method can only be called during request_layout, or prepaint"
);
}
#[track_caller]
pub fn debug_assert_paint_or_prepaint(&self) {
debug_assert!(
matches!(
self.inner.borrow().draw_phase,
DrawPhase::Paint | DrawPhase::Prepaint
),
"this method can only be called during request_layout, prepaint, or paint"
);
}
}
type AnyObserver = Box<dyn FnMut(&mut Window, &mut App) -> bool + 'static>;
pub(crate) type AnyWindowFocusListener =
Box<dyn FnMut(&WindowFocusEvent, &mut Window, &mut App) -> bool + 'static>;
pub(crate) struct WindowFocusEvent {
pub(crate) previous_focus_path: SmallVec<[FocusId; 8]>,
pub(crate) current_focus_path: SmallVec<[FocusId; 8]>,
}
impl WindowFocusEvent {
pub fn is_focus_in(&self, focus_id: FocusId) -> bool {
!self.previous_focus_path.contains(&focus_id) && self.current_focus_path.contains(&focus_id)
}
pub fn is_focus_out(&self, focus_id: FocusId) -> bool {
self.previous_focus_path.contains(&focus_id) && !self.current_focus_path.contains(&focus_id)
}
}
/// This is provided when subscribing for `Context::on_focus_out` events.
pub struct FocusOutEvent {
/// A weak focus handle representing what was blurred.
pub blurred: WeakFocusHandle,
}
slotmap::new_key_type! {
/// A globally unique identifier for a focusable element.
pub struct FocusId;
}
thread_local! {
/// Fallback arena used when no app-specific arena is active.
/// In production, each window draw sets CURRENT_ELEMENT_ARENA to the app's arena.
pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(1024 * 1024));
/// Points to the current App's element arena during draw operations.
/// This allows multiple test Apps to have isolated arenas, preventing
/// cross-session corruption when the scheduler interleaves their tasks.
static CURRENT_ELEMENT_ARENA: Cell<Option<*const RefCell<Arena>>> = const { Cell::new(None) };
}
/// Whether a window draw is currently in progress on this thread.
///
/// This holds exactly while an `ElementArenaScope` is active: nested scopes
/// restore the previous (still set) arena pointer, so `CURRENT_ELEMENT_ARENA`
/// is `Some` from the outermost draw's start to its end.
///
/// The `on_request_frame` callback uses this to defer draw requests that
/// arrive re-entrantly while a draw is already on the stack (e.g. via nested
/// message pumping in the Windows window procedure), instead of running a
/// nested draw or panicking on the already-borrowed App.
pub(crate) fn draw_in_progress() -> bool {
CURRENT_ELEMENT_ARENA.with(|current| current.get().is_some())
}
/// vue-native fork: how a window's frame request went, for an embedder's frame meter.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FrameOutcome {
/// The window was drawn and presented.
Drew,
/// Next-frame callbacks ran (or a present), with nothing to redraw.
NoDraw,
/// Held back by the frame-rate limit: an inactive window, low power or thermal state.
Throttled,
}
/// One frame request: `started..ended` is the time it took on this thread.
#[derive(Clone, Copy, Debug)]
pub struct FrameWork {
/// The window whose frame this was.
pub window_id: WindowId,
/// When the request began.
pub started: Instant,
/// When it finished, presented or not.
pub ended: Instant,
/// What the request did.
pub outcome: FrameOutcome,
}
static FRAME_OBSERVER: std::sync::OnceLock<fn(FrameWork)> = std::sync::OnceLock::new();
/// vue-native fork: `observer` hears about every frame request that did work or was throttled.
/// The first call wins.
pub fn observe_frames(observer: fn(FrameWork)) {
let _ = FRAME_OBSERVER.set(observer);
}
fn report_frame(window_id: WindowId, started: Instant, outcome: FrameOutcome) {
if let Some(observer) = FRAME_OBSERVER.get() {
observer(FrameWork { window_id, started, ended: Instant::now(), outcome });
}
}
/// Allocates an element in the current arena. Uses the app-specific arena if one
/// is active (during draw), otherwise falls back to the thread-local ELEMENT_ARENA.
#[inline(always)]
pub(crate) fn with_element_arena<R>(callback: impl FnOnce(&mut Arena) -> R) -> R {
let mut callback = Some(callback);
let mut result = None;
let access = with_element_arena_erased(&mut |arena| {
result = Some(callback.take().expect("arena callback runs once")(arena));
});
drop(callback);
access.expect("cannot access a Thread Local Storage value during or after destruction");
result.expect("arena callback produces a result")
}
/// Scope guard that sets CURRENT_ELEMENT_ARENA for the duration of a draw
/// operation and tracks the arena's scope depth, so that a nested draw's
/// `ArenaClearNeeded::clear` is deferred rather than freeing memory the outer
/// draw still references (see `Arena::clear`).
///
/// Call [`ElementArenaScope::exit`] with the same arena that was entered to
/// obtain the [`ArenaClearNeeded`] token the draw now owes; requiring `exit`
/// makes it impossible to request a clear before the scope has ended. The
/// scope's teardown — restoring the thread-local and balancing `begin_scope`
/// with `end_scope` — happens in `Drop`, so the arena's scope depth stays
/// balanced on every path, including when a panic unwinds a draw before `exit`
/// is reached. (If teardown lived only in `exit`, such a panic would leave the
/// scope depth permanently elevated and defer every future clear, leaking
/// memory unboundedly.)
pub(crate) struct ElementArenaScope {
/// The entered arena: compared against the argument in `exit`, and
/// dereferenced in `Drop` to end its scope (see the SAFETY note there).
entered: *const RefCell<Arena>,
previous: Option<*const RefCell<Arena>>,
exited: bool,
}
impl ElementArenaScope {
/// Enter a scope where element allocations use the given arena.
pub(crate) fn enter(arena: &RefCell<Arena>) -> Self {
arena.borrow_mut().begin_scope();
let previous = CURRENT_ELEMENT_ARENA.with(|current| {
let prev = current.get();
current.set(Some(arena as *const RefCell<Arena>));
prev
});
Self {
entered: arena as *const RefCell<Arena>,
previous,
exited: false,
}
}
/// End the scope: restores the previously-current arena and ends the
/// arena's clear-deferral scope. Returns the token for the arena clear the
/// draw now owes; producing it here makes it impossible to request a clear
/// before the scope has ended (which would be silently deferred forever).
///
/// Panics if passed a different arena than was entered: ending the scope
/// of the wrong arena would unbalance two arenas' scope depths, allowing
/// one of them to clear while a draw still references its memory.
pub(crate) fn exit(mut self, arena: &RefCell<Arena>) -> ArenaClearNeeded {
assert!(
std::ptr::eq(self.entered, arena),
"ElementArenaScope::exit called with a different arena than was entered"
);
self.exited = true;
// Teardown (restoring the thread-local and ending the arena's
// clear-deferral scope) runs in `Drop`, which fires both here — `self`
// is dropped as `exit` returns, before the token reaches the caller —
// and when a panic unwinds the draw before `exit` is reached.
ArenaClearNeeded::new(arena)
}
}
impl Drop for ElementArenaScope {
fn drop(&mut self) {
// Teardown lives here (rather than in `exit`) so it runs exactly once on
// every path: `exit` consumes and drops the guard on the normal path,
// and unwinding drops it on the panic path. Balancing `begin_scope` here
// keeps the arena's scope depth correct even when a draw panics; if this
// only happened in `exit`, a panic between `enter` and `exit` would leave
// the depth elevated and defer every future clear.
CURRENT_ELEMENT_ARENA.with(|current| {
current.set(self.previous);
});
// SAFETY: `entered` came from a `&RefCell<Arena>` in `enter`, and the
// arena (owned by the `App` being drawn) outlives this guard on both the
// normal and unwinding paths, since the guard is a local of the draw.
unsafe { &*self.entered }.borrow_mut().end_scope();
if !self.exited && !std::thread::panicking() {
debug_assert!(false, "ElementArenaScope dropped without calling exit()");
log::error!(
"ElementArenaScope dropped without calling exit(); \
the arena clear for this draw was never requested"
);
}
}
}
/// Returned when the element arena has been used and so must be cleared before the next draw.
#[must_use]
pub struct ArenaClearNeeded {
/// Identity of the arena that was drawn into. Only ever compared against
/// another pointer in `clear`; never dereferenced.
arena: *const RefCell<Arena>,
}
impl ArenaClearNeeded {
/// Create a new ArenaClearNeeded token for the App whose arena was drawn
/// into. Private: the only way to obtain one is [`ElementArenaScope::exit`].
fn new(arena: &RefCell<Arena>) -> Self {
Self {
arena: arena as *const RefCell<Arena>,
}
}
/// Clear the element arena of the App the draw ran against. If an enclosing
/// draw is still in progress (this draw was nested inside it), the clear is
/// deferred to the enclosing draw's own `ArenaClearNeeded` so that its live
/// allocations aren't freed.
///
/// Panics if passed a different App than the draw ran against, since
/// clearing another App's arena could free memory its draws still
/// reference.
pub fn clear(self, cx: &mut App) {
assert!(
std::ptr::eq(self.arena, &*cx.element_arena),
"ArenaClearNeeded::clear called with a different App than the draw ran against"
);
RefCell::borrow_mut(&cx.element_arena).clear();
}
}
#[derive(Default)]
pub(crate) struct FocusMap {
pub(crate) handles: SlotMap<FocusId, FocusRef>,
pub(crate) dropped_handles: Vec<FocusId>,
}
pub(crate) struct FocusRef {
pub(crate) ref_count: AtomicUsize,
pub(crate) tab_index: isize,
pub(crate) tab_stop: bool,
}
impl FocusId {
/// Obtains whether the element associated with this handle is currently focused.
pub fn is_focused(&self, window: &Window) -> bool {
window.focus == Some(*self)
}
/// Obtains whether the element associated with this handle contains the focused
/// element or is itself focused.
pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
window
.focused(cx)
.is_some_and(|focused| self.contains(focused.id, window))
}
/// Obtains whether the element associated with this handle is contained within the
/// focused element or is itself focused.
pub fn within_focused(&self, window: &Window, cx: &App) -> bool {
let focused = window.focused(cx);
focused.is_some_and(|focused| focused.id.contains(*self, window))
}
/// Obtains whether this handle contains the given handle in the most recently rendered frame.
pub(crate) fn contains(&self, other: Self, window: &Window) -> bool {
window
.rendered_frame
.dispatch_tree
.focus_contains(*self, other)
}
}
/// A handle which can be used to track and manipulate the focused element in a window.
pub struct FocusHandle {
pub(crate) id: FocusId,
handles: Arc<RwLock<FocusMap>>,
/// The index of this element in the tab order.
pub tab_index: isize,
/// Whether this element can be focused by tab navigation.
pub tab_stop: bool,
}
impl std::fmt::Debug for FocusHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!("FocusHandle({:?})", self.id))
}
}
impl FocusHandle {
pub(crate) fn new(handles: &Arc<RwLock<FocusMap>>) -> Self {
let id = handles.write().handles.insert(FocusRef {
ref_count: AtomicUsize::new(1),
tab_index: 0,
tab_stop: false,
});
Self {
id,
tab_index: 0,
tab_stop: false,
handles: handles.clone(),
}
}
pub(crate) fn for_id(id: FocusId, handles: &Arc<RwLock<FocusMap>>) -> Option<Self> {
let lock = handles.read();
let focus = lock.handles.get(id)?;
if atomic_incr_if_not_zero(&focus.ref_count) == 0 {
return None;
}
Some(Self {
id,
tab_index: focus.tab_index,
tab_stop: focus.tab_stop,
handles: handles.clone(),
})
}
/// Sets the tab index of the element associated with this handle.
pub fn tab_index(mut self, index: isize) -> Self {
self.tab_index = index;
if let Some(focus) = self.handles.write().handles.get_mut(self.id) {
focus.tab_index = index;
}
self
}
/// Sets whether the element associated with this handle is a tab stop.
///
/// When `false`, the element will not be included in the tab order.
pub fn tab_stop(mut self, tab_stop: bool) -> Self {
self.tab_stop = tab_stop;
if let Some(focus) = self.handles.write().handles.get_mut(self.id) {
focus.tab_stop = tab_stop;
}
self
}
/// Converts this focus handle into a weak variant, which does not prevent it from being released.
pub fn downgrade(&self) -> WeakFocusHandle {
WeakFocusHandle {
id: self.id,
handles: Arc::downgrade(&self.handles),
}
}
/// Moves the focus to the element associated with this handle.
pub fn focus(&self, window: &mut Window, cx: &mut App) {
window.focus(self, cx)
}
/// Obtains whether the element associated with this handle is currently focused.
pub fn is_focused(&self, window: &Window) -> bool {
self.id.is_focused(window)
}
/// Obtains whether the element associated with this handle contains the focused
/// element or is itself focused.
pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
self.id.contains_focused(window, cx)
}
/// Obtains whether the element associated with this handle is contained within the
/// focused element or is itself focused.
pub fn within_focused(&self, window: &Window, cx: &mut App) -> bool {
self.id.within_focused(window, cx)
}
/// Obtains whether this handle contains the given handle in the most recently rendered frame.
pub fn contains(&self, other: &Self, window: &Window) -> bool {
self.id.contains(other.id, window)
}
/// Obtains whether the element associated with this handle is part of the most recently rendered frame.
pub fn is_rendered(&self, window: &Window) -> bool {
window
.rendered_frame
.dispatch_tree
.focusable_node_id(self.id)
.is_some()
}
/// Dispatch an action on the element that rendered this focus handle
pub fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut App) {
if let Some(node_id) = window
.rendered_frame
.dispatch_tree
.focusable_node_id(self.id)
{
window.dispatch_action_on_node(node_id, action, cx)
}
}
}
impl Clone for FocusHandle {
fn clone(&self) -> Self {
Self::for_id(self.id, &self.handles).unwrap()
}
}
impl PartialEq for FocusHandle {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl Eq for FocusHandle {}
impl Drop for FocusHandle {
fn drop(&mut self) {
let handles = self.handles.upgradable_read();
let focus = handles.handles.get(self.id).expect("focus handle missing");
let previous_count = focus.ref_count.fetch_sub(1, SeqCst);
assert_ne!(previous_count, 0, "over-released focus handle");
if previous_count == 1 {
RwLockUpgradableReadGuard::upgrade(handles)
.dropped_handles
.push(self.id);
}
}
}
/// A weak reference to a focus handle.
#[derive(Clone, Debug)]
pub struct WeakFocusHandle {
pub(crate) id: FocusId,
pub(crate) handles: Weak<RwLock<FocusMap>>,
}
impl WeakFocusHandle {
/// Attempts to upgrade the [WeakFocusHandle] to a [FocusHandle].
pub fn upgrade(&self) -> Option<FocusHandle> {
let handles = self.handles.upgrade()?;
FocusHandle::for_id(self.id, &handles)
}
}
impl PartialEq for WeakFocusHandle {
fn eq(&self, other: &WeakFocusHandle) -> bool {
self.id == other.id
}
}
impl Eq for WeakFocusHandle {}
impl PartialEq<FocusHandle> for WeakFocusHandle {
fn eq(&self, other: &FocusHandle) -> bool {
self.id == other.id
}
}
impl PartialEq<WeakFocusHandle> for FocusHandle {
fn eq(&self, other: &WeakFocusHandle) -> bool {
self.id == other.id
}
}
/// Focusable allows users of your view to easily
/// focus it (using window.focus_view(cx, view))
pub trait Focusable: 'static {
/// Returns the focus handle associated with this view.
fn focus_handle(&self, cx: &App) -> FocusHandle;
}
impl<V: Focusable> Focusable for Entity<V> {
fn focus_handle(&self, cx: &App) -> FocusHandle {
self.read(cx).focus_handle(cx)
}
}
/// ManagedView is a view (like a Modal, Popover, Menu, etc.)
/// where the lifecycle of the view is handled by another view.
pub trait ManagedView: Focusable + EventEmitter<DismissEvent> + Render {}
impl<M: Focusable + EventEmitter<DismissEvent> + Render> ManagedView for M {}
/// Emitted by implementers of [`ManagedView`] to indicate the view should be dismissed, such as when a view is presented as a modal.
pub struct DismissEvent;
type FrameCallback = Box<dyn FnOnce(&mut Window, &mut App)>;
pub(crate) type AnyMouseListener =
Box<dyn FnMut(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
#[derive(Clone)]
pub(crate) struct CursorStyleRequest {
pub(crate) hitbox_id: Option<HitboxId>,
pub(crate) style: CursorStyle,
}
#[derive(Default, Eq, PartialEq)]
pub(crate) struct HitTest {
pub(crate) ids: SmallVec<[HitboxId; 8]>,
pub(crate) hover_hitbox_count: usize,
}
/// A type of window control area that corresponds to the platform window.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WindowControlArea {
/// An area that allows dragging of the platform window.
Drag,
/// An area that allows closing of the platform window.
Close,
/// An area that allows maximizing of the platform window.
Max,
/// An area that allows minimizing of the platform window.
Min,
/// An area that is explicitly NOT a window control: ordinary client
/// content, even when an ancestor declared [`WindowControlArea::Drag`].
///
/// This is what makes CSS `window-drag: none` (`-webkit-app-region:
/// no-drag`) expressible: without a positive "not a control" answer, a
/// descendant can only opt out of an ancestor's drag region by blocking
/// the mouse entirely (`.occlude()`), which also swallows every event
/// meant for content painted behind it.
NoDrag,
}
/// An identifier for a [Hitbox] which also includes [HitboxBehavior].
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub struct HitboxId(u64);
#[cfg(feature = "test-support")]
impl HitboxId {
/// A placeholder HitboxId exclusively for integration testing API's that
/// need a hitbox but where the value of the hitbox does not matter. The
/// alternative is to make the Hitbox optional but that complicates the
/// implementation.
pub const fn placeholder() -> Self {
Self(0)
}
}
impl HitboxId {
/// vue-native fork: the id of a PICK record ([`Window::vn_insert_pick`]),
/// which is in [`Frame::vn_tagged_hitboxes`] but never in
/// [`Frame::hitboxes`], so no hit test of gpui's own ever hovers it.
pub const VN_PICK: HitboxId = HitboxId(u64::MAX);
/// Checks if the hitbox with this ID is currently hovered. Returns `false` during keyboard
/// input modality so that keyboard navigation suppresses hover highlights. Except when handling
/// `ScrollEvent`, this is typically what you want when determining whether to handle mouse
/// events or paint hover styles.
///
/// See [`Hitbox::is_hovered`] for details.
pub fn is_hovered(self, window: &Window) -> bool {
// If this hitbox has captured the pointer, it's always considered hovered
if window.captured_hitbox == Some(self) {
return true;
}
if window.last_input_was_keyboard() {
return false;
}
self.hit_test(window)
}
/// Checks if the hitbox with this ID is currently hovered, regardless of the last
/// input modality used.
///
/// See [`HitboxId::is_hovered`] for more details.
pub(crate) fn is_hovered_ignoring_last_input(self, window: &Window) -> bool {
// If this hitbox has captured the pointer, it's always considered hovered
if window.captured_hitbox == Some(self) {
return true;
}
self.hit_test(window)
}
fn hit_test(self, window: &Window) -> bool {
// vue-native fork: a pointer that is not in the window hovers nothing,
// wherever `mouse_position` says it is (`Window::pointer_inside`). A
// browser shows no `:hover` under a cursor that is over another
// window, or that has left this one.
if !window.pointer_inside {
return false;
}
let hit_test = &window.mouse_hit_test;
for id in hit_test.ids.iter().take(hit_test.hover_hitbox_count) {
if self == *id {
return true;
}
}
false
}
/// Checks if the hitbox with this ID contains the mouse and should handle scroll events.
/// Typically this should only be used when handling `ScrollEvent`, and otherwise
/// `is_hovered` should be used. See the documentation of `Hitbox::is_hovered` for details about
/// this distinction.
pub fn should_handle_scroll(self, window: &Window) -> bool {
window.mouse_hit_test.ids.contains(&self)
}
fn next(self) -> HitboxId {
HitboxId(self.0.wrapping_add(1))
}
}
/// The axis-aligned bounding box of `bounds` after `matrix`.
///
/// `matrix` is a DEVICE-space transform (that is what the primitives carry)
/// and `bounds` are logical pixels, so the corners are scaled in and back
/// out again; at scale 1 the two cancel. Exact for a translation, a
/// superset for a rotation — see the caller in
/// [`Window::with_content_mask`].
#[inline]
fn transform_bounds(
matrix: TransformationMatrix,
bounds: Bounds<Pixels>,
scale_factor: f32,
) -> Bounds<Pixels> {
if matrix.is_unit() {
return bounds;
}
// `TransformationMatrix::apply` is unit-agnostic (it multiplies the raw
// floats), so the conversion is explicit: logical in, device through the
// matrix, logical out.
let map = |p: Point<Pixels>| {
let d = matrix.apply(Point::new(px(p.x.0 * scale_factor), px(p.y.0 * scale_factor)));
Point::new(px(d.x.0 / scale_factor), px(d.y.0 / scale_factor))
};
let corners = [
map(bounds.origin),
map(bounds.top_right()),
map(bounds.bottom_left()),
map(bounds.bottom_right()),
];
let min_x = corners.iter().map(|p| p.x).fold(Pixels::MAX, Pixels::min);
let max_x = corners.iter().map(|p| p.x).fold(Pixels::MIN, Pixels::max);
let min_y = corners.iter().map(|p| p.y).fold(Pixels::MAX, Pixels::min);
let max_y = corners.iter().map(|p| p.y).fold(Pixels::MIN, Pixels::max);
Bounds::from_corners(Point::new(min_x, min_y), Point::new(max_x, max_y))
}
/// vue-native fork: a content mask mapped like [`transform_bounds`]. Its radii
/// survive a translation and a positive scale. A non-uniform scale takes the
/// smaller factor, a circular corner inside the elliptical one, so the clip
/// shows a little more rather than less. A rotation, skew or flip drops the
/// radii, leaving the square bounding box that `transform_bounds` gives.
/// The key of `spec`'s history on `element`, 0 for none.
fn vn_history_key(element: u64, spec: &EffectSpec) -> u64 {
use std::hash::{Hash, Hasher};
if element == 0 || spec.flags & crate::EFFECT_FLAG_HISTORY == 0 {
return 0;
}
let mut hasher = collections::FxHasher::default();
(element, spec.id).hash(&mut hasher);
hasher.finish().max(1)
}
/// The phase an effect's `[SkAnimated]` speed has accumulated: its integral
/// over the effect clock, so a change of speed bends the motion instead of
/// rescaling all the time elapsed since the clock's zero. It starts at
/// `speed * time`, which is what an unchanged speed gives anyway.
#[derive(Clone, Copy, Debug, PartialEq)]
struct VnEffectPhase {
at: f32,
phase: f64,
}
impl VnEffectPhase {
/// Seconds an element may go unpainted before its phase is forgotten.
const KEEP: f32 = 10.;
fn advance(previous: Option<Self>, speed: f32, now: f32) -> Self {
match previous {
None => Self {
at: now,
phase: f64::from(speed) * f64::from(now),
},
Some(previous) if now > previous.at => Self {
at: now,
phase: previous.phase + f64::from(speed) * f64::from(now - previous.at),
},
Some(previous) => previous,
}
}
/// The speed the shader reads in place of the authored one: `time` times
/// it is the phase.
fn speed(&self, now: f32) -> Option<f32> {
(now > 1e-3).then(|| (self.phase / f64::from(now)) as f32)
}
}
fn vn_phase_key(element: u64, spec: &EffectSpec) -> u64 {
use std::hash::{Hash, Hasher};
let mut hasher = collections::FxHasher::default();
(element, spec.id, "phase").hash(&mut hasher);
hasher.finish()
}
fn transform_mask(
matrix: TransformationMatrix,
mask: ContentMask<Pixels>,
scale_factor: f32,
) -> ContentMask<Pixels> {
let bounds = transform_bounds(matrix, mask.bounds, scale_factor);
if !mask.is_rounded() || matrix.is_unit() {
return ContentMask {
bounds,
corner_radii: mask.corner_radii,
corner_shapes: mask.corner_shapes,
};
}
let [[a, b], [c, d]] = matrix.rotation_scale;
let (corner_radii, corner_shapes) = if b == 0. && c == 0. && a > 0. && d > 0. {
let factor = a.min(d);
let radii = mask.corner_radii
.map(|radius| *radius * factor)
.clamp_radii_for_quad_size(bounds.size);
(radii, mask.corner_shapes.scale(factor))
} else {
(Corners::default(), CornerShapes::default())
};
ContentMask {
bounds,
corner_radii,
corner_shapes,
}
}
/// A rectangular region that potentially blocks hitboxes inserted prior.
/// See [Window::insert_hitbox] for more details.
#[derive(Clone, Debug)]
pub struct Hitbox {
/// A unique identifier for the hitbox.
pub id: HitboxId,
/// The bounds of the hitbox.
pub bounds: Bounds<Pixels>,
/// The content mask when the hitbox was inserted.
pub content_mask: ContentMask<Pixels>,
/// Flags that specify hitbox behavior.
pub behavior: HitboxBehavior,
/// The composed CSS `transform` in force when the hitbox was inserted, in
/// DEVICE space (the same matrix the primitives carry).
///
/// `bounds` stays the UNTRANSFORMED rect, because that is the frame the
/// element and everything that reads a hitbox (autoscroll, tooltip
/// placement, `Hitbox::bounds`) thinks in. Hit-testing therefore maps the
/// pointer BACKWARDS through this rather than mapping the rect forwards —
/// see [`Frame::hit_test`].
pub transformation: TransformationMatrix,
/// vue-native fork: the `clip-path` shapes that are no rounded rectangle
/// around the hitbox when it was inserted, in window device pixels. A
/// point outside any of them does not hit it (CSS Masking 1 §5).
pub vn_clip: Option<Arc<crate::VnClipNode>>,
}
impl_deref!([] Hitbox => bounds: Bounds<Pixels>);
impl Hitbox {
/// Checks if the hitbox is currently hovered. Returns `false` during keyboard input modality
/// so that keyboard navigation suppresses hover highlights. Except when handling
/// `ScrollEvent`, this is typically what you want when determining whether to handle mouse
/// events or paint hover styles.
///
/// This can return `false` even when the hitbox contains the mouse, if a hitbox in front of
/// this sets `HitboxBehavior::BlockMouse` (`InteractiveElement::occlude`) or
/// `HitboxBehavior::BlockMouseExceptScroll` (`InteractiveElement::block_mouse_except_scroll`),
/// or if the current input modality is keyboard (see [`Window::last_input_was_keyboard`]).
///
/// Handling of `ScrollEvent` should typically use `should_handle_scroll` instead.
/// Concretely, this is due to use-cases like overlays that cause the elements under to be
/// non-interactive while still allowing scrolling. More abstractly, this is because
/// `is_hovered` is about element interactions directly under the mouse - mouse moves, clicks,
/// hover styling, etc. In contrast, scrolling is about finding the current outer scrollable
/// container.
pub fn is_hovered(&self, window: &Window) -> bool {
self.id.is_hovered(window)
}
/// Checks whether this hitbox would be hovered at `position`, regardless of the current input
/// modality or mouse position.
pub fn is_hovered_at(&self, position: Point<Pixels>, window: &Window) -> bool {
// Our hit test maps the pointer back through each hitbox's transform, so
// it needs the window's scale factor (see `Frame::hit_test`).
let hit_test = window
.rendered_frame
.hit_test(position, window.scale_factor);
hit_test
.ids
.iter()
.take(hit_test.hover_hitbox_count)
.any(|id| self.id == *id)
}
/// Checks if the hitbox contains the mouse and should handle scroll events. Typically this
/// should only be used when handling `ScrollEvent`, and otherwise `is_hovered` should be
/// used. See the documentation of `Hitbox::is_hovered` for details about this distinction.
///
/// This can return `false` even when the hitbox contains the mouse, if a hitbox in front of
/// this sets `HitboxBehavior::BlockMouse` (`InteractiveElement::occlude`).
pub fn should_handle_scroll(&self, window: &Window) -> bool {
self.id.should_handle_scroll(window)
}
}
/// vue-native fork: the bit an embedder ORs into a hitbox tag
/// ([`Window::set_hitbox_tag`]) for a box that belongs to the node but is not
/// where the node is — a scroll container's wheel viewport, inserted after
/// the content it covers. [`Window::vn_tags_at`] leaves such boxes out;
/// [`Window::vn_restrict_mouse_hit`] judges them by the node.
pub const VN_TAG_PASSIVE: u32 = 1 << 31;
/// vue-native fork: which mouse event a [`VnHitRefiner`] is refining.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum VnHitKind {
/// A [`MouseDownEvent`](crate::MouseDownEvent).
Down,
/// A [`MouseUpEvent`].
Up,
/// A [`ScrollEvent`](crate::ScrollEvent).
Scroll,
}
/// vue-native fork: the embedder's say over which hitboxes a mouse event is
/// for, run once per press, release and wheel before any listener sees it.
/// See [`Window::set_vn_hit_refiner`].
pub type VnHitRefiner = Rc<dyn Fn(VnHitKind, Point<Pixels>, &mut Window, &mut App)>;
/// vue-native fork: how [`Window::vn_lock_pointer`] holds the pointer.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum VnPointerLock {
/// The platform hides and holds the cursor ([`PlatformWindow::lock_pointer`]).
System {
/// The device's own counts, without pointer acceleration.
unadjusted: bool,
},
/// gpui's half alone, for tests: mouse events hold still at the lock position and moves
/// report how far their own position moved. The cursor is left alone.
Simulated,
}
/// How the hitbox affects mouse behavior.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub enum HitboxBehavior {
/// Normal hitbox mouse behavior, doesn't affect mouse handling for other hitboxes.
#[default]
Normal,
/// All hitboxes behind this hitbox will be ignored and so will have `hitbox.is_hovered() ==
/// false` and `hitbox.should_handle_scroll() == false`. Typically for elements this causes
/// skipping of all mouse events, hover styles, and tooltips. This flag is set by
/// [`InteractiveElement::occlude`].
///
/// For mouse handlers that check those hitboxes, this behaves the same as registering a
/// bubble-phase handler for every mouse event type:
///
/// ```ignore
/// window.on_mouse_event(move |_: &EveryMouseEventTypeHere, phase, window, cx| {
/// if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
/// cx.stop_propagation();
/// }
/// })
/// ```
///
/// This has effects beyond event handling - any use of hitbox checking, such as hover
/// styles and tooltips. These other behaviors are the main point of this mechanism. An
/// alternative might be to not affect mouse event handling - but this would allow
/// inconsistent UI where clicks and moves interact with elements that are not considered to
/// be hovered.
BlockMouse,
/// All hitboxes behind this hitbox will have `hitbox.is_hovered() == false`, even when
/// `hitbox.should_handle_scroll() == true`. Typically for elements this causes all mouse
/// interaction except scroll events to be ignored - see the documentation of
/// [`Hitbox::is_hovered`] for details. This flag is set by
/// [`InteractiveElement::block_mouse_except_scroll`].
///
/// For mouse handlers that check those hitboxes, this behaves the same as registering a
/// bubble-phase handler for every mouse event type **except** `ScrollEvent`:
///
/// ```ignore
/// window.on_mouse_event(move |_: &EveryMouseEventTypeExceptScroll, phase, window, cx| {
/// if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
/// cx.stop_propagation();
/// }
/// })
/// ```
///
/// See the documentation of [`Hitbox::is_hovered`] for details of why `ScrollEvent` is
/// handled differently than other mouse events. If also blocking these scroll events is
/// desired, then a `cx.stop_propagation()` handler like the one above can be used.
///
/// This has effects beyond event handling - this affects any use of `is_hovered`, such as
/// hover styles and tooltips. These other behaviors are the main point of this mechanism.
/// An alternative might be to not affect mouse event handling - but this would allow
/// inconsistent UI where clicks and moves interact with elements that are not considered to
/// be hovered.
BlockMouseExceptScroll,
}
/// An identifier for a tooltip.
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
pub struct TooltipId(usize);
impl TooltipId {
/// Checks if the tooltip is currently hovered.
pub fn is_hovered(&self, window: &Window) -> bool {
window
.tooltip_bounds
.as_ref()
.is_some_and(|tooltip_bounds| {
tooltip_bounds.id == *self
&& tooltip_bounds.bounds.contains(&window.mouse_position())
})
}
}
pub(crate) struct TooltipBounds {
id: TooltipId,
bounds: Bounds<Pixels>,
}
#[derive(Clone)]
pub(crate) struct TooltipRequest {
id: TooltipId,
tooltip: AnyTooltip,
}
/// The ids of the elements being drawn, root first, with the hash of every
/// prefix alongside: a [`GlobalElementId`] for the current element is then
/// the ids cloned out and the hash on top of the stack, without walking the
/// path — the ids of every ancestor, string names byte by byte — for each
/// element on every frame.
#[derive(Clone, Default)]
pub(crate) struct ElementIdStack {
ids: SmallVec<[ElementId; 32]>,
hashes: SmallVec<[u64; 32]>,
}
impl ElementIdStack {
pub(crate) fn push(&mut self, id: ElementId) {
self.hashes.push(crate::extend_path_hash(self.hash(), &id));
self.ids.push(id);
}
pub(crate) fn pop(&mut self) -> Option<ElementId> {
self.hashes.pop();
self.ids.pop()
}
pub(crate) fn clear(&mut self) {
self.ids.clear();
self.hashes.clear();
}
/// The hash of the whole path on the stack.
fn hash(&self) -> u64 {
self.hashes
.last()
.copied()
.unwrap_or(crate::EMPTY_PATH_HASH)
}
pub(crate) fn global_id(&self) -> GlobalElementId {
GlobalElementId::with_hash(&self.ids, self.hash())
}
}
impl std::ops::Deref for ElementIdStack {
type Target = [ElementId];
fn deref(&self) -> &Self::Target {
&self.ids
}
}
pub(crate) struct DeferredDraw {
current_view: EntityId,
priority: usize,
parent_node: DispatchNodeId,
element_id_stack: ElementIdStack,
text_style_stack: Vec<TextStyleRefinement>,
content_mask: Option<ContentMask<Pixels>>,
rem_size: Pixels,
element: Option<AnyElement>,
absolute_offset: Point<Pixels>,
/// The CSS `transform` in force where the element was deferred FROM.
///
/// A deferred draw is replayed at the top of the frame, where the transform
/// stack is empty — so without this, an element that escapes its siblings'
/// paint order (`position: fixed`, `z-index`) also escapes its ancestors'
/// transforms and paints somewhere nobody asked for. A `z-10` sticky header
/// inside a `translate(-50%, -50%)` dialog landed half the window away from
/// the dialog it belongs to.
element_transform: TransformationMatrix,
/// vue-native fork: the accessibility node on top of the stack where the
/// element was deferred FROM, which its nodes belong under
/// (`A11yNodeBuilder::begin_adopted`). `None` when accessibility was off.
a11y_parent: Option<accesskit::NodeId>,
/// vue-native fork: where the draw sorts among draws of equal `priority`,
/// compared lexicographically — see [`crate::Deferred::with_stack_key`].
/// `None` sorts first.
vn_stack: Option<Rc<[u128]>>,
/// vue-native fork: the opacity in force where the element was deferred
/// FROM. Like the transform, it would otherwise be lost at the top of the
/// frame: CSS applies an ancestor's `opacity` to everything inside it,
/// out-of-flow descendants included.
element_opacity: f32,
/// vue-native fork: the `clip-path` shapes in force where the element
/// was deferred FROM, taken with the content mask (none when the draw
/// escapes its ancestors' clips). Its prepaint re-enters them, and its
/// paint re-opens an isolated layer for each ([`Window::vn_with_clip_shape`]).
vn_clip: Option<Arc<crate::VnClipNode>>,
/// vue-native fork: the `[SkContent]` effect the draw was deferred from
/// inside, which paints it into its content ([`VnDeferScope`]).
vn_scope: Option<VnDeferScope>,
prepaint_range: Range<PrepaintStateIndex>,
paint_range: Range<PaintIndex>,
/// The entities the deferred element accessed while it was last drawn, in
/// any phase, restored when its prepaint is reused.
accessed_entities: FxHashSet<EntityId>,
}
/// vue-native fork: an element whose effect reads its own content. A draw
/// deferred from inside it (a positioned descendant) paints into that
/// content, after the element's in-flow subtree, rather than after the whole
/// tree where the effect never sees it. `id` is the element's
/// [`vn_element_key`]; `clip` the clip stack its subtree prepainted in, which
/// the content group is already inside of.
#[derive(Clone, Debug)]
pub(crate) struct VnDeferScope {
id: u64,
clip: Option<Arc<crate::VnClipNode>>,
}
/// vue-native fork: an element's identity for per-element paint state, 0
/// for none. Views are left out: a cached subtree is painted inside its view
/// on one frame and replayed without it on the next.
pub(crate) fn vn_element_key(id: Option<&GlobalElementId>) -> u64 {
use std::hash::{Hash, Hasher};
id.map_or(0, |id| {
let mut hasher = collections::FxHasher::default();
for id in id.iter() {
if !matches!(id, ElementId::View(_)) {
id.hash(&mut hasher);
}
}
hasher.finish().max(1)
})
}
impl DeferredDraw {
/// The paint order: `priority`, then the embedder's stack key.
fn order(&self) -> (usize, Option<&[u128]>) {
(self.priority, self.vn_stack.as_deref())
}
}
pub(crate) struct Frame {
pub(crate) focus: Option<FocusId>,
pub(crate) window_active: bool,
pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
accessed_element_states: Vec<(GlobalElementId, TypeId)>,
pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
pub(crate) dispatch_tree: DispatchTree,
pub(crate) scene: Scene,
pub(crate) hitboxes: Vec<Hitbox>,
/// vue-native fork: the hitboxes inserted while [`Window::hitbox_tag`] was
/// non-zero, paired with the tag in force.
///
/// An embedder that mirrors its own retained tree into gpui elements has no
/// other way to get from one of ITS node ids to the hitbox gpui made for it
/// — and without that, `Hitbox::is_hovered_at` (the only public door onto
/// gpui's hit test) cannot be asked about a node. Insertion order is
/// preserved, and an element's own hitbox is inserted before any of its
/// descendants', so the FIRST entry for a tag is that node's own box.
pub(crate) vn_tagged_hitboxes: Vec<(u32, Hitbox)>,
/// vue-native fork: [`Frame::hitboxes`]' indices in PAINT order, which
/// [`Frame::hit_test`] walks topmost-first. Empty means insertion order.
///
/// Hitboxes are inserted in prepaint order, and deferred draws prepaint in
/// nesting rounds: a draw nested one round deeper is inserted after every
/// draw of the round before, wherever it paints. Hit-testing by insertion
/// let a box that paints UNDER a later overlay take its clicks. The vector
/// itself is not reordered, because cached views replay ranges of it.
pub(crate) vn_hit_order: Vec<u32>,
/// vue-native fork: the slice of [`Frame::vn_tagged_hitboxes`] the
/// deferred draws' prepaint inserted — what
/// [`Frame::vn_tagged_paint_order`] reorders, as `vn_hit_order` does the
/// hitboxes.
pub(crate) vn_deferred_tagged: Range<usize>,
/// vue-native fork: [`Frame::vn_tagged_paint_order`], worked out on the
/// first question about this frame and kept until it is cleared.
vn_tagged_order: std::cell::OnceCell<Option<Vec<u32>>>,
pub(crate) window_control_hitboxes: Vec<(WindowControlArea, Hitbox)>,
pub(crate) deferred_draws: Vec<DeferredDraw>,
pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
pub(crate) cursor_styles: Vec<CursorStyleRequest>,
#[cfg(any(test, feature = "test-support"))]
pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
#[cfg(any(test, feature = "test-support"))]
debug_bounds_records: Vec<(String, Bounds<Pixels>)>,
#[cfg(any(feature = "inspector", debug_assertions))]
pub(crate) next_inspector_instance_ids: FxHashMap<Rc<crate::InspectorElementPath>, usize>,
#[cfg(any(feature = "inspector", debug_assertions))]
pub(crate) inspector_hitboxes: FxHashMap<HitboxId, crate::InspectorElementId>,
pub(crate) tab_stops: TabStopMap,
}
#[derive(Clone, Default)]
pub(crate) struct PrepaintStateIndex {
hitboxes_index: usize,
/// vue-native fork: the embedder's tagged-hitbox list is a frame structure
/// like `hitboxes` beside it, so a reused prepaint span has to carry its
/// slice forward too — see [`Window::reuse_prepaint`].
vn_tagged_hitboxes_index: usize,
tooltips_index: usize,
deferred_draws_index: usize,
dispatch_tree_index: usize,
accessed_element_states_index: usize,
line_layout_index: LineLayoutIndex,
}
#[derive(Clone, Default)]
pub(crate) struct PaintIndex {
scene_index: usize,
#[cfg(any(test, feature = "test-support"))]
debug_bounds_index: usize,
mouse_listeners_index: usize,
input_handlers_index: usize,
cursor_styles_index: usize,
window_control_hitboxes_index: usize,
accessed_element_states_index: usize,
tab_handle_index: usize,
line_layout_index: LineLayoutIndex,
}
impl Frame {
#[cfg(any(test, feature = "test-support"))]
pub(crate) fn record_debug_bounds(&mut self, selector: String, bounds: Bounds<Pixels>) {
self.debug_bounds.insert(selector.clone(), bounds);
self.debug_bounds_records.push((selector, bounds));
}
pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
Frame {
focus: None,
window_active: false,
element_states: FxHashMap::default(),
accessed_element_states: Vec::new(),
mouse_listeners: Vec::new(),
dispatch_tree,
scene: Scene::default(),
hitboxes: Vec::new(),
vn_tagged_hitboxes: Vec::new(),
vn_hit_order: Vec::new(),
vn_deferred_tagged: 0..0,
vn_tagged_order: std::cell::OnceCell::new(),
window_control_hitboxes: Vec::new(),
deferred_draws: Vec::new(),
input_handlers: Vec::new(),
tooltip_requests: Vec::new(),
cursor_styles: Vec::new(),
#[cfg(any(test, feature = "test-support"))]
debug_bounds: FxHashMap::default(),
#[cfg(any(test, feature = "test-support"))]
debug_bounds_records: Vec::new(),
#[cfg(any(feature = "inspector", debug_assertions))]
next_inspector_instance_ids: FxHashMap::default(),
#[cfg(any(feature = "inspector", debug_assertions))]
inspector_hitboxes: FxHashMap::default(),
tab_stops: TabStopMap::default(),
}
}
pub(crate) fn clear(&mut self) {
self.element_states.clear();
self.accessed_element_states.clear();
self.mouse_listeners.clear();
self.dispatch_tree.clear();
self.scene.clear();
self.input_handlers.clear();
self.tooltip_requests.clear();
self.cursor_styles.clear();
self.hitboxes.clear();
self.vn_tagged_hitboxes.clear();
self.vn_hit_order.clear();
self.vn_deferred_tagged = 0..0;
self.vn_tagged_order = std::cell::OnceCell::new();
self.window_control_hitboxes.clear();
self.deferred_draws.clear();
self.tab_stops.clear();
self.focus = None;
#[cfg(any(test, feature = "test-support"))]
{
self.debug_bounds.clear();
self.debug_bounds_records.clear();
}
#[cfg(any(feature = "inspector", debug_assertions))]
{
self.next_inspector_instance_ids.clear();
self.inspector_hitboxes.clear();
}
}
pub(crate) fn cursor_style(&self, window: &Window) -> Option<CursorStyle> {
self.cursor_styles
.iter()
.rev()
.fold_while(None, |style, request| match request.hitbox_id {
None => Done(Some(request.style)),
Some(hitbox_id) => Continue(style.or_else(|| {
hitbox_id
.is_hovered_ignoring_last_input(window)
.then_some(request.style)
})),
})
.into_inner()
}
/// Is `position` (window space) inside `hitbox`, as the hit test sees it?
fn box_contains(hitbox: &Hitbox, position: Point<Pixels>, scale_factor: f32) -> bool {
// A transformed element keeps its untransformed `bounds`, so the
// POINTER is mapped back into the element's own frame rather than
// the rect being mapped forward into a polygon. That keeps the test
// a rectangle containment (exact for rotation and scale alike) and
// costs nothing at all when there is no transform.
//
// The matrix is in DEVICE space (it is the same one the primitives
// carry), so the pointer goes there and back; at scale 1 the two
// conversions cancel and this is what it always was.
//
// A singular matrix (`scale(0)`) has no inverse, which is the right
// answer: an element scaled to nothing is not hittable, exactly as
// in a browser.
let local = if hitbox.transformation.is_unit() {
position
} else {
match hitbox.transformation.inverse() {
Some(inverse) => {
let d = inverse.apply(Point::new(
px(position.x.0 * scale_factor),
px(position.y.0 * scale_factor),
));
Point::new(px(d.x.0 / scale_factor), px(d.y.0 / scale_factor))
}
None => return false,
}
};
// The CONTENT MASK is a window-space rect (see
// `Window::with_content_mask`, which maps it through the transform
// in force when it was pushed), so it is tested against the pointer
// as it came in — not against the element-local one. Testing both in
// one intersected rect was only right while transforms did not
// exist: a `translate(-50%, -50%)` dialog painted 500px to the left
// of a clip rect that had not moved, and every clipping element
// inside it hit-tested against a region it no longer covered.
hitbox.content_mask.contains(&position)
&& hitbox.bounds.contains(&local)
// vue-native fork: and inside every `clip-path` shape around it,
// which is in window device pixels.
&& hitbox.vn_clip.as_ref().is_none_or(|clip| {
clip.contains([position.x.0 * scale_factor, position.y.0 * scale_factor])
})
}
/// vue-native fork: [`Frame::vn_tagged_hitboxes`]' indices in PAINT
/// order — what [`Frame::compute_hit_order`]-style reordering does for
/// the hitboxes, done for the tagged list, which also holds the pick
/// records no hitbox list has. `None` means insertion order is paint
/// order (no deferred draw inserted anything). Worked out once per frame,
/// on the first question.
fn vn_tagged_paint_order(&self) -> Option<&[u32]> {
self.vn_tagged_order
.get_or_init(|| {
let deferred = self.vn_deferred_tagged.clone();
if deferred.is_empty() {
return None;
}
let len = self.vn_tagged_hitboxes.len();
let mut order: Vec<u32> = Vec::with_capacity(len);
order.extend(0..deferred.start as u32);
let draws = &self.deferred_draws;
let mut traversal = (0..draws.len()).collect::<Vec<_>>();
traversal.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
for ix in traversal {
let range = &draws[ix].prepaint_range;
let (start, end) = (
range.start.vn_tagged_hitboxes_index,
range.end.vn_tagged_hitboxes_index,
);
if start >= deferred.start && end <= deferred.end && start < end {
order.extend(start as u32..end as u32);
}
}
order.extend(deferred.end as u32..len as u32);
// Anything a draw's range did not account for keeps insertion
// order rather than vanishing (as `compute_hit_order`).
(order.len() == len).then_some(order)
})
.as_deref()
}
// The iterator is stack-only: native WM_NCHITTEST can precede every mouse
// move, so constructing its paint-order traversal must not allocate.
fn topmost_hitboxes(&self) -> impl Iterator<Item = &Hitbox> {
let in_paint_order = self.vn_hit_order.len() == self.hitboxes.len();
(0..self.hitboxes.len()).rev().map(move |index| {
let index = if in_paint_order { self.vn_hit_order[index] as usize } else { index };
&self.hitboxes[index]
})
}
pub(crate) fn hit_test(&self, position: Point<Pixels>, scale_factor: f32) -> HitTest {
let mut set_hover_hitbox_count = false;
let mut hit_test = HitTest::default();
for hitbox in self.topmost_hitboxes() {
if Self::box_contains(hitbox, position, scale_factor) {
hit_test.ids.push(hitbox.id);
if !set_hover_hitbox_count
&& hitbox.behavior == HitboxBehavior::BlockMouseExceptScroll
{
hit_test.hover_hitbox_count = hit_test.ids.len();
set_hover_hitbox_count = true;
}
if hitbox.behavior == HitboxBehavior::BlockMouse {
break;
}
}
}
if !set_hover_hitbox_count {
hit_test.hover_hitbox_count = hit_test.ids.len();
}
hit_test
}
pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
self.focus
.map(|focus_id| self.dispatch_tree.focus_path(focus_id))
.unwrap_or_default()
}
pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
for element_state_key in &self.accessed_element_states {
if let Some((element_state_key, element_state)) =
prev_frame.element_states.remove_entry(element_state_key)
{
self.element_states.insert(element_state_key, element_state);
}
}
self.scene.finish();
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
enum InputModality {
Mouse,
Keyboard,
Touch,
}
/// vue-native fork: what an effect's host-filled pointer parameters read, and
/// the views whose effects read them.
struct VnEffectPointer {
/// Effect-clock seconds of the last move, entry and exit; the pointer is
/// inside while `entered > left`.
moved: f32,
entered: f32,
left: f32,
/// Notified on the next pointer change, and re-registered when they paint.
views: FxHashSet<EntityId>,
}
impl VnEffectPointer {
/// Long enough ago for any fade an effect keys off these times to be over.
const NEVER: f32 = -1.0e4;
fn new(inside: bool) -> Self {
let (entered, left) = if inside {
(Self::NEVER, Self::NEVER - 1.)
} else {
(Self::NEVER - 1., Self::NEVER)
};
Self {
moved: Self::NEVER,
entered,
left,
views: FxHashSet::default(),
}
}
fn update(&mut self, was_inside: bool, inside: bool, moved: bool, cx: &mut App) {
if was_inside == inside && !moved {
return;
}
let now = crate::effect_clock_seconds();
if moved {
self.moved = now;
}
if inside && !was_inside {
self.entered = now;
} else if was_inside && !inside {
self.left = now;
}
for view in self.views.drain() {
cx.notify(view);
}
}
}
/// Holds the state for a specific window.
pub struct Window {
pub(crate) handle: AnyWindowHandle,
pub(crate) invalidator: WindowInvalidator,
pub(crate) removed: bool,
pub(crate) platform_window: Box<dyn PlatformWindow>,
pub(crate) display_id: Option<DisplayId>,
pub(crate) display_observers: SingleSubscriberSet<AnyObserver>,
is_resizable: bool,
is_minimizable: bool,
last_window_bounds: WindowBounds,
sprite_atlas: Arc<dyn PlatformAtlas>,
text_system: Rc<WindowTextSystem>,
text_rendering_mode: Rc<Cell<TextRenderingMode>>,
rem_size: Pixels,
/// The stack of override values for the window's rem size.
///
/// This is used by `with_rem_size` to allow rendering an element tree with
/// a given rem size.
rem_size_override_stack: SmallVec<[Pixels; 8]>,
pub(crate) viewport_size: Size<Pixels>,
layout_engine: Option<TaffyLayoutEngine>,
pub(crate) root: Option<AnyView>,
pub(crate) element_id_stack: ElementIdStack,
pub(crate) text_style_stack: Vec<TextStyleRefinement>,
pub(crate) rendered_entity_stack: Vec<EntityId>,
pub(crate) element_offset_stack: Vec<Point<Pixels>>,
pub(crate) element_opacity: f32,
/// vue-native fork: the colour [`Window::paint_image`] tints with
/// ([`Window::with_image_tint`]); transparent outside a tint scope.
element_image_tint: Hsla,
/// The composed CSS `transform` of every ancestor currently being painted,
/// in DEVICE space. Identity outside a `Style::vn_transform`.
///
/// A field rather than a stack, for the same reason `element_opacity` is:
/// every push already has to compose with what is above it, so the "stack"
/// is one saved value per frame of the paint recursion and lives on the
/// Rust stack instead.
pub(crate) element_transform: TransformationMatrix,
/// vue-native fork: the embedder node id every hitbox inserted from here
/// down is recorded under (0 = record nothing). See
/// [`Frame::vn_tagged_hitboxes`].
vn_hitbox_tag: u32,
/// vue-native fork: no element has prepainted yet under the tag that
/// [`Window::with_hitbox_tag`] set, so the next one is the tagged node's
/// own. See [`Window::note_tagged_transform`].
vn_tag_fresh: bool,
/// vue-native fork: the tagged node's whole `transform` (ancestors' and
/// its own), when it has one of its own.
vn_tag_transform: Option<TransformationMatrix>,
/// vue-native fork: while set, EVERY element gets a hitbox, not only an
/// interactive one — the same thing gpui's own inspector does while it is
/// picking, and for the same reason: a hit test can only answer for a node
/// that has a hitbox.
vn_tag_every_hitbox: bool,
/// vue-native fork: while set, an element that gets no hitbox records a
/// PICK instead ([`Window::vn_insert_pick`]).
vn_pick_every_box: bool,
/// vue-native fork: see [`Window::set_vn_hit_refiner`].
vn_hit_refiner: Option<VnHitRefiner>,
// Optional modal input interception, e.g. an external element inspector.
input_interceptor: Option<Rc<dyn Fn(&PlatformInput, &mut Window, &mut App) -> bool>>,
/// vue-native fork: see [`Window::vn_key_event_seq`].
vn_key_event_seq: u64,
/// vue-native fork: [`Window::vn_lock_pointer`]'s mode and the position mouse events hold at.
vn_pointer_lock: Option<(VnPointerLock, Point<Pixels>)>,
/// vue-native fork: the last mouse move's position as delivered, before a lock pinned it.
vn_raw_mouse_position: Option<Point<Pixels>>,
/// vue-native fork: see [`Window::vn_mouse_movement`].
vn_mouse_movement: Point<Pixels>,
pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
/// vue-native fork: the `clip-path` shapes in force that are no rounded
/// rectangle, innermost first ([`Window::vn_with_clip_shape`]). A hitbox
/// and a deferred draw take it as they take the content mask.
pub(crate) vn_clip_stack: Option<Arc<crate::VnClipNode>>,
/// vue-native fork: every capture drawn and not forgotten, with the
/// pixels its snapshot covers ([Window::vn_with_capture]).
vn_capture_records: FxHashMap<u64, (crate::VnCaptureInfo, Bounds<ScaledPixels>)>,
pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
/// The [`TextInputConfiguration`] most recently forwarded to the platform
/// window, so that only actual changes are forwarded (reconfiguring a live
/// input session can restart the IME connection).
last_text_input_configuration: Option<TextInputConfiguration>,
focused_text_input: Option<FocusId>,
pub(crate) image_cache_stack: Vec<AnyImageCache>,
pub(crate) rendered_frame: Frame,
pub(crate) next_frame: Frame,
next_hitbox_id: HitboxId,
pub(crate) next_tooltip_id: TooltipId,
pub(crate) tooltip_bounds: Option<TooltipBounds>,
pub(crate) next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
/// Whether a queued next-frame callback asked for a frame (passive ones do
/// not; see [`Window::on_next_frame_passive`]).
pub(crate) next_frame_wanted: Rc<Cell<bool>>,
pub(crate) dirty_views: FxHashSet<EntityId>,
focus_listeners: SingleSubscriberSet<AnyWindowFocusListener>,
pub(crate) focus_lost_listeners: SingleSubscriberSet<AnyObserver>,
focus_lost_path: SmallVec<[FocusId; 8]>,
default_prevented: bool,
mouse_position: Point<Pixels>,
mouse_hit_test: HitTest,
modifiers: Modifiers,
capslock: Capslock,
scale_factor: f32,
pub(crate) bounds_observers: SingleSubscriberSet<AnyObserver>,
appearance: WindowAppearance,
pub(crate) appearance_observers: SingleSubscriberSet<AnyObserver>,
pub(crate) button_layout_observers: SingleSubscriberSet<AnyObserver>,
active: Rc<Cell<bool>>,
/// vue-native fork: [`Window::set_assume_active`].
assume_active: bool,
visibility: WindowVisibility,
pub(crate) visibility_observers:
SingleSubscriberSet<Box<dyn FnMut(WindowVisibility, &mut Window, &mut App) -> bool>>,
hovered: Rc<Cell<bool>>,
/// vue-native fork: is the pointer in this window, as far as the input
/// gpui has seen says? Until it is, `mouse_position` is only where the OS
/// cursor projects onto the client area (`Window::new` and
/// `bounds_changed` read it from the platform). The cursor may be over
/// another window that covers this one, or the position may be stale
/// since the pointer left. No hitbox counts as hovered while this is
/// false ([`HitboxId::is_hovered`]). The hit test itself is kept, because
/// the platform's window-control hit test (`WM_NCHITTEST`) reads it.
///
/// Any pointer input dispatched to the window sets it, a synthesized
/// one included (a test harness or devtools moving the pointer means it).
/// `MouseExited`, a file drag leaving, and the platform's hover-status
/// change to false clear it. It starts as the platform's `is_hovered()`.
pointer_inside: bool,
vn_effect_pointer: VnEffectPointer,
/// vue-native fork: the identity of the element whose style paints next,
/// which keys an `[SkHistory]` effect's state; 0 when it has none.
vn_effect_element: u64,
/// vue-native fork: per element and effect, how far its `[SkAnimated]`
/// speed has advanced it ([`VnEffectPhase`]).
vn_effect_phases: FxHashMap<u64, VnEffectPhase>,
/// vue-native fork: the scope a draw deferred now goes to, while
/// prepainting.
vn_defer_scope: Option<VnDeferScope>,
/// vue-native fork: the scopes whose content painted their draws this
/// frame.
vn_scopes_painted: FxHashSet<u64>,
pub(crate) needs_present: Rc<Cell<bool>>,
/// The rendered scene's [`Scene::animation_frame_interval`]. While it is
/// `Some`, the scene must keep being presented even when nothing is redrawn.
scene_animation_interval: Rc<Cell<Option<Duration>>>,
/// Tracks recent input event timestamps to determine if input is arriving at a high rate.
/// Used to selectively enable VRR optimization only when input rate exceeds 60fps.
pub(crate) input_rate_tracker: Rc<RefCell<InputRateTracker>>,
#[cfg(feature = "profiler")]
pub(crate) window_profiler: profiler::WindowProfiler,
last_input_modality: InputModality,
touch_gestures: TouchGestureRecognizer,
touch_prediction_enabled: bool,
long_press_timer: Option<Task<()>>,
long_press_capture: Option<EntityId>,
pub(crate) refreshing: bool,
pub(crate) activation_observers: SingleSubscriberSet<AnyObserver>,
pub(crate) focus: Option<FocusId>,
focus_enabled: bool,
/// Incremented every time focus moves. Used to invalidate a
/// pending keyboard activation state when focus changes.
pub(crate) focus_generation: u64,
pending_input: Option<PendingInput>,
pending_modifier: ModifierState,
pub(crate) pending_input_observers: SingleSubscriberSet<AnyObserver>,
prompt: Option<RenderablePromptHandle>,
pub(crate) client_inset: Option<Pixels>,
/// The hitbox that has captured the pointer, if any.
/// While captured, mouse events route to this hitbox regardless of hit testing.
captured_hitbox: Option<HitboxId>,
#[cfg(any(feature = "inspector", debug_assertions))]
inspector: Option<Entity<Inspector>>,
#[cfg(feature = "profiler")]
debug_frame_overlay: crate::debug_overlay::DebugFrameOverlay,
pub(crate) a11y: A11y,
}
#[derive(Clone, Debug, Default)]
struct ModifierState {
modifiers: Modifiers,
saw_other_input: bool,
}
/// Tracks input event timestamps to determine if input is arriving at a high rate.
/// Used for selective VRR (Variable Refresh Rate) optimization.
#[derive(Clone, Debug)]
pub(crate) struct InputRateTracker {
timestamps: Vec<Instant>,
window: Duration,
inputs_per_second: u32,
sustain_until: Instant,
sustain_duration: Duration,
}
const FRAME_INTERVAL_TOLERANCE: Duration = Duration::from_millis(1);
/// Keeps throttled frames on a stable cadence despite callback delivery jitter.
#[derive(Default)]
struct FramePacer {
last_frame: Option<Instant>,
}
impl FramePacer {
fn should_defer(&mut self, now: Instant, minimum_interval: Option<Duration>) -> bool {
if let Some(interval) = minimum_interval
&& let Some(last_frame) = self.last_frame
{
let deadline = last_frame + interval;
if now + FRAME_INTERVAL_TOLERANCE < deadline {
return true;
}
// Correct small dispatch delays without shifting subsequent deadlines,
// but bound the correction to a quarter interval. Larger delays restart
// the cadence so recovery cannot produce closely spaced catch-up frames.
self.last_frame = Some(if now.saturating_duration_since(deadline) <= interval / 4 {
deadline
} else {
now
});
} else {
self.last_frame = Some(now);
}
false
}
}
fn minimum_frame_interval(
should_throttle: bool,
inactive_without_high_rate_input: bool,
inactive_frame_interval: Option<Duration>,
low_power_frame_interval: Option<Duration>,
thermal_frame_interval: Option<Duration>,
thermal_state: ThermalState,
power_mode: crate::PowerMode,
) -> Option<Duration> {
if !should_throttle {
return None;
}
[
inactive_frame_interval.filter(|_| inactive_without_high_rate_input),
low_power_frame_interval.filter(|_| power_mode == crate::PowerMode::LowPower),
thermal_frame_interval.filter(|_| {
matches!(
thermal_state,
ThermalState::Critical | ThermalState::Serious
)
}),
]
.into_iter()
.flatten()
.max()
}
impl Default for InputRateTracker {
fn default() -> Self {
Self {
timestamps: Vec::new(),
window: Duration::from_millis(100),
inputs_per_second: 60,
sustain_until: Instant::now(),
sustain_duration: Duration::from_secs(1),
}
}
}
impl InputRateTracker {
pub fn record_input(&mut self) {
let now = Instant::now();
self.timestamps.push(now);
self.prune_old_timestamps(now);
let min_events = self.inputs_per_second as u128 * self.window.as_millis() / 1000;
if self.timestamps.len() as u128 >= min_events {
self.sustain_until = now + self.sustain_duration;
}
}
pub fn is_high_rate(&self) -> bool {
Instant::now() < self.sustain_until
}
fn prune_old_timestamps(&mut self, now: Instant) {
self.timestamps
.retain(|&t| now.duration_since(t) <= self.window);
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum DrawPhase {
None,
Prepaint,
Paint,
Focus,
}
pub(crate) const PENDING_INPUT_TIMEOUT: Duration = Duration::from_secs(1);
/// Pending input for a potential multi-stroke key binding.
pub struct PendingInputStatus<'a> {
keystrokes: &'a [Keystroke],
timeout: Option<PendingInputTimeoutStatus>,
}
impl<'a> PendingInputStatus<'a> {
/// Returns the keystrokes entered so far.
pub fn keystrokes(&self) -> &'a [Keystroke] {
self.keystrokes
}
/// Returns the timeout state for flushing this input, if it needs a timeout.
pub fn timeout(&self) -> Option<PendingInputTimeoutStatus> {
self.timeout
}
}
/// The timeout state for pending input.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct PendingInputTimeoutStatus {
duration: Duration,
remaining: Duration,
started_at: Option<Instant>,
paused: bool,
}
impl PendingInputTimeoutStatus {
/// Returns the full timeout duration.
pub fn duration(&self) -> Duration {
self.duration
}
/// Returns the duration remaining before pending input is flushed.
pub fn remaining(&self, cx: &App) -> Duration {
self.started_at
.map(|started_at| {
self.remaining
.saturating_sub(cx.background_executor().now() - started_at)
})
.unwrap_or(self.remaining)
}
/// Returns whether the timeout is paused.
pub fn is_paused(&self) -> bool {
self.paused
}
}
#[derive(Debug)]
struct PendingInputTimeout {
duration: Duration,
remaining: Duration,
state: PendingInputTimeoutState,
}
#[derive(Debug)]
enum PendingInputTimeoutState {
Running { started_at: Instant, task: Task<()> },
Paused { pause: PendingInputTimeoutPause },
}
#[derive(Debug)]
struct PendingInputTimeoutPause {
owner_id: EntityId,
_release_subscription: Subscription,
}
impl PendingInputTimeout {
fn is_paused(&self) -> bool {
matches!(&self.state, PendingInputTimeoutState::Paused { .. })
}
fn pause(&mut self, pause: PendingInputTimeoutPause, now: Instant) -> bool {
match std::mem::replace(&mut self.state, PendingInputTimeoutState::Paused { pause }) {
PendingInputTimeoutState::Running { started_at, task } => {
self.remaining = self.remaining.saturating_sub(now - started_at);
drop(task);
true
}
previous_state @ PendingInputTimeoutState::Paused { .. } => {
self.state = previous_state;
false
}
}
}
fn pause_owner_id(&self) -> Option<EntityId> {
match &self.state {
PendingInputTimeoutState::Running { .. } => None,
PendingInputTimeoutState::Paused { pause } => Some(pause.owner_id),
}
}
fn resume(&mut self, owner_id: EntityId, started_at: Instant, task: Task<()>) -> bool {
match std::mem::replace(
&mut self.state,
PendingInputTimeoutState::Running { started_at, task },
) {
PendingInputTimeoutState::Paused { pause } if pause.owner_id == owner_id => true,
previous_state => {
self.state = previous_state;
false
}
}
}
fn reset_duration(&mut self, duration: Duration) {
self.duration = duration;
self.remaining = duration;
}
fn status(&self) -> PendingInputTimeoutStatus {
let (started_at, paused) = match &self.state {
PendingInputTimeoutState::Running { started_at, .. } => (Some(*started_at), false),
PendingInputTimeoutState::Paused { .. } => (None, true),
};
PendingInputTimeoutStatus {
duration: self.duration,
remaining: self.remaining,
started_at,
paused,
}
}
}
#[derive(Default, Debug)]
struct PendingInput {
keystrokes: SmallVec<[Keystroke; 1]>,
focus: Option<FocusId>,
timeout: Option<PendingInputTimeout>,
}
pub(crate) struct ElementStateBox {
pub(crate) inner: Box<dyn Any>,
#[cfg(debug_assertions)]
pub(crate) type_name: &'static str,
}
fn default_bounds(
active_window_bounds: Option<WindowBounds>,
display: Option<&dyn PlatformDisplay>,
) -> WindowBounds {
const CASCADE_OFFSET: f32 = 25.0;
let default_placement = || Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE);
// Use visible_bounds to exclude taskbar/dock areas
let display_bounds = display
.map(|d| d.visible_bounds())
.unwrap_or_else(default_placement);
let (
Bounds {
origin: base_origin,
size: base_size,
},
window_bounds_ctor,
): (_, fn(Bounds<Pixels>) -> WindowBounds) = match active_window_bounds {
Some(bounds) => match bounds {
WindowBounds::Windowed(bounds) => (bounds, WindowBounds::Windowed),
WindowBounds::Maximized(bounds) => (bounds, WindowBounds::Maximized),
WindowBounds::Fullscreen(bounds) => (bounds, WindowBounds::Fullscreen),
},
None => (
display
.map(|d| d.default_bounds())
.unwrap_or_else(default_placement),
WindowBounds::Windowed,
),
};
let cascade_offset = point(px(CASCADE_OFFSET), px(CASCADE_OFFSET));
let proposed_origin = base_origin + cascade_offset;
let proposed_bounds = Bounds::new(proposed_origin, base_size);
let display_right = display_bounds.origin.x + display_bounds.size.width;
let display_bottom = display_bounds.origin.y + display_bounds.size.height;
let window_right = proposed_bounds.origin.x + proposed_bounds.size.width;
let window_bottom = proposed_bounds.origin.y + proposed_bounds.size.height;
let fits_horizontally = window_right <= display_right;
let fits_vertically = window_bottom <= display_bottom;
let final_origin = match (fits_horizontally, fits_vertically) {
(true, true) => proposed_origin,
(false, true) => point(display_bounds.origin.x, base_origin.y),
(true, false) => point(base_origin.x, display_bounds.origin.y),
(false, false) => display_bounds.origin,
};
window_bounds_ctor(Bounds::new(final_origin, base_size))
}
impl Window {
pub(crate) fn new(
handle: AnyWindowHandle,
options: WindowOptions,
cx: &mut App,
) -> Result<Self> {
let WindowOptions {
window_bounds,
titlebar,
focus,
show,
kind,
is_movable,
app_owns_titlebar_drag,
inactive_frame_interval,
low_power_frame_interval,
thermal_frame_interval,
is_resizable,
is_minimizable,
display_id,
window_background,
app_id,
window_min_size,
window_decorations,
#[cfg_attr(
not(any(target_os = "linux", target_os = "freebsd")),
allow(unused_variables)
)]
icon,
#[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
tabbing_identifier,
#[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
use_display_p3,
} = options;
let initial_window_title = titlebar
.as_ref()
.and_then(|titlebar| titlebar.title.clone());
let active_window_placement = cx.active_window_placement();
// Explicit bounds only make sense on the display they were computed for.
let target_display_id = display_id.or_else(|| {
active_window_placement
.filter(|_| window_bounds.is_none())
.and_then(|(display_id, _)| display_id)
});
let display = target_display_id
.and_then(|display_id| cx.find_display(display_id))
.or_else(|| cx.primary_display());
let display_id = display
.as_ref()
.map(|display| display.id())
.or(target_display_id);
let active_window_bounds = active_window_placement
.filter(|(active_display_id, _)| *active_display_id == display_id)
.map(|(_, bounds)| bounds);
let window_bounds = window_bounds
.unwrap_or_else(|| default_bounds(active_window_bounds, display.as_deref()));
let mut platform_window = cx.platform.open_window(
handle,
WindowParams {
bounds: window_bounds.get_bounds(),
titlebar,
kind,
is_movable,
app_owns_titlebar_drag,
is_resizable,
is_minimizable,
focus,
show,
display_id,
window_min_size,
app_id: app_id.clone(),
icon,
#[cfg(target_os = "macos")]
tabbing_identifier,
#[cfg(target_os = "macos")]
use_display_p3,
},
)?;
let tab_bar_visible = platform_window.tab_bar_visible();
SystemWindowTabController::init_visible(cx, tab_bar_visible);
if let Some(tabs) = platform_window.tabbed_windows() {
SystemWindowTabController::add_tab(cx, handle.window_id(), tabs);
}
let display_id = platform_window.display().map(|display| display.id());
let sprite_atlas = platform_window.sprite_atlas();
let mouse_position = platform_window.mouse_position();
let modifiers = platform_window.modifiers();
let capslock = platform_window.capslock();
let content_size = platform_window.content_size();
let scale_factor = platform_window.scale_factor();
let appearance = platform_window.appearance();
let text_system = Rc::new(WindowTextSystem::new(cx.text_system().clone()));
let invalidator = WindowInvalidator::new(handle.window_id());
let active = Rc::new(Cell::new(platform_window.is_active()));
let visibility = platform_window.visibility();
#[cfg(feature = "profiler")]
profiler::journal::record_window_visibility(handle.window_id(), visibility);
let hovered = Rc::new(Cell::new(platform_window.is_hovered()));
let needs_present = Rc::new(Cell::new(false));
let scene_animation_interval = Rc::new(Cell::new(None::<Duration>));
let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
let next_frame_wanted: Rc<Cell<bool>> = Default::default();
let input_rate_tracker = Rc::new(RefCell::new(InputRateTracker::default()));
platform_window
.request_decorations(window_decorations.unwrap_or(WindowDecorations::Server));
platform_window.set_background_appearance(window_background);
match window_bounds {
WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
WindowBounds::Maximized(_) => platform_window.zoom(),
WindowBounds::Windowed(_) => {}
}
let accessibility_force_disabled = cx.accessibility_force_disabled;
let a11y_active_flag = Arc::new(AtomicBool::new(false));
#[cfg(not(target_family = "wasm"))]
if !accessibility_force_disabled {
let mut initial_root_node = accesskit::Node::new(accesskit::Role::Window);
if let Some(title) = &initial_window_title {
initial_root_node.set_label(title.to_string());
}
let initial_tree = accesskit::TreeUpdate {
nodes: vec![(ROOT_NODE_ID, initial_root_node)],
tree: Some(accesskit::Tree::new(ROOT_NODE_ID)),
tree_id: accesskit::TreeId::ROOT,
focus: ROOT_NODE_ID,
};
let (activation_sender, activation_receiver) = async_channel::unbounded::<()>();
let (deactivation_sender, deactivation_receiver) = async_channel::unbounded::<()>();
let (action_sender, action_receiver) =
async_channel::unbounded::<accesskit::ActionRequest>();
platform_window.a11y_init(crate::A11yCallbacks {
activation: {
let active_flag = a11y_active_flag.clone();
Box::new(move || {
log::info!("Accessibility activated");
active_flag.store(true, SeqCst);
activation_sender
.send_blocking(())
.with_context(|| {
format!(
"queuing accessibility activation for window {:?}",
handle.window_id()
)
})
.log_err();
Some(initial_tree.clone())
})
},
action: Box::new(move |request| {
action_sender
.send_blocking(request)
.with_context(|| {
format!(
"queuing accessibility action for window {:?}",
handle.window_id()
)
})
.log_err();
}),
deactivation: {
let active_flag = a11y_active_flag.clone();
Box::new(move || {
log::info!("Accessibility deactivated");
active_flag.store(false, SeqCst);
deactivation_sender
.send_blocking(())
.with_context(|| {
format!(
"queuing accessibility deactivation for window {:?}",
handle.window_id()
)
})
.log_err();
})
},
});
// A11y can be activated at any time, and so we cannot compute a
// correct `TreeUpdate` on-demand. When this happens, we return a
// default empty `TreeUpdate`.
//
// So we force a new frame, which will then send a correct `TreeUpdate`.
let mut async_cx = cx.to_async();
cx.foreground_executor()
.spawn(async move {
while activation_receiver.recv().await.is_ok() {
handle
.update(&mut async_cx, |_, window, _| window.refresh())
.with_context(|| {
format!(
"handling accessibility activation for window {:?}",
handle.window_id()
)
})
.log_err();
}
})
.detach();
let mut async_cx = cx.to_async();
cx.foreground_executor()
.spawn(async move {
while deactivation_receiver.recv().await.is_ok() {
handle
.update(&mut async_cx, |_, window, _| window.refresh())
.with_context(|| {
format!(
"handling accessibility deactivation for window {:?}",
handle.window_id()
)
})
.log_err();
}
})
.detach();
let mut async_cx = cx.to_async();
cx.foreground_executor()
.spawn(async move {
while let Ok(request) = action_receiver.recv().await {
handle
.update(&mut async_cx, |_, window, cx| {
window.handle_a11y_action(request, cx);
})
.with_context(|| {
format!(
"handling accessibility action for window {:?}",
handle.window_id()
)
})
.log_err();
}
})
.detach();
}
platform_window.on_close(Box::new({
let window_id = handle.window_id();
let cx = cx.to_async();
move || {
// Native destruction can re-enter while the app is borrowed.
// Schedule both operations without borrowing the app here.
cx.spawn(async move |cx| {
cx.update(|cx| {
// App-driven closure may already have removed the window.
if cx.windows.contains_key(window_id) {
handle
.update(cx, |_, window, _| window.remove_window())
.with_context(|| format!("handling close for window {window_id:?}"))
.log_err();
}
SystemWindowTabController::remove_tab(cx, window_id);
});
})
.detach();
}
}));
platform_window.on_request_frame(Box::new({
let mut cx = cx.to_async();
let invalidator = invalidator.clone();
let active = active.clone();
let needs_present = needs_present.clone();
let scene_animation_interval = scene_animation_interval.clone();
let next_frame_callbacks = next_frame_callbacks.clone();
let next_frame_wanted = next_frame_wanted.clone();
let input_rate_tracker = input_rate_tracker.clone();
let mut deferred_force_render = false;
let mut frame_pacer = FramePacer::default();
move |request_frame_options| {
#[cfg(feature = "profiler")]
let (_foreground_turn, window_id) = {
let foreground_turn = profiler::journal::foreground_turn();
let window_id = handle.window_id();
profiler::journal::record_platform_signal(profiler::journal::PlatformSignal {
window_id,
signal_at: request_frame_options.signal_at,
handled_at: Instant::now(),
source: request_frame_options.signal_source,
});
(foreground_turn, window_id)
};
// This must be checked before accessing App: if this request
// arrived re-entrantly while a draw is on this thread's stack
// (e.g. via a nested message pump in the Windows window
// procedure), drawing would nest draws, and even touching the
// App would panic on its already-mutable borrow. Skip instead;
// the platform leaves the window invalidated (or re-invalidates
// it), so a fresh request arrives once the in-progress draw
// unwinds. Remember force_render so the deferred frame still
// bypasses the view cache.
//
// Returning here skips `complete_frame`, which on Wayland would
// stall the window's frame callbacks (no `surface.commit()`) —
// but calling it would hit the App borrow panic above, and this
// branch is unreachable there in practice: only Windows pumps
// platform events (and thus requests frames) mid-draw.
if draw_in_progress() {
log::debug!("deferring re-entrant window draw request");
deferred_force_render |= request_frame_options.force_render;
#[cfg(feature = "profiler")]
profiler::journal::record_reentrant_frame_skipped(window_id, Instant::now());
return;
}
// Take the deferred flag first: `||` short-circuits, and leaving
// the flag set when this request already forces a render would
// force a second, redundant render on the next frame.
let force_render =
mem::take(&mut deferred_force_render) || request_frame_options.force_render;
let power_state = handle
.update(&mut cx, |_, _, cx| (cx.thermal_state(), cx.power_mode()))
.with_context(|| {
format!(
"reading power state for frame request for window {:?}",
handle.window_id()
)
})
.log_err();
// Keep presenting briefly after high-rate input to prevent display
// underclocking, but subject to the same power limits as redraws.
let high_rate_input = input_rate_tracker.borrow_mut().is_high_rate();
// vue-native: only macOS ProMotion underclocks an idle layer. On
// Windows a present re-renders the whole unchanged scene, so the
// sustain would cost a full GPU frame per refresh for a second.
let present_for_high_rate_input = cfg!(target_os = "macos") && high_rate_input;
let has_next_frame_callbacks = !next_frame_callbacks.borrow().is_empty();
// vue-native fork: demand that asks the platform for a frame.
// Passive next-frame callbacks (`Window::on_next_frame_passive`)
// are paced like any other frame work but never wake the frame
// source on their own.
let wants_frame_besides_animation = invalidator.is_dirty()
|| force_render
|| next_frame_wanted.get()
|| request_frame_options.require_presentation
|| needs_present.get()
|| present_for_high_rate_input;
let has_demand_besides_animation =
wants_frame_besides_animation || has_next_frame_callbacks;
let wants_frame =
wants_frame_besides_animation || scene_animation_interval.get().is_some();
let has_frame_demand = wants_frame || has_next_frame_callbacks;
let should_throttle = !request_frame_options.require_presentation;
let inactive_without_high_rate_input =
should_throttle && !active.get() && !high_rate_input;
let (thermal_state, power_mode) =
power_state.unwrap_or((ThermalState::Nominal, crate::PowerMode::Unknown));
let min_frame_interval = minimum_frame_interval(
should_throttle,
inactive_without_high_rate_input,
inactive_frame_interval,
low_power_frame_interval,
thermal_frame_interval,
thermal_state,
power_mode,
);
let animation_frame_interval = scene_animation_interval
.get()
.filter(|interval| !has_demand_besides_animation && !interval.is_zero());
let min_frame_interval = min_frame_interval.max(animation_frame_interval);
let now = Instant::now();
// Idle display-link ticks must neither consume a frame slot nor
// wake a demand-driven frame source.
if has_frame_demand && frame_pacer.should_defer(now, min_frame_interval) {
// Don't lose a pending forced render to throttling.
deferred_force_render |= force_render;
// Passive callbacks alone wait for the next delivered frame.
if wants_frame {
// Deferred by throttling: ask demand-driven platforms to retry.
handle
.update(&mut cx, |_, window, _| {
window.platform_window.schedule_frame();
})
.with_context(|| {
format!(
"rescheduling throttled frame for window {:?}",
handle.window_id()
)
})
.log_err();
// The demand is still unserved; platforms that stop
// requesting frames for idle windows need a wakeup to retry.
invalidator.wake_platform();
}
#[cfg(feature = "profiler")]
profiler::journal::record_frame_skipped(
window_id,
Instant::now(),
if animation_frame_interval.is_some()
&& animation_frame_interval == min_frame_interval
{
profiler::journal::FrameSkipReason::AnimationFrameRateLimit
} else if inactive_without_high_rate_input
&& inactive_frame_interval == min_frame_interval
{
profiler::journal::FrameSkipReason::InactiveFrameRateLimit
} else if power_mode == crate::PowerMode::LowPower
&& low_power_frame_interval == min_frame_interval
{
profiler::journal::FrameSkipReason::LowPowerFrameRateLimit
} else {
profiler::journal::FrameSkipReason::ThermalFrameRateLimit
},
);
report_frame(handle.window_id(), now, FrameOutcome::Throttled);
return;
}
if !next_frame_callbacks.borrow().is_empty() {
handle
.update(&mut cx, |_, window, cx| {
// A native frame request can re-enter while App is borrowed.
// Keep the callbacks queued if updating the window fails,
// or a self-rescheduling frame pump would be lost forever.
window.next_frame_wanted.set(false);
for callback in next_frame_callbacks.take() {
callback(window, cx);
}
})
.with_context(|| {
format!(
"running next-frame callbacks for window {:?}",
handle.window_id()
)
})
.log_err();
}
let should_draw = invalidator.is_dirty() || force_render;
let needs_present = request_frame_options.require_presentation
|| needs_present.get()
|| scene_animation_interval.get().is_some()
|| present_for_high_rate_input;
if should_draw {
measure("frame duration", || {
handle
.update(&mut cx, |_, window, cx| {
#[cfg(feature = "profiler")]
window
.window_profiler
.record_frame_signal(request_frame_options.signal_at);
if force_render {
// Bypass cached view reuse so we don't replay stale
// atlas tile references after a GPU device recovery.
window.refresh();
}
let arena_clear_needed = window.draw(cx);
window.advance_scene_animations(cx);
window.present();
arena_clear_needed.clear(cx);
})
.with_context(|| {
format!(
"drawing and presenting frame for window {:?}",
handle.window_id()
)
})
.log_err();
})
} else if needs_present {
handle
.update(&mut cx, |_, window, cx| {
window.advance_scene_animations(cx);
window.present();
})
.with_context(|| {
format!("presenting frame for window {:?}", handle.window_id())
})
.log_err();
}
handle
.update(&mut cx, |_, window, _| {
if window.invalidator.is_dirty()
|| window.next_frame_wanted.get()
|| window.scene_animation_interval.get().is_some()
{
window.platform_window.schedule_frame();
}
})
.with_context(|| {
format!(
"scheduling follow-up frame for window {:?}",
handle.window_id()
)
})
.log_err();
// Platforms that stop requesting frames for idle windows only
// deliver another request after a wakeup. If demand remains
// after this frame (the window was re-invalidated mid-draw, or
// animations scheduled next-frame callbacks), re-arm the frame
// source explicitly. Passive callbacks are not demand.
if invalidator.is_dirty()
|| next_frame_wanted.get()
|| scene_animation_interval.get().is_some()
{
invalidator.wake_platform();
}
#[cfg(feature = "profiler")]
if !should_draw {
profiler::journal::record_frame_skipped(
window_id,
Instant::now(),
profiler::journal::FrameSkipReason::NoRenderNeeded,
);
}
if should_draw {
report_frame(handle.window_id(), now, FrameOutcome::Drew);
} else if has_next_frame_callbacks || needs_present {
report_frame(handle.window_id(), now, FrameOutcome::NoDraw);
}
}
}));
invalidator.set_platform_waker(platform_window.frame_waker());
platform_window.on_visual_viewport_changed(Box::new({
let mut cx = cx.to_async();
move || {
handle
.update(&mut cx, |_, window, _| window.refresh())
.with_context(|| {
format!(
"handling visual viewport change for window {:?}",
handle.window_id()
)
})
.log_err();
}
}));
platform_window.on_insets_changed(Box::new({
let mut cx = cx.to_async();
move |_| {
handle
.update(&mut cx, |_, window, _| window.refresh())
.with_context(|| {
format!("handling insets change for window {:?}", handle.window_id())
})
.log_err();
}
}));
platform_window.on_resize(Box::new({
let mut cx = cx.to_async();
move |_, _| {
handle
.update(&mut cx, |_, window, cx| window.bounds_changed(cx))
.with_context(|| format!("handling resize for window {:?}", handle.window_id()))
.log_err();
}
}));
platform_window.on_moved(Box::new({
let mut cx = cx.to_async();
move || {
handle
.update(&mut cx, |_, window, cx| window.bounds_changed(cx))
.with_context(|| format!("handling move for window {:?}", handle.window_id()))
.log_err();
}
}));
platform_window.on_display_changed(Box::new({
let cx = cx.to_async();
move || cx.update(|cx| Window::display_changed(handle, cx))
}));
platform_window.on_appearance_changed(Box::new({
let cx = cx.to_async();
let foreground_executor = cx.foreground_executor().clone();
move || {
let mut cx = cx.clone();
// Defer the update because changing the AppKit appearance may
// synchronously invoke this callback while App is already borrowed.
foreground_executor
.spawn(async move {
handle
.update(&mut cx, |_, window, cx| window.appearance_changed(cx))
.with_context(|| {
format!(
"handling appearance change for window {:?}",
handle.window_id()
)
})
.log_err();
})
.detach();
}
}));
platform_window.on_button_layout_changed(Box::new({
let mut cx = cx.to_async();
move || {
handle
.update(&mut cx, |_, window, cx| window.button_layout_changed(cx))
.with_context(|| {
format!(
"handling button layout change for window {:?}",
handle.window_id()
)
})
.log_err();
}
}));
platform_window.on_active_status_change(Box::new({
let mut cx = cx.to_async();
move |active| {
handle
.update(&mut cx, |_, window, cx| {
// vue-native fork: an assumed-active window keeps
// reading as active whatever the OS says
// (`Window::set_assume_active`).
if window.assume_active {
return;
}
window.active.set(active);
window.modifiers = window.platform_window.modifiers();
window.capslock = window.platform_window.capslock();
window
.activation_observers
.clone()
.retain(|callback| callback(window, cx));
window.bounds_changed(cx);
window.refresh();
SystemWindowTabController::update_last_active(cx, window.handle.id);
})
.with_context(|| {
format!(
"handling active status change for window {:?}",
handle.window_id()
)
})
.log_err();
}
}));
platform_window.on_visibility_change(Box::new({
let mut cx = cx.to_async();
move |_| {
handle
.update(&mut cx, |_, window, cx| {
window.refresh_visibility(cx);
})
.with_context(|| {
format!(
"handling visibility change for window {:?}",
handle.window_id()
)
})
.log_err();
}
}));
platform_window.on_hover_status_change(Box::new({
let mut cx = cx.to_async();
move |active| {
handle
.update(&mut cx, |_, window, cx| {
window.hovered.set(active);
let was_inside = std::mem::replace(&mut window.pointer_inside, active);
window
.vn_effect_pointer
.update(was_inside, active, false, cx);
window.refresh();
})
.with_context(|| {
format!(
"handling hover status change for window {:?}",
handle.window_id()
)
})
.log_err();
}
}));
platform_window.on_input({
let mut cx = cx.to_async();
Box::new(move |event| {
handle
.update(&mut cx, |_, window, cx| window.dispatch_event(event, cx))
.with_context(|| {
format!("dispatching input for window {:?}", handle.window_id())
})
.log_err()
.unwrap_or(DispatchEventResult::default())
})
});
platform_window.on_hit_test_window_control_at({
let mut cx = cx.to_async();
Box::new(move |position| {
handle
.update(&mut cx, |_, window, _cx| {
// WM_NCHITTEST precedes the next mouse-move and can run
// after a cached repaint. The previous input's hit set
// may name another point/frame, or be narrowed to a DOM
// event path; it is not a native caption hit test.
let position = position.unwrap_or_else(|| window.platform_window.mouse_position());
window.window_control_area_at(position)
})
.with_context(|| {
format!(
"hit-testing window controls for window {:?}",
handle.window_id()
)
})
.log_err()
.unwrap_or(None)
})
});
platform_window.on_move_tab_to_new_window({
let mut cx = cx.to_async();
Box::new(move || {
handle
.update(&mut cx, |_, _window, cx| {
SystemWindowTabController::move_tab_to_new_window(cx, handle.window_id());
})
.with_context(|| {
format!(
"moving tab to new window from window {:?}",
handle.window_id()
)
})
.log_err();
})
});
platform_window.on_merge_all_windows({
let mut cx = cx.to_async();
Box::new(move || {
handle
.update(&mut cx, |_, _window, cx| {
SystemWindowTabController::merge_all_windows(cx, handle.window_id());
})
.with_context(|| {
format!("merging all windows into window {:?}", handle.window_id())
})
.log_err();
})
});
platform_window.on_select_next_tab({
let mut cx = cx.to_async();
Box::new(move || {
handle
.update(&mut cx, |_, _window, cx| {
SystemWindowTabController::select_next_tab(cx, handle.window_id());
})
.with_context(|| {
format!("selecting next tab for window {:?}", handle.window_id())
})
.log_err();
})
});
platform_window.on_select_previous_tab({
let mut cx = cx.to_async();
Box::new(move || {
handle
.update(&mut cx, |_, _window, cx| {
SystemWindowTabController::select_previous_tab(cx, handle.window_id())
})
.with_context(|| {
format!("selecting previous tab for window {:?}", handle.window_id())
})
.log_err();
})
});
platform_window.on_toggle_tab_bar({
let mut cx = cx.to_async();
Box::new(move || {
handle
.update(&mut cx, |_, window, cx| {
let tab_bar_visible = window.platform_window.tab_bar_visible();
SystemWindowTabController::set_visible(cx, tab_bar_visible);
})
.with_context(|| {
format!("toggling tab bar for window {:?}", handle.window_id())
})
.log_err();
})
});
if let Some(app_id) = app_id {
platform_window.set_app_id(&app_id);
}
platform_window.map_window().unwrap();
Ok(Window {
handle,
invalidator,
removed: false,
platform_window,
display_id,
display_observers: SingleSubscriberSet::new(),
is_resizable,
is_minimizable,
last_window_bounds: window_bounds,
sprite_atlas,
text_system,
text_rendering_mode: cx.text_rendering_mode.clone(),
rem_size: px(16.),
rem_size_override_stack: SmallVec::new(),
viewport_size: content_size,
layout_engine: Some(TaffyLayoutEngine::new()),
root: None,
element_id_stack: ElementIdStack::default(),
text_style_stack: Vec::new(),
rendered_entity_stack: Vec::new(),
element_offset_stack: Vec::new(),
content_mask_stack: Vec::new(),
vn_clip_stack: None,
vn_capture_records: FxHashMap::default(),
element_opacity: 1.0,
element_image_tint: Hsla::transparent_black(),
element_transform: TransformationMatrix::unit(),
vn_hitbox_tag: 0,
vn_tag_fresh: false,
vn_tag_transform: None,
vn_tag_every_hitbox: false,
vn_pick_every_box: false,
vn_hit_refiner: None,
input_interceptor: None,
vn_key_event_seq: 0,
vn_pointer_lock: None,
vn_raw_mouse_position: None,
vn_mouse_movement: Point::default(),
requested_autoscroll: None,
last_text_input_configuration: None,
focused_text_input: None,
rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
next_frame_callbacks,
next_frame_wanted,
next_hitbox_id: HitboxId(0),
next_tooltip_id: TooltipId::default(),
tooltip_bounds: None,
dirty_views: FxHashSet::default(),
focus_listeners: SingleSubscriberSet::new(),
focus_lost_listeners: SingleSubscriberSet::new(),
focus_lost_path: SmallVec::new(),
default_prevented: true,
mouse_position,
mouse_hit_test: HitTest::default(),
modifiers,
capslock,
scale_factor,
bounds_observers: SingleSubscriberSet::new(),
appearance,
appearance_observers: SingleSubscriberSet::new(),
button_layout_observers: SingleSubscriberSet::new(),
active,
assume_active: false,
visibility,
visibility_observers: SingleSubscriberSet::new(),
vn_effect_pointer: VnEffectPointer::new(hovered.get()),
vn_effect_element: 0,
vn_effect_phases: FxHashMap::default(),
vn_defer_scope: None,
vn_scopes_painted: FxHashSet::default(),
pointer_inside: hovered.get(),
hovered,
needs_present,
scene_animation_interval,
input_rate_tracker,
#[cfg(feature = "profiler")]
window_profiler: profiler::WindowProfiler::new(handle.window_id())?,
last_input_modality: InputModality::Mouse,
touch_gestures: TouchGestureRecognizer::new(
cx.platform
.gestures()
.map_or_else(GestureTuning::default, |gestures| gestures.tuning()),
),
touch_prediction_enabled: true,
long_press_timer: None,
long_press_capture: None,
refreshing: false,
activation_observers: SingleSubscriberSet::new(),
focus: None,
focus_enabled: true,
focus_generation: 0,
pending_input: None,
pending_modifier: ModifierState::default(),
pending_input_observers: SingleSubscriberSet::new(),
prompt: None,
client_inset: None,
image_cache_stack: Vec::new(),
captured_hitbox: None,
#[cfg(any(feature = "inspector", debug_assertions))]
inspector: None,
#[cfg(feature = "profiler")]
debug_frame_overlay: crate::debug_overlay::DebugFrameOverlay::new(),
a11y: A11y::new(
a11y_active_flag,
accessibility_force_disabled,
initial_window_title,
),
})
}
pub(crate) fn new_focus_listener(
&self,
value: AnyWindowFocusListener,
) -> (Subscription, impl FnOnce() + use<>) {
self.focus_listeners.insert_pending(value)
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[expect(missing_docs)]
pub struct DispatchEventResult {
pub propagate: bool,
pub default_prevented: bool,
}
/// Indicates which region of the window is visible. Content falling outside of this mask will not be
/// rendered.
///
/// vue-native fork: the mask is a ROUNDED rect. All-zero `corner_radii` is the plain rectangle gpui
/// always had, and costs each fragment shader one uniform branch. With radii, every primitive's
/// fragment shader multiplies its coverage by the rounded rect's antialiased SDF
/// (`content_mask_coverage` in each backend), on top of the hardware clip to `bounds`. CSS
/// `overflow` under a `border-radius` is what pushes one ([`crate::Style::overflow_mask`]).
/// [`ContentMask::intersect`] says what nesting two masks keeps exact.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
#[repr(C)]
pub struct ContentMask<P: Clone + Debug + Default + PartialEq> {
/// The bounds
pub bounds: Bounds<P>,
/// vue-native fork: each corner's radius, zero for a square corner. Every
/// primitive carries it right after `bounds`, so the shaders' structs do too.
pub corner_radii: Corners<P>,
/// vue-native fork: CSS `corner-shape`, after `corner_radii` in every primitive. A shaped
/// corner's radius is the outer one of the border its insets describe.
pub corner_shapes: CornerShapes,
}
impl<P: Clone + Debug + Default + PartialEq> ContentMask<P> {
/// vue-native fork: a plain rectangular mask.
pub fn rect(bounds: Bounds<P>) -> Self {
ContentMask {
bounds,
corner_radii: Corners::default(),
corner_shapes: CornerShapes::default(),
}
}
/// vue-native fork: whether any corner is rounded.
pub fn is_rounded(&self) -> bool {
self.corner_radii != Corners::default()
}
}
impl ContentMask<Pixels> {
/// Scale the content mask's pixel units by the given scaling factor.
pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
ContentMask {
bounds: self.bounds.scale(factor),
corner_radii: self.corner_radii.scale(factor),
corner_shapes: self.corner_shapes.scale(factor),
}
}
}
impl<P> ContentMask<P>
where
P: Copy
+ Ord
+ Debug
+ Default
+ Add<P, Output = P>
+ Sub<P, Output = P>
+ Div<f32, Output = P>
+ Into<f64>,
{
/// Intersect the content mask with the given content mask.
///
/// vue-native fork, the rounded corners:
/// - Two rectangles intersect exactly, as before.
/// - A corner of the result that is also a corner of one of the masks keeps
/// that mask's radius. When both masks have a corner there, the larger
/// radius wins. Two corners at one point nest, so the larger radius is the
/// smaller region, and that is exact.
/// - Any other corner of the result is square. That is exact when the
/// rounded mask's curve does not reach it: a rect clip inside the curve's
/// span, or a scroller inset from its rounded card. Where a rect clip cuts
/// through a curve, the cut corner comes out square and shows the sliver
/// the curve would have hidden. That is the one approximation; the common
/// case, one rounded ancestor around rect clips that fill it or sit
/// inside it, is exact.
pub fn intersect(&self, other: &Self) -> Self {
let bounds = self.bounds.intersect(&other.bounds);
if !self.is_rounded() && !other.is_rounded() {
return ContentMask::rect(bounds);
}
let at = |mask: &Self, left: bool, top: bool| {
let x = if left { mask.bounds.left() } else { mask.bounds.right() };
let y = if top { mask.bounds.top() } else { mask.bounds.bottom() };
(x, y)
};
let radius = |left: bool, top: bool, mine: (P, u32), theirs: (P, u32)| {
let here = at(&ContentMask::rect(bounds), left, top);
let mine = if at(self, left, top) == here { mine } else { (P::default(), 0) };
let theirs = if at(other, left, top) == here { theirs } else { (P::default(), 0) };
if theirs.0 > mine.0 { theirs } else { mine }
};
let (a, b) = (&self.corner_radii, &other.corner_radii);
let (sa, sb) = (self.corner_shapes.corners(), other.corner_shapes.corners());
let top_left = radius(true, true, (a.top_left, sa.top_left), (b.top_left, sb.top_left));
let top_right = radius(false, true, (a.top_right, sa.top_right), (b.top_right, sb.top_right));
let bottom_right = radius(
false,
false,
(a.bottom_right, sa.bottom_right),
(b.bottom_right, sb.bottom_right),
);
let bottom_left =
radius(true, false, (a.bottom_left, sa.bottom_left), (b.bottom_left, sb.bottom_left));
let corner_radii = Corners {
top_left: top_left.0,
top_right: top_right.0,
bottom_right: bottom_right.0,
bottom_left: bottom_left.0,
}
.clamp_radii_for_quad_size(bounds.size);
ContentMask {
bounds,
corner_radii,
corner_shapes: CornerShapes {
top_left: top_left.1,
top_right: top_right.1,
bottom_right: bottom_right.1,
bottom_left: bottom_left.1,
},
}
}
/// vue-native fork: whether `point` is inside the mask, its rounded
/// corners included. The hit test asks this, so a click outside a rounded
/// clip's curve does not reach what the clip hides.
pub fn contains(&self, point: &Point<P>) -> bool {
if !self.bounds.contains(point) {
return false;
}
if !self.is_rounded() {
return true;
}
if !self.corner_shapes.is_round() {
return crate::corner_shape::shaped_rect_sdf(
*point,
&self.bounds,
&self.corner_radii,
&self.corner_shapes,
) <= 0.;
}
let b = &self.bounds;
let r = &self.corner_radii;
for (radius, cx, cy, left, top) in [
(r.top_left, b.left() + r.top_left, b.top() + r.top_left, true, true),
(r.top_right, b.right() - r.top_right, b.top() + r.top_right, false, true),
(r.bottom_right, b.right() - r.bottom_right, b.bottom() - r.bottom_right, false, false),
(r.bottom_left, b.left() + r.bottom_left, b.bottom() - r.bottom_left, true, false),
] {
let in_x = if left { point.x < cx } else { point.x > cx };
let in_y = if top { point.y < cy } else { point.y > cy };
if radius > P::default() && in_x && in_y {
let (dx, dy): (f64, f64) = ((point.x - cx).into(), (point.y - cy).into());
let radius: f64 = radius.into();
return dx * dx + dy * dy <= radius * radius;
}
}
true
}
}
impl Window {
fn mark_view_dirty(&mut self, view_id: EntityId) {
// Mark ancestor views as dirty. If already in the `dirty_views` set, then all its ancestors
// should already be dirty.
for view_id in self
.rendered_frame
.dispatch_tree
.view_path_reversed(view_id)
{
if !self.dirty_views.insert(view_id) {
break;
}
}
}
pub(crate) fn refresh_visibility(&mut self, cx: &mut App) {
let visibility = self.platform_window.visibility();
if self.visibility != visibility {
self.visibility = visibility;
#[cfg(feature = "profiler")]
profiler::journal::record_window_visibility(self.handle.window_id(), visibility);
self.visibility_observers
.clone()
.retain(|callback| callback(visibility, self, cx));
}
#[cfg(feature = "profiler")]
if self.invalidator.is_dirty() || self.needs_present.get() {
profiler::journal::record_frame_pending(self.handle.window_id(), Instant::now());
}
}
/// This window's part of [`App::debug_state`].
///
/// Values GPUI caches are reported next to what the platform reports now,
/// so a stale cache shows up as a mismatch.
pub(crate) fn debug_state(&self) -> serde_json::Value {
let platform_window = &self.platform_window;
serde_json::json!({
"id": self.handle.window_id().as_u64(),
"title": platform_window.get_title(),
"bounds": platform_window.bounds(),
"window_bounds": format!("{:?}", platform_window.window_bounds()),
"content_size": platform_window.content_size(),
"viewport_size": self.viewport_size,
"scale_factor": {
"cached": self.scale_factor,
"platform": platform_window.scale_factor(),
},
"display_id": {
"cached": self.display_id.map(u64::from),
"platform": platform_window.display().map(|display| u64::from(display.id())),
},
"active": {
"cached": self.active.get(),
"platform": platform_window.is_active(),
},
"hovered": {
"cached": self.hovered.get(),
"platform": platform_window.is_hovered(),
},
"visibility": {
"cached": format!("{:?}", self.visibility),
"platform": format!("{:?}", platform_window.visibility()),
},
"appearance": {
"cached": format!("{:?}", self.appearance),
"platform": format!("{:?}", platform_window.appearance()),
},
"is_fullscreen": platform_window.is_fullscreen(),
"is_maximized": platform_window.is_maximized(),
"mouse_position": {
"cached": self.mouse_position,
"platform": platform_window.mouse_position(),
},
"modifiers": {
"cached": self.modifiers,
"platform": platform_window.modifiers(),
},
"cursor_style": self.rendered_frame.cursor_style(self),
"frame": {
"dirty": self.invalidator.is_dirty(),
"needs_present": self.needs_present.get(),
"refreshing": self.refreshing,
"next_frame_callbacks": self.next_frame_callbacks.borrow().len(),
},
"gpu": platform_window.gpu_specs(),
"platform": platform_window.debug_state(),
})
}
/// Whether the platform is presenting this window's frames (see
/// [`WindowVisibility`]).
pub fn visibility(&self) -> WindowVisibility {
self.visibility
}
/// Whether frames drawn for this window will be shown.
///
/// This is not the window's shown/hidden state: a shown window that is
/// fully behind another window, minimized, or on a sleeping display is not
/// visible here.
pub fn is_visible(&self) -> bool {
self.visibility.is_visible()
}
/// Registers a callback to be invoked when the window's visibility changes.
pub fn observe_window_visibility(
&self,
mut callback: impl FnMut(WindowVisibility, &mut Window, &mut App) + 'static,
) -> Subscription {
self.visibility_observers
.insert(Box::new(move |visibility, window, cx| {
callback(visibility, window, cx);
true
}))
}
/// Registers a callback to be invoked when the window is activated or
/// deactivated, without an entity to update (vue-native fork).
pub fn observe_window_activation(
&self,
mut callback: impl FnMut(&mut Window, &mut App) + 'static,
) -> Subscription {
self.activation_observers
.insert(Box::new(move |window, cx| {
callback(window, cx);
true
}))
}
/// Registers a callback to be invoked when the window appearance changes.
pub fn observe_window_appearance(
&self,
mut callback: impl FnMut(&mut Window, &mut App) + 'static,
) -> Subscription {
self.appearance_observers
.insert(Box::new(move |window, cx| {
callback(window, cx);
true
}))
}
/// Registers a callback to be invoked when the window button layout changes.
pub fn observe_button_layout_changed(
&self,
mut callback: impl FnMut(&mut Window, &mut App) + 'static,
) -> Subscription {
self.button_layout_observers
.insert(Box::new(move |window, cx| {
callback(window, cx);
true
}))
}
/// Replaces the root entity of the window with a new one.
pub fn replace_root<E>(
&mut self,
cx: &mut App,
build_view: impl FnOnce(&mut Window, &mut Context<E>) -> E,
) -> Entity<E>
where
E: 'static + Render,
{
let view = cx.new(|cx| build_view(self, cx));
self.root = Some(view.clone().into());
self.refresh();
view
}
/// Returns the root entity of the window, if it has one.
pub fn root<E>(&self) -> Option<Option<Entity<E>>>
where
E: 'static + Render,
{
self.root
.as_ref()
.map(|view| view.clone().downcast::<E>().ok())
}
/// Obtain a handle to the window that belongs to this context.
pub fn window_handle(&self) -> AnyWindowHandle {
self.handle
}
/// Mark the window as dirty, scheduling it to be redrawn on the next frame.
pub fn refresh(&mut self) {
if self.invalidator.not_drawing() {
self.refreshing = true;
self.invalidator.set_dirty(true);
}
}
/// Close this window.
pub fn remove_window(&mut self) {
self.removed = true;
}
/// Obtain the currently focused [`FocusHandle`]. If no elements are focused, returns `None`.
pub fn focused(&self, cx: &App) -> Option<FocusHandle> {
self.focus
.and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
}
/// While focus-lost listeners are being dispatched, returns the closest ancestor of the
/// previously focused element that can still receive focus, making it a suitable target
/// for focus restoration. Returns `None` at all other times, or when no such ancestor exists.
pub fn focus_lost_restore_target(&self, cx: &App) -> Option<FocusHandle> {
let (_leaf, ancestors) = self.focus_lost_path.split_last()?;
ancestors.iter().rev().find_map(|id| {
self.rendered_frame.dispatch_tree.focusable_node_id(*id)?;
FocusHandle::for_id(*id, &cx.focus_handles)
})
}
/// Move focus to the element associated with the given [`FocusHandle`].
pub fn focus(&mut self, handle: &FocusHandle, cx: &mut App) {
if !self.focus_enabled || self.focus == Some(handle.id) {
return;
}
self.focus = Some(handle.id);
self.focus_generation = self.focus_generation.wrapping_add(1);
self.clear_pending_keystrokes(cx);
self.refresh();
}
/// Remove focus from all elements within this context's window.
pub fn blur(&mut self, cx: &mut App) {
self.clear_pending_keystrokes(cx);
if !self.focus_enabled {
return;
}
if self.focus.is_some() {
self.focus_generation = self.focus_generation.wrapping_add(1);
}
self.focus = None;
self.refresh();
}
/// Blur the window and don't allow anything in it to be focused again.
pub fn disable_focus(&mut self, cx: &mut App) {
self.blur(cx);
self.focus_enabled = false;
}
/// Move focus to next tab stop.
pub fn focus_next(&mut self, cx: &mut App) {
if !self.focus_enabled {
return;
}
if let Some(handle) = self.rendered_frame.tab_stops.next(self.focus.as_ref()) {
self.focus(&handle, cx)
}
}
/// Move focus to previous tab stop.
pub fn focus_prev(&mut self, cx: &mut App) {
if !self.focus_enabled {
return;
}
if let Some(handle) = self.rendered_frame.tab_stops.prev(self.focus.as_ref()) {
self.focus(&handle, cx)
}
}
/// Accessor for the text system.
pub fn text_system(&self) -> &Rc<WindowTextSystem> {
&self.text_system
}
/// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
pub fn text_style(&self) -> TextStyle {
let mut style = TextStyle::default();
for refinement in &self.text_style_stack {
style.refine(refinement);
}
style
}
/// Check if the platform window is maximized.
///
/// On some platforms (namely Windows) this is different than the bounds being the size of the display
pub fn is_maximized(&self) -> bool {
self.platform_window.is_maximized()
}
/// request a certain window decoration (Wayland)
pub fn request_decorations(&self, decorations: WindowDecorations) {
self.platform_window.request_decorations(decorations);
}
/// Set the exclusive zone for a layer-shell surface: how much screen space it
/// reserves so other surfaces avoid occluding it (e.g. a panel reserving space).
/// Positive values reserve that distance from the anchored edge, 0 lets the
/// surface be moved out of others' exclusive zones, and -1 ignores reserved
/// space and may extend under other surfaces. (Wayland layer-shell windows only)
pub fn set_exclusive_zone(&self, zone: Pixels) {
self.platform_window.set_exclusive_zone(zone);
}
/// Set which anchored edge a layer-shell surface's exclusive zone applies to.
/// This is only needed to disambiguate a corner-anchored surface; otherwise the
/// edge is deduced from the anchor. The edge must be a single edge the surface
/// is anchored to, or it is ignored. (Wayland layer-shell windows only)
#[cfg(all(target_os = "linux", feature = "wayland"))]
pub fn set_exclusive_edge(&self, edge: crate::layer_shell::Anchor) {
self.platform_window.set_exclusive_edge(edge);
}
/// Start an interactive window resize operation if this window is resizable.
pub fn start_window_resize(&self, edge: ResizeEdge) {
if self.is_resizable {
self.platform_window.start_window_resize(edge);
}
}
/// Linux (wayland) only: Set the window's input region, the area that receives pointer
/// and touch input. Events outside it pass through to whatever is below the window.
///
/// - `Some(rects)` restricts input to the union of `rects`, in window coordinates.
/// - `Some(&[])` is an empty region, so the window receives no pointer or touch input.
/// - `None` resets the region to the default, so the whole window receives input again.
pub fn set_input_region(&self, region: Option<&[Bounds<Pixels>]>) {
self.platform_window.set_input_region(region);
}
/// Return the `WindowBounds` to indicate that how a window should be opened
/// after it has been closed
pub fn window_bounds(&self) -> WindowBounds {
self.platform_window.window_bounds()
}
pub(crate) fn last_window_bounds(&self) -> WindowBounds {
self.last_window_bounds
}
pub(crate) fn display_id(&self) -> Option<DisplayId> {
self.display_id
}
/// Return the `WindowBounds` excluding insets (Wayland and X11)
pub fn inner_window_bounds(&self) -> WindowBounds {
self.platform_window.inner_window_bounds()
}
/// vue-native: Windows' composition device and the container visual drawn
/// UNDER this window's surface (see `PlatformWindow::vn_composition_underlay`):
/// owned COM pointers, released by the caller.
pub fn vn_composition_underlay(&self) -> Option<(usize, usize)> {
self.platform_window.vn_composition_underlay()
}
/// vue-native: maximizes or leaves the maximized state without toggling.
pub fn vn_set_maximized(&self, maximized: bool) {
self.platform_window.vn_set_maximized(maximized)
}
/// vue-native: the platform's own maximized (zoomed) state.
pub fn vn_is_zoomed(&self) -> bool {
self.platform_window.vn_is_zoomed()
}
/// vue-native: minimized, where the platform reports it.
pub fn vn_is_minimized(&self) -> bool {
self.platform_window.vn_is_minimized()
}
/// vue-native: leaves the minimized state.
pub fn vn_unminimize(&self) {
self.platform_window.vn_unminimize()
}
/// vue-native: hides the window without minimizing it; false where unsupported.
pub fn vn_hide(&self) -> bool {
self.platform_window.vn_hide()
}
/// vue-native: false while hidden by [`Self::vn_hide`] or not yet shown.
pub fn vn_is_shown(&self) -> bool {
self.platform_window.vn_is_shown()
}
/// vue-native: moves and/or resizes the outer frame, in the space of [`Self::bounds`];
/// false when the platform refuses part of it.
pub fn vn_set_frame(&self, origin: Option<Point<Pixels>>, size: Option<Size<Pixels>>) -> bool {
self.platform_window.vn_set_frame(origin, size)
}
/// vue-native: keeps the window above normal windows; false where unsupported.
pub fn vn_set_always_on_top(&self, on: bool) -> bool {
self.platform_window.vn_set_always_on_top(on)
}
/// vue-native: whether the platform's own maximize control is enabled.
pub fn vn_set_maximizable(&self, maximizable: bool) {
self.platform_window.vn_set_maximizable(maximizable)
}
/// vue-native: lets pointer input pass through; false where unsupported.
pub fn vn_set_ignore_mouse(&self, ignore: bool) -> bool {
self.platform_window.vn_set_ignore_mouse(ignore)
}
/// vue-native: keeps the contents out of screen capture; false where unsupported.
pub fn vn_set_content_protection(&self, on: bool) -> bool {
self.platform_window.vn_set_content_protection(on)
}
/// vue-native: closes as the platform's close button would; the should-close callback decides.
pub fn vn_request_close(&self) {
self.platform_window.vn_request_close()
}
/// Encode the window's native restorable state into an opaque blob.
/// Returns `None` on platforms without native state restoration or if encoding fails.
pub fn native_window_state(&self) -> Option<Vec<u8>> {
self.platform_window.native_window_state()
}
/// Restore the window's native state from a blob previously produced
/// by [`Window::native_window_state`]. A no-op on platforms without native state restoration.
pub fn restore_native_window_state(&self, state: &[u8]) {
self.platform_window.restore_native_window_state(state);
}
/// Dispatch the given action on the currently focused element.
pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
let focus_id = self.focused(cx).map(|handle| handle.id);
let window = self.handle;
cx.defer(move |cx| {
window
.update(cx, |_, window, cx| {
let node_id = window.focus_node_id_in_rendered_frame(focus_id);
window.dispatch_action_on_node(node_id, action.as_ref(), cx);
})
.with_context(|| format!("dispatching action for window {:?}", window.window_id()))
.log_err();
})
}
pub(crate) fn dispatch_keystroke_observers(
&mut self,
keystroke: &Keystroke,
input_preference: InputPreference,
action: Option<&dyn Action>,
context_stack: Vec<KeyContext>,
cx: &mut App,
) {
cx.keystroke_observers.clone().retain(move |callback| {
(callback)(
&KeystrokeEvent {
keystroke: keystroke.clone(),
input_preference,
action: action.map(|action| action.boxed_clone()),
context_stack: context_stack.clone(),
},
self,
cx,
)
});
}
pub(crate) fn dispatch_keystroke_interceptors(
&mut self,
keystroke: &Keystroke,
input_preference: InputPreference,
context_stack: Vec<KeyContext>,
cx: &mut App,
) {
cx.keystroke_interceptors.clone().retain(move |callback| {
(callback)(
&KeystrokeEvent {
keystroke: keystroke.clone(),
input_preference,
action: None,
context_stack: context_stack.clone(),
},
self,
cx,
)
});
}
/// Schedules the given function to be run at the end of the current effect cycle, allowing entities
/// that are currently on the stack to be returned to the app.
pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
let handle = self.handle;
cx.defer(move |cx| {
handle.update(cx, |_, window, cx| f(window, cx)).ok();
});
}
/// Subscribe to events emitted by a entity.
/// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
/// The callback will be invoked a handle to the emitting entity, the event, and a window context for the current window.
pub fn observe<T: 'static>(
&mut self,
observed: &Entity<T>,
cx: &mut App,
mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
) -> Subscription {
let entity_id = observed.entity_id();
let observed = observed.downgrade();
let window_handle = self.handle;
cx.new_observer(
entity_id,
Box::new(move |cx| {
window_handle
.update(cx, |_, window, cx| {
if let Some(handle) = observed.upgrade() {
on_notify(handle, window, cx);
true
} else {
false
}
})
.unwrap_or(false)
}),
)
}
/// Subscribe to events emitted by a entity.
/// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
/// The callback will be invoked a handle to the emitting entity, the event, and a window context for the current window.
pub fn subscribe<Emitter, Evt>(
&mut self,
entity: &Entity<Emitter>,
cx: &mut App,
mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
) -> Subscription
where
Emitter: EventEmitter<Evt>,
Evt: 'static,
{
let entity_id = entity.entity_id();
let handle = entity.downgrade();
let window_handle = self.handle;
cx.new_subscription(
entity_id,
(
TypeId::of::<Evt>(),
Box::new(move |event, cx| {
window_handle
.update(cx, |_, window, cx| {
if let Some(entity) = handle.upgrade() {
let event = event.downcast_ref().expect("invalid event type");
on_event(entity, event, window, cx);
true
} else {
false
}
})
.unwrap_or(false)
}),
),
)
}
/// Register a callback to be invoked when the given `Entity` is released.
pub fn observe_release<T>(
&self,
entity: &Entity<T>,
cx: &mut App,
on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
) -> Subscription
where
T: 'static,
{
let entity_id = entity.entity_id();
let window_handle = self.handle;
cx.release_listeners.insert(
entity_id,
Box::new(move |entity, cx| {
let entity = entity.downcast_mut().expect("invalid entity type");
let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
}),
)
}
/// Creates an [`AsyncWindowContext`], which has a static lifetime and can be held across
/// await points in async code.
pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
AsyncWindowContext::new_context(cx.to_async(), self.handle)
}
/// Schedule the given closure to be run directly after the current frame is rendered.
pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
self.next_frame_wanted.set(true);
self.platform_window.schedule_frame();
// Next-frame callbacks create frame demand without dirtying the
// window, so the platform's frame source must be woken explicitly.
self.invalidator.wake_platform();
}
/// vue-native fork: like [`Self::on_next_frame`], but rides along with the
/// next frame the platform delivers without asking for one. A frame source
/// that paces idle windows can then let a self-rescheduling pump wait for
/// real demand (input, an invalidation, an `on_next_frame`) or its own
/// deadline; one that delivers every refresh runs it on the next.
pub fn on_next_frame_passive(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
}
/// Schedule a frame to be drawn on the next animation frame.
///
/// This is useful for elements that need to animate continuously, such as a video player or an animated GIF.
/// It will cause the window to redraw on the next frame, even if no other changes have occurred.
///
/// If called from within a view, it will notify that view on the next frame. Otherwise, it will refresh the entire window.
///
/// Callers driving purely decorative animations (spinners, pulses, and the
/// like) should prefer [`AnimationExt::with_animation`](crate::AnimationExt::with_animation),
/// which automatically respects [`App::reduce_motion`]. When using this
/// method directly for decorative motion, check [`App::reduce_motion`]
/// and skip the frame request when it is set.
pub fn request_animation_frame(&self) {
let entity = self.current_view();
self.on_next_frame(move |_, cx| cx.notify(entity));
}
pub(crate) fn advance_scene_animations(&mut self, cx: &App) {
let elapsed = cx.background_executor().now() - cx.synced_animation_epoch;
self.rendered_frame.scene.advance_animations(elapsed);
}
/// Runs all callbacks scheduled via [`Self::on_next_frame`], returning how many ran.
///
/// Tests have no platform frame loop, so this simulates the delivery of the
/// next frame.
#[cfg(any(test, feature = "test-support"))]
pub fn simulate_next_frame(&mut self, cx: &mut App) -> usize {
let callbacks = self.next_frame_callbacks.take();
self.next_frame_wanted.set(false);
let count = callbacks.len();
for callback in callbacks {
callback(self, cx);
}
count
}
/// Spawn the future returned by the given closure on the application thread pool.
/// The closure is provided a handle to the current window and an `AsyncWindowContext` for
/// use within your future.
#[track_caller]
pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R>
where
R: 'static,
AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
{
let handle = self.handle;
cx.spawn(async move |app| {
let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
f(&mut async_window_cx).await
})
}
/// Spawn the future returned by the given closure on the application thread
/// pool, with the given priority. The closure is provided a handle to the
/// current window and an `AsyncWindowContext` for use within your future.
#[track_caller]
pub fn spawn_with_priority<AsyncFn, R>(
&self,
priority: Priority,
cx: &App,
f: AsyncFn,
) -> Task<R>
where
R: 'static,
AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
{
let handle = self.handle;
cx.spawn_with_priority(priority, async move |app| {
let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
f(&mut async_window_cx).await
})
}
/// Notify the window that its bounds have changed.
///
/// This updates internal state like `viewport_size` and `scale_factor` from
/// the platform window, then notifies observers. Normally called automatically
/// by the platform's resize callback, but exposed publicly for test infrastructure.
pub fn bounds_changed(&mut self, cx: &mut App) {
self.scale_factor = self.platform_window.scale_factor();
self.viewport_size = self.platform_window.content_size();
self.last_window_bounds = self.platform_window.window_bounds();
cx.sync_window_update_entry(self);
self.mouse_position = self.platform_window.mouse_position();
self.refresh();
self.bounds_observers
.clone()
.retain(|callback| callback(self, cx));
}
fn display_changed(handle: AnyWindowHandle, cx: &mut App) {
let moved_to = handle
.update(cx, |_, window, _| {
let display_id = window.platform_window.display().map(|display| display.id());
let moved = display_id != window.display_id;
window.display_id = display_id;
moved.then_some(display_id)
})
.with_context(|| {
format!(
"handling display change for window {:?}",
handle.window_id()
)
})
.log_err()
.flatten();
let Some(display_id) = moved_to else {
return;
};
// The platform's notifications about the window and about displays
// arrive in no guaranteed order, so make sure App knows the display
// before the window's observers read its state.
if let Some(display_id) = display_id
&& !cx.knows_display(display_id)
{
cx.displays_changed();
}
handle
.update(cx, |_, window, cx| window.notify_display_observers(cx))
.with_context(|| {
format!(
"notifying display observers for window {:?}",
handle.window_id()
)
})
.log_err();
}
pub(crate) fn notify_display_observers(&mut self, cx: &mut App) {
self.display_observers
.clone()
.retain(|callback| callback(self, cx));
}
/// The time between refreshes of the display the window is on, as of the
/// platform's last display change notification. Variable refresh rate
/// displays report their maximum rate. Returns `None` when the platform
/// doesn't report it.
pub fn refresh_interval(&self, cx: &App) -> Option<Duration> {
cx.display_refresh_interval(self.display_id?)
}
/// Registers a callback invoked when the window moves to another display
/// or its display's properties change, for example its refresh
/// interval. [`Self::refresh_interval`] already returns the new value
/// when the callback runs.
pub fn observe_window_display(
&self,
mut callback: impl FnMut(&mut Window, &mut App) + 'static,
) -> Subscription {
self.display_observers.insert(Box::new(move |window, cx| {
callback(window, cx);
true
}))
}
/// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays.
pub fn bounds(&self) -> Bounds<Pixels> {
self.platform_window.bounds()
}
/// Returns the regions of this window obscured by system UI and the keyboard.
pub fn insets(&self) -> WindowInsets {
self.platform_window.insets()
}
/// Renders the current frame's scene to a texture and returns the pixel data as an RGBA image.
/// This does not present the frame to screen - useful for visual testing where we want
/// to capture what would be rendered without displaying it or requiring the window to be visible.
//
// vue-native: upstream gates this on `test`/`test-support`. Our devtools
// screenshot command is a first-class *product* feature that an agent
// drives against a normal (non-test) build, and a headless readback of the
// render target is strictly better than `PrintWindow` for it — it is the
// client area exactly, needs no invisible-border correction, and does not
// depend on DWM holding a live composition. So the gate is dropped rather
// than widened to another feature flag: a feature would have to be plumbed
// through `gpui`, `gpui_windows`, `gpui_macos` and `gpui_apple`, which is
// four more merge surfaces than deleting four attributes.
pub fn render_to_image(&self) -> anyhow::Result<image::RgbaImage> {
self.platform_window
.render_to_image(&self.rendered_frame.scene)
}
/// Borrows the most recently rendered frame's scene, so benchmarks can validate their
/// output and report batch counts without cloning it.
#[cfg(feature = "bench-support")]
pub fn rendered_scene(&self) -> &Scene {
&self.rendered_frame.scene
}
/// Returns the quads in the most recently rendered frame's scene, so tests can assert on
/// painted output without rasterizing the frame. Quad bounds are in scaled pixels and are
/// not clipped; each quad carries the content mask it will be clipped to when drawn. Quads
/// whose bounds don't intersect their content mask are culled at paint time and won't appear.
#[cfg(any(test, feature = "test-support"))]
pub fn painted_quads(&self) -> Vec<Quad> {
self.rendered_frame.scene.quads.clone()
}
/// Returns the underlines in the most recently rendered frame's scene.
#[cfg(any(test, feature = "test-support"))]
pub fn painted_underlines(&self) -> Vec<Underline> {
self.rendered_frame.scene.underlines.clone()
}
/// Set the content size of the window.
pub fn resize(&mut self, size: Size<Pixels>) {
self.platform_window.resize(size);
}
/// Returns whether or not the window is currently fullscreen
pub fn is_fullscreen(&self) -> bool {
self.platform_window.is_fullscreen()
}
/// Returns whether the window is currently in simple (borderless) fullscreen,
/// where it covers the entire screen including the menu bar and notch area.
/// Always `false` on platforms other than macOS.
pub fn is_simple_fullscreen(&self) -> bool {
self.platform_window.is_simple_fullscreen()
}
pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
self.appearance = self.platform_window.appearance();
self.appearance_observers
.clone()
.retain(|callback| callback(self, cx));
}
pub(crate) fn button_layout_changed(&mut self, cx: &mut App) {
self.button_layout_observers
.clone()
.retain(|callback| callback(self, cx));
}
/// Returns the appearance of the current window.
pub fn appearance(&self) -> WindowAppearance {
self.appearance
}
/// Returns the size of the drawable area within the window.
pub fn viewport_size(&self) -> Size<Pixels> {
self.viewport_size
}
/// Returns the platform's visible viewport in window-local logical pixels.
///
/// Unlike `viewport_size`, this can shrink or move when the keyboard opens.
/// During drawing this is a consistent frame snapshot. Outside drawing it
/// reflects the latest platform sample, not a synchronous geometry query.
pub fn visual_viewport_bounds(&self) -> Bounds<Pixels> {
self.platform_window.visual_viewport_bounds()
}
/// Returns a conservative rectangle avoiding platform-known obscured content.
///
/// Intersects the visual viewport with the full layout area inset by system
/// safe areas and keyboard occlusion. Unknown overlays cannot be excluded.
pub fn fully_visible_bounds(&self) -> Bounds<Pixels> {
let insets = self.platform_window.insets().effective();
let viewport = self.viewport_size();
let left = insets.left.max(Pixels::ZERO).min(viewport.width);
let top = insets.top.max(Pixels::ZERO).min(viewport.height);
let right = (viewport.width - insets.right.max(Pixels::ZERO)).max(left);
let bottom = (viewport.height - insets.bottom.max(Pixels::ZERO)).max(top);
let safe_bounds = Bounds::from_corners(point(left, top), point(right, bottom));
let mut visible = safe_bounds.intersect(&self.visual_viewport_bounds());
visible.size.width = visible.size.width.max(Pixels::ZERO);
visible.size.height = visible.size.height.max(Pixels::ZERO);
visible
}
/// Requests the virtual keyboard for the currently focused text input.
///
/// Call from a user gesture on platforms that require one. The platform may
/// decline the request; this does not change focus or the layout viewport.
pub fn request_virtual_keyboard(&self) {
self.platform_window.show_soft_keyboard();
}
/// Requests dismissal of the virtual keyboard without changing GPUI focus.
pub fn dismiss_virtual_keyboard(&self) {
self.platform_window.hide_soft_keyboard();
}
/// Returns whether this window is focused by the operating system (receiving key events).
pub fn is_window_active(&self) -> bool {
self.active.get()
}
/// vue-native fork: while `on`, gpui treats this window as active whatever
/// the operating system says. That covers [`Window::is_window_active`],
/// the focus paths a frame's focus events carry (with no OS activation
/// they are empty, so `on_focus` never fires), and the inactive-window
/// frame throttle. The platform's activation changes are ignored while it
/// is set.
///
/// Nothing at the OS level changes: the window is not raised, activated
/// or given keyboard focus. vue-native's test hosts open their windows
/// behind everything and never take the foreground, yet must run focus
/// exactly as a window in front does. Turning it off goes back to what
/// the platform reports.
pub fn set_assume_active(&mut self, on: bool) {
self.assume_active = on;
let active = on || self.platform_window.is_active();
if self.active.replace(active) != active {
self.refresh();
}
}
/// vue-native fork: a window covered by others keeps drawing and reads as
/// visible (macOS stops it otherwise); minimised or hidden still stops.
pub fn set_draws_while_occluded(&self, on: bool) {
self.platform_window.set_draws_while_occluded(on);
}
/// Returns whether this window is considered to be the window
/// that currently owns the mouse cursor.
/// On mac, this is equivalent to `is_window_active`.
pub fn is_window_hovered(&self) -> bool {
if cfg!(any(
target_os = "windows",
target_os = "linux",
target_os = "freebsd"
)) {
self.hovered.get()
} else {
self.is_window_active()
}
}
/// Toggle zoom on the window.
pub fn zoom_window(&self) {
self.platform_window.zoom();
}
/// Opens the native title bar context menu, useful when implementing client side decorations (Wayland and X11)
pub fn show_window_menu(&self, position: Point<Pixels>) {
self.platform_window.show_window_menu(position)
}
/// Handle window movement for Linux and macOS.
/// Tells the compositor to take control of window movement (Wayland and X11)
///
/// Events may not be received during a move operation.
pub fn start_window_move(&self) {
self.platform_window.start_window_move()
}
/// When using client side decorations, set this to the width of the invisible decorations (Wayland and X11)
pub fn set_client_inset(&mut self, inset: Pixels) {
self.client_inset = Some(inset);
self.platform_window.set_client_inset(inset);
}
/// Sets the client-drawn corner radii so platform effects can match the window's shape.
pub fn set_client_corner_radii(&mut self, radii: Corners<Pixels>) {
self.platform_window.set_client_corner_radii(radii);
}
/// Returns the client_inset value by [`Self::set_client_inset`].
pub fn client_inset(&self) -> Option<Pixels> {
self.client_inset
}
/// Returns whether the title bar window controls need to be rendered by the application (Wayland and X11)
pub fn window_decorations(&self) -> Decorations {
self.platform_window.window_decorations()
}
/// Returns whether this window is resizable.
pub fn is_resizable(&self) -> bool {
self.is_resizable
}
/// Returns whether this window is minimizable.
pub fn is_minimizable(&self) -> bool {
self.is_minimizable
}
/// Returns the controls supported by the platform.
pub fn window_controls(&self) -> WindowControls {
self.platform_window.window_controls()
}
/// Updates the window's title at the platform level.
pub fn set_window_title(&mut self, title: &str) {
self.platform_window.set_title(title);
self.a11y.set_window_title(title.to_string());
}
/// Sets the position of the macOS traffic light buttons.
#[cfg(target_os = "macos")]
pub fn set_traffic_light_position(&self, position: Point<Pixels>) {
self.platform_window.set_traffic_light_position(position);
}
/// Shows or hides the native macOS titlebar, including the traffic light buttons.
#[cfg(target_os = "macos")]
pub fn set_native_titlebar_visibility(&self, visible: bool) {
self.platform_window.set_native_titlebar_visibility(visible);
}
/// Sets the application identifier.
pub fn set_app_id(&mut self, app_id: &str) {
self.platform_window.set_app_id(app_id);
}
/// Sets the window background appearance.
pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
self.platform_window
.set_background_appearance(background_appearance);
}
/// Whether the window currently draws the appearance last given to
/// [`Self::set_background_appearance`]. `false` only while the platform
/// stands in for it — a blurred macOS window in native fullscreen whose
/// desktop picture could not be shown behind the blur — so an app can
/// paint a background of its own exactly then.
pub fn is_background_appearance_drawn(&self) -> bool {
self.platform_window.is_background_appearance_drawn()
}
/// Mark the window as dirty at the platform level.
pub fn set_window_edited(&mut self, edited: bool) {
self.platform_window.set_edited(edited);
}
/// Set the path of the file this window represents.
/// On macOS, this sets the window's accessibility document property (AXDocument).
pub fn set_document_path(&self, path: Option<&std::path::Path>) {
self.platform_window.set_document_path(path);
}
/// Determine the display on which the window is visible.
pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
cx.platform
.displays()
.into_iter()
.find(|display| Some(display.id()) == self.display_id)
}
/// Show the platform character palette.
pub fn show_character_palette(&self) {
self.platform_window.show_character_palette();
}
/// The scale factor of the display associated with the window. For example, it could
/// return 2.0 for a "retina" display, indicating that each logical pixel should actually
/// be rendered as two pixels on screen.
pub fn scale_factor(&self) -> f32 {
self.scale_factor
}
/// Overrides the display scale factor for tests.
#[cfg(any(test, feature = "test-support"))]
pub fn set_scale_factor(&mut self, scale_factor: f32) {
self.scale_factor = scale_factor;
self.refresh();
}
/// The size of an em for the base font of the application. Adjusting this value allows the
/// UI to scale, just like zooming a web page.
pub fn rem_size(&self) -> Pixels {
self.rem_size_override_stack
.last()
.copied()
.unwrap_or(self.rem_size)
}
/// Sets the size of an em for the base font of the application. Adjusting this value allows the
/// UI to scale, just like zooming a web page.
pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
self.rem_size = rem_size.into();
}
/// Acquire a globally unique identifier for the given ElementId.
/// Only valid for the duration of the provided closure.
pub fn with_global_id<R>(
&mut self,
element_id: ElementId,
f: impl FnOnce(&GlobalElementId, &mut Self) -> R,
) -> R {
self.with_id(element_id, |this| {
let global_id = this.element_id_stack.global_id();
f(&global_id, this)
})
}
/// Calls the provided closure with the element ID pushed on the stack.
#[inline]
pub fn with_id<R>(
&mut self,
element_id: impl Into<ElementId>,
f: impl FnOnce(&mut Self) -> R,
) -> R {
self.element_id_stack.push(element_id.into());
let result = f(self);
self.element_id_stack.pop();
result
}
/// Executes the provided function with the specified rem size.
///
/// This method must only be called as part of element drawing.
// This function is called in a highly recursive manner in editor
// prepainting, make sure its inlined to reduce the stack burden
#[inline]
pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
where
F: FnOnce(&mut Self) -> R,
{
self.invalidator.debug_assert_paint_or_prepaint();
if let Some(rem_size) = rem_size {
self.rem_size_override_stack.push(rem_size.into());
let result = f(self);
self.rem_size_override_stack.pop();
result
} else {
f(self)
}
}
/// The line height associated with the current text style.
pub fn line_height(&self) -> Pixels {
self.text_style().line_height_in_pixels(self.rem_size())
}
/// Rounds a logical value to the nearest device pixel.
#[inline]
pub fn pixel_snap(&self, value: Pixels) -> Pixels {
px(round_to_device_pixel(value.0, self.scale_factor()) / self.scale_factor())
}
/// f64 variant of [`Self::pixel_snap`].
#[inline]
pub fn pixel_snap_f64(&self, value: f64) -> f64 {
let scale_factor = f64::from(self.scale_factor());
round_half_toward_zero_f64(value * scale_factor) / scale_factor
}
/// Snaps a bounds' origin and size to the nearest device pixel.
#[inline]
pub fn pixel_snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<Pixels> {
bounds.map(|c| self.pixel_snap(c))
}
/// Snaps a point's coordinates to the nearest device pixel.
#[inline]
pub fn pixel_snap_point(&self, position: Point<Pixels>) -> Point<Pixels> {
position.map(|c| self.pixel_snap(c))
}
/// Returns the snapped device-space bounds used to paint an underline.
pub fn underline_bounds(
&self,
origin: Point<Pixels>,
width: Pixels,
style: &UnderlineStyle,
) -> Bounds<ScaledPixels> {
let scale_factor = self.scale_factor();
let thickness = self.snap_stroke(style.thickness);
let height = if style.wavy {
ScaledPixels(thickness.0 * 3.)
} else {
thickness
};
Bounds {
origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
size: size(self.snap_stroke(width), height),
}
}
/// Paints an underline excluding absolute device-space horizontal spans.
pub fn paint_underline_with_exclusions(
&mut self,
origin: Point<Pixels>,
width: Pixels,
style: &UnderlineStyle,
exclusions: &[Range<ScaledPixels>],
) {
self.invalidator.debug_assert_paint();
let underline = self.underline(origin, width, style);
if exclusions.is_empty() {
self.next_frame.scene.insert_primitive(underline);
return;
}
let bounds = underline.bounds.intersect(&underline.content_mask.bounds);
if bounds.is_empty() {
return;
}
let mut exclusions = exclusions
.iter()
.filter_map(|span| {
let start = span.start.max(bounds.left());
let end = span.end.min(bounds.right());
(start < end).then_some(start..end)
})
.collect::<SmallVec<[_; 4]>>();
if exclusions.is_empty() {
self.next_frame.scene.insert_primitive(underline);
return;
}
exclusions.sort_unstable_by_key(|span| span.start);
let mut paint_span = |start, end| {
// vue-native fork: through `intersect`, so a span that ends at a
// rounded mask's corner keeps the curve.
let span = ContentMask::rect(Bounds::from_corners(
point(start, bounds.top()),
point(end, bounds.bottom()),
));
self.next_frame.scene.insert_primitive(Underline {
content_mask: underline.content_mask.intersect(&span),
..underline
});
};
let mut start = bounds.left();
for exclusion in exclusions {
if start < exclusion.start {
paint_span(start, exclusion.start);
}
start = start.max(exclusion.end);
}
if start < bounds.right() {
paint_span(start, bounds.right());
}
}
fn underline(&self, origin: Point<Pixels>, width: Pixels, style: &UnderlineStyle) -> Underline {
Underline {
order: 0,
pad: 0,
bounds: self.underline_bounds(origin, width, style),
content_mask: self.snapped_content_mask(),
color: style
.color
.unwrap_or_default()
.opacity(self.element_opacity()),
thickness: self.snap_stroke(style.thickness),
wavy: style.wavy.into(),
// vue-native fork: an underline inside a transformed box turns
// with it, like every other primitive pushed here.
transformation: self.element_transform,
}
}
#[inline]
fn snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
let scale_factor = self.scale_factor();
let left = round_to_device_pixel(bounds.left().0, scale_factor);
let top = round_to_device_pixel(bounds.top().0, scale_factor);
let right = round_to_device_pixel(bounds.right().0, scale_factor).max(left);
let bottom = round_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
Bounds::from_corners(
point(ScaledPixels(left), ScaledPixels(top)),
point(ScaledPixels(right), ScaledPixels(bottom)),
)
}
/// Rounds half-to-zero but clamps any non-zero input up to 1 dp so thin strokes do not disappear.
#[inline]
fn snap_stroke(&self, value: Pixels) -> ScaledPixels {
ScaledPixels(round_stroke_to_device_pixel(value.0, self.scale_factor()))
}
#[inline]
fn snap_border_widths(&self, edges: Edges<Pixels>) -> Edges<ScaledPixels> {
edges.map(|e| self.snap_stroke(*e))
}
/// Floors the near edge and ceils the far edge, producing a strict superset of the raw region.
#[inline]
fn cover_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
let scale_factor = self.scale_factor();
let left = floor_to_device_pixel(bounds.left().0, scale_factor);
let top = floor_to_device_pixel(bounds.top().0, scale_factor);
let right = ceil_to_device_pixel(bounds.right().0, scale_factor).max(left);
let bottom = ceil_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
Bounds::from_corners(
point(ScaledPixels(left), ScaledPixels(top)),
point(ScaledPixels(right), ScaledPixels(bottom)),
)
}
#[inline]
fn snapped_content_mask(&self) -> ContentMask<ScaledPixels> {
let mask = self.content_mask();
ContentMask {
bounds: self.cover_bounds(mask.bounds),
// vue-native fork: the radii scale as they are. The curve then
// sits on the covered bounds, which are at most one device pixel
// out from the exact ones, as the straight edges already are.
corner_radii: mask.corner_radii.scale(self.scale_factor()),
corner_shapes: mask.corner_shapes.scale(self.scale_factor()),
}
}
/// Call to prevent the default action of an event. Currently only used to prevent
/// parent elements from becoming focused on mouse down.
pub fn prevent_default(&mut self) {
self.default_prevented = true;
}
/// Obtain whether default has been prevented for the event currently being dispatched.
pub fn default_prevented(&self) -> bool {
self.default_prevented
}
/// Determine whether the given action is available along the dispatch path to the currently focused element.
pub fn is_action_available(&self, action: &dyn Action, cx: &App) -> bool {
let node_id =
self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
self.rendered_frame
.dispatch_tree
.is_action_available(action, node_id)
}
/// Determine whether the given action is available along the dispatch path to the given focus_handle.
pub fn is_action_available_in(&self, action: &dyn Action, focus_handle: &FocusHandle) -> bool {
let node_id = self.focus_node_id_in_rendered_frame(Some(focus_handle.id));
self.rendered_frame
.dispatch_tree
.is_action_available(action, node_id)
}
/// The position of the mouse relative to the window.
pub fn mouse_position(&self) -> Point<Pixels> {
self.mouse_position
}
/// Captures the pointer for the given hitbox. While captured, all mouse move and mouse up
/// events will be routed to listeners that check this hitbox's `is_hovered` status,
/// regardless of actual hit testing. This enables drag operations that continue
/// even when the pointer moves outside the element's bounds.
///
/// The capture is automatically released on mouse up.
pub fn capture_pointer(&mut self, hitbox_id: HitboxId) {
self.captured_hitbox = Some(hitbox_id);
}
/// Releases any active pointer capture.
pub fn release_pointer(&mut self) {
self.captured_hitbox = None;
}
/// Returns the hitbox that has captured the pointer, if any.
pub fn captured_hitbox(&self) -> Option<HitboxId> {
self.captured_hitbox
}
/// Captures the current long press for the given entity.
///
/// The capture is released when the gesture ends or is cancelled, or when
/// a replacement touch begins. A listener must also call
/// [`Self::prevent_default`] on the started event to claim the gesture.
pub fn capture_long_press<T: 'static>(&mut self, entity: &Entity<T>) {
self.long_press_capture = Some(entity.entity_id());
}
/// Returns whether the given entity has captured the current long press.
pub fn has_long_press_capture<T: 'static>(&self, entity: &Entity<T>) -> bool {
self.long_press_capture == Some(entity.entity_id())
}
/// The current state of the keyboard's modifiers
pub fn modifiers(&self) -> Modifiers {
self.modifiers
}
/// Returns true if the last input event was keyboard-based (key press, tab navigation, etc.)
/// This is used for focus-visible styling to show focus indicators only for keyboard navigation.
pub fn last_input_was_keyboard(&self) -> bool {
self.last_input_modality == InputModality::Keyboard
}
/// Returns whether the last input event came from a touch screen.
pub fn last_input_was_touch(&self) -> bool {
self.last_input_modality == InputModality::Touch
}
/// The current state of the keyboard's capslock
pub fn capslock(&self) -> Capslock {
self.capslock
}
/// Produces a new frame and assigns it to `rendered_frame`. To actually show
/// the contents of the new [`Scene`], use [`Self::present`].
#[profiling::function]
pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
let _profile_window = crate::native_profiling::window_scope(self.platform_window.as_ref());
let _profile = crate::native_profiling::current_span("native", "GPUI draw");
// Drain every draw in profiler builds so a previous frame's
// first-invalidation timestamp can't be attributed to this one.
#[cfg(feature = "profiler")]
let frame_dirty = self.invalidator.take_frame_dirty();
#[cfg(feature = "profiler")]
self.window_profiler.begin_draw();
// Set up the per-App arena for element allocation during this draw.
// This ensures that multiple test Apps have isolated arenas.
let arena_scope = ElementArenaScope::enter(&cx.element_arena);
if self.platform_window.prepare_frame() {
self.refresh();
}
self.invalidate_entities();
cx.entities.clear_accessed();
debug_assert!(self.rendered_entity_stack.is_empty());
self.invalidator.set_dirty(false);
self.requested_autoscroll = None;
// Restore the previously-used input handler.
// Place it back into a None slot (left by a previous .take()) so that
// cached paint_range indices in reuse_paint find the handler at the
// expected position.
if let Some(input_handler) = self.platform_window.take_input_handler() {
if let Some(slot) = self
.rendered_frame
.input_handlers
.iter_mut()
.rev()
.find(|h| h.is_none())
{
*slot = Some(input_handler);
} else {
self.rendered_frame.input_handlers.push(Some(input_handler));
}
}
if !cx.mode.skip_drawing() {
self.vn_scopes_painted.clear();
self.draw_roots(cx);
let now = crate::effect_clock_seconds();
self.vn_effect_phases
.retain(|_, phase| now - phase.at < VnEffectPhase::KEEP);
#[cfg(feature = "profiler")]
{
let viewport_size = self.viewport_size;
let scale_factor = self.scale_factor();
self.debug_frame_overlay.paint(
&mut self.next_frame.scene,
viewport_size,
scale_factor,
);
}
}
let _finalize = crate::native_profiling::current_span("native", "GPUI finalize frame");
self.dirty_views.clear();
self.next_frame.window_active = self.active.get();
// Register requested input handler with the platform window.
// Use .take() instead of .pop() to preserve Vec length, so that cached
// paint_range indices remain valid for reuse_paint on the next frame.
// Search backwards to find the last Some entry, since reuse_paint may
// have copied None slots from the previous frame. (Fixes #50456)
let focused_text_input = if let Some(mut input_handler) = self
.next_frame
.input_handlers
.iter_mut()
.rev()
.find_map(|h| h.take())
{
let accepts_text_input = input_handler.accepts_text_input(self, cx);
self.platform_window.set_input_handler(input_handler);
self.focus.filter(|_| accepts_text_input)
} else {
None
};
self.apply_text_input_configuration(cx);
let previous = mem::replace(&mut self.focused_text_input, focused_text_input);
if previous.is_some() != focused_text_input.is_some() {
self.platform_window
.text_input_state_changed(if focused_text_input.is_some() {
TextInputStateChange::FocusGained
} else {
TextInputStateChange::FocusLost
});
}
{
let _profile = crate::native_profiling::current_span("native", "GPUI finish layout and text");
self.layout_engine.as_mut().unwrap().clear();
self.text_system().finish_frame();
}
{
let _profile = crate::native_profiling::current_span("native", "GPUI finish scene");
self.next_frame.finish(&mut self.rendered_frame);
self.vn_settle_captures();
}
self.invalidator.set_phase(DrawPhase::Focus);
let previous_focus_path = self.rendered_frame.focus_path();
let previous_window_active = self.rendered_frame.window_active;
mem::swap(&mut self.rendered_frame, &mut self.next_frame);
self.scene_animation_interval
.set(self.rendered_frame.scene.animation_frame_interval());
{
let _profile = crate::native_profiling::current_span("native", "GPUI clear previous frame");
self.next_frame.clear();
}
let current_focus_path = self.rendered_frame.focus_path();
let current_window_active = self.rendered_frame.window_active;
let mut focus_before_listeners = self.focus;
if previous_focus_path != current_focus_path
|| previous_window_active != current_window_active
{
if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
self.focus_lost_path = previous_focus_path.clone();
self.focus_lost_listeners
.clone()
.retain(|listener| listener(self, cx));
self.focus_lost_path = SmallVec::new();
// The focus-lost fallback (e.g. a workspace refocusing itself) may target
// an element that isn't part of the element tree, in which case scheduling
// a redraw below would dispatch focus-lost again, looping forever. Only
// track focus movement caused by the focus listeners.
focus_before_listeners = self.focus;
}
let event = WindowFocusEvent {
previous_focus_path: if previous_window_active {
previous_focus_path
} else {
Default::default()
},
current_focus_path: if current_window_active {
current_focus_path
} else {
Default::default()
},
};
self.focus_listeners
.clone()
.retain(|listener| listener(&event, self, cx));
}
debug_assert!(self.rendered_entity_stack.is_empty());
self.record_entities_accessed(cx);
self.reset_cursor_style(cx);
self.refreshing = false;
self.invalidator.set_phase(DrawPhase::None);
// Focus listeners may move focus (e.g. a dock forwarding focus to its active
// panel). `Window::focus` suppresses `refresh` while a draw is in progress, so
// schedule another frame here to render the new focus state and dispatch the
// resulting focus events.
if self.focus != focus_before_listeners {
self.refresh();
}
self.needs_present.set(true);
#[cfg(feature = "profiler")]
{
self.window_profiler
.set_refresh_interval(self.refresh_interval(cx));
let draw_duration = self
.window_profiler
.end_draw(frame_dirty.dirty_at, frame_dirty.invalidations);
self.debug_frame_overlay.record_frame(draw_duration);
}
// Exit the scope to obtain the arena-clear token this draw owes; the
// scope's teardown itself happens in `ElementArenaScope::drop`.
arena_scope.exit(&cx.element_arena)
}
fn record_entities_accessed(&mut self, cx: &mut App) {
let entities = cx.entities.take_accessed();
let handle = self.handle;
cx.record_entities_accessed(
handle,
// Try moving window invalidator into the Window
self.invalidator.clone(),
&entities,
);
cx.entities.restore_accessed(entities);
}
fn invalidate_entities(&mut self) {
let mut views = self.invalidator.take_views();
for entity in views.drain() {
self.mark_view_dirty(entity);
}
self.invalidator.replace_views(views);
}
#[profiling::function]
fn present(&mut self) {
#[cfg(feature = "profiler")]
let _foreground_turn = profiler::journal::foreground_turn();
#[cfg(feature = "profiler")]
let present_start = Instant::now();
self.platform_window.draw(&self.rendered_frame.scene);
#[cfg(feature = "profiler")]
self.window_profiler.record_present(
present_start,
Instant::now(),
self.active.get(),
!self.next_frame_callbacks.borrow().is_empty(),
);
self.needs_present.set(false);
profiling::finish_frame!();
}
/// Presents the most recently drawn frame if it hasn't been presented yet.
#[cfg(all(test, feature = "profiler"))]
pub fn present_if_needed(&mut self) {
if self.needs_present.get() {
self.present();
}
}
/// Returns a snapshot of the current input-latency histograms.
#[cfg(feature = "profiler")]
pub fn input_latency_snapshot(&self) -> profiler::InputLatencySnapshot {
self.window_profiler.input_latency_snapshot()
}
/// Returns a snapshot of the current frame-duration histograms.
#[cfg(feature = "profiler")]
pub fn frame_duration_snapshot(&self) -> profiler::FrameDurationSnapshot {
self.window_profiler.frame_duration_snapshot()
}
/// Returns the current mode of the debug frame overlay.
#[cfg(feature = "profiler")]
pub fn debug_frame_overlay_mode(&self) -> DebugFrameOverlayMode {
self.debug_frame_overlay.mode()
}
/// Sets the mode of the debug frame overlay and schedules a redraw.
#[cfg(feature = "profiler")]
pub fn set_debug_frame_overlay_mode(&mut self, mode: DebugFrameOverlayMode) {
self.debug_frame_overlay.set_mode(mode);
self.refresh();
}
/// Advances the debug frame overlay through its hidden, frame-time-only,
/// and detailed modes.
#[cfg(feature = "profiler")]
pub fn cycle_debug_frame_overlay_mode(&mut self) {
self.set_debug_frame_overlay_mode(self.debug_frame_overlay.mode().next());
}
/// Clears the debug frame overlay's frame-time statistics, except for the
/// total frame count, and schedules a redraw.
#[cfg(feature = "profiler")]
pub fn reset_debug_frame_overlay_stats(&mut self) {
self.debug_frame_overlay.reset_stats();
self.refresh();
}
fn draw_roots(&mut self, cx: &mut App) {
self.invalidator.set_phase(DrawPhase::Prepaint);
self.tooltip_bounds.take();
self.a11y.sync_active_flag();
if self.a11y.is_active() {
self.a11y.begin_frame();
}
let _inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size());
let root_size = {
#[cfg(any(feature = "inspector", debug_assertions))]
{
if self.inspector.is_some() {
let mut size = self.viewport_size;
size.width = (size.width - _inspector_width).max(px(0.0));
size
} else {
self.viewport_size
}
}
#[cfg(not(any(feature = "inspector", debug_assertions)))]
{
self.viewport_size
}
};
// Layout all root elements. Like the root element on the web, which
// stretches to fill the viewport unless explicitly sized, window roots
// fill the window when their size is `auto`.
let scale_factor = self.scale_factor();
#[cfg(feature = "profiler")]
let request_layout_start = Instant::now();
let mut root_element = self.root.as_ref().unwrap().clone().into_any_element();
let root_layout_id = root_element.request_layout(self, cx);
#[cfg(feature = "profiler")]
let prepaint_start = Instant::now();
self.layout_engine
.as_mut()
.unwrap()
.stretch_auto_size_to_fill(root_layout_id, root_size, scale_factor);
root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
#[cfg(any(feature = "inspector", debug_assertions))]
let inspector_element = self.prepaint_inspector(_inspector_width, cx);
let deferred_hitboxes_start = self.next_frame.hitboxes.len();
let deferred_tagged_start = self.next_frame.vn_tagged_hitboxes.len();
self.prepaint_deferred_draws(cx);
let deferred_hitboxes = deferred_hitboxes_start..self.next_frame.hitboxes.len();
self.next_frame.vn_deferred_tagged =
deferred_tagged_start..self.next_frame.vn_tagged_hitboxes.len();
let mut prompt_element = None;
let mut active_drag_element = None;
let mut tooltip_element = None;
if let Some(prompt) = self.prompt.take() {
let mut element = prompt.view.any_view().into_any_element();
let prompt_layout_id = element.request_layout(self, cx);
self.layout_engine
.as_mut()
.unwrap()
.stretch_auto_size_to_fill(prompt_layout_id, root_size, scale_factor);
element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
prompt_element = Some(element);
self.prompt = Some(prompt);
} else if let Some(active_drag) = cx.active_drag.take() {
let mut element = active_drag.view.clone().into_any_element();
let offset = self.mouse_position() - active_drag.cursor_offset;
element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
active_drag_element = Some(element);
cx.active_drag = Some(active_drag);
} else {
tooltip_element = self.prepaint_tooltip(cx);
}
self.compute_hit_order(deferred_hitboxes);
self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position, self.scale_factor);
// Now actually paint the elements.
#[cfg(feature = "profiler")]
let paint_start = Instant::now();
self.invalidator.set_phase(DrawPhase::Paint);
root_element.paint(self, cx);
#[cfg(any(feature = "inspector", debug_assertions))]
self.paint_inspector(inspector_element, cx);
self.paint_deferred_draws(cx);
if let Some(mut prompt_element) = prompt_element {
prompt_element.paint(self, cx);
} else if let Some(mut drag_element) = active_drag_element {
drag_element.paint(self, cx);
} else if let Some(mut tooltip_element) = tooltip_element {
tooltip_element.paint(self, cx);
}
#[cfg(any(feature = "inspector", debug_assertions))]
self.paint_inspector_hitbox(cx);
#[cfg(feature = "profiler")]
self.window_profiler
.record_draw_phases(profiler::DrawPhases {
request_layout: prepaint_start.duration_since(request_layout_start),
prepaint: paint_start.duration_since(prepaint_start),
paint: Instant::now().duration_since(paint_start),
});
let _profile = crate::native_profiling::current_span("native", "GPUI postpaint accessibility");
// a11y may have been activated/deactivated halfway through the frame
let a11y_active_start_of_frame = self.a11y.is_active();
self.a11y.sync_active_flag();
let a11y_active_end_of_frame = self.a11y.is_active();
let should_send_a11y_update = a11y_active_start_of_frame && a11y_active_end_of_frame;
if a11y_active_start_of_frame {
// Harvest frame metadata for the debug dump while the live window
// and frame are still in scope.
let frame_info = crate::window::a11y::debug::FrameDebugInfo {
viewport_size: self.viewport_size,
scale_factor: self.scale_factor,
tab_stop_count: self.next_frame.tab_stops.tab_stop_count(),
};
// clear the builder state regardless
let tree_update = self.a11y.end_frame(frame_info);
if should_send_a11y_update {
log::debug!(
"Sending a11y tree update: {} nodes",
tree_update.nodes.len()
);
self.platform_window.a11y_tree_update(tree_update);
}
}
}
fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
// Use indexing instead of iteration to avoid borrowing self for the duration of the loop.
for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
let Some(Some(tooltip_request)) = self
.next_frame
.tooltip_requests
.get(tooltip_request_index)
.cloned()
else {
log::error!("Unexpectedly absent TooltipRequest");
continue;
};
let mut element = tooltip_request.tooltip.view.clone().into_any_element();
let mouse_position = tooltip_request.tooltip.mouse_position;
let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
let mut tooltip_bounds =
Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
let window_bounds = Bounds {
origin: Point::default(),
size: self.viewport_size(),
};
if tooltip_bounds.right() > window_bounds.right() {
let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
if new_x >= Pixels::ZERO {
tooltip_bounds.origin.x = new_x;
} else {
tooltip_bounds.origin.x = cmp::max(
Pixels::ZERO,
tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
);
}
}
if tooltip_bounds.bottom() > window_bounds.bottom() {
let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
if new_y >= Pixels::ZERO {
tooltip_bounds.origin.y = new_y;
} else {
tooltip_bounds.origin.y = cmp::max(
Pixels::ZERO,
tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
);
}
}
// It's possible for an element to have an active tooltip while not being painted (e.g.
// via the `visible_on_hover` method). Since mouse listeners are not active in this
// case, instead update the tooltip's visibility here.
let is_visible =
(tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
if !is_visible {
continue;
}
self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
element.prepaint(window, cx)
});
self.tooltip_bounds = Some(TooltipBounds {
id: tooltip_request.id,
bounds: tooltip_bounds,
});
return Some(element);
}
None
}
fn prepaint_deferred_draws(&mut self, cx: &mut App) {
assert_eq!(self.element_id_stack.len(), 0);
// Process deferred draws in multiple rounds to support nesting.
// Each round processes all current deferred draws, which may push new ones.
//
// The draws are processed in place rather than being moved out of
// `next_frame.deferred_draws`: `prepaint_index` snapshots that vector's
// length, so any prepaint range recorded during a round (view caches,
// nested deferred draws) must index the same vector `reuse_prepaint`
// slices on the next frame. Moving the draws out and re-appending them
// shifts the indices of nested draws, causing reused subtrees to graft
// the wrong deferred draws and panic in the dispatch tree.
let mut round_start = 0;
let mut depth = 0;
loop {
let round_end = self.next_frame.deferred_draws.len();
if round_start == round_end {
break;
}
// Limit maximum nesting depth to prevent infinite loops.
//
// vue-native fork: 64, not 10. An embedder that paints CSS
// stacking contexts defers one level per out-of-flow ancestor, and
// a round costs one pass over the draws it adds; the paint order
// does not depend on rounds (`DeferredDraw::order`).
assert!(depth < 64, "Exceeded maximum (64) deferred depth");
depth += 1;
// Sort this round by priority.
let mut traversal_order = (round_start..round_end).collect::<SmallVec<[usize; 8]>>();
{
let draws = &self.next_frame.deferred_draws;
traversal_order.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
}
for deferred_draw_ix in traversal_order {
let (
element,
parent_node,
current_view,
rem_size,
absolute_offset,
element_transform,
element_opacity,
content_mask,
vn_clip,
vn_scope,
prepaint_range,
) = {
let deferred_draw = &mut self.next_frame.deferred_draws[deferred_draw_ix];
self.element_id_stack
.clone_from(&deferred_draw.element_id_stack);
self.text_style_stack
.clone_from(&deferred_draw.text_style_stack);
(
deferred_draw.element.take(),
deferred_draw.parent_node,
deferred_draw.current_view,
deferred_draw.rem_size,
deferred_draw.absolute_offset,
deferred_draw.element_transform,
deferred_draw.element_opacity,
deferred_draw.content_mask,
deferred_draw.vn_clip.clone(),
deferred_draw.vn_scope.clone(),
deferred_draw.prepaint_range.clone(),
)
};
self.next_frame.dispatch_tree.set_active_node(parent_node);
// vue-native fork: the element's accessibility nodes go under
// the node it was deferred from, not the window root.
let a11y_parent = self.next_frame.deferred_draws[deferred_draw_ix]
.a11y_parent
.filter(|&p| p != a11y::ROOT_NODE_ID && self.a11y.is_active());
let prepaint_start = self.prepaint_index();
if let Some(mut element) = element {
if let Some(parent) = a11y_parent {
self.a11y.nodes.begin_adopted(parent);
}
let ((), accessed_entities) = cx.detect_accessed_entities(|cx| {
self.with_rendered_view(current_view, |window| {
window.with_rem_size(Some(rem_size), |window| {
// Masks are captured before transforms, in window space.
window.with_content_mask(content_mask, |window| {
window.vn_with_absolute_clip_stack(vn_clip, |window| {
window.with_absolute_element_opacity(element_opacity, |window| {
window.with_absolute_element_transform(element_transform, |window| {
window.with_absolute_element_offset(absolute_offset, |window| {
let outer = mem::replace(&mut window.vn_defer_scope, vn_scope);
element.prepaint(window, cx);
window.vn_defer_scope = outer;
});
});
});
});
});
});
});
});
if a11y_parent.is_some() {
self.a11y.nodes.end_adopted();
}
self.next_frame.deferred_draws[deferred_draw_ix].accessed_entities = accessed_entities;
self.next_frame.deferred_draws[deferred_draw_ix].element = Some(element);
} else {
cx.entities.extend_accessed(
self.next_frame.deferred_draws[deferred_draw_ix]
.accessed_entities
.iter()
.copied(),
);
self.reuse_prepaint(prepaint_range);
}
let prepaint_end = self.prepaint_index();
self.next_frame.deferred_draws[deferred_draw_ix].prepaint_range =
prepaint_start..prepaint_end;
}
self.element_id_stack.clear();
self.text_style_stack.clear();
round_start = round_end;
}
}
fn paint_deferred_draws(&mut self, cx: &mut App) {
let _profile = crate::native_profiling::current_span("paint", "GPUI paint deferred draws");
assert_eq!(self.element_id_stack.len(), 0);
// Paint all deferred draws in priority order.
// Since prepaint has already processed nested deferreds, we just paint them all.
if self.next_frame.deferred_draws.len() == 0 {
return;
}
// vue-native fork: the draws stay in place, since a `VnDeferScope`
// painting among them looks its own draws up.
let traversal_order = self.deferred_draw_traversal_order();
for deferred_draw_ix in traversal_order {
let draw = &self.next_frame.deferred_draws[deferred_draw_ix];
// A replayed one was painted by its scope's replay.
if let Some(scope) = &draw.vn_scope
&& (self.vn_scopes_painted.contains(&scope.id) || draw.element.is_none())
{
continue;
}
self.vn_paint_deferred_draw(deferred_draw_ix, None, cx);
}
self.element_id_stack.clear();
self.text_style_stack.clear();
}
/// Paints the deferred draw `ix`. In a scope, `scope` is the absolute
/// opacity the scope's content group took off, and the clip stack it is
/// inside of.
fn vn_paint_deferred_draw(
&mut self,
ix: usize,
scope: Option<(f32, Option<Arc<crate::VnClipNode>>)>,
cx: &mut App,
) {
let deferred_draw = &mut self.next_frame.deferred_draws[ix];
self.element_id_stack
.clone_from(&deferred_draw.element_id_stack);
// vue-native fork: the text style too, as the prepaint side does.
// Without it a deferred element that reads `Window::text_style` in
// PAINT read the default, not what its ancestors set: an inline
// `<svg>` tinted by the inherited `color` painted black when it was
// `position: absolute` (m26 client sweep #36).
self.text_style_stack
.clone_from(&deferred_draw.text_style_stack);
self.next_frame
.dispatch_tree
.set_active_node(deferred_draw.parent_node);
let deferred_draw = &mut self.next_frame.deferred_draws[ix];
let content_mask = deferred_draw.content_mask;
let element_transform = deferred_draw.element_transform;
let (element_opacity, base) = match &scope {
Some((opacity, base)) => (
(deferred_draw.element_opacity / opacity).min(1.),
base.as_ref(),
),
None => (deferred_draw.element_opacity, None),
};
let vn_clip = deferred_draw.vn_clip.clone();
let view = deferred_draw.current_view;
let rem_size = deferred_draw.rem_size;
let paint_range = deferred_draw.paint_range.clone();
let mut element = deferred_draw.element.take();
let paint_start = self.paint_index();
if let Some(element) = element.as_mut() {
let ((), accessed_entities) = cx.detect_accessed_entities(|cx| {
self.with_rendered_view(view, |window| {
// Reopen inherited clipping and transforms in their original order.
window.with_content_mask(content_mask, |window| {
window.vn_reopen_clip_layers(vn_clip, base, cx, |window, cx| {
window.with_absolute_element_opacity(element_opacity, |window| {
window.with_absolute_element_transform(element_transform, |window| {
window.with_rem_size(Some(rem_size), |window| {
element.paint(window, cx);
});
});
});
});
});
});
});
self.next_frame.deferred_draws[ix]
.accessed_entities
.extend(accessed_entities);
} else {
self.reuse_paint(paint_range);
}
let paint_end = self.paint_index();
let deferred_draw = &mut self.next_frame.deferred_draws[ix];
deferred_draw.element = element;
deferred_draw.paint_range = paint_start..paint_end;
}
/// vue-native fork: paints the draws deferred from inside the content
/// effect of element `id` ([`VnDeferScope`]) in their stacking order,
/// into its content group, whose absolute opacity was `opacity`.
fn vn_paint_scope(&mut self, id: u64, opacity: f32, cx: &mut App) {
if id == 0 || !self.vn_scopes_painted.insert(id) {
return;
}
let mut order: SmallVec<[usize; 8]> = self
.next_frame
.deferred_draws
.iter()
.enumerate()
.filter(|(_, draw)| draw.vn_scope.as_ref().is_some_and(|scope| scope.id == id))
.map(|(ix, _)| ix)
.collect();
if order.is_empty() {
return;
}
let draws = &self.next_frame.deferred_draws;
order.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
let element_id_stack = self.element_id_stack.clone();
let text_style_stack = self.text_style_stack.clone();
let active_node = self.next_frame.dispatch_tree.active_node_id();
for ix in order {
let base = self.next_frame.deferred_draws[ix]
.vn_scope
.as_ref()
.and_then(|scope| scope.clip.clone());
self.vn_paint_deferred_draw(ix, Some((opacity, base)), cx);
}
self.element_id_stack = element_id_stack;
self.text_style_stack = text_style_stack;
if let Some(node) = active_node {
self.next_frame.dispatch_tree.set_active_node(node);
}
}
/// vue-native fork: draws deferred in `f` belong to the content effect of
/// element `id` (0: none), which paints them ([`VnDeferScope`]).
pub fn vn_with_defer_scope<R>(&mut self, id: u64, f: impl FnOnce(&mut Self) -> R) -> R {
if id == 0 {
return f(self);
}
let scope = VnDeferScope {
id,
clip: self.vn_clip_stack.clone(),
};
let previous = self.vn_defer_scope.replace(scope);
let result = f(self);
self.vn_defer_scope = previous;
result
}
fn deferred_draw_traversal_order(&mut self) -> SmallVec<[usize; 8]> {
let deferred_count = self.next_frame.deferred_draws.len();
let mut sorted_indices = (0..deferred_count).collect::<SmallVec<[_; 8]>>();
let draws = &self.next_frame.deferred_draws;
sorted_indices.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
sorted_indices
}
/// vue-native fork: fills [`Frame::vn_hit_order`] once prepaint is done.
/// `deferred_hitboxes` is the range of hitbox indices the deferred draws'
/// prepaint inserted. Everything before it (the root tree, the inspector)
/// paints first and everything after it (a prompt, a drag, a tooltip)
/// paints last, as inserted; inside it, each draw's hitboxes go where the
/// draw paints. A draw's range never contains a nested draw's, which
/// prepaints in a later round.
fn compute_hit_order(&mut self, deferred_hitboxes: Range<usize>) {
let frame = &mut self.next_frame;
frame.vn_hit_order.clear();
if deferred_hitboxes.is_empty() {
return;
}
let mut order: Vec<u32> = Vec::with_capacity(frame.hitboxes.len());
order.extend(0..deferred_hitboxes.start as u32);
let mut traversal = (0..frame.deferred_draws.len()).collect::<Vec<_>>();
let draws = &frame.deferred_draws;
traversal.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
for ix in traversal {
let range = &draws[ix].prepaint_range;
let (start, end) = (range.start.hitboxes_index, range.end.hitboxes_index);
// Draws replayed from a cached view outside this frame's
// deferred pass hold ranges of the frame they were recorded in.
if start >= deferred_hitboxes.start && end <= deferred_hitboxes.end && start < end {
order.extend(start as u32..end as u32);
}
}
order.extend(deferred_hitboxes.end as u32..frame.hitboxes.len() as u32);
// Anything a draw's range did not account for keeps insertion order
// rather than vanishing from the hit test.
if order.len() != frame.hitboxes.len() {
return;
}
frame.vn_hit_order = order;
}
pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
PrepaintStateIndex {
hitboxes_index: self.next_frame.hitboxes.len(),
// vue-native fork.
vn_tagged_hitboxes_index: self.next_frame.vn_tagged_hitboxes.len(),
tooltips_index: self.next_frame.tooltip_requests.len(),
deferred_draws_index: self.next_frame.deferred_draws.len(),
dispatch_tree_index: self.next_frame.dispatch_tree.len(),
accessed_element_states_index: self.next_frame.accessed_element_states.len(),
line_layout_index: self.text_system.layout_index(),
}
}
pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
self.next_frame.hitboxes.extend(
self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
.iter()
.cloned(),
);
// vue-native fork: the tags travel with the hitboxes they name. Without
// this line a cached subtree keeps its hitboxes — so it still hovers and
// still takes clicks — while `Window::tagged_hitbox` answers `None` for
// every node inside it, which is what the embedder's element picker,
// highlight overlay and `:hover` reporting are built on.
self.next_frame.vn_tagged_hitboxes.extend(
self.rendered_frame.vn_tagged_hitboxes
[range.start.vn_tagged_hitboxes_index..range.end.vn_tagged_hitboxes_index]
.iter()
.cloned(),
);
self.next_frame.tooltip_requests.extend(
self.rendered_frame.tooltip_requests
[range.start.tooltips_index..range.end.tooltips_index]
.iter_mut()
.map(|request| request.take()),
);
self.next_frame.accessed_element_states.extend(
self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
..range.end.accessed_element_states_index]
.iter()
.map(|(id, type_id)| (id.clone(), *type_id)),
);
self.text_system
.reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
range.start.dispatch_tree_index..range.end.dispatch_tree_index,
&mut self.rendered_frame.dispatch_tree,
self.focus,
);
if reused_subtree.contains_focus() {
self.next_frame.focus = self.focus;
}
self.next_frame.deferred_draws.extend(
self.rendered_frame.deferred_draws
[range.start.deferred_draws_index..range.end.deferred_draws_index]
.iter()
.map(|deferred_draw| DeferredDraw {
current_view: deferred_draw.current_view,
parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
element_id_stack: deferred_draw.element_id_stack.clone(),
text_style_stack: deferred_draw.text_style_stack.clone(),
content_mask: deferred_draw.content_mask,
rem_size: deferred_draw.rem_size,
priority: deferred_draw.priority,
element: None,
absolute_offset: deferred_draw.absolute_offset,
element_transform: deferred_draw.element_transform,
a11y_parent: deferred_draw.a11y_parent,
vn_stack: deferred_draw.vn_stack.clone(),
element_opacity: deferred_draw.element_opacity,
vn_clip: deferred_draw.vn_clip.clone(),
vn_scope: deferred_draw.vn_scope.clone(),
prepaint_range: deferred_draw.prepaint_range.clone(),
paint_range: deferred_draw.paint_range.clone(),
accessed_entities: deferred_draw.accessed_entities.clone(),
}),
);
}
pub(crate) fn paint_index(&self) -> PaintIndex {
PaintIndex {
scene_index: self.next_frame.scene.len(),
#[cfg(any(test, feature = "test-support"))]
debug_bounds_index: self.next_frame.debug_bounds_records.len(),
mouse_listeners_index: self.next_frame.mouse_listeners.len(),
input_handlers_index: self.next_frame.input_handlers.len(),
cursor_styles_index: self.next_frame.cursor_styles.len(),
window_control_hitboxes_index: self.next_frame.window_control_hitboxes.len(),
accessed_element_states_index: self.next_frame.accessed_element_states.len(),
tab_handle_index: self.next_frame.tab_stops.paint_index(),
line_layout_index: self.text_system.layout_index(),
}
}
pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
// Cached elements still exist in the frame even when their paint methods don't run.
#[cfg(any(test, feature = "test-support"))]
for (selector, bounds) in &self.rendered_frame.debug_bounds_records
[range.start.debug_bounds_index..range.end.debug_bounds_index]
{
self.next_frame
.record_debug_bounds(selector.clone(), *bounds);
}
// Caption areas are paint output just like listeners and cursors.
// Dropping this span makes a retained titlebar stop dragging, and
// loses NoDrag cutouts when only an ancestor repaints.
self.next_frame.window_control_hitboxes.extend(
self.rendered_frame.window_control_hitboxes
[range.start.window_control_hitboxes_index..range.end.window_control_hitboxes_index]
.iter()
.cloned(),
);
self.next_frame.cursor_styles.extend(
self.rendered_frame.cursor_styles
[range.start.cursor_styles_index..range.end.cursor_styles_index]
.iter()
.cloned(),
);
self.next_frame.input_handlers.extend(
self.rendered_frame.input_handlers
[range.start.input_handlers_index..range.end.input_handlers_index]
.iter_mut()
.map(|handler| handler.take()),
);
self.next_frame.mouse_listeners.extend(
self.rendered_frame.mouse_listeners
[range.start.mouse_listeners_index..range.end.mouse_listeners_index]
.iter_mut()
.map(|listener| listener.take()),
);
self.next_frame.accessed_element_states.extend(
self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
..range.end.accessed_element_states_index]
.iter()
.map(|(id, type_id)| (id.clone(), *type_id)),
);
self.next_frame.tab_stops.replay(
&self.rendered_frame.tab_stops.insertion_history
[range.start.tab_handle_index..range.end.tab_handle_index],
);
self.text_system
.reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
self.next_frame.scene.replay(
range.start.scene_index..range.end.scene_index,
&self.rendered_frame.scene,
);
}
/// Push a text style onto the stack, and call a function with that style active.
/// Use [`Window::text_style`] to get the current, combined text style. This method
/// should only be called as part of element drawing.
pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
where
F: FnOnce(&mut Self) -> R,
{
self.invalidator.debug_assert_paint_or_prepaint();
if let Some(style) = style {
self.text_style_stack.push(style);
let result = f(self);
self.text_style_stack.pop();
result
} else {
f(self)
}
}
/// Updates the cursor style at the platform level. This method should only be called
/// during the paint phase of element drawing.
pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
self.invalidator.debug_assert_paint();
self.next_frame.cursor_styles.push(CursorStyleRequest {
hitbox_id: Some(hitbox.id),
style,
});
}
/// Updates the cursor style for the entire window at the platform level. A cursor
/// style using this method will have precedence over any cursor style set using
/// `set_cursor_style`. This method should only be called during the paint
/// phase of element drawing.
pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
self.invalidator.debug_assert_paint();
self.next_frame.cursor_styles.push(CursorStyleRequest {
hitbox_id: None,
style,
})
}
/// Sets a tooltip to be rendered for the upcoming frame. This method should only be called
/// during the paint phase of element drawing.
pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
self.invalidator.debug_assert_prepaint();
let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
self.next_frame
.tooltip_requests
.push(Some(TooltipRequest { id, tooltip }));
id
}
/// Invoke the given function with the given content mask after intersecting it
/// with the current mask. This method should only be called during element drawing.
// This function is called in a highly recursive manner in editor
// prepainting, make sure its inlined to reduce the stack burden
#[inline]
pub fn with_content_mask<R>(
&mut self,
mask: Option<ContentMask<Pixels>>,
f: impl FnOnce(&mut Self) -> R,
) -> R {
self.invalidator.debug_assert_paint_or_prepaint();
if let Some(mask) = mask {
// A clip rect is expressed in the element's OWN frame, and the
// element may be transformed — so the rect has to be mapped into
// window space before it can be intersected with an ancestor's.
// Without this a `transform: translate(-50%, -50%)` element paints
// its subtree half a box away from the region it clips it to, and
// everything that lands outside the old, unmoved rect disappears.
// (reka's dialog is exactly that shape: `fixed top-1/2 left-1/2
// translate-x-[-50%] translate-y-[-50%]` with a scrolling body
// inside, and it came up as a black slab with one stray line of
// text in the corner where the two rects happened to overlap.)
//
// Exact for a translation; a rotation or scale gives the axis-
// aligned bounding box of the mapped rect, which is a superset — a
// clip that shows a little too much rather than one that hides
// content that should be visible. (vue-native fork: the corner
// radii map along; `transform_mask` says when they survive.)
let mask = transform_mask(self.element_transform, mask, self.scale_factor);
let mask = mask.intersect(&self.content_mask());
self.content_mask_stack.push(mask);
let result = f(self);
self.content_mask_stack.pop();
result
} else {
f(self)
}
}
/// vue-native fork: runs `f` under a `clip-path` that is no rounded
/// rectangle ([`crate::Style::vn_clip_outline`]), laid out in the
/// element's own frame. The outline is flattened through the transform in
/// force into window device pixels and pushed on the clip stack, which
/// every hitbox inserted in `f` takes (prepaint). While painting, `f`'s
/// primitives also go into an isolated layer that the renderer composites
/// through the shape ([`crate::Scene::vn_push_isolation`]). The caller
/// pushes the outline's box as a content mask around this, which culls.
pub fn vn_with_clip_shape<R>(
&mut self,
outline: Option<&crate::VnClipOutline>,
f: impl FnOnce(&mut Self) -> R,
) -> R {
let Some(outline) = outline else {
return f(self);
};
let geometry = Arc::new(crate::VnClipGeometry::new(
outline,
self.scale_factor,
self.element_transform,
));
let node = Arc::new(crate::VnClipNode {
geometry,
color_matrix: None,
capture: None,
mask: None,
parent: self.vn_clip_stack.clone(),
});
let previous = self.vn_clip_stack.replace(node.clone());
let result = self.vn_with_clip_layer(&node, f);
self.vn_clip_stack = previous;
result
}
/// Applies an SVG color matrix to the entire painted subtree. The same
/// stack node is retained in prepaint so deferred descendants reopen it.
pub fn vn_with_color_matrix<R>(
&mut self,
matrix: Option<crate::VnColorMatrix>,
f: impl FnOnce(&mut Self) -> R,
) -> R {
let Some(matrix) = matrix else { return f(self) };
let bounds = self.snapped_content_mask().bounds;
let left = bounds.origin.x.0;
let top = bounds.origin.y.0;
let right = left + bounds.size.width.0;
let bottom = top + bounds.size.height.0;
let geometry = Arc::new(crate::VnClipGeometry {
fill_rule: crate::VnFillRule::NonZero,
segments: vec![
[left, top, right, top], [right, top, right, bottom],
[right, bottom, left, bottom], [left, bottom, left, top],
],
bounds,
});
let node = Arc::new(crate::VnClipNode {
geometry,
color_matrix: Some(matrix),
capture: None,
mask: None,
parent: self.vn_clip_stack.clone(),
});
let previous = self.vn_clip_stack.replace(node.clone());
let result = self.vn_with_clip_layer(&node, f);
self.vn_clip_stack = previous;
result
}
/// Resolve a text brush once at its owner, before descendant overflow masks.
pub fn vn_text_paint(&self, fill: crate::VnTextFill, bounds: Bounds<Pixels>) -> Arc<crate::VnTextPaint> {
let x = bounds.origin.x.0; let y = bounds.origin.y.0;
let right = x + bounds.size.width.0; let bottom = y + bounds.size.height.0;
let outline = crate::VnClipOutline {
fill_rule: crate::VnFillRule::NonZero,
verbs: vec![crate::VnPathVerb::MoveTo([x,y]), crate::VnPathVerb::LineTo([right,y]),
crate::VnPathVerb::LineTo([right,bottom]), crate::VnPathVerb::LineTo([x,bottom]), crate::VnPathVerb::Close],
};
let m = self.element_transform.inverse().unwrap_or_else(TransformationMatrix::unit);
Arc::new(crate::VnTextPaint {
fill, bounds: [x, y, bounds.size.width.0, bounds.size.height.0],
inverse: [m.rotation_scale[0][0], m.rotation_scale[0][1], m.rotation_scale[1][0], m.rotation_scale[1][1], m.translation[0], m.translation[1]],
scale_factor: self.scale_factor,
geometry: Arc::new(crate::VnClipGeometry::new(&outline, self.scale_factor, self.element_transform)),
content_mask: self.snapped_content_mask(),
})
}
/// Paint only glyph alpha into the owner's shared mask. Child overflow
/// masks still apply to their sprites without clipping later sibling glyphs.
pub fn vn_with_text_mask<R>(&mut self, paint: Arc<crate::VnTextPaint>, f: impl FnOnce(&mut Self) -> R) -> R {
self.next_frame.scene.vn_push_isolation(crate::VnIsolation {
geometry: paint.geometry.clone(), color_matrix: None,
content_mask: paint.content_mask, text_paint: Some(paint), capture: None,
});
let result = f(self);
self.next_frame.scene.vn_pop_isolation();
result
}
/// vue-native fork: CSS `mask`. While painting, `f` goes into an isolated
/// layer cut to the border box `bounds`, composited multiplied by the alpha
/// (or luminance) of what the mask paints over `bounds`. The mask is on the
/// clip stack meanwhile, in prepaint too, so a deferred descendant paints
/// through it again ([`Window::vn_reopen_clip_layers`]).
pub fn vn_with_mask<R>(
&mut self,
mask: Option<&crate::VnMask>,
bounds: Bounds<Pixels>,
cx: &mut App,
f: impl FnOnce(&mut Self, &mut App) -> R,
) -> R {
let Some(mask) = mask.filter(|mask| mask.paint.is_some()) else {
return f(self, cx);
};
let node = Arc::new(crate::VnClipNode {
geometry: self.vn_box_geometry(bounds),
color_matrix: None,
capture: None,
mask: Some(crate::VnClipMask {
mask: mask.clone(),
bounds,
transform: self.element_transform,
}),
parent: self.vn_clip_stack.clone(),
});
let previous = self.vn_clip_stack.replace(node.clone());
let result = if self.invalidator.is_painting() {
let content_mask = self.snapped_content_mask();
self.next_frame.scene.vn_push_isolation(crate::VnIsolation {
geometry: node.geometry.clone(),
color_matrix: None,
text_paint: None,
content_mask,
capture: None,
});
let result = f(self, cx);
self.vn_paint_mask(&node, cx);
self.next_frame.scene.vn_pop_isolation();
result
} else {
f(self, cx)
};
self.vn_clip_stack = previous;
result
}
/// Ends the content of `node`'s open layer with its mask, if it has one.
fn vn_paint_mask(&mut self, node: &crate::VnClipNode, cx: &mut App) {
let Some(clip) = &node.mask else { return };
let Some(paint) = clip.mask.paint.clone() else { return };
self.next_frame.scene.vn_begin_mask(clip.mask.luminance);
// The content already carries the element's opacity; the mask must not
// apply it a second time.
let opacity = mem::replace(&mut self.element_opacity, 1.);
let tint = mem::replace(&mut self.element_image_tint, Hsla::transparent_black());
let transform = mem::replace(&mut self.element_transform, clip.transform);
paint(clip.bounds, None, self, cx);
self.element_opacity = opacity;
self.element_image_tint = tint;
self.element_transform = transform;
}
/// The border box `bounds` as a clip shape through the element transform.
fn vn_box_geometry(&self, bounds: Bounds<Pixels>) -> Arc<crate::VnClipGeometry> {
let (x, y) = (bounds.origin.x.0, bounds.origin.y.0);
let (right, bottom) = (x + bounds.size.width.0, y + bounds.size.height.0);
let outline = crate::VnClipOutline {
fill_rule: crate::VnFillRule::NonZero,
verbs: vec![
crate::VnPathVerb::MoveTo([x, y]),
crate::VnPathVerb::LineTo([right, y]),
crate::VnPathVerb::LineTo([right, bottom]),
crate::VnPathVerb::LineTo([x, bottom]),
crate::VnPathVerb::Close,
],
};
Arc::new(crate::VnClipGeometry::new(
&outline,
self.scale_factor,
self.element_transform,
))
}
/// vue-native fork: `f` inside an isolated layer for `node`'s shape when
/// painting, and as it is otherwise.
fn vn_with_clip_layer<R>(
&mut self,
node: &Arc<crate::VnClipNode>,
f: impl FnOnce(&mut Self) -> R,
) -> R {
if !self.invalidator.is_painting() {
return f(self);
}
let content_mask = self.snapped_content_mask();
self.next_frame.scene.vn_push_isolation(crate::VnIsolation {
geometry: node.geometry.clone(),
color_matrix: node.color_matrix,
text_paint: None,
content_mask,
capture: node.capture,
});
let result = f(self);
self.next_frame.scene.vn_pop_isolation();
result
}
/// vue-native fork: `f` with the clip stack set to `clip`, as a deferred
/// draw's prepaint re-enters the clips it was deferred from inside.
fn vn_with_absolute_clip_stack<R>(
&mut self,
clip: Option<Arc<crate::VnClipNode>>,
f: impl FnOnce(&mut Self) -> R,
) -> R {
let previous = mem::replace(&mut self.vn_clip_stack, clip);
let result = f(self);
self.vn_clip_stack = previous;
result
}
/// vue-native fork: a deferred draw's paint, inside an isolated layer for
/// each clip shape it was deferred from inside, the outermost first. It
/// paints after the clipped ancestor closed its own layer, so it is
/// composited through the same shapes on its own. Painted inside a
/// [`VnDeferScope`], it reopens only the shapes inside the scope's `base`.
fn vn_reopen_clip_layers<R>(
&mut self,
clip: Option<Arc<crate::VnClipNode>>,
base: Option<&Arc<crate::VnClipNode>>,
cx: &mut App,
f: impl FnOnce(&mut Self, &mut App) -> R,
) -> R {
let Some(innermost) = clip.clone() else {
return self.vn_with_absolute_clip_stack(None, |window| f(window, cx));
};
let chain = crate::VnClipNode::inside_of(&innermost, base);
self.vn_with_absolute_clip_stack(clip, |window| {
for node in &chain {
let content_mask = window.snapped_content_mask();
window.next_frame.scene.vn_push_isolation(crate::VnIsolation {
geometry: node.geometry.clone(),
color_matrix: node.color_matrix,
text_paint: None,
content_mask,
capture: node.capture,
});
}
let result = f(window, cx);
for node in chain.iter().rev() {
window.vn_paint_mask(node, cx);
window.next_frame.scene.vn_pop_isolation();
}
result
})
}
/// vue-native fork: `f` paints into the snapshot `id` rather than the
/// page: untransformed, unclipped by its ancestors and at full opacity,
/// in a group the renderer draws first and keeps
/// ([`crate::Scene::vn_captures`]). `bounds` and `own` (the element's
/// transform) are what the capture reports of the element.
pub fn vn_with_capture<R>(
&mut self,
id: Option<u64>,
bounds: Bounds<Pixels>,
own: TransformationMatrix,
f: impl FnOnce(&mut Self) -> R,
) -> R {
let Some(id) = id else { return f(self) };
let scale_factor = self.scale_factor();
let viewport = Bounds { origin: Point::default(), size: self.viewport_size };
let device = viewport.scale(scale_factor);
let info = crate::VnCaptureInfo {
id,
border_box: bounds.scale(scale_factor),
transform: self.element_transform.compose(own),
};
let node = Arc::new(crate::VnClipNode {
geometry: Arc::new(crate::VnClipGeometry::rect(device)),
color_matrix: None,
capture: Some(info),
mask: None,
parent: None,
});
let previous_clip = self.vn_clip_stack.replace(node.clone());
self.content_mask_stack.push(ContentMask::rect(viewport));
let result = self.with_absolute_element_transform(TransformationMatrix::unit(), |window| {
window.with_absolute_element_opacity(1., |window| {
if !window.invalidator.is_painting() {
return f(window);
}
window.next_frame.scene.vn_push_isolation(crate::VnIsolation {
geometry: node.geometry.clone(),
color_matrix: None,
text_paint: None,
content_mask: ContentMask::rect(device),
capture: Some(info),
});
let result = f(window);
window.next_frame.scene.vn_pop_isolation();
result
})
});
self.content_mask_stack.pop();
self.vn_clip_stack = previous_clip;
result
}
/// vue-native fork: `f` paints into an isolated group composited
/// source-over, so what blends inside it blends with the group only.
pub fn vn_with_isolation<R>(&mut self, isolate: bool, f: impl FnOnce(&mut Self) -> R) -> R {
if !isolate || !self.invalidator.is_painting() {
return f(self);
}
let device = Bounds { origin: Point::default(), size: self.viewport_size }.scale(self.scale_factor());
let content_mask = self.snapped_content_mask();
self.next_frame.scene.vn_push_isolation(crate::VnIsolation {
geometry: Arc::new(crate::VnClipGeometry::rect(device)),
color_matrix: None,
text_paint: None,
content_mask,
capture: None,
});
let result = f(self);
self.next_frame.scene.vn_pop_isolation();
result
}
/// vue-native fork: draws the snapshot `id` so that the border box it
/// captured fills `bounds`, through the transform and opacity in force.
/// Ink outside the border box scales along. Nothing is drawn for a
/// snapshot the renderer does not hold.
pub fn vn_paint_snapshot(&mut self, id: u64, bounds: Bounds<Pixels>, plus_lighter: bool) {
self.invalidator.debug_assert_paint();
let scale_factor = self.scale_factor();
let device = bounds.scale(scale_factor);
if device.size.width.0 <= 0. || device.size.height.0 <= 0. {
return;
}
let Some(inverse) = self.element_transform.inverse() else { return };
let (w, h) = (device.size.width.0, device.size.height.0);
let [[a, b], [c, d]] = inverse.rotation_scale;
let [tx, ty] = inverse.translation;
let (x, y) = (device.origin.x.0, device.origin.y.0);
let to_unit = [a / w, b / w, (tx - x) / w, c / h, d / h, (ty - y) / h];
let covered = crate::scene::transformed_bounds(device, self.element_transform);
let covered = Bounds::from_corners(
point(ScaledPixels(covered.origin.x.0.floor()), ScaledPixels(covered.origin.y.0.floor())),
point(
ScaledPixels((covered.origin.x.0 + covered.size.width.0).ceil()),
ScaledPixels((covered.origin.y.0 + covered.size.height.0).ceil()),
),
);
let opacity = self.element_opacity;
let content_mask = self.snapped_content_mask();
self.next_frame.scene.vn_insert_snapshot(crate::VnSnapshotPaint {
id,
to_unit,
bounds: covered,
content_mask,
opacity,
plus_lighter,
in_place: false,
});
}
/// vue-native fork: draws the snapshot `id` where its element was when
/// captured, through the opacity in force.
pub fn vn_paint_snapshot_in_place(&mut self, id: u64) {
self.invalidator.debug_assert_paint();
let viewport = Bounds { origin: Point::default(), size: self.viewport_size }.scale(self.scale_factor());
let opacity = self.element_opacity;
let content_mask = self.snapped_content_mask();
self.next_frame.scene.vn_insert_snapshot(crate::VnSnapshotPaint {
id,
to_unit: [0.; 6],
bounds: viewport,
content_mask,
opacity,
plus_lighter: false,
in_place: true,
});
}
/// vue-native fork: what the last drawn frame knows of capture `id`:
/// the element's border box and transform in device pixels.
pub fn vn_capture(&self, id: u64) -> Option<crate::VnCaptureInfo> {
self.vn_capture_records.get(&id).map(|(info, _)| *info)
}
/// vue-native fork: forgets captures; their snapshots stop drawing and
/// the renderer frees them once no frame paints them.
pub fn vn_forget_captures(&mut self, ids: &[u64]) {
for id in ids {
self.vn_capture_records.remove(id);
}
}
/// vue-native fork: whether this window's renderer keeps snapshots
/// ([`Window::vn_with_capture`]).
pub fn vn_supports_snapshots(&self) -> bool {
self.platform_window.vn_supports_snapshots()
}
fn vn_settle_captures(&mut self) {
let viewport = Bounds { origin: Point::default(), size: self.viewport_size }.scale(self.scale_factor());
let scene = &mut self.next_frame.scene;
for capture in &mut scene.vn_captures {
capture.ink = capture.ink.intersect(&viewport);
self.vn_capture_records.insert(capture.info.id, (capture.info, capture.ink));
}
let records = &self.vn_capture_records;
scene.vn_resolve_snapshots(|id| records.get(&id).copied());
}
/// Updates the global element offset relative to the current offset. This is used to implement
/// scrolling. This method should only be called during the prepaint phase of element drawing.
pub fn with_element_offset<R>(
&mut self,
offset: Point<Pixels>,
f: impl FnOnce(&mut Self) -> R,
) -> R {
self.invalidator.debug_assert_prepaint();
if offset.is_zero() {
return f(self);
};
let abs_offset = self.element_offset() + offset;
self.with_absolute_element_offset(abs_offset, f)
}
/// Updates the global element offset based on the given offset. This is used to implement
/// drag handles and other manual painting of elements. This method should only be called during
/// the prepaint phase of element drawing.
pub fn with_absolute_element_offset<R>(
&mut self,
offset: Point<Pixels>,
f: impl FnOnce(&mut Self) -> R,
) -> R {
self.invalidator.debug_assert_prepaint();
self.element_offset_stack.push(offset);
let result = f(self);
self.element_offset_stack.pop();
result
}
pub(crate) fn with_element_opacity<R>(
&mut self,
opacity: Option<f32>,
f: impl FnOnce(&mut Self) -> R,
) -> R {
self.invalidator.debug_assert_paint_or_prepaint();
let Some(opacity) = opacity else {
return f(self);
};
let previous_opacity = self.element_opacity;
self.element_opacity = previous_opacity * opacity;
let result = f(self);
self.element_opacity = previous_opacity;
result
}
/// vue-native fork: every image [`Window::paint_image`] paints inside `f`
/// is tinted with `tint`: its pixels take the colour by the colour's alpha,
/// keeping their own alpha. In straight alpha that is
/// `rgb = mix(rgb, tint.rgb, tint.a)`, `a = a`, which is a canvas filling
/// the image with `tint` in `source-atop`. A transparent `tint` (the value
/// outside any scope) leaves an image as it is; an opaque one paints the
/// image's alpha in that colour, a monochrome emoji in `currentColor`.
///
/// The tile is the same one an untinted paint samples: tinting costs no
/// upload, and two tints of one image share it.
pub fn with_image_tint<R>(&mut self, tint: Hsla, f: impl FnOnce(&mut Self) -> R) -> R {
self.invalidator.debug_assert_paint_or_prepaint();
let previous = std::mem::replace(&mut self.element_image_tint, tint);
let result = f(self);
self.element_image_tint = previous;
result
}
/// Paints everything `f` paints — this element's own quads, shadows, text
/// and its whole subtree — through `transformation`, which is composed on
/// top of whatever an ancestor already pushed.
///
/// This is CSS `transform`'s propagation rule: a transform applies to the
/// element's rendering and to all of its descendants, and to none of the
/// layout. Nothing here touches taffy, `bounds`, or the content mask; the
/// primitives are still emitted in layout coordinates and carry the matrix
/// for the vertex shader to apply.
///
/// Hitboxes inserted under it record the same matrix, so hit-testing
/// follows the picture (see [`Frame::hit_test`]).
///
/// The identity is free — it early-returns without touching the field.
/// Installs `transformation` as THE transform, discarding whatever is on the
/// stack, for the duration of `f`.
///
/// The deferred-draw replay needs this rather than
/// [`Window::with_element_transform`]: it re-enters a subtree that was
/// prepainted somewhere else in the tree, so the transform it has to restore
/// is absolute, not something to compose onto the current one. Same
/// reasoning as [`Window::with_absolute_element_offset`].
pub fn with_absolute_element_transform<R>(
&mut self,
transformation: TransformationMatrix,
f: impl FnOnce(&mut Self) -> R,
) -> R {
let previous = mem::replace(&mut self.element_transform, transformation);
let result = f(self);
self.element_transform = previous;
result
}
/// vue-native fork: [`Window::with_absolute_element_transform`] for the
/// opacity a deferred draw captured where it was deferred from.
fn with_absolute_element_opacity<R>(
&mut self,
opacity: f32,
f: impl FnOnce(&mut Self) -> R,
) -> R {
let previous = mem::replace(&mut self.element_opacity, opacity);
let result = f(self);
self.element_opacity = previous;
result
}
/// vue-native fork: composes `transformation` onto the current element
/// transform (the child's own transform applied first) for the duration of
/// `f`. A unit transform is free.
pub fn with_element_transform<R>(
&mut self,
transformation: TransformationMatrix,
f: impl FnOnce(&mut Self) -> R,
) -> R {
if transformation.is_unit() {
return f(self);
}
let previous = self.element_transform;
// `compose(other)` applies `other` first: the child's own transform
// runs before the ancestors' — which is what nesting means.
self.element_transform = previous.compose(transformation);
let result = f(self);
self.element_transform = previous;
result
}
/// The current content mask, expressed in the frame the CALLER is drawing in
/// — i.e. mapped BACK through the CSS `transform` in force.
///
/// Painting code computes a primitive's rectangle in the element's own,
/// untransformed space (the shader is what applies the matrix), while
/// [`Window::content_mask`] is a window-space rect. Anything that decides
/// whether to emit a primitive at all by comparing the two has to bring
/// them into one frame first, and this is the cheap end to move.
///
/// A singular matrix (`scale(0)`) has no inverse; the element is drawn to
/// nothing, so the mask is empty and everything is culled.
pub fn content_mask_in_element_space(&self) -> ContentMask<Pixels> {
let mask = self.content_mask();
if self.element_transform.is_unit() {
return mask;
}
match self.element_transform.inverse() {
Some(inverse) => transform_mask(inverse, mask, self.scale_factor),
None => ContentMask::rect(Bounds::default()),
}
}
/// The composed transform of the element currently being painted. Identity
/// unless an ancestor pushed one with [`Window::with_element_transform`].
#[inline]
pub fn element_transform(&self) -> TransformationMatrix {
self.element_transform
}
/// Perform prepaint on child elements in a "retryable" manner, so that any side effects
/// of prepaints can be discarded before prepainting again. This is used to support autoscroll
/// where we need to prepaint children to detect the autoscroll bounds, then adjust the
/// element offset and prepaint again. See [`crate::List`] for an example. This method should only be
/// called during the prepaint phase of element drawing.
pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
self.invalidator.debug_assert_prepaint();
let index = self.prepaint_index();
let result = f(self);
if result.is_err() {
self.next_frame.hitboxes.truncate(index.hitboxes_index);
// vue-native fork: the tagged boxes (and picks) of the attempt go
// with its hitboxes, or a retried prepaint records them twice.
self.next_frame
.vn_tagged_hitboxes
.truncate(index.vn_tagged_hitboxes_index);
self.next_frame
.tooltip_requests
.truncate(index.tooltips_index);
self.next_frame
.deferred_draws
.truncate(index.deferred_draws_index);
self.next_frame
.dispatch_tree
.truncate(index.dispatch_tree_index);
self.next_frame
.accessed_element_states
.truncate(index.accessed_element_states_index);
self.text_system.truncate_layouts(index.line_layout_index);
}
result
}
/// When you call this method during [`Element::prepaint`], containing elements will attempt to
/// scroll to cause the specified bounds to become visible. When they decide to autoscroll, they will call
/// [`Element::prepaint`] again with a new set of bounds. See [`crate::List`] for an example of an element
/// that supports this method being called on the elements it contains. This method should only be
/// called during the prepaint phase of element drawing.
pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
self.invalidator.debug_assert_prepaint();
self.requested_autoscroll = Some(bounds);
}
/// This method can be called from a containing element such as [`crate::List`] to support the autoscroll behavior
/// described in [`Self::request_autoscroll`].
pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
self.invalidator.debug_assert_prepaint();
self.requested_autoscroll.take()
}
/// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
/// Your view will be re-drawn once the asset has finished loading.
///
/// Note that the multiple calls to this method will only result in one `Asset::load` call at a
/// time.
pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
cx.asset_entry::<A>(source).use_by(self.current_view())
}
/// Asynchronously load an asset, if the asset hasn't finished loading or doesn't exist this will return None.
/// Your view will not be re-drawn once the asset has finished loading.
///
/// Note that the multiple calls to this method will only result in one `Asset::load` call at a
/// time.
pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
cx.fetch_asset::<A>(source)
}
/// Obtain the current element offset. This method should only be called during the
/// prepaint phase of element drawing.
pub fn element_offset(&self) -> Point<Pixels> {
self.invalidator.debug_assert_prepaint();
self.element_offset_stack
.last()
.copied()
.unwrap_or_default()
}
/// Obtain the current element opacity. This method should only be called during the
/// prepaint phase of element drawing.
#[inline]
pub(crate) fn element_opacity(&self) -> f32 {
self.invalidator.debug_assert_paint_or_prepaint();
self.element_opacity
}
/// Obtain the current content mask. This method should only be called during element drawing.
pub fn content_mask(&self) -> ContentMask<Pixels> {
self.invalidator.debug_assert_paint_or_prepaint();
self.content_mask_stack
.last()
.cloned()
.unwrap_or_else(|| {
ContentMask::rect(Bounds {
origin: Point::default(),
size: self.viewport_size,
})
})
}
/// Provide elements in the called function with a new namespace in which their identifiers must be unique.
/// This can be used within a custom element to distinguish multiple sets of child elements.
pub fn with_element_namespace<R>(
&mut self,
element_id: impl Into<ElementId>,
f: impl FnOnce(&mut Self) -> R,
) -> R {
self.element_id_stack.push(element_id.into());
let result = f(self);
self.element_id_stack.pop();
result
}
/// Use a piece of state that exists as long this element is being rendered in consecutive frames.
pub fn use_keyed_state<S: 'static>(
&mut self,
key: impl Into<ElementId>,
cx: &mut App,
init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
) -> Entity<S> {
let current_view = self.current_view();
self.with_global_id(key.into(), |global_id, window| {
window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
if let Some(state) = state {
(state.clone(), state)
} else {
let new_state = cx.new(|cx| init(window, cx));
Self::observe_keyed_state(&new_state, current_view, cx);
(new_state.clone(), new_state)
}
})
})
}
/// Use a piece of state that exists as long this element is being rendered in consecutive frames, without needing to specify a key
///
/// NOTE: This method uses the location of the caller to generate an ID for this state.
/// If this is not sufficient to identify your state (e.g. you're rendering a list item),
/// you can provide a custom ElementID using the `use_keyed_state` method.
#[track_caller]
pub fn use_state<S: 'static>(
&mut self,
cx: &mut App,
init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
) -> Entity<S> {
self.use_keyed_state(
ElementId::CodeLocation(*core::panic::Location::caller()),
cx,
init,
)
}
/// Updates or initializes state for an element with the given id that lives across multiple
/// frames. If an element with this ID existed in the rendered frame, its state will be passed
/// to the given closure. The state returned by the closure will be stored so it can be referenced
/// when drawing the next frame. This method should only be called as part of element drawing.
#[inline(always)]
pub fn with_element_state<S, R>(
&mut self,
global_id: &GlobalElementId,
f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
) -> R
where
S: 'static,
{
self.invalidator.debug_assert_paint_or_prepaint();
let (key, state) = self.take_element_state(global_id, TypeId::of::<S>());
if let Some(any) = state {
let ElementStateBox {
inner,
#[cfg(debug_assertions)]
type_name,
} = any;
// Using the extra inner option to avoid needing to reallocate a new box.
let mut state_box = inner
.downcast::<Option<S>>()
.map_err(|_| {
#[cfg(debug_assertions)]
{
anyhow::anyhow!(
"invalid element state type for id, requested {:?}, actual: {:?}",
std::any::type_name::<S>(),
type_name
)
}
#[cfg(not(debug_assertions))]
{
anyhow::anyhow!(
"invalid element state type for id, requested {:?}",
std::any::type_name::<S>(),
)
}
})
.unwrap();
let state = state_box.take().expect(
"reentrant call to with_element_state for the same state type and element id",
);
let (result, state) = f(Some(state), self);
state_box.replace(state);
self.insert_element_state(
key,
ElementStateBox {
inner: state_box,
#[cfg(debug_assertions)]
type_name,
},
);
result
} else {
let (result, state) = f(None, self);
self.insert_element_state(
key,
ElementStateBox {
inner: Box::new(Some(state)),
#[cfg(debug_assertions)]
type_name: std::any::type_name::<S>(),
},
);
result
}
}
/// A variant of `with_element_state` that allows the element's id to be optional. This is a convenience
/// method for elements where the element id may or may not be assigned. Prefer using `with_element_state`
/// when the element is guaranteed to have an id.
///
/// The first option means 'no ID provided'
/// The second option means 'not yet initialized'
pub fn with_optional_element_state<S, R>(
&mut self,
global_id: Option<&GlobalElementId>,
f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
) -> R
where
S: 'static,
{
self.invalidator.debug_assert_paint_or_prepaint();
if let Some(global_id) = global_id {
self.with_element_state(global_id, |state, cx| {
let (result, state) = f(Some(state), cx);
let state =
state.expect("you must return some state when you pass some element id");
(result, state)
})
} else {
let (result, state) = f(None, self);
debug_assert!(
state.is_none(),
"you must not return an element state when passing None for the global id"
);
result
}
}
/// Executes the given closure within the context of a tab group.
#[inline]
pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
if let Some(index) = index {
self.next_frame.tab_stops.begin_group(index);
let result = f(self);
self.next_frame.tab_stops.end_group();
result
} else {
f(self)
}
}
/// Defers the drawing of the given element, scheduling it to be painted on top of the currently-drawn tree
/// at a later time. The `priority` parameter determines the drawing order relative to other deferred elements,
/// with higher values being drawn on top.
///
/// When `content_mask` is provided, the deferred element will be clipped to that region during
/// both prepaint and paint. When `None`, no additional clipping is applied.
///
/// This method should only be called as part of the prepaint phase of element drawing.
pub fn defer_draw(
&mut self,
element: AnyElement,
absolute_offset: Point<Pixels>,
priority: usize,
content_mask: Option<ContentMask<Pixels>>,
) {
self.defer_draw_with_stack_key(element, absolute_offset, priority, content_mask, None)
}
/// vue-native fork: [`Window::defer_draw`], sorted among draws of equal
/// `priority` by `stack_key` (see [`crate::Deferred::with_stack_key`]).
pub fn defer_draw_with_stack_key(
&mut self,
element: AnyElement,
absolute_offset: Point<Pixels>,
priority: usize,
content_mask: Option<ContentMask<Pixels>>,
stack_key: Option<Rc<[u128]>>,
) {
self.invalidator.debug_assert_prepaint();
let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
self.next_frame.deferred_draws.push(DeferredDraw {
current_view: self.current_view(),
parent_node,
element_id_stack: self.element_id_stack.clone(),
text_style_stack: self.text_style_stack.clone(),
content_mask,
rem_size: self.rem_size(),
priority,
element: Some(element),
absolute_offset,
element_transform: self.element_transform,
a11y_parent: self
.a11y
.is_active()
.then(|| self.a11y.nodes.current_id()),
vn_stack: stack_key,
element_opacity: self.element_opacity,
vn_clip: if content_mask.is_some() {
self.vn_clip_stack.clone()
} else {
crate::VnClipNode::color_filters(&self.vn_clip_stack)
},
vn_scope: self.vn_defer_scope.clone(),
prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
paint_range: PaintIndex::default()..PaintIndex::default(),
accessed_entities: FxHashSet::default(),
});
}
/// Creates a new painting layer. A "layer" is a batch of geometry that are
/// non-overlapping and have the same draw order. This is typically used
/// for performance reasons.
///
/// Layers painted inside `f` are drawn above this layer, including above
/// what `f` paints after them.
///
/// This method should only be called as part of the paint phase of element drawing.
pub fn paint_layer<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
self.invalidator.debug_assert_paint();
self.next_frame.scene.push_layer();
let result = f(self);
self.next_frame.scene.pop_layer();
result
}
/// Paint the drop (non-inset) shadows from `shadows` into the scene at the current
/// z-index. Inset shadows are skipped; paint those with [`Self::paint_inset_shadows`]
/// after the element's background so they layer on top of the fill.
///
/// This method should only be called as part of the paint phase of element drawing.
///
/// vue-native fork: a drop shadow is drawn outside the element's border box
/// only, as CSS clips an outer `box-shadow` (CSS Backgrounds 3 §7.1). So a
/// translucent background shows what is behind the element, not the
/// shadow; a focus ring (`0 0 0 3px`) on a transparent control is a ring.
pub fn paint_drop_shadows(
&mut self,
bounds: Bounds<Pixels>,
corner_radii: Corners<Pixels>,
shadows: &[BoxShadow],
) {
self.paint_outer_shadows(bounds, corner_radii, Corners::default(), shadows, SHADOW_OUTSIDE_BOX);
}
/// vue-native fork: [`Self::paint_drop_shadows`] without the cut-out: the
/// shadow also fills the area under the border box. For a shadow that
/// stands in for the element's own painting ([`Style::vn_shadow_under_box`]).
pub fn paint_drop_shadows_under_box(
&mut self,
bounds: Bounds<Pixels>,
corner_radii: Corners<Pixels>,
shadows: &[BoxShadow],
) {
self.paint_outer_shadows(bounds, corner_radii, Corners::default(), shadows, SHADOW_UNDER_BOX);
}
/// vue-native fork: [`Self::paint_drop_shadows`] (or, with `under_box`,
/// [`Self::paint_drop_shadows_under_box`]) for a box with CSS `corner-shape`.
pub fn vn_paint_drop_shadows(
&mut self,
bounds: Bounds<Pixels>,
corner_radii: Corners<Pixels>,
corner_shapes: Corners<CornerShape>,
shadows: &[BoxShadow],
under_box: bool,
) {
let kind = if under_box { SHADOW_UNDER_BOX } else { SHADOW_OUTSIDE_BOX };
self.paint_outer_shadows(bounds, corner_radii, corner_shapes, shadows, kind);
}
fn paint_outer_shadows(
&mut self,
bounds: Bounds<Pixels>,
corner_radii: Corners<Pixels>,
corner_shapes: Corners<CornerShape>,
shadows: &[BoxShadow],
kind: u32,
) {
self.invalidator.debug_assert_paint();
let scale_factor = self.scale_factor();
let content_mask = self.snapped_content_mask();
let opacity = self.element_opacity();
let element_bounds = self.cover_bounds(bounds);
let element_corner_radii = corner_radii.scale(scale_factor);
for shadow in shadows {
if shadow.inset {
continue;
}
let shape_bounds =
self.cover_bounds((bounds + shadow.offset).dilate(shadow.spread_radius));
if shape_bounds.is_empty() {
continue;
}
let blur_radius = shadow.blur_radius.scale(scale_factor);
let spread = shadow.spread_radius;
let shadow_radius = |r: Pixels| spread_shadow_radius(r, spread);
let shadow_corner_radii = Corners {
top_left: shadow_radius(corner_radii.top_left),
top_right: shadow_radius(corner_radii.top_right),
bottom_right: shadow_radius(corner_radii.bottom_right),
bottom_left: shadow_radius(corner_radii.bottom_left),
};
self.next_frame.scene.insert_primitive(Shadow {
order: 0,
blur_radius,
// Leave room for the tail of the blur.
bounds: shape_bounds.dilate(blur_radius * 3.),
content_mask,
corner_radii: element_corner_radii,
color: shadow.color.opacity(opacity),
shape_bounds,
shape_corner_radii: shadow_corner_radii.scale(scale_factor),
inset: kind,
pad: 0,
transformation: self.element_transform,
element_bounds,
corner_shapes: CornerShapes::new(&corner_shapes),
});
}
}
/// Paint the inset shadows from `shadows` into the scene at the current z-index. Should
/// be called after the element's background so the shadow layers on top of the fill.
/// Drop shadows are skipped; paint those with [`Self::paint_drop_shadows`] before the background.
pub fn paint_inset_shadows(
&mut self,
bounds: Bounds<Pixels>,
corner_radii: Corners<Pixels>,
shadows: &[BoxShadow],
) {
self.vn_paint_inset_shadows(bounds, corner_radii, Corners::default(), shadows);
}
/// vue-native fork: [`Self::paint_inset_shadows`] for a box with CSS `corner-shape`. A
/// shaped corner's hole is the inner edge of a border as wide as the spread (css-borders-4
/// §3.9.4), not the corner shrunk by it.
pub fn vn_paint_inset_shadows(
&mut self,
bounds: Bounds<Pixels>,
corner_radii: Corners<Pixels>,
corner_shapes: Corners<CornerShape>,
shadows: &[BoxShadow],
) {
self.invalidator.debug_assert_paint();
let scale_factor = self.scale_factor();
let content_mask = self.snapped_content_mask();
let opacity = self.element_opacity();
let element_bounds = self.cover_bounds(bounds);
let element_corner_radii = corner_radii.scale(scale_factor);
for shadow in shadows {
if !shadow.inset {
continue;
}
let hole = (bounds + shadow.offset).dilate(-shadow.spread_radius);
// Clamp at zero so a large spread can't produce negative radii, which would
// break the SDF in the shader.
let zero = Pixels::ZERO;
let spread = shadow.spread_radius;
let hole_radius = |radius: Pixels, shape: CornerShape| {
if shape.is_round() || spread <= zero { (radius - spread).max(zero) } else { radius }
};
let hole_corner_radii = Corners {
top_left: hole_radius(corner_radii.top_left, corner_shapes.top_left),
top_right: hole_radius(corner_radii.top_right, corner_shapes.top_right),
bottom_right: hole_radius(corner_radii.bottom_right, corner_shapes.bottom_right),
bottom_left: hole_radius(corner_radii.bottom_left, corner_shapes.bottom_left),
};
let inset = f32::from(spread.max(zero)) * scale_factor;
self.next_frame.scene.insert_primitive(Shadow {
order: 0,
blur_radius: shadow.blur_radius.scale(scale_factor),
bounds: element_bounds,
content_mask,
corner_radii: element_corner_radii,
color: shadow.color.opacity(opacity),
shape_bounds: self.cover_bounds(hole),
shape_corner_radii: hole_corner_radii.scale(scale_factor),
inset: SHADOW_INSET,
pad: 0,
transformation: self.element_transform,
element_bounds,
corner_shapes: CornerShapes::new(&corner_shapes)
.with_insets(Corners {
top_left: (inset, inset),
top_right: (inset, inset),
bottom_right: (inset, inset),
bottom_left: (inset, inset),
}),
});
}
}
fn largest_border_interior(quad: &Quad) -> Bounds<ScaledPixels> {
let size = quad.bounds.size;
let diagonal = (size.width.0 * size.width.0 + size.height.0 * size.height.0).sqrt();
if diagonal == 0. {
return Bounds::default();
}
// The interior's corners sit on the corner arcs. Taking the angle along
// the arc whose tangent is the quad's aspect ratio stays within 1% of
// the largest interior.
let cos = size.height.0 / diagonal;
let sin = size.width.0 / diagonal;
// A corner's inner border edge is a quarter ellipse around the
// corner's center, with the border widths taken off its radius.
let corner_inset = |radius: ScaledPixels, width_x: ScaledPixels, width_y: ScaledPixels| {
point(
width_x.max(radius - (radius - width_x) * cos),
width_y.max(radius - (radius - width_y) * sin),
)
};
let radii = &quad.corner_radii;
let widths = &quad.border_widths;
let top_left = corner_inset(radii.top_left, widths.left, widths.top);
let top_right = corner_inset(radii.top_right, widths.right, widths.top);
let bottom_right = corner_inset(radii.bottom_right, widths.right, widths.bottom);
let bottom_left = corner_inset(radii.bottom_left, widths.left, widths.bottom);
let antialias_inset = point(ScaledPixels(1.0), ScaledPixels(1.0));
Bounds::from_corners(
quad.bounds.origin
+ point(top_left.x.max(bottom_left.x), top_left.y.max(top_right.y))
+ antialias_inset,
quad.bounds.bottom_right()
- point(
top_right.x.max(bottom_right.x),
bottom_left.y.max(bottom_right.y),
)
- antialias_inset,
)
}
/// Paint one or more quads into the scene for the next frame at the current stacking context.
/// Quads are colored rectangular regions with an optional background, border, and corner radius.
/// see [`fill`], [`outline`], and [`quad`] to construct this type.
///
/// This method should only be called as part of the paint phase of element drawing.
///
/// Note that the `quad.corner_radii` are allowed to exceed the bounds, creating sharp corners
/// where the circular arcs meet. This will not display well when combined with dashed borders.
/// Use `Corners::clamp_radii_for_quad_size` if the radii should fit within the bounds.
pub fn paint_quad(&mut self, quad: PaintQuad) {
self.invalidator.debug_assert_paint();
let opacity = self.element_opacity();
let snapped_bounds = self.snap_bounds(quad.bounds);
let snapped_border_widths = self.snap_border_widths(quad.border_widths);
let quad = Quad {
order: 0,
bounds: snapped_bounds,
content_mask: self.snapped_content_mask(),
background: quad.background.opacity(opacity),
border_color: quad.border_color.opacity(opacity),
corner_radii: quad.corner_radii.scale(self.scale_factor()),
border_widths: snapped_border_widths,
border_style: quad.border_style,
transformation: self.element_transform,
corner_shapes: CornerShapes::new(&quad.corner_shapes),
};
self.insert_quad(quad);
}
fn insert_quad(&mut self, quad: Quad) {
let has_background = !quad.background.is_transparent();
let has_border =
quad.border_widths != Edges::default() && !quad.border_color.is_transparent();
if !has_background && !has_border {
return;
}
let is_rectangle =
quad.border_widths == Edges::default() && quad.corner_radii == Corners::default();
if has_background && is_rectangle {
self.next_frame.scene.insert_primitive(quad);
return;
}
// The strip split below carves the quad into AXIS-ALIGNED pieces and
// clips each with an axis-aligned content mask. Under a rotation those
// masks no longer correspond to the pieces they are clipping, so the
// optimisation is skipped rather than made wrong. (vue-native fork:
// under a rounded content mask too: a strip's mask would cut through
// the curve, and `ContentMask::intersect` squares such a corner.)
// A shaped corner reaches past the rounded interior the split assumes.
if !quad.transformation.is_unit()
|| quad.content_mask.is_rounded()
|| !quad.corner_shapes.is_round()
{
self.next_frame.scene.insert_primitive(quad);
return;
}
let plain_border = quad.corner_radii == Corners::default()
&& quad.border_style == BorderStyle::Solid
&& (!has_background || quad.border_color.is_opaque());
// Splitting off the interior leaves only the strips around it for the
// border and corner shading.
let outer_bounds = quad.bounds;
let inner_bounds = if plain_border {
quad.bounds.extend(quad.border_widths.map(|width| -*width))
} else {
Self::largest_border_interior(&quad)
};
// A plain border's strips can be plain rectangles of the border color.
// Otherwise, each strip is the whole quad masked to the strip, so the
// border, corners and gradients are still shaded relative to the full quad.
let strip_quad = if plain_border {
Quad {
background: quad.border_color.into(),
border_widths: Edges::default(),
..quad
}
} else {
quad
};
if inner_bounds.is_empty() {
self.next_frame.scene.insert_primitive(strip_quad);
return;
}
// vue-native fork: a ring background paints nothing inside the border.
if has_background && !quad.background.is_ring() {
self.next_frame.scene.insert_primitive(Quad {
content_mask: ContentMask::rect(quad.content_mask.bounds.intersect(&inner_bounds)),
border_widths: Edges::default(),
corner_radii: Corners::default(),
..quad
});
}
let strips = [
// Top
Bounds::from_corners(
outer_bounds.origin,
point(outer_bounds.right(), inner_bounds.top()),
),
// Bottom
Bounds::from_corners(
point(outer_bounds.left(), inner_bounds.bottom()),
outer_bounds.bottom_right(),
),
// Left
Bounds::from_corners(
point(outer_bounds.left(), inner_bounds.top()),
inner_bounds.bottom_left(),
),
// Right
Bounds::from_corners(
inner_bounds.top_right(),
point(outer_bounds.right(), inner_bounds.bottom()),
),
];
for strip in strips {
self.next_frame.scene.insert_primitive(Quad {
content_mask: ContentMask::rect(quad.content_mask.bounds.intersect(&strip)),
..strip_quad
});
}
}
/// Paint a backdrop blur rectangle into the scene at the current z-index.
///
/// This is the primitive behind CSS `backdrop-filter: blur()`: the pixels
/// already painted behind `bounds` are replaced with a blurred copy of
/// themselves, clipped to the rounded rect described by `corner_radii`.
///
/// The blur samples the render target as it exists at its paint position,
/// so renderers may need to break the current pass when this primitive is
/// encountered. Prefer one blur rect per glass surface rather than many
/// small ones. Renderers without backdrop blur support ignore this
/// primitive entirely, including its tint.
///
/// This method should only be called as part of the paint phase of element
/// drawing.
pub fn paint_backdrop_blur_rect(
&mut self,
bounds: Bounds<Pixels>,
corner_radii: Corners<Pixels>,
effect: BackdropBlurEffect,
) {
self.vn_paint_backdrop_blur_rect(bounds, corner_radii, Corners::default(), effect);
}
/// vue-native fork: [`Self::paint_backdrop_blur_rect`] with CSS `corner-shape`.
pub fn vn_paint_backdrop_blur_rect(
&mut self,
bounds: Bounds<Pixels>,
corner_radii: Corners<Pixels>,
corner_shapes: Corners<CornerShape>,
effect: BackdropBlurEffect,
) {
self.invalidator.debug_assert_paint();
let opacity = self.element_opacity();
if opacity <= 0. {
return;
}
let scale_factor = self.scale_factor();
let blur_radius = effect.radius.scale(scale_factor);
if blur_radius.0 <= 0. {
let tint = effect.tint.opacity(opacity);
if tint.a > 0. {
self.paint_quad(
fill(bounds, tint).corner_radii(corner_radii).corner_shapes(corner_shapes),
);
}
return;
}
// vue-native fork: the blur has no `transformation` of its own, so the
// element transform is folded into its rect — without this a popper
// positioned by `transform: translate()` blurred a ghost at its
// untransformed place. Under a rotation there is no rect to fold it
// into, and nothing is drawn rather than the ghost.
let Some((bounds, k)) =
crate::scene::axis_aligned_through(self.snap_bounds(bounds), self.element_transform)
else {
return;
};
self.next_frame.scene.insert_primitive(BackdropBlurRect {
order: 0,
pad: 0,
bounds,
content_mask: self.snapped_content_mask(),
corner_radii: corner_radii.scale(scale_factor * k),
blur_radius,
opacity,
tint: effect.tint,
corner_shapes: CornerShapes::new(&corner_shapes),
});
}
/// Paint a custom-shaded rounded rect into the scene at the current
/// z-index — the primitive behind the `--shading` CSS property.
///
/// `spec.id` selects one of the built-in fragment pipelines and `params`
/// are its positional arguments. Parameters the schema marks as lengths
/// arrive in LOGICAL pixels and are scaled here, exactly like every other
/// length in a primitive.
///
/// An effect that reads the backdrop ([`EFFECT_FLAG_NEEDS_BACKDROP`])
/// samples the render target as it exists at its paint position, so — like
/// [`Self::paint_backdrop_blur_rect`] — renderers break the current pass
/// when they meet one, and the scene forces everything painted afterwards
/// to draw above it. An effect that does not is an ordinary blended quad
/// and costs nothing extra.
///
/// Renderers without effect support (or on hardware below D3D feature
/// level 11) ignore this primitive entirely.
///
/// This method should only be called as part of the paint phase of element
/// drawing.
pub fn paint_effect_quad(
&mut self,
bounds: Bounds<Pixels>,
corner_radii: Corners<Pixels>,
spec: EffectSpec,
) {
self.vn_paint_effect(bounds, corner_radii, spec, 0);
}
/// vue-native fork: [`Self::paint_effect_quad`] for `element`
/// ([`Self::vn_take_effect_element`]), which keys an `[SkHistory]` state.
pub fn vn_paint_effect(
&mut self,
bounds: Bounds<Pixels>,
corner_radii: Corners<Pixels>,
spec: EffectSpec,
element: u64,
) {
self.vn_paint_effect_with(bounds, corner_radii, Corners::default(), spec, element, None);
}
/// vue-native: [`Self::vn_paint_effect`] with the images `spec` samples,
/// resolved through [`crate::set_effect_texture_resolver`].
pub fn vn_paint_textured_effect(
&mut self,
bounds: Bounds<Pixels>,
corner_radii: Corners<Pixels>,
corner_shapes: Corners<CornerShape>,
spec: EffectSpec,
element: u64,
cx: &mut App,
) {
let textures = crate::resolve_effect_textures(&spec, self, cx);
self.vn_paint_effect_with(bounds, corner_radii, corner_shapes, spec, element, textures);
}
fn vn_paint_effect_with(
&mut self,
bounds: Bounds<Pixels>,
corner_radii: Corners<Pixels>,
corner_shapes: Corners<CornerShape>,
spec: EffectSpec,
element: u64,
textures: Option<Arc<crate::EffectTextureSet>>,
) {
self.invalidator.debug_assert_paint();
let opacity = self.element_opacity();
let Some(mut quad) =
self.vn_effect_quad(bounds, corner_radii, corner_shapes, spec, element, opacity, textures.as_deref())
else {
return;
};
quad.flags &= !crate::EFFECT_FLAG_NEEDS_CONTENT;
let history = vn_history_key(element, &spec);
if history == 0 {
quad.flags &= !crate::EFFECT_FLAG_HISTORY;
self.next_frame
.scene
.insert_primitive(crate::Primitive::EffectQuad(quad, textures));
return;
}
let content_mask = quad.content_mask;
self.next_frame.scene.vn_push_effect(crate::VnEffectPaint {
draws: vec![crate::VnEffectDraw {
quad,
history,
textures,
}],
content: false,
content_mask,
});
self.next_frame.scene.vn_pop_isolation();
}
/// vue-native fork: names the element whose style paints next
/// ([`Self::vn_take_effect_element`]).
pub fn vn_set_effect_element(&mut self, id: Option<&GlobalElementId>) {
self.vn_effect_element = vn_element_key(id);
}
/// vue-native fork: the element [`Self::vn_set_effect_element`] named, 0
/// for none; taken, so a child without an identity does not inherit it.
pub fn vn_take_effect_element(&mut self) -> u64 {
mem::take(&mut self.vn_effect_element)
}
/// vue-native fork: paints `f` into an isolated group at full opacity, which
/// the `[SkContent]` effects among `effects` composite in its place; the
/// opacity share none of them takes composites the group as it is.
#[allow(clippy::too_many_arguments)]
pub fn vn_with_effect_content<R>(
&mut self,
bounds: Bounds<Pixels>,
corner_radii: Corners<Pixels>,
corner_shapes: Corners<CornerShape>,
effects: &[(EffectSpec, f32, Option<Arc<crate::EffectTextureSet>>)],
element: u64,
cx: &mut App,
f: impl FnOnce(&mut Self, &mut App) -> R,
) -> R {
let opacity = self.element_opacity();
if !self.invalidator.is_painting() || opacity <= 0. {
return f(self, cx);
}
let mut draws = Vec::new();
let mut plain = 1.;
for (spec, weight, textures) in effects {
if spec.flags & crate::EFFECT_FLAG_NEEDS_CONTENT == 0 || *weight <= 0. {
continue;
}
let Some(mut quad) = self.vn_effect_quad(
bounds,
corner_radii,
corner_shapes,
*spec,
element,
opacity * weight,
textures.as_deref(),
) else {
continue;
};
let history = vn_history_key(element, spec);
if history == 0 {
quad.flags &= !crate::EFFECT_FLAG_HISTORY;
}
plain -= weight;
draws.push(crate::VnEffectDraw {
quad,
history,
textures: textures.clone(),
});
}
let content_mask = self.snapped_content_mask();
if plain > 1e-3 {
draws.insert(
0,
crate::VnEffectDraw {
quad: EffectQuad {
effect_id: crate::effect_id::CONTENT,
bounds: content_mask.bounds,
content_mask,
opacity: opacity * plain.min(1.),
scale: self.scale_factor(),
flags: crate::EFFECT_FLAG_NEEDS_CONTENT,
..Default::default()
},
history: 0,
textures: None,
},
);
}
self.next_frame.scene.vn_push_effect(crate::VnEffectPaint {
draws,
content: true,
content_mask,
});
let outer = mem::replace(&mut self.element_opacity, 1.);
let result = f(self, cx);
self.vn_paint_scope(element, opacity, cx);
self.element_opacity = outer;
self.next_frame.scene.vn_pop_isolation();
result
}
/// The quad `spec` draws over `bounds` at `opacity`, None when it draws
/// nothing; asks for the next frame while it animates.
#[allow(clippy::too_many_arguments)]
fn vn_effect_quad(
&mut self,
bounds: Bounds<Pixels>,
corner_radii: Corners<Pixels>,
corner_shapes: Corners<CornerShape>,
spec: EffectSpec,
element: u64,
opacity: f32,
textures: Option<&crate::EffectTextureSet>,
) -> Option<EffectQuad> {
if !spec.is_some() || opacity <= 0. {
return None;
}
let scale_factor = self.scale_factor();
let bleed = px(spec.bleed());
// An outer glow needs somewhere to land, so the drawn quad is the
// border box dilated by `bleed` — with the corner radii dilated to
// match, which keeps the dilated shape a true Minkowski offset and
// therefore keeps the SDF relationship the shader relies on exact.
let draw_bounds = bounds.dilate(bleed);
let draw_radii = Corners {
top_left: corner_radii.top_left + bleed,
top_right: corner_radii.top_right + bleed,
bottom_right: corner_radii.bottom_right + bleed,
bottom_left: corner_radii.bottom_left + bleed,
};
let mut params = spec.params;
for (index, param) in params.iter_mut().enumerate() {
if spec.length_mask & (1 << index) != 0 {
*param *= scale_factor;
}
}
crate::write_effect_texture_sizes(&spec, textures, &mut params);
// vue-native fork: as for the backdrop blur — no `transformation`
// field, so the element transform is folded into the rect, and a
// rotated effect is not drawn rather than drawn unrotated elsewhere.
let Some((draw_bounds, k)) = crate::scene::axis_aligned_through(
self.snap_bounds(draw_bounds),
self.element_transform,
) else {
return None;
};
let bleed = bleed.scale(scale_factor);
let now = crate::effect_clock_seconds();
if let Some(slot) = spec.pointer_param.map(usize::from)
&& slot + 2 <= params.len()
{
// The element box as the shader recovers it from the drawn quad.
let origin = draw_bounds.origin.map(|c| c.0 + bleed.0);
let size = draw_bounds.size.map(|c| (c.0 - 2. * bleed.0).max(1.));
let pointer = self.mouse_position.map(|c| c.0 * scale_factor);
params[slot] = (pointer.x - origin.x) / size.width;
params[slot + 1] = (pointer.y - origin.y) / size.height;
}
if let Some(slot) = spec.pointer_times_param.map(usize::from)
&& slot + 3 <= params.len()
{
let times = &self.vn_effect_pointer;
params[slot..slot + 3].copy_from_slice(&[times.moved, times.entered, times.left]);
}
if spec.follows_pointer() {
let view = self.current_view();
self.vn_effect_pointer.views.insert(view);
}
if let Some(slot) = spec.animated_param.map(usize::from)
&& slot < params.len()
&& element != 0
{
let key = vn_phase_key(element, &spec);
let previous = self.vn_effect_phases.get(&key).copied();
let phase = VnEffectPhase::advance(previous, params[slot], now);
self.vn_effect_phases.insert(key, phase);
if let Some(speed) = phase.speed(now) {
params[slot] = speed;
}
}
let mut clocked = spec;
clocked.params = params;
if spec.animated || clocked.clock_running(now) {
// Nothing else in the frame is going to ask for the next one.
self.request_animation_frame();
}
Some(EffectQuad {
order: 0,
effect_id: spec.id,
bounds: draw_bounds,
content_mask: self.snapped_content_mask(),
corner_radii: draw_radii.scale(scale_factor * k),
params,
opacity,
time: now,
bleed,
backdrop_blur_radius: px(spec.backdrop_blur_radius()).scale(scale_factor),
scale: scale_factor,
flags: spec.flags,
corner_shapes: CornerShapes::new(&corner_shapes),
})
}
/// vue-native: makes `bounds` (rounded by `corner_radii`) transparent in
/// this window's surface, erasing what was painted there so far; what is
/// painted after it draws over the hole as usual. The window has to
/// present with alpha for anything to show through (on Windows,
/// DirectComposition: `Window::vn_composition_underlay`).
///
/// This method should only be called as part of the paint phase of element
/// drawing.
pub fn vn_paint_punch(&mut self, bounds: Bounds<Pixels>, corner_radii: Corners<Pixels>) {
self.invalidator.debug_assert_paint();
let opacity = self.element_opacity();
if opacity <= 0. {
return;
}
let scale_factor = self.scale_factor();
// No `transformation` field, as for the effects: a rotated box is not
// punched rather than punched somewhere else.
let Some((draw_bounds, k)) =
crate::scene::axis_aligned_through(self.snap_bounds(bounds), self.element_transform)
else {
return;
};
self.next_frame.scene.insert_primitive(EffectQuad {
order: 0,
effect_id: crate::effect_id::PUNCH,
bounds: draw_bounds,
content_mask: self.snapped_content_mask(),
corner_radii: corner_radii.scale(scale_factor * k),
params: [0.; crate::EFFECT_PARAM_SLOTS],
opacity,
time: 0.,
bleed: ScaledPixels(0.),
backdrop_blur_radius: ScaledPixels(0.),
scale: scale_factor,
flags: 0,
corner_shapes: CornerShapes::default(),
});
}
/// Paint the given `Path` into the scene for the next frame at the current z-index.
///
/// This method should only be called as part of the paint phase of element drawing.
pub fn paint_path(&mut self, path: Path, color: impl Into<Background>) {
self.invalidator.debug_assert_paint();
let scale_factor = self.scale_factor();
let content_mask = self.content_mask();
let opacity = self.element_opacity();
let color: Background = color.into();
// vue-native fork: every other primitive carries `element_transform`;
// a path painted under one (a `<select>`'s chevron in a dialog centred
// with `translate(-50%, -50%)`) stayed at its layout position, and was
// culled against a content mask that is already in window space.
let path = if self.element_transform.is_unit() {
path
} else {
path.transformed(self.element_transform, scale_factor)
};
self.next_frame.scene.insert_primitive(PaintedPath::new(
path,
scale_factor,
content_mask,
color.opacity(opacity),
));
}
/// Paint an underline into the scene for the next frame at the current z-index.
///
/// This method should only be called as part of the paint phase of element drawing.
pub fn paint_underline(
&mut self,
origin: Point<Pixels>,
width: Pixels,
style: &UnderlineStyle,
) {
self.invalidator.debug_assert_paint();
// vue-native fork: `Self::underline` carries `element_transform`.
let underline = self.underline(origin, width, style);
self.next_frame.scene.insert_primitive(underline);
}
/// Paint a strikethrough into the scene for the next frame at the current z-index.
///
/// This method should only be called as part of the paint phase of element drawing.
pub fn paint_strikethrough(
&mut self,
origin: Point<Pixels>,
width: Pixels,
style: &StrikethroughStyle,
) {
self.invalidator.debug_assert_paint();
let scale_factor = self.scale_factor();
let height = style.thickness;
let bounds = Bounds {
origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
size: size(self.snap_stroke(width), self.snap_stroke(height)),
};
let opacity = self.element_opacity();
self.next_frame.scene.insert_primitive(Underline {
order: 0,
pad: 0,
bounds,
content_mask: self.snapped_content_mask(),
thickness: self.snap_stroke(style.thickness),
color: style.color.unwrap_or_default().opacity(opacity),
wavy: false.into(),
transformation: self.element_transform,
});
}
/// Paints a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
///
/// The y component of the origin is the baseline of the glyph.
/// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
/// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
/// This method is only useful if you need to paint a single glyph that has already been shaped.
///
/// This method should only be called as part of the paint phase of element drawing.
pub fn paint_glyph(
&mut self,
origin: Point<Pixels>,
font_id: FontId,
glyph_id: GlyphId,
font_size: Pixels,
color: Hsla,
) -> Result<()> {
self.invalidator.debug_assert_paint();
let element_opacity = self.element_opacity();
let scale_factor = self.scale_factor();
let glyph_origin = origin.scale(scale_factor);
let quantized_origin = Point::new(
round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32)
/ SUBPIXEL_VARIANTS_X as f32,
round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32)
/ SUBPIXEL_VARIANTS_Y as f32,
);
let subpixel_variant = Point::new(
(quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8,
(quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8,
);
let integer_origin = quantized_origin.map(|c| ScaledPixels(c.trunc()));
let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
let dilation = self.text_system().glyph_dilation_for_color(color);
let params = RenderGlyphParams {
font_id,
glyph_id,
font_size,
subpixel_variant,
scale_factor,
is_emoji: false,
subpixel_rendering,
dilation,
};
let raster_bounds = self.text_system().raster_bounds(¶ms)?;
if !raster_bounds.is_zero() {
let tile = self
.sprite_atlas
.get_or_insert_with(params.clone().into(), &mut || {
let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
Ok(Some((size, Cow::Owned(bytes))))
})?
.expect("Callback above only errors or returns Some");
let bounds = Bounds {
origin: integer_origin + raster_bounds.origin.map(Into::into),
size: tile.bounds.size.map(Into::into),
};
let content_mask = self.snapped_content_mask();
if subpixel_rendering {
self.next_frame.scene.insert_primitive(SubpixelSprite {
order: 0,
pad: 0,
bounds,
content_mask,
color: color.opacity(element_opacity),
tile,
transformation: self.element_transform,
});
} else {
self.next_frame.scene.insert_primitive(MonochromeSprite {
order: 0,
raw_coverage: false.into(),
animation: SpriteAnimationId::NONE,
pad: 0,
bounds,
content_mask,
color: color.opacity(element_opacity),
tile,
transformation: self.element_transform,
});
}
}
Ok(())
}
/// vue-native fork: paints a glyph's CSS `text-shadow`, its coverage in `color` blurred by
/// `blur_radius`. `origin` is the shadow's baseline origin, offset included.
pub fn paint_glyph_shadow(
&mut self,
origin: Point<Pixels>,
font_id: FontId,
glyph_id: GlyphId,
font_size: Pixels,
is_emoji: bool,
color: Hsla,
blur_radius: Pixels,
) -> Result<()> {
self.invalidator.debug_assert_paint();
if blur_radius <= px(0.) && !is_emoji {
return self.paint_glyph(origin, font_id, glyph_id, font_size, color);
}
let scale_factor = self.scale_factor();
let glyph_origin = origin.scale(scale_factor);
let (integer_origin, subpixel_variant) = if is_emoji {
(
glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0))),
Point::default(),
)
} else {
let quantized_origin = Point::new(
round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32)
/ SUBPIXEL_VARIANTS_X as f32,
round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32)
/ SUBPIXEL_VARIANTS_Y as f32,
);
(
quantized_origin.map(|c| ScaledPixels(c.trunc())),
Point::new(
(quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8,
(quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8,
),
)
};
let glyph = RenderGlyphParams {
font_id,
glyph_id,
font_size,
subpixel_variant,
scale_factor,
is_emoji,
subpixel_rendering: false,
dilation: if is_emoji {
0
} else {
self.text_system().glyph_dilation_for_color(color)
},
};
let raster_bounds = self.text_system().raster_bounds(&glyph)?;
if raster_bounds.is_zero() {
return Ok(());
}
let params = GlyphShadowParams {
sigma_quarters: GlyphShadowParams::quantize_sigma(blur_radius.0 / 2. * scale_factor),
glyph,
};
let padding = params.padding();
let sigma = params.sigma();
let Some(tile) = self.sprite_atlas.get_or_insert_with(
AtlasKey::GlyphShadow(params.clone()),
&mut || {
let (size, coverage) = self.text_system().rasterize_glyph(¶ms.glyph)?;
let (size, blurred) = blur_glyph_coverage(size, &coverage, sigma);
Ok(Some((size, Cow::Owned(blurred))))
},
)?
else {
return Ok(());
};
let bounds = Bounds {
origin: integer_origin
+ raster_bounds.origin.map(Into::into)
- point(ScaledPixels(padding as f32), ScaledPixels(padding as f32)),
size: tile.bounds.size.map(Into::into),
};
let content_mask = self.snapped_content_mask();
self.next_frame.scene.insert_primitive(MonochromeSprite {
order: 0,
raw_coverage: true.into(),
animation: SpriteAnimationId::NONE,
pad: 0,
bounds,
content_mask,
color: color.opacity(self.element_opacity()),
tile,
transformation: self.element_transform,
});
Ok(())
}
fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
// Checked first because it's cheap, while some platforms lock the window to read its
// background appearance, and this runs for every glyph.
if !self.platform_window.is_subpixel_rendering_supported() {
return false;
}
// vue-native fork: an isolated layer starts transparent, and
// subpixel text has no alpha of its own to composite it with
// (Chromium too draws grayscale text into a layer that is not opaque).
if self.next_frame.scene.vn_is_isolating() {
return false;
}
if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
return false;
}
let mode = match self.text_rendering_mode.get() {
TextRenderingMode::PlatformDefault => self
.text_system()
.recommended_rendering_mode(font_id, font_size),
mode => mode,
};
mode == TextRenderingMode::Subpixel
}
/// Paints an emoji glyph into the scene for the next frame at the current z-index.
///
/// The y component of the origin is the baseline of the glyph.
/// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
/// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
/// This method is only useful if you need to paint a single emoji that has already been shaped.
///
/// This method should only be called as part of the paint phase of element drawing.
pub fn paint_emoji(
&mut self,
origin: Point<Pixels>,
font_id: FontId,
glyph_id: GlyphId,
font_size: Pixels,
) -> Result<()> {
self.invalidator.debug_assert_paint();
let scale_factor = self.scale_factor();
let glyph_origin = origin.scale(scale_factor);
let integer_origin = glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0)));
let params = RenderGlyphParams {
font_id,
glyph_id,
font_size,
subpixel_variant: Default::default(),
scale_factor,
is_emoji: true,
subpixel_rendering: false,
dilation: 0,
};
let raster_bounds = self.text_system().raster_bounds(¶ms)?;
if !raster_bounds.is_zero() {
let tile = self
.sprite_atlas
.get_or_insert_with(params.clone().into(), &mut || {
let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
Ok(Some((size, Cow::Owned(bytes))))
})?
.expect("Callback above only errors or returns Some");
let bounds = Bounds {
origin: integer_origin + raster_bounds.origin.map(Into::into),
size: tile.bounds.size.map(Into::into),
};
let content_mask = self.snapped_content_mask();
let opacity = self.element_opacity();
self.next_frame.scene.insert_primitive(PolychromeSprite {
order: 0,
pad: 0,
grayscale: false.into(),
bounds,
corner_radii: Default::default(),
content_mask,
tile,
opacity,
transformation: self.element_transform,
tint: Hsla::transparent_black(),
corner_shapes: CornerShapes::default(),
});
}
Ok(())
}
/// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
///
/// This method should only be called as part of the paint phase of element drawing.
pub fn paint_svg(
&mut self,
bounds: Bounds<Pixels>,
path: SharedString,
data: Option<&[u8]>,
transformation: TransformationMatrix,
color: Hsla,
cx: &App,
) -> Result<()> {
self.paint_animated_svg(bounds, path, data, transformation, None, color, cx)
}
/// Like [`Self::paint_svg`], with an `animation` the window applies before every
/// present, so the view isn't re-rendered to advance it.
pub(crate) fn paint_animated_svg(
&mut self,
bounds: Bounds<Pixels>,
path: SharedString,
data: Option<&[u8]>,
transformation: TransformationMatrix,
animation: Option<SpriteAnimation>,
color: Hsla,
cx: &App,
) -> Result<()> {
self.invalidator.debug_assert_paint();
let element_opacity = self.element_opacity();
let bounds = self.snap_bounds(bounds);
let params = RenderSvgParams {
path,
size: bounds.size.map(|pixels| {
DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
}),
};
let Some(tile) =
self.sprite_atlas
.get_or_insert_with(params.clone().into(), &mut || {
let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(¶ms, data)?
else {
return Ok(None);
};
Ok(Some((size, Cow::Owned(bytes))))
})?
else {
return Ok(());
};
let content_mask = self.snapped_content_mask();
let svg_bounds = Bounds {
origin: bounds.center()
- Point::new(
ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
),
size: tile
.bounds
.size
.map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
};
let final_bounds = svg_bounds
.map_origin(|value| ScaledPixels(round_half_toward_zero(value.0)))
.map_size(|size| size.ceil());
let sprite = MonochromeSprite {
order: 0,
raw_coverage: false.into(),
animation: SpriteAnimationId::NONE,
pad: 0,
bounds: final_bounds,
content_mask,
color: color.opacity(element_opacity),
tile,
// The caller's own matrix (gpui's `Svg::with_transformation`)
// composed under whatever CSS `transform` an ancestor pushed.
transformation: self.element_transform.compose(transformation),
};
match animation {
Some(animation) => self.next_frame.scene.insert_animated_sprite(
sprite,
animation.under(self.element_transform),
),
None => self.next_frame.scene.insert_primitive(sprite),
}
Ok(())
}
/// Paint an image into the scene for the next frame at the current z-index.
/// This method will panic if the frame_index is not valid
///
/// This method should only be called as part of the paint phase of element drawing.
/// Paint an image into `bounds`, positioning and scaling it according to `image_bounds`.
///
/// vue-native: with an [`ImageResampler`] installed, an image that is not
/// [`RenderImage::dynamic`] may be drawn from the smaller copy it returns.
///
/// The visible region rendered is `bounds.intersect(&image_bounds)`, with `corner_radii`
/// applied to `bounds`.
pub fn paint_image(
&mut self,
bounds: Bounds<Pixels>,
image_bounds: Bounds<Pixels>,
corner_radii: Corners<Pixels>,
data: Arc<RenderImage>,
frame_index: usize,
grayscale: bool,
) -> Result<()> {
self.invalidator.debug_assert_paint();
let visible_bounds = bounds.intersect(&image_bounds);
if visible_bounds.size.width <= Pixels::ZERO || visible_bounds.size.height <= Pixels::ZERO {
return Ok(());
}
if image_bounds.size.width <= Pixels::ZERO || image_bounds.size.height <= Pixels::ZERO {
return Ok(());
}
// vue-native: an image drawn well below its own size is drawn from the
// host's smaller copy, when it has one (see `ImageResampler`).
let (data, frame_index) = match IMAGE_RESAMPLER.get() {
Some(resample) if !data.is_dynamic() => {
let scale = self.scale_factor();
let device = size(
DevicePixels((image_bounds.size.width.0 * scale).round() as i32),
DevicePixels((image_bounds.size.height.0 * scale).round() as i32),
);
match resample(&data, frame_index, device) {
Some(smaller) => (smaller, 0),
None => (data, frame_index),
}
}
_ => (data, frame_index),
};
let params = RenderImageParams {
image_id: data.id,
frame_index,
};
let tile = self.sprite_atlas.get_or_insert_with(params.into(), &mut || {
Ok(data.as_bytes(frame_index).map(|bytes| (data.size(frame_index), Cow::Borrowed(bytes))))
})?;
let Some(tile) = tile else { return Ok(()); };
let visible_bounds_snapped = self.snap_bounds(visible_bounds);
let sub_tile = if visible_bounds == image_bounds {
tile
} else {
let x_offset_ratio =
(visible_bounds.origin.x - image_bounds.origin.x) / image_bounds.size.width;
let y_offset_ratio =
(visible_bounds.origin.y - image_bounds.origin.y) / image_bounds.size.height;
let width_ratio = visible_bounds.size.width / image_bounds.size.width;
let height_ratio = visible_bounds.size.height / image_bounds.size.height;
let tile_origin_x = tile.bounds.origin.x.0;
let tile_origin_y = tile.bounds.origin.y.0;
let tile_width = tile.bounds.size.width.0;
let tile_height = tile.bounds.size.height.0;
let sub_origin_x = tile_origin_x + (x_offset_ratio * tile_width as f32).round() as i32;
let sub_origin_y = tile_origin_y + (y_offset_ratio * tile_height as f32).round() as i32;
let sub_width = (width_ratio * tile_width as f32).round() as i32;
let sub_height = (height_ratio * tile_height as f32).round() as i32;
let max_x = tile_origin_x + tile_width;
let max_y = tile_origin_y + tile_height;
let clamped_origin_x = sub_origin_x.clamp(tile_origin_x, max_x);
let clamped_origin_y = sub_origin_y.clamp(tile_origin_y, max_y);
let clamped_width = sub_width.min(max_x - clamped_origin_x).max(0);
let clamped_height = sub_height.min(max_y - clamped_origin_y).max(0);
AtlasTile {
bounds: Bounds {
origin: point(
DevicePixels(clamped_origin_x),
DevicePixels(clamped_origin_y),
),
size: size(DevicePixels(clamped_width), DevicePixels(clamped_height)),
},
..tile
}
};
let content_mask = self.snapped_content_mask();
let corner_radii = corner_radii
.clamp_radii_for_quad_size(visible_bounds.size)
.scale(self.scale_factor());
let opacity = self.element_opacity();
self.next_frame.scene.insert_primitive(PolychromeSprite {
order: 0,
pad: 0,
grayscale: grayscale.into(),
bounds: visible_bounds_snapped,
content_mask,
corner_radii,
tile: sub_tile,
opacity,
transformation: self.element_transform,
tint: self.element_image_tint,
corner_shapes: CornerShapes::default(),
});
Ok(())
}
/// Paint a surface into the scene for the next frame at the current z-index.
///
/// This method should only be called as part of the paint phase of element drawing.
#[cfg(any(target_os = "macos", target_os = "ios"))]
pub fn paint_surface(
&mut self,
bounds: Bounds<Pixels>,
image_buffer: CFRetained<CVPixelBuffer>,
) {
use crate::PaintSurface;
self.invalidator.debug_assert_paint();
let bounds = self.snap_bounds(bounds);
let content_mask = self.snapped_content_mask();
self.next_frame.scene.insert_primitive(PaintSurface {
order: 0,
bounds,
content_mask,
image_buffer,
});
}
/// Fills the sprite-atlas tile that backs `data` from a texture that is
/// already in the renderer's own GPU memory, with no CPU round trip.
///
/// `data` is used for its **identity and its size only** — its pixel buffer
/// is never read on this path, so a producer that decodes onto the GPU can
/// keep one zero-filled `RenderImage` alive for the life of the element and
/// overwrite its tile every frame. `paint_image` then finds the tile
/// already populated and never runs its `build` closure.
///
/// Returns `Ok(false)` when the platform has no GPU path or refused the
/// texture (wrong device, wrong format, too small) — the caller is expected
/// to fall back to a `RenderImage` carrying real bytes. This is not a paint
/// method: call it from a frame pump, before the draw that paints the image.
///
/// # Contract
///
/// See [`PlatformAtlas::upload_from_gpu`]. On Windows `texture` must be an
/// `ID3D11Texture2D` on the device `gpui_windows::renderer_d3d11_device()`
/// publishes, in `DXGI_FORMAT_B8G8R8A8_UNORM`, at least as large as
/// `data.size(frame_index)`.
pub fn upload_image_from_gpu(
&mut self,
data: &RenderImage,
frame_index: usize,
texture: GpuTextureHandle,
) -> Result<bool> {
Ok(self.write_image_tile(data, frame_index, TileSource::Gpu(texture))? != TileWrite::Refused)
}
/// vue-native fork: writes a new frame into the sprite-atlas tile that backs
/// `image`, outside any draw, and says whether the frame already drawn will
/// show it.
///
/// The tile is keyed by `image.id`. A producer that keeps one id for the
/// life of a picture (a zero-copy video placeholder, or
/// [`RenderImage::successor`] for CPU frames) keeps one tile, and the
/// scene that painted it samples whatever was written last. When the write
/// lands [`TileWrite::InPlace`], [`Window::request_present`] shows it with
/// no layout, prepaint or paint. The size is `image.size(frame_index)`.
/// Call it from a frame callback, before the frame's draw, never during one.
///
/// `TileSource::Bytes` writes `image`'s own pixels (premultiplied BGRA).
/// It always succeeds: a backend with no in-place path re-inserts the key,
/// which reports [`TileWrite::Placed`]. `TileSource::Gpu` has the contract
/// of [`PlatformAtlas::upload_from_gpu`] and reports
/// [`TileWrite::Refused`] where that returns `None`.
pub fn write_image_tile(
&mut self,
image: &RenderImage,
frame_index: usize,
source: TileSource,
) -> Result<TileWrite> {
let key: AtlasKey = RenderImageParams {
image_id: image.id,
frame_index,
}
.into();
let size = image.size(frame_index);
let before = self.sprite_atlas.tile(&key);
let after = match source {
TileSource::Gpu(texture) => {
match self.sprite_atlas.upload_from_gpu(&key, size, texture)? {
Some(tile) => tile,
None => return Ok(TileWrite::Refused),
}
}
TileSource::Bytes => {
let bytes = image
.as_bytes(frame_index)
.ok_or_else(|| anyhow!("write_image_tile: no frame {frame_index}"))?;
match self.sprite_atlas.write_bytes(&key, size, bytes)? {
Some(tile) => tile,
None => {
self.sprite_atlas.remove(&key);
self.sprite_atlas
.get_or_insert_with(key, &mut || {
Ok(Some((size, Cow::Borrowed(bytes))))
})?
.ok_or_else(|| anyhow!("write_image_tile: the atlas took no tile"))?;
return Ok(TileWrite::Placed);
}
}
}
};
Ok(match before {
Some(tile) if tile == after => TileWrite::InPlace,
_ => TileWrite::Placed,
})
}
/// Writes a GPU frame while retaining its producer until the asynchronous
/// atlas copy completes. See [`PlatformAtlas::upload_from_d3d12`].
pub fn write_image_tile_d3d12(
&mut self,
image: &RenderImage,
frame_index: usize,
texture: crate::D3D12TextureHandle,
owner: std::sync::Arc<dyn std::any::Any + Send + Sync>,
) -> Result<TileWrite> {
let key: AtlasKey = RenderImageParams {
image_id: image.id,
frame_index,
}
.into();
let before = self.sprite_atlas.tile(&key);
let Some(after) = self.sprite_atlas.upload_from_d3d12(
&key,
image.size(frame_index),
texture,
owner,
)? else {
return Ok(TileWrite::Refused);
};
Ok(match before {
Some(tile) if tile == after => TileWrite::InPlace,
_ => TileWrite::Placed,
})
}
/// vue-native fork: [`Window::write_image_tile`] from a finished Metal
/// texture. See [`PlatformAtlas::upload_from_metal`].
pub fn write_image_tile_metal(
&mut self,
image: &RenderImage,
frame_index: usize,
texture: GpuTextureHandle,
ready: Option<(*mut std::ffi::c_void, u64)>,
owner: std::sync::Arc<dyn std::any::Any + Send + Sync>,
) -> Result<TileWrite> {
let key: AtlasKey = RenderImageParams {
image_id: image.id,
frame_index,
}
.into();
let before = self.sprite_atlas.tile(&key);
let Some(after) =
self.sprite_atlas
.upload_from_metal(&key, image.size(frame_index), texture, ready, owner)?
else {
return Ok(TileWrite::Refused);
};
Ok(match before {
Some(tile) if tile == after => TileWrite::InPlace,
_ => TileWrite::Placed,
})
}
/// vue-native fork: presents the frame already drawn once more, with no
/// layout, prepaint or paint: the renderer encodes the same scene again, so
/// an atlas tile overwritten in place since ([`Window::write_image_tile`],
/// [`TileWrite::InPlace`]) shows its new pixels. From an `on_next_frame`
/// callback it takes effect in that frame; elsewhere, on the next one. A
/// frame that draws anyway presents what it drew.
pub fn request_present(&self) {
self.needs_present.set(true);
self.invalidator.wake_platform();
}
/// Removes an image from the sprite atlas.
pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
for frame_index in 0..data.frame_count() {
let params = RenderImageParams {
image_id: data.id,
frame_index,
};
self.sprite_atlas.remove(¶ms.into());
}
Ok(())
}
/// vue-native fork: this window's sprite atlas footprint (pages and bytes
/// per texture kind, keys, image tiles), for an embedder's memory report.
/// `None` when the platform's atlas does not keep count.
pub fn sprite_atlas_stats(&self) -> Option<AtlasStats> {
self.sprite_atlas.stats()
}
/// Reports a live atlas tile on backends supporting GPU image imports.
pub fn has_image_atlas_tile(&self, data: &RenderImage, frame_index: usize) -> bool {
self.sprite_atlas.tile(&RenderImageParams {image_id:data.id,frame_index}.into()).is_some()
}
/// Returns whether every frame of an image is present in the sprite atlas.
#[cfg(any(test, feature = "test-support"))]
pub fn has_image_atlas_entry(&self, data: &RenderImage) -> bool {
data.frame_count() > 0
&& (0..data.frame_count()).all(|frame_index| {
self.sprite_atlas.contains(
&RenderImageParams {
image_id: data.id,
frame_index,
}
.into(),
)
})
}
/// Enable node retention for this window before its first layout request.
/// Generic GPUI windows retain upstream's per-frame layout by default.
pub fn vn_enable_retained_layout(&mut self) {
self.layout_engine.as_mut().unwrap().enable_retention();
}
/// Enable counters only while a profiling capture is active.
pub fn vn_profile_retained_layout(&mut self, enabled: bool) {
self.layout_engine
.as_mut()
.unwrap()
.profile_retention(enabled);
}
/// Drain this window's retention counters, or None while profiling is off.
pub fn vn_take_retained_layout_stats(&mut self) -> Option<crate::VnRetainedLayoutStats> {
self.layout_engine.as_mut().unwrap().take_retention_stats()
}
/// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
/// layout is being requested, along with the layout ids of any children. This method is called during
/// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout.
///
/// This method should only be called as part of the request_layout or prepaint phase of element drawing.
#[must_use]
pub fn request_layout(
&mut self,
style: Style,
children: impl IntoIterator<Item = LayoutId>,
cx: &mut App,
) -> LayoutId {
self.invalidator.debug_assert_prepaint();
cx.layout_id_buffer.clear();
cx.layout_id_buffer.extend(children);
let rem_size = self.rem_size();
let scale_factor = self.scale_factor();
let scope = self
.layout_engine
.as_ref()
.unwrap()
.retention_enabled()
.then(|| self.element_id_stack.global_id());
let engine = self.layout_engine.as_mut().unwrap();
if let Some(scope) = scope {
engine.request_layout_in_scope(
Some(scope),
style,
rem_size,
scale_factor,
&cx.layout_id_buffer,
)
} else {
engine.request_layout(style, rem_size, scale_factor, &cx.layout_id_buffer)
}
}
/// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
/// this variant takes a function that is invoked during layout so you can use arbitrary logic to
/// determine the element's size. One place this is used internally is when measuring text.
///
/// The given closure is invoked at layout time with the known dimensions and available space and
/// returns a `Size`.
///
/// This method should only be called as part of the request_layout or prepaint phase of element drawing.
pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
where
F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
+ 'static,
{
self.invalidator.debug_assert_prepaint();
let rem_size = self.rem_size();
let scale_factor = self.scale_factor();
let scope = self
.layout_engine
.as_ref()
.unwrap()
.retention_enabled()
.then(|| self.element_id_stack.global_id());
let engine = self.layout_engine.as_mut().unwrap();
if let Some(scope) = scope {
engine.request_measured_layout_in_scope(
Some(scope),
style,
rem_size,
scale_factor,
measure,
)
} else {
engine.request_measured_layout(style, rem_size, scale_factor, measure)
}
}
/// Compute the layout for the given id within the given available space.
/// This method is called for its side effect, typically by the framework prior to painting.
/// After calling it, you can request the bounds of the given layout node id or any descendant.
///
/// This method should only be called as part of the prepaint phase of element drawing.
pub fn compute_layout(
&mut self,
layout_id: LayoutId,
available_space: Size<AvailableSpace>,
cx: &mut App,
) {
self.invalidator.debug_assert_prepaint();
let mut layout_engine = self.layout_engine.take().unwrap();
layout_engine.compute_layout(layout_id, available_space, self, cx);
self.layout_engine = Some(layout_engine);
}
/// vue-native fork: whether the layout node is out of flow (`position:
/// absolute`).
pub fn layout_is_absolute(&self, layout_id: LayoutId) -> bool {
self.layout_engine
.as_ref()
.is_some_and(|engine| engine.is_absolute(layout_id))
}
/// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
/// GPUI itself automatically in order to pass your element its `Bounds` automatically.
///
/// This method should only be called as part of element drawing.
pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
self.invalidator.debug_assert_prepaint();
let scale_factor = self.scale_factor();
let mut bounds = self
.layout_engine
.as_mut()
.unwrap()
.layout_bounds(layout_id, scale_factor)
.map(Into::into);
let snapped_offset = self.pixel_snap_point(self.element_offset());
bounds.origin += snapped_offset;
bounds
}
/// This method should be called during `prepaint`. You can use
/// the returned [Hitbox] during `paint` or in an event handler
/// to determine whether the inserted hitbox was the topmost.
///
/// This method should only be called as part of the prepaint phase of element drawing.
pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
self.invalidator.debug_assert_prepaint();
let content_mask = self.content_mask();
let id = self.next_hitbox_id;
self.next_hitbox_id = self.next_hitbox_id.next();
let hitbox = Hitbox {
id,
bounds,
content_mask,
behavior,
// Whatever CSS `transform` the paint walk is inside. Prepaint
// pushes the same matrix paint does, so a rotated element's hitbox
// knows it is rotated (see `Frame::hit_test`).
transformation: self.element_transform,
vn_clip: self.vn_clip_stack.clone(),
};
self.next_frame.hitboxes.push(hitbox.clone());
// vue-native fork.
if self.vn_hitbox_tag != 0 {
self.next_frame
.vn_tagged_hitboxes
.push((self.vn_hitbox_tag, hitbox.clone()));
}
hitbox
}
/// vue-native fork: tag every hitbox inserted from now until the tag is set
/// back, with an embedder node id. Returns the previous tag, which the
/// caller must restore — the pair brackets one node's prepaint, so a child
/// tags itself and hands the parent's tag back on the way out.
///
/// `0` disables tagging. See [`Frame::vn_tagged_hitboxes`].
pub fn set_hitbox_tag(&mut self, tag: u32) -> u32 {
mem::replace(&mut self.vn_hitbox_tag, tag)
}
/// vue-native fork: [`Window::set_hitbox_tag`] for the duration of `f`,
/// which prepaints one embedder node, answering also the node's whole CSS
/// `transform` (its ancestors' composed with its own) when it has one of
/// its own. `None` means its picture moved only with its ancestors', by
/// [`Window::element_transform`] as it stood before `f`.
///
/// "The node's own" is the FIRST element to prepaint inside `f`: the
/// node's element runs before anything inside it, and what it builds
/// internally under the same tag (a `::before` box, a list marker) after,
/// so a transformed pseudo-element does not move its node.
pub fn with_hitbox_tag<R>(
&mut self,
tag: u32,
f: impl FnOnce(&mut Self) -> R,
) -> (R, Option<TransformationMatrix>) {
let tag = mem::replace(&mut self.vn_hitbox_tag, tag);
let fresh = mem::replace(&mut self.vn_tag_fresh, true);
let noted = self.vn_tag_transform.take();
let result = f(self);
let own = mem::replace(&mut self.vn_tag_transform, noted);
self.vn_tag_fresh = fresh;
self.vn_hitbox_tag = tag;
(result, own)
}
/// vue-native fork: called by every element's prepaint once its own
/// `transform` is pushed. The first one inside a
/// [`Window::with_hitbox_tag`] is the tagged node's.
pub(crate) fn note_tagged_transform(&mut self, own_is_unit: bool) {
if self.vn_tag_fresh {
self.vn_tag_fresh = false;
if !own_is_unit {
self.vn_tag_transform = Some(self.element_transform);
}
}
}
/// vue-native fork: the axis-aligned bounding box of `bounds` (logical
/// pixels) under `matrix` (device space, as [`Window::element_transform`]
/// is) — the rectangle a browser's `getBoundingClientRect()` reports for a
/// transformed box.
pub fn transformed_bounds(
&self,
matrix: TransformationMatrix,
bounds: Bounds<Pixels>,
) -> Bounds<Pixels> {
transform_bounds(matrix, bounds, self.scale_factor)
}
/// vue-native fork: give EVERY element a hitbox, not only an interactive
/// one, so that [`Window::tagged_hitbox`] can answer for any node. Costs
/// one `Hitbox` per element per frame and the same number of rectangle
/// tests per mouse move, so it is opt-in; a dev host turns it on at boot
/// and a shipped one never does.
pub fn set_tag_every_hitbox(&mut self, on: bool) {
self.vn_tag_every_hitbox = on;
}
/// vue-native fork: is [`Window::set_tag_every_hitbox`] on?
pub fn tags_every_hitbox(&self) -> bool {
self.vn_tag_every_hitbox
}
/// vue-native fork: the hitbox the RENDERED frame made for the element
/// tagged `tag` — the handle [`Hitbox::is_hovered_at`] takes.
///
/// The first entry wins: an element's own hitbox is inserted before any box
/// its subtree makes, and boxes a node's build produces internally (a
/// pseudo-element, a list marker) carry the same tag. A pick
/// ([`Window::vn_insert_pick`]) is not a hitbox and is passed over.
pub fn tagged_hitbox(&self, tag: u32) -> Option<&Hitbox> {
self.rendered_frame
.vn_tagged_hitboxes
.iter()
.find(|(t, hitbox)| *t == tag && hitbox.id != HitboxId::VN_PICK)
.map(|(_, hitbox)| hitbox)
}
/// vue-native fork: the embedder tags of the hitboxes under `position` in
/// the RENDERED frame, topmost first — the order a press resolves in
/// ([`Frame::hit_test`], so a deferred draw's boxes sort where it paints).
/// A hitbox no node tagged is left out; a node with several boxes there
/// appears once per box.
///
/// An embedder asks it to learn which of ITS nodes is on top under the
/// pointer, which gpui's own answer (`Hitbox::is_hovered`, true for every
/// box under the pointer) cannot say. One hit test plus one pass over the
/// frame's tagged boxes: meant for a press or a drag, not for every mouse
/// move.
///
/// The PICK records ([`Window::vn_insert_pick`]) are boxes too, so with
/// [`Window::set_vn_pick_every_box`] on this answers for every element,
/// listening or not. It walks the tagged list in paint order itself rather
/// than asking [`Frame::hit_test`], whose list has no picks; a
/// `BlockMouse` box ends it, as it ends gpui's.
///
/// A box tagged [`VN_TAG_PASSIVE`] is left out: it is a node's, but it is
/// not where the node is (a scroll container's wheel viewport, which lies
/// over the content it scrolls).
pub fn vn_tags_at(&self, position: Point<Pixels>) -> Vec<u32> {
let frame = &self.rendered_frame;
let tagged = &frame.vn_tagged_hitboxes;
let mut out = Vec::new();
let mut visit = |(tag, hitbox): &(u32, Hitbox)| {
if tag & VN_TAG_PASSIVE != 0 || !Frame::box_contains(hitbox, position, self.scale_factor) {
return true;
}
out.push(*tag);
hitbox.behavior != HitboxBehavior::BlockMouse
};
match frame.vn_tagged_paint_order() {
Some(order) => {
for &ix in order.iter().rev() {
if !visit(&tagged[ix as usize]) {
break;
}
}
}
None => {
for entry in tagged.iter().rev() {
if !visit(entry) {
break;
}
}
}
}
out
}
/// vue-native fork: give an element that needs no hitbox a PICK record
/// instead — its box, content mask, transform and tag, in
/// [`Frame::vn_tagged_hitboxes`] only. gpui's own hit test (the one every
/// mouse move runs) never sees a pick, so it costs a move nothing; it is
/// there for [`Window::vn_tags_at`], which an embedder asks at a press to
/// learn the topmost of ALL its elements, the way a browser targets an
/// event. Replayed with the rest of a cached view's prepaint.
pub fn set_vn_pick_every_box(&mut self, on: bool) {
self.vn_pick_every_box = on;
}
/// vue-native fork: is [`Window::set_vn_pick_every_box`] on?
pub fn vn_picks_every_box(&self) -> bool {
self.vn_pick_every_box
}
/// vue-native fork: records a pick for `bounds` under the current tag
/// (nothing outside a tag). Called where an element would insert its
/// hitbox, so the content mask and transform are the ones a hitbox there
/// would carry.
pub fn vn_insert_pick(&mut self, bounds: Bounds<Pixels>) {
self.invalidator.debug_assert_prepaint();
if self.vn_hitbox_tag == 0 {
return;
}
let hitbox = Hitbox {
id: HitboxId::VN_PICK,
bounds,
content_mask: self.content_mask(),
behavior: HitboxBehavior::Normal,
transformation: self.element_transform,
vn_clip: self.vn_clip_stack.clone(),
};
self.next_frame
.vn_tagged_hitboxes
.push((self.vn_hitbox_tag, hitbox));
}
/// vue-native fork: installs (or removes) the embedder's hit refiner.
///
/// gpui hands a mouse event to EVERY hitbox under the pointer, so a box
/// that listens takes a press through anything painted over it that does
/// not, and a box that does not listen is never anybody's target. A
/// browser targets the topmost element and bubbles from there. The
/// refiner is run at the start of the dispatch of each press, release and
/// wheel event, before any listener, and may narrow what the event is for
/// with [`Window::vn_restrict_mouse_hit`]. Moves are not refined.
pub fn set_vn_hit_refiner(&mut self, refiner: Option<VnHitRefiner>) {
self.vn_hit_refiner = refiner;
}
/// vue-native fork: is a hit refiner installed?
pub fn has_vn_hit_refiner(&self) -> bool {
self.vn_hit_refiner.is_some()
}
/// vue-native fork: which key event this window is dispatching — one
/// number per key-down, key-up or modifiers change, taken before the
/// keystroke interceptors run, so everything that hears one event (an
/// interceptor, the capture listeners, the bubble listeners) reads the
/// same number and the next event reads another.
///
/// gpui hands a key event to every listener on the focus path, and an
/// editor's interceptor sees it before any of them. An embedder that turns
/// it into ONE event of its own (a browser's `keydown`, dispatched once at
/// the focused element) records the number it dispatched for and lets the
/// others pass. Interceptor order and listener order do not matter, and a
/// listener whose element the first dispatch removed still reads the same
/// number, because gpui walks the path it computed before any of them ran.
pub fn vn_key_event_seq(&self) -> u64 {
self.vn_key_event_seq
}
/// vue-native fork: is the pointer in this window? `false` once it has
/// left (a `MouseExited`, the end of a file drag over it), `true` again at
/// the next pointer event here. [`Window::mouse_position`] keeps the last
/// position inside either way, so an embedder that decides hover itself
/// (a browser's `:hover` and `mouseenter`, from its own hit test) asks
/// this to know that nothing is hovered, as [`Hitbox::is_hovered`] does.
pub fn vn_pointer_inside(&self) -> bool {
self.pointer_inside
}
/// vue-native fork: a browser's pointer lock. Until [`Window::vn_unlock_pointer`], every
/// mouse event is delivered at the position the pointer had now, and a move's motion is
/// [`Window::vn_mouse_movement`]. Locking again changes the mode.
pub fn vn_lock_pointer(&mut self, how: VnPointerLock) -> Result<(), crate::PointerLockError> {
let anchor = match self.vn_pointer_lock.take() {
Some((previous, anchor)) => {
if matches!(previous, VnPointerLock::System { .. }) {
self.platform_window.unlock_pointer();
}
anchor
}
None => self.mouse_position,
};
if let VnPointerLock::System { unadjusted } = how {
self.platform_window.lock_pointer(unadjusted)?;
}
self.vn_pointer_lock = Some((how, anchor));
self.vn_raw_mouse_position = None;
Ok(())
}
/// vue-native fork: releases [`Window::vn_lock_pointer`]'s lock, if any.
pub fn vn_unlock_pointer(&mut self) {
if let Some((VnPointerLock::System { .. }, _)) = self.vn_pointer_lock.take() {
self.platform_window.unlock_pointer();
}
self.vn_raw_mouse_position = None;
}
/// vue-native fork: is the pointer still locked? The platform lets go by itself when the
/// window loses activation.
pub fn vn_pointer_locked(&self) -> bool {
match self.vn_pointer_lock {
Some((VnPointerLock::System { .. }, _)) => self.platform_window.is_pointer_locked(),
Some((VnPointerLock::Simulated, _)) => true,
None => false,
}
}
/// vue-native fork: how far the mouse move being dispatched moved the pointer since the
/// previous move, logical pixels: a browser's `movementX`/`movementY`. While the pointer is
/// locked by the system it is the platform's measure (device counts when unadjusted).
pub fn vn_mouse_movement(&self) -> Point<Pixels> {
self.vn_mouse_movement
}
fn vn_pin_to_pointer_lock(&mut self, mut event: PlatformInput) -> PlatformInput {
let system = matches!(
self.vn_pointer_lock,
Some((VnPointerLock::System { .. }, _))
);
if system && !self.platform_window.is_pointer_locked() {
self.vn_pointer_lock = None;
self.vn_raw_mouse_position = None;
}
if let PlatformInput::MouseMove(mouse_move) = &event {
let previous = self.vn_raw_mouse_position.replace(mouse_move.position);
let motion = system.then(|| self.platform_window.take_pointer_motion());
self.vn_mouse_movement = motion.flatten().unwrap_or_else(|| {
previous.map_or_else(Point::default, |previous| mouse_move.position - previous)
});
}
let Some((_, anchor)) = self.vn_pointer_lock else {
return event;
};
match &mut event {
PlatformInput::MouseMove(e) => e.position = anchor,
PlatformInput::MouseDown(e) => e.position = anchor,
PlatformInput::MouseUp(e) => e.position = anchor,
PlatformInput::Scroll(e) => e.position = anchor,
PlatformInput::MouseExited(e) => e.position = anchor,
_ => {}
}
event
}
/// vue-native fork: will this frame draw the window? `true` once anything
/// invalidated it since its last draw (a notify, a `refresh`, a resize).
/// An embedder with work that must follow the frame's layout and precede
/// its paint (a browser's ResizeObserver delivery) draws the window itself
/// from an `on_next_frame` callback when this is set; the frame then finds
/// it clean and presents what that draw produced.
pub fn vn_is_dirty(&self) -> bool {
self.invalidator.is_dirty()
}
/// vue-native fork: for the mouse event being dispatched, keep only the
/// hitboxes whose tag `keep` accepts (an untagged hitbox is not the
/// embedder's and stays). With `add`, the accepted tags' boxes that do
/// NOT contain the pointer join the hovered set as well: a browser's
/// event reaches every ancestor of its target, wherever their boxes are.
///
/// Only meant from inside a [`VnHitRefiner`]. The next frame or the next
/// mouse event recomputes the hit test from geometry.
pub fn vn_restrict_mouse_hit(&mut self, keep: &dyn Fn(u32) -> bool, add: bool) {
let frame = &self.rendered_frame;
let mut tag_of: FxHashMap<HitboxId, u32> = FxHashMap::default();
// A passive box is judged by the node it belongs to.
for (tag, hitbox) in &frame.vn_tagged_hitboxes {
if hitbox.id != HitboxId::VN_PICK {
tag_of.entry(hitbox.id).or_insert(tag & !VN_TAG_PASSIVE);
}
}
let old = mem::take(&mut self.mouse_hit_test);
let mut ids: SmallVec<[HitboxId; 8]> = SmallVec::new();
let mut hover = 0;
for (ix, id) in old.ids.iter().enumerate() {
if tag_of.get(id).is_none_or(|tag| keep(*tag)) {
ids.push(*id);
if ix < old.hover_hitbox_count {
hover += 1;
}
}
}
// Nothing was cut from hover by a `BlockMouseExceptScroll` box: the
// added boxes are hovered too.
let all_hovered = old.hover_hitbox_count == old.ids.len();
if add {
for (tag, hitbox) in &frame.vn_tagged_hitboxes {
if hitbox.id != HitboxId::VN_PICK
&& keep(tag & !VN_TAG_PASSIVE)
&& !ids.contains(&hitbox.id)
{
ids.push(hitbox.id);
}
}
}
if all_hovered {
hover = ids.len();
}
self.mouse_hit_test = HitTest {
ids,
hover_hitbox_count: hover,
};
}
/// Resolves native caption behavior at a point in the current painted frame.
/// This does not reuse or modify the hit set narrowed for a DOM input event.
pub fn window_control_area_at(&self, position: Point<Pixels>) -> Option<WindowControlArea> {
for hitbox in self.rendered_frame.topmost_hitboxes() {
if !Frame::box_contains(hitbox, position, self.scale_factor) {
continue;
}
if let Some((area, _)) = self.rendered_frame.window_control_hitboxes.iter()
.find(|(_, control)| control.id == hitbox.id)
{
return Some(*area);
}
if hitbox.behavior == HitboxBehavior::BlockMouse {
break;
}
}
None
}
/// Set a hitbox which will act as a control area of the platform window.
///
/// This method should only be called as part of the paint phase of element drawing.
pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
self.invalidator.debug_assert_paint();
self.next_frame.window_control_hitboxes.push((area, hitbox));
}
/// Sets the key context for the current element. This context will be used to translate
/// keybindings into actions.
///
/// This method should only be called as part of the paint phase of element drawing.
pub fn set_key_context(&mut self, context: KeyContext) {
self.invalidator.debug_assert_paint();
self.next_frame.dispatch_tree.set_key_context(context);
}
/// Sets the focus handle for the current element. This handle will be used to manage focus state
/// and keyboard event dispatch for the element.
///
/// This method should only be called as part of the prepaint phase of element drawing.
pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
self.invalidator.debug_assert_prepaint();
if focus_handle.is_focused(self) {
self.next_frame.focus = Some(focus_handle.id);
}
self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
}
/// Sets the view id for the current element, which will be used to manage view caching.
///
/// This method should only be called as part of element prepaint. We plan on removing this
/// method eventually when we solve some issues that require us to construct editor elements
/// directly instead of always using editors via views.
pub fn set_view_id(&mut self, view_id: EntityId) {
self.invalidator.debug_assert_prepaint();
self.next_frame.dispatch_tree.set_view_id(view_id);
}
/// Get the entity ID for the currently rendering view
pub fn current_view(&self) -> EntityId {
self.invalidator.debug_assert_paint_or_prepaint();
self.rendered_entity_stack.last().copied().unwrap()
}
#[inline]
pub(crate) fn with_rendered_view<R>(
&mut self,
id: EntityId,
f: impl FnOnce(&mut Self) -> R,
) -> R {
self.rendered_entity_stack.push(id);
let result = f(self);
self.rendered_entity_stack.pop();
result
}
/// Executes the provided function with the specified image cache.
pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
where
F: FnOnce(&mut Self) -> R,
{
if let Some(image_cache) = image_cache {
self.image_cache_stack.push(image_cache);
let result = f(self);
self.image_cache_stack.pop();
result
} else {
f(self)
}
}
/// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
/// platform to receive textual input with proper integration with concerns such
/// as IME interactions. This handler will be active for the upcoming frame until the following frame is
/// rendered.
///
/// This method should only be called as part of the paint phase of element drawing.
///
/// [element_input_handler]: crate::ElementInputHandler
pub fn handle_input(
&mut self,
focus_handle: &FocusHandle,
input_handler: impl InputHandler,
cx: &App,
) {
self.invalidator.debug_assert_paint();
if focus_handle.is_focused(self) {
let cx = self.to_async(cx);
self.next_frame.input_handlers.push(Some(
PlatformInputHandler::new(cx, Box::new(input_handler)).with_focus(focus_handle.id),
));
}
}
/// Notifies native text services that the focused component's text changed.
///
/// Text components should call this after application-driven edits, in addition
/// to notifying GPUI to redraw. Unfocused or unregistered components are ignored.
pub fn notify_text_input_changed(&self, focus_handle: &FocusHandle) {
if self.focused_text_input == Some(focus_handle.id) && focus_handle.is_focused(self) {
self.platform_window
.text_input_state_changed(TextInputStateChange::ContentChanged);
}
}
/// Notifies native text services that the focused component's selection changed.
///
/// Text components should call this after application-driven selection changes,
/// in addition to notifying GPUI to redraw.
pub fn notify_text_selection_changed(&self, focus_handle: &FocusHandle) {
if self.focused_text_input == Some(focus_handle.id) && focus_handle.is_focused(self) {
self.platform_window
.text_input_state_changed(TextInputStateChange::SelectionChanged);
}
}
/// Forwards the focused input handler's [`TextInputConfiguration`] to the
/// platform window when it differs from the last forwarded value. With no
/// input handler the default configuration applies, so a field's
/// preferences don't outlive its focus.
fn apply_text_input_configuration(&mut self, cx: &mut App) {
let configuration = match self.platform_window.take_input_handler() {
Some(mut input_handler) => {
let configuration = input_handler.text_input_configuration(self, cx);
self.platform_window.set_input_handler(input_handler);
configuration
}
None => TextInputConfiguration::default(),
};
if self.last_text_input_configuration.as_ref() != Some(&configuration) {
self.platform_window
.set_text_input_configuration(configuration.clone());
self.last_text_input_configuration = Some(configuration);
}
}
/// Register a mouse event listener on the window for the next frame. The type of event
/// is determined by the first parameter of the given listener. When the next frame is rendered
/// the listener will be cleared.
///
/// This method should only be called as part of the paint phase of element drawing.
pub fn on_mouse_event<Event: MouseEvent>(
&mut self,
mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
) {
self.invalidator.debug_assert_paint();
self.next_frame.mouse_listeners.push(Some(Box::new(
move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
if let Some(event) = event.downcast_ref() {
listener(event, phase, window, cx)
}
},
)));
}
/// Register a key event listener on this node for the next frame. The type of event
/// is determined by the first parameter of the given listener. When the next frame is rendered
/// the listener will be cleared.
///
/// This is a fairly low-level method, so prefer using event handlers on elements unless you have
/// a specific need to register a listener yourself.
///
/// This method should only be called as part of the paint phase of element drawing.
pub fn on_key_event<Event: KeyEvent>(
&mut self,
listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
) {
self.invalidator.debug_assert_paint();
self.next_frame.dispatch_tree.on_key_event(Rc::new(
move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
if let Some(event) = event.downcast_ref::<Event>() {
listener(event, phase, window, cx)
}
},
));
}
/// Register a modifiers changed event listener on the window for the next frame.
///
/// This is a fairly low-level method, so prefer using event handlers on elements unless you have
/// a specific need to register a global listener.
///
/// This method should only be called as part of the paint phase of element drawing.
pub fn on_modifiers_changed(
&mut self,
listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
) {
self.invalidator.debug_assert_paint();
self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
listener(event, window, cx)
},
));
}
/// Register a listener to be called when the given focus handle or one of its descendants receives focus.
/// This does not fire if the given focus handle - or one of its descendants - was previously focused.
/// Returns a subscription and persists until the subscription is dropped.
pub fn on_focus_in(
&mut self,
handle: &FocusHandle,
cx: &mut App,
mut listener: impl FnMut(&mut Window, &mut App) + 'static,
) -> Subscription {
let focus_id = handle.id;
let (subscription, activate) =
self.new_focus_listener(Box::new(move |event, window, cx| {
if event.is_focus_in(focus_id) {
listener(window, cx);
}
true
}));
cx.defer(move |_| activate());
subscription
}
/// Register a listener to be called when the given focus handle or one of its descendants loses focus.
/// Returns a subscription and persists until the subscription is dropped.
pub fn on_focus_out(
&mut self,
handle: &FocusHandle,
cx: &mut App,
mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
) -> Subscription {
let focus_id = handle.id;
let (subscription, activate) =
self.new_focus_listener(Box::new(move |event, window, cx| {
if let Some(blurred_id) = event.previous_focus_path.last().copied()
&& event.is_focus_out(focus_id)
{
let event = FocusOutEvent {
blurred: WeakFocusHandle {
id: blurred_id,
handles: Arc::downgrade(&cx.focus_handles),
},
};
listener(event, window, cx)
}
true
}));
cx.defer(move |_| activate());
subscription
}
fn reset_cursor_style(&self, cx: &mut App) {
// Set the cursor only if we're the active window.
if self.is_window_hovered() {
// A drag can start before the next paint records its cursor in the frame.
let style = cx
.active_drag_cursor_style()
.or_else(|| self.rendered_frame.cursor_style(self))
.unwrap_or(CursorStyle::Arrow);
cx.platform.set_cursor_style(style);
}
}
/// Dispatch a given keystroke as though the user had typed it.
/// You can create a keystroke with Keystroke::parse("").
pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
let keystroke = keystroke.with_simulated_ime();
let result = self.dispatch_event(
PlatformInput::KeyDown(KeyDownEvent {
keystroke: keystroke.clone(),
is_held: false,
prefer_character_input: false,
}),
cx,
);
if !result.propagate {
return true;
}
if let Some(input) = keystroke.key_char
&& let Some(mut input_handler) = self.platform_window.take_input_handler()
{
input_handler.dispatch_input(&input, self, cx);
self.platform_window.set_input_handler(input_handler);
return true;
}
false
}
/// Return a key binding string for an action, to display in the UI. Uses the highest precedence
/// binding for the action (last binding added to the keymap).
pub fn keystroke_text_for(&self, action: &dyn Action, cx: &App) -> String {
self.highest_precedence_binding_for_action(action)
.map(|binding| {
binding
.keystrokes()
.iter()
.map(|keystroke| keystroke.display(cx.platform_info().os).to_string())
.collect::<Vec<_>>()
.join(" ")
})
.unwrap_or_else(|| action.name().to_string())
}
/// Installs a modal input interceptor. Return true to consume the event
/// before normal dispatch. Passing None restores the ordinary input path.
/// The callback may remove itself. No callback runs while it is absent.
pub fn set_input_interceptor(
&mut self,
interceptor: Option<Rc<dyn Fn(&PlatformInput, &mut Window, &mut App) -> bool>>,
) {
self.input_interceptor = interceptor;
}
/// Dispatch a mouse, keyboard, or touch event on the window.
#[profiling::function]
pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
// A modal tool consumes the complete gesture before focus, native widgets,
// click tracking and application listeners can observe it. Cloning the
// Rc permits the interceptor to remove itself while handling an event.
if let Some(intercept) = self.input_interceptor.clone() {
if intercept(&event, self, cx) {
return DispatchEventResult { propagate: false, default_prevented: true };
}
}
#[cfg(feature = "profiler")]
self.window_profiler.begin_input(event.kind_name());
let update_count_before = self.invalidator.update_count();
// Track input modality for focus-visible styling and hover suppression.
// Hover is suppressed during keyboard modality so that keyboard navigation
// doesn't show hover highlights on the item under the mouse cursor.
let old_modality = self.last_input_modality;
self.last_input_modality = match &event {
PlatformInput::KeyDown(_) => InputModality::Keyboard,
PlatformInput::MouseMove(_) | PlatformInput::MouseDown(_) => InputModality::Mouse,
PlatformInput::Touch(_) => InputModality::Touch,
_ => self.last_input_modality,
};
if self.last_input_modality != old_modality {
self.refresh();
}
let was_inside = self.pointer_inside;
let pointer_moved = matches!(event, PlatformInput::MouseMove(_));
// vue-native fork: [`Window::pointer_inside`]. Exhaustive on purpose,
// so a new kind of input has to say which side it is on. A leave
// applies AFTER the event is dispatched, so the listeners that handle
// it (a file drag's exit, say) still see the element the pointer left.
let pointer_leaves = match &event {
PlatformInput::MouseMove(_)
| PlatformInput::MouseDown(_)
| PlatformInput::MouseUp(_)
| PlatformInput::MousePressure(_)
| PlatformInput::Scroll(_)
| PlatformInput::Pinch(_)
| PlatformInput::LongPress(_)
| PlatformInput::TouchDrag(_)
| PlatformInput::BackGesture(_)
| PlatformInput::Touch(_) => {
self.pointer_inside = true;
false
}
PlatformInput::FileDrop(FileDropEvent::Exited) | PlatformInput::MouseExited(_) => true,
PlatformInput::FileDrop(_) => {
self.pointer_inside = true;
false
}
PlatformInput::KeyDown(_)
| PlatformInput::KeyUp(_)
| PlatformInput::ModifiersChanged(_) => false,
};
// Handlers may set this to false by calling `stop_propagation`.
cx.propagate_event = true;
// Handlers may set this to true by calling `prevent_default`.
self.default_prevented = false;
let event = self.vn_pin_to_pointer_lock(event);
let event = match event {
// Track the mouse position with our own state, since accessing the platform
// API for the mouse position can only occur on the main thread.
PlatformInput::MouseMove(mouse_move) => {
self.mouse_position = mouse_move.position;
self.modifiers = mouse_move.modifiers;
PlatformInput::MouseMove(mouse_move)
}
PlatformInput::MouseDown(mouse_down) => {
self.mouse_position = mouse_down.position;
self.modifiers = mouse_down.modifiers;
PlatformInput::MouseDown(mouse_down)
}
PlatformInput::MouseUp(mouse_up) => {
self.mouse_position = mouse_up.position;
self.modifiers = mouse_up.modifiers;
PlatformInput::MouseUp(mouse_up)
}
PlatformInput::MousePressure(mouse_pressure) => {
PlatformInput::MousePressure(mouse_pressure)
}
PlatformInput::MouseExited(mouse_exited) => {
self.modifiers = mouse_exited.modifiers;
PlatformInput::MouseExited(mouse_exited)
}
PlatformInput::ModifiersChanged(modifiers_changed) => {
self.modifiers = modifiers_changed.modifiers;
self.capslock = modifiers_changed.capslock;
PlatformInput::ModifiersChanged(modifiers_changed)
}
PlatformInput::Scroll(scroll_wheel) => {
self.mouse_position = scroll_wheel.position;
self.modifiers = scroll_wheel.modifiers;
PlatformInput::Scroll(scroll_wheel)
}
PlatformInput::Pinch(pinch) => {
self.mouse_position = pinch.position;
self.modifiers = pinch.modifiers;
PlatformInput::Pinch(pinch)
}
// Translate dragging and dropping of external files from the operating system
// to internal drag and drop events.
PlatformInput::FileDrop(file_drop) => match file_drop {
FileDropEvent::Entered { position, paths } => {
self.mouse_position = position;
let source_window = self.handle.window_id();
if !cx.restore_platform_drag(source_window) && cx.active_drag.is_none() {
cx.active_drag = Some(AnyDrag {
value: Arc::new(paths.clone()),
view: cx.new(|_| paths).into(),
cursor_offset: position,
cursor_style: None,
external_payload_source: None,
});
}
PlatformInput::MouseMove(MouseMoveEvent {
position,
pressed_button: Some(MouseButton::Left),
modifiers: Modifiers::default(),
})
}
FileDropEvent::Pending { position } => {
self.mouse_position = position;
PlatformInput::MouseMove(MouseMoveEvent {
position,
pressed_button: Some(MouseButton::Left),
modifiers: Modifiers::default(),
})
}
FileDropEvent::Submit { position } => {
cx.activate(true);
self.mouse_position = position;
PlatformInput::MouseUp(MouseUpEvent {
button: MouseButton::Left,
position,
modifiers: Modifiers::default(),
click_count: 1,
})
}
FileDropEvent::Exited => {
if !cx.hand_restored_drag_to_platform(self.handle.window_id()) {
cx.active_drag.take();
}
self.refresh();
PlatformInput::FileDrop(FileDropEvent::Exited)
}
FileDropEvent::Ended => {
cx.end_platform_drag(self.handle.window_id());
self.refresh();
PlatformInput::FileDrop(FileDropEvent::Ended)
}
},
PlatformInput::Touch(touch) => PlatformInput::Touch(touch),
PlatformInput::LongPress(long_press) => {
self.mouse_position = if long_press.phase == crate::TouchPhase::Started {
long_press.start_position
} else {
long_press.position
};
if long_press.phase == crate::TouchPhase::Started {
self.long_press_capture = None;
}
PlatformInput::LongPress(long_press)
}
PlatformInput::TouchDrag(touch_drag) => {
self.mouse_position = touch_drag.start_position;
PlatformInput::TouchDrag(touch_drag)
}
PlatformInput::BackGesture(back) => {
self.mouse_position = back.start_position;
PlatformInput::BackGesture(back)
}
PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
};
if let Some(any_mouse_event) = event.mouse_event() {
self.dispatch_mouse_event(any_mouse_event, cx);
} else if let Some(any_key_event) = event.keyboard_event() {
self.dispatch_key_event(any_key_event, cx);
} else if let Some(touch_event) = event.touch_event() {
self.dispatch_touch_event(touch_event, cx);
}
if let PlatformInput::LongPress(long_press) = &event {
match long_press.phase {
crate::TouchPhase::Started if !self.default_prevented => {
self.long_press_capture = None;
}
crate::TouchPhase::Ended | crate::TouchPhase::Cancelled => {
self.long_press_capture = None;
}
crate::TouchPhase::Started | crate::TouchPhase::Moved => {}
}
}
// Must run after the move is dispatched: the platform owns the gesture afterwards, so this
// is the last chance for drag listeners to see the pointer leave and reset their state.
self.promote_external_drag_to_platform(&event, cx);
// vue-native fork: the leave, now that its listeners have run. The
// frame that drops the hover styles is asked for here.
if pointer_leaves && std::mem::replace(&mut self.pointer_inside, false) {
self.refresh();
}
self.vn_effect_pointer
.update(was_inside, self.pointer_inside, pointer_moved, cx);
let caused_invalidation = self.invalidator.update_count() > update_count_before;
if caused_invalidation {
self.input_rate_tracker.borrow_mut().record_input();
}
#[cfg(feature = "profiler")]
self.window_profiler.end_input(caused_invalidation);
DispatchEventResult {
propagate: cx.propagate_event,
default_prevented: self.default_prevented,
}
}
fn promote_external_drag_to_platform(&mut self, event: &PlatformInput, cx: &mut App) {
let PlatformInput::MouseMove(mouse_move) = event else {
return;
};
if mouse_move.pressed_button != Some(MouseButton::Left) {
return;
}
if Bounds::new(Point::default(), self.viewport_size).contains(&mouse_move.position) {
return;
}
if !self.platform_window.can_start_external_drag() {
return;
}
let Some(payload_source) = cx
.active_drag
.as_mut()
.and_then(|drag| drag.external_payload_source.take())
else {
return;
};
let Some(payload) = payload_source(self, cx) else {
return;
};
if self.platform_window.start_external_drag(&payload)
&& cx.hand_active_drag_to_platform(self.handle.window_id())
{
self.refresh();
}
}
/// Whether recognized touch pans may use the platform's predicted touch
/// positions ([`TouchEvent::predicted_position`]) to compensate for input
/// latency. Defaults to true.
pub fn touch_prediction_enabled(&self) -> bool {
self.touch_prediction_enabled
}
/// Sets whether recognized touch pans may use the platform's predicted
/// touch positions. Disabling drops [`TouchEvent::predicted_position`]
/// before gesture recognition, so pans track only raw touch positions.
pub fn set_touch_prediction_enabled(&mut self, enabled: bool) {
self.touch_prediction_enabled = enabled;
}
/// Runs the portable gesture recognizer over a raw touch event and
/// dispatches whatever it resolves (scroll steps, synthesized taps)
/// through the ordinary mouse-event path.
fn dispatch_touch_event(&mut self, event: &TouchEvent, cx: &mut App) {
let mut event = event.clone();
if !self.touch_prediction_enabled {
event.predicted_position = None;
}
let recognized_gestures = self.touch_gestures.handle_event(&event);
if event.phase == crate::TouchPhase::Started
&& let Some(touch_drag) = self.touch_gestures.offer_touch_drag(event.id)
{
self.dispatch_recognized_touch_gesture(touch_drag, cx);
}
if event.phase == crate::TouchPhase::Started
&& self.touch_gestures.pending_long_press().is_some()
{
self.long_press_capture = None;
}
let mut tapped = false;
for gesture in recognized_gestures {
tapped |= matches!(gesture, RecognizedTouchGesture::Tap { .. });
self.dispatch_recognized_touch_gesture(gesture, cx);
}
if event.phase == crate::TouchPhase::Started {
self.schedule_long_press_timer(cx);
} else if self.touch_gestures.pending_long_press().is_none() {
self.long_press_timer.take();
}
// The platform's touch-release handler may inspect the input handler
// as soon as this dispatch returns (the web platform decides virtual
// keyboard visibility there, inside the user gesture). Input handlers
// are registered during draw, so draw now to make them reflect any
// focus change the tap just caused.
if tapped && self.invalidator.is_dirty() {
self.draw(cx).clear(cx);
}
if self.touch_gestures.has_momentum() {
self.schedule_touch_momentum_tick();
}
}
fn dispatch_recognized_touch_gesture(&mut self, gesture: RecognizedTouchGesture, cx: &mut App) {
match gesture {
RecognizedTouchGesture::Scroll(scroll_wheel) => {
self.mouse_position = scroll_wheel.position;
cx.propagate_event = true;
self.dispatch_mouse_event(&scroll_wheel, cx);
}
RecognizedTouchGesture::Tap { down, up } => {
self.mouse_position = up.position;
cx.propagate_event = true;
self.dispatch_mouse_event(&down, cx);
cx.propagate_event = true;
self.dispatch_mouse_event(&up, cx);
}
RecognizedTouchGesture::TouchDrag(touch_drag) => {
self.mouse_position = touch_drag.start_position;
cx.propagate_event = true;
self.default_prevented = false;
let started = touch_drag.phase == crate::TouchPhase::Started;
self.dispatch_mouse_event(&touch_drag, cx);
if started {
self.touch_gestures
.resolve_touch_drag(self.default_prevented);
}
}
RecognizedTouchGesture::LongPress(long_press) => {
self.mouse_position = if long_press.phase == crate::TouchPhase::Started {
long_press.start_position
} else {
long_press.position
};
cx.propagate_event = true;
self.default_prevented = false;
let started = long_press.phase == crate::TouchPhase::Started;
let ended = matches!(
long_press.phase,
crate::TouchPhase::Ended | crate::TouchPhase::Cancelled
);
self.dispatch_mouse_event(&long_press, cx);
if started {
let claimed = self.default_prevented;
self.touch_gestures.resolve_long_press(claimed);
if !claimed {
self.long_press_capture = None;
}
}
if ended {
self.long_press_capture = None;
}
}
}
}
fn schedule_long_press_timer(&mut self, cx: &mut App) {
self.long_press_timer.take();
let Some((touch_id, duration)) = self.touch_gestures.pending_long_press() else {
return;
};
self.long_press_timer = Some(self.spawn(cx, async move |cx| {
cx.background_executor.timer(duration).await;
cx.update(move |window, cx| {
window.long_press_timer.take();
if let Some(gesture) = window.touch_gestures.offer_long_press(touch_id) {
window.dispatch_recognized_touch_gesture(gesture, cx);
}
})
.with_context(|| {
format!(
"handling long-press timer for window {:?}",
cx.window_handle().window_id()
)
})
.log_err();
}));
}
fn schedule_touch_momentum_tick(&mut self) {
self.on_next_frame(|window, cx| {
if let Some(gesture) = window.touch_gestures.tick_momentum() {
window.dispatch_recognized_touch_gesture(gesture, cx);
}
if window.touch_gestures.has_momentum() {
window.schedule_touch_momentum_tick();
}
});
}
fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
self.mouse_hit_test = self.rendered_frame.hit_test(self.mouse_position(), self.scale_factor);
// vue-native fork: the embedder narrows a press, a release or a wheel
// to the hitboxes it is FOR, before anyone hears it.
if let Some(refiner) = self.vn_hit_refiner.clone() {
let kind = if event.is::<crate::MouseDownEvent>() {
Some(VnHitKind::Down)
} else if event.is::<MouseUpEvent>() {
Some(VnHitKind::Up)
} else if event.is::<crate::ScrollEvent>() {
Some(VnHitKind::Scroll)
} else {
None
};
if let Some(kind) = kind {
let position = self.mouse_position();
refiner(kind, position, self, cx);
}
}
#[cfg(any(feature = "inspector", debug_assertions))]
if self.is_inspector_picking(cx) {
self.reset_cursor_style(cx);
self.handle_inspector_mouse_event(event, cx);
// When inspector is picking, all other mouse handling is skipped.
return;
}
let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
// Capture phase, events bubble from back to front. Handlers for this phase are used for
// special purposes, such as detecting events outside of a given Bounds.
for listener in &mut mouse_listeners {
let listener = listener.as_mut().unwrap();
listener(event, DispatchPhase::Capture, self, cx);
if !cx.propagate_event {
break;
}
}
// Bubble phase, where most normal handlers do their work.
if cx.propagate_event {
for listener in mouse_listeners.iter_mut().rev() {
let listener = listener.as_mut().unwrap();
listener(event, DispatchPhase::Bubble, self, cx);
if !cx.propagate_event {
break;
}
}
}
self.rendered_frame.mouse_listeners = mouse_listeners;
if cx.has_active_drag() {
if event.is::<MouseMoveEvent>() {
// If this was a mouse move event, redraw the window so that the
// active drag can follow the mouse cursor.
self.refresh();
} else if event.is::<MouseUpEvent>() {
// If this was a mouse up event, cancel the active drag and redraw
// the window.
cx.active_drag = None;
self.refresh();
}
}
// Auto-release pointer capture on mouse up
if event.is::<MouseUpEvent>() && self.captured_hitbox.is_some() {
self.captured_hitbox = None;
}
// Runs after the listeners so that a drag they start takes effect in this event. Resolving
// the cursor any earlier would briefly select whatever is under the pointer instead.
self.reset_cursor_style(cx);
}
// If modifiers are not excessive (e.g. AltGr), and the input handler is accepting text input,
// we prefer the text input over bindings.
fn input_preference(&mut self, event: &dyn Any, cx: &mut App) -> InputPreference {
let prefer_character_input = event
.downcast_ref::<KeyDownEvent>()
.is_some_and(|key_down_event| key_down_event.prefer_character_input);
if !prefer_character_input {
return InputPreference::KeyBindings;
}
let Some(mut input_handler) = self.platform_window.take_input_handler() else {
return InputPreference::KeyBindings;
};
let accepts_text_input = input_handler.accepts_text_input(self, cx);
self.platform_window.set_input_handler(input_handler);
if accepts_text_input {
InputPreference::CharacterInput
} else {
InputPreference::KeyBindings
}
}
fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
if self.invalidator.is_dirty() {
self.draw(cx).clear(cx);
}
// vue-native fork: `Window::vn_key_event_seq`.
self.vn_key_event_seq = self.vn_key_event_seq.wrapping_add(1);
let node_id = self.focus_node_id_in_rendered_frame(self.focus);
let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
let mut keystroke: Option<Keystroke> = None;
if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
if event.modifiers.number_of_modifiers() == 0
&& self.pending_modifier.modifiers.number_of_modifiers() == 1
&& !self.pending_modifier.saw_other_input
{
let key = match self.pending_modifier.modifiers {
modifiers if modifiers.shift => Some("shift"),
modifiers if modifiers.control => Some("control"),
modifiers if modifiers.alt => Some("alt"),
modifiers if modifiers.platform => Some("platform"),
modifiers if modifiers.function => Some("function"),
_ => None,
};
if let Some(key) = key {
keystroke = Some(Keystroke {
key: key.to_string(),
key_char: None,
modifiers: Modifiers::default(),
});
}
}
if self.pending_modifier.modifiers.number_of_modifiers() == 0
&& event.modifiers.number_of_modifiers() == 1
{
self.pending_modifier.saw_other_input = false
} else if event.modifiers.number_of_modifiers() > 1 {
self.pending_modifier.saw_other_input = true
}
self.pending_modifier.modifiers = event.modifiers
} else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
self.pending_modifier.saw_other_input = true;
keystroke = Some(key_down_event.keystroke.clone());
if key_down_event.keystroke.key_char.is_some()
&& matches!(
cx.cursor_hide_mode,
CursorHideMode::OnTyping | CursorHideMode::OnTypingAndAction
)
{
cx.platform.hide_cursor_until_mouse_moves();
}
}
let Some(keystroke) = keystroke else {
self.finish_dispatch_key_event(
event,
None,
InputPreference::KeyBindings,
dispatch_path,
self.context_stack(),
cx,
);
return;
};
let input_preference = self.input_preference(event, cx);
cx.propagate_event = true;
self.dispatch_keystroke_interceptors(
&keystroke,
input_preference,
self.context_stack(),
cx,
);
if !cx.propagate_event {
self.finish_dispatch_key_event(
event,
Some(&keystroke),
input_preference,
dispatch_path,
self.context_stack(),
cx,
);
return;
}
let mut currently_pending = self.pending_input.take().unwrap_or_default();
if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
currently_pending = PendingInput::default();
}
let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
currently_pending.keystrokes,
keystroke.clone(),
&dispatch_path,
);
if !match_result.to_replay.is_empty() {
self.replay_pending_input(match_result.to_replay, cx);
cx.propagate_event = true;
}
if !match_result.pending.is_empty() {
let previous_timeout = currently_pending.timeout.take();
currently_pending.keystrokes = match_result.pending;
currently_pending.focus = self.focus;
let text_input_requires_timeout = event
.downcast_ref::<KeyDownEvent>()
.filter(|key_down| key_down.keystroke.key_char.is_some())
.and_then(|_| self.platform_window.take_input_handler())
.map_or(false, |mut input_handler| {
let accepts = input_handler.accepts_text_input(self, cx);
self.platform_window.set_input_handler(input_handler);
accepts
});
let standalone_modifier = matches!(currently_pending.keystrokes.as_slice(), [keystroke] if keystroke.is_modifier_key());
let needs_timeout = previous_timeout.is_some()
|| match_result.pending_has_binding
|| text_input_requires_timeout
|| standalone_modifier;
currently_pending.timeout = if needs_timeout {
match previous_timeout {
Some(mut timeout) if timeout.is_paused() => {
timeout.reset_duration(PENDING_INPUT_TIMEOUT);
Some(timeout)
}
previous_timeout => {
drop(previous_timeout);
Some(self.new_pending_input_timeout(PENDING_INPUT_TIMEOUT, cx))
}
}
} else {
None
};
self.pending_input = Some(currently_pending);
self.pending_input_changed(cx);
cx.propagate_event = false;
return;
}
// Interceptors or replayed actions may have changed whether the input handler accepts text.
let input_preference = self.input_preference(event, cx);
if input_preference == InputPreference::KeyBindings {
for binding in match_result.bindings {
self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
if !cx.propagate_event {
self.dispatch_keystroke_observers(
&keystroke,
input_preference,
Some(binding.action.as_ref()),
match_result.context_stack,
cx,
);
self.pending_input_changed(cx);
return;
}
}
}
self.finish_dispatch_key_event(
event,
Some(&keystroke),
input_preference,
dispatch_path,
match_result.context_stack,
cx,
);
self.pending_input_changed(cx);
}
fn new_pending_input_timeout(&self, duration: Duration, cx: &App) -> PendingInputTimeout {
let (started_at, task) = self.start_pending_input_timeout(duration, cx);
PendingInputTimeout {
duration,
remaining: duration,
state: PendingInputTimeoutState::Running { started_at, task },
}
}
fn start_pending_input_timeout(&self, remaining: Duration, cx: &App) -> (Instant, Task<()>) {
let started_at = cx.background_executor().now();
let task = self.spawn(cx, async move |cx| {
cx.background_executor.timer(remaining).await;
cx.update(move |window, cx| {
let Some(currently_pending) = window
.pending_input
.take()
.filter(|pending| pending.focus == window.focus)
else {
return;
};
let node_id = window.focus_node_id_in_rendered_frame(window.focus);
let dispatch_path = window.rendered_frame.dispatch_tree.dispatch_path(node_id);
let to_replay = window
.rendered_frame
.dispatch_tree
.flush_dispatch(currently_pending.keystrokes, &dispatch_path);
window.pending_input_changed(cx);
window.replay_pending_input(to_replay, cx)
})
.with_context(|| {
format!(
"handling pending input timeout for window {:?}",
cx.window_handle().window_id()
)
})
.log_err();
});
(started_at, task)
}
fn finish_dispatch_key_event(
&mut self,
event: &dyn Any,
recognized_keystroke: Option<&Keystroke>,
input_preference: InputPreference,
dispatch_path: SmallVec<[DispatchNodeId; 32]>,
context_stack: Vec<KeyContext>,
cx: &mut App,
) {
self.dispatch_key_down_up_event(event, &dispatch_path, cx);
if !cx.propagate_event {
return;
}
self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
if !cx.propagate_event {
return;
}
if let Some(keystroke) = recognized_keystroke {
self.dispatch_keystroke_observers(keystroke, input_preference, None, context_stack, cx);
}
}
pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
self.pending_input_observers
.clone()
.retain(|callback| callback(self, cx));
}
fn defer_pending_input_changed(&self, cx: &mut App) {
// Avoid re-entrant entity updates by deferring observer notifications to the end of the
// current effect cycle, and only for this window.
let window_handle = self.handle;
cx.defer(move |cx| {
window_handle
.update(cx, |_, window, cx| {
window.pending_input_changed(cx);
})
.ok();
});
}
fn dispatch_key_down_up_event(
&mut self,
event: &dyn Any,
dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
cx: &mut App,
) {
// Capture phase
for node_id in dispatch_path {
let node = self.rendered_frame.dispatch_tree.node(*node_id);
for key_listener in node.key_listeners.clone() {
key_listener(event, DispatchPhase::Capture, self, cx);
if !cx.propagate_event {
return;
}
}
}
// Bubble phase
for node_id in dispatch_path.iter().rev() {
// Handle low level key events
let node = self.rendered_frame.dispatch_tree.node(*node_id);
for key_listener in node.key_listeners.clone() {
key_listener(event, DispatchPhase::Bubble, self, cx);
if !cx.propagate_event {
return;
}
}
}
}
fn dispatch_modifiers_changed_event(
&mut self,
event: &dyn Any,
dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
cx: &mut App,
) {
let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
return;
};
for node_id in dispatch_path.iter().rev() {
let node = self.rendered_frame.dispatch_tree.node(*node_id);
for listener in node.modifiers_changed_listeners.clone() {
listener(event, self, cx);
if !cx.propagate_event {
return;
}
}
}
}
/// Determine whether a potential multi-stroke key binding is in progress on this window.
pub fn has_pending_keystrokes(&self) -> bool {
self.pending_input().is_some()
}
#[cfg(test)]
pub(crate) fn pending_input_is_none(&self) -> bool {
self.pending_input.is_none()
}
pub(crate) fn clear_pending_keystrokes(&mut self, cx: &mut App) {
if self.pending_input.take().is_some() {
self.defer_pending_input_changed(cx);
}
}
/// Returns pending input that can still complete a multi-stroke key binding. Input left over
/// from a previous focus can never complete one.
pub fn pending_input(&self) -> Option<PendingInputStatus<'_>> {
self.pending_input
.as_ref()
.filter(|pending_input| pending_input.focus == self.focus)
.map(|pending_input| PendingInputStatus {
keystrokes: pending_input.keystrokes.as_slice(),
timeout: pending_input
.timeout
.as_ref()
.map(PendingInputTimeout::status),
})
}
/// Pauses or resumes the current pending input timeout on behalf of `owner`.
///
/// A paused timeout resumes automatically if `owner` is released. Returns whether the timeout
/// state changed. A timeout paused by one owner cannot be resumed by another.
pub fn set_pending_input_timeout_paused<T: 'static>(
&mut self,
owner: &Entity<T>,
paused: bool,
cx: &mut App,
) -> bool {
let owner_id = owner.entity_id();
if !paused {
return self.resume_pending_input_timeout(owner_id, cx);
}
let timeout = self
.pending_input
.as_ref()
.filter(|pending_input| pending_input.focus == self.focus)
.and_then(|pending_input| pending_input.timeout.as_ref());
let Some(timeout) = timeout else {
return false;
};
if timeout.is_paused() {
return false;
}
let release_subscription = self.observe_release(owner, cx, move |_, window, cx| {
window.resume_pending_input_timeout(owner_id, cx);
});
let now = cx.background_executor().now();
let changed = self
.pending_input
.as_mut()
.filter(|pending_input| pending_input.focus == self.focus)
.and_then(|pending_input| pending_input.timeout.as_mut())
.is_some_and(|timeout| {
timeout.pause(
PendingInputTimeoutPause {
owner_id,
_release_subscription: release_subscription,
},
now,
)
});
if changed {
self.defer_pending_input_changed(cx);
}
changed
}
fn resume_pending_input_timeout(&mut self, owner_id: EntityId, cx: &mut App) -> bool {
let Some(remaining) = self
.pending_input
.as_ref()
.and_then(|pending_input| pending_input.timeout.as_ref())
.filter(|timeout| timeout.pause_owner_id() == Some(owner_id))
.map(|timeout| timeout.remaining)
else {
return false;
};
let (started_at, task) = self.start_pending_input_timeout(remaining, cx);
let changed = self
.pending_input
.as_mut()
.and_then(|pending_input| pending_input.timeout.as_mut())
.is_some_and(|timeout| timeout.resume(owner_id, started_at, task));
if changed {
self.defer_pending_input_changed(cx);
}
changed
}
/// Returns the currently pending input keystrokes that might result in a multi-stroke key binding.
pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
self.pending_input()
.map(|pending_input| pending_input.keystrokes())
}
fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
let node_id = self.focus_node_id_in_rendered_frame(self.focus);
let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
'replay: for replay in replays {
let event = KeyDownEvent {
keystroke: replay.keystroke.clone(),
is_held: false,
prefer_character_input: true,
};
cx.propagate_event = true;
for binding in replay.bindings {
self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
if !cx.propagate_event {
self.dispatch_keystroke_observers(
&replay.keystroke,
InputPreference::KeyBindings,
Some(binding.action.as_ref()),
Vec::default(),
cx,
);
continue 'replay;
}
}
self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
if !cx.propagate_event {
continue 'replay;
}
if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
&& let Some(mut input_handler) = self.platform_window.take_input_handler()
{
input_handler.dispatch_input(&input, self, cx);
self.platform_window.set_input_handler(input_handler)
}
}
}
fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
focus_id
.and_then(|focus_id| {
self.rendered_frame
.dispatch_tree
.focusable_node_id(focus_id)
})
.unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
}
fn dispatch_action_on_node(
&mut self,
node_id: DispatchNodeId,
action: &dyn Action,
cx: &mut App,
) {
self.dispatch_action_on_node_inner(node_id, action, cx);
if !cx.propagate_event
&& cx.cursor_hide_mode == CursorHideMode::OnTypingAndAction
&& self.last_input_was_keyboard()
{
cx.platform.hide_cursor_until_mouse_moves();
}
}
fn dispatch_action_on_node_inner(
&mut self,
node_id: DispatchNodeId,
action: &dyn Action,
cx: &mut App,
) {
let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
// Capture phase for global actions.
cx.propagate_event = true;
if let Some(mut global_listeners) = cx
.global_action_listeners
.remove(&action.as_any().type_id())
{
for listener in &global_listeners {
#[cfg(feature = "profiler")]
self.window_profiler.begin_action_handler(action, cx);
listener(action.as_any(), DispatchPhase::Capture, cx);
#[cfg(feature = "profiler")]
self.window_profiler.end_action_handler();
if !cx.propagate_event {
break;
}
}
global_listeners.extend(
cx.global_action_listeners
.remove(&action.as_any().type_id())
.unwrap_or_default(),
);
cx.global_action_listeners
.insert(action.as_any().type_id(), global_listeners);
}
if !cx.propagate_event {
return;
}
// Capture phase for window actions.
for node_id in &dispatch_path {
let node = self.rendered_frame.dispatch_tree.node(*node_id);
for DispatchActionListener {
action_type,
listener,
} in node.action_listeners.clone()
{
let any_action = action.as_any();
if action_type == any_action.type_id() {
#[cfg(feature = "profiler")]
self.window_profiler.begin_action_handler(action, cx);
listener(any_action, DispatchPhase::Capture, self, cx);
#[cfg(feature = "profiler")]
self.window_profiler.end_action_handler();
if !cx.propagate_event {
return;
}
}
}
}
// Bubble phase for window actions.
for node_id in dispatch_path.iter().rev() {
let node = self.rendered_frame.dispatch_tree.node(*node_id);
for DispatchActionListener {
action_type,
listener,
} in node.action_listeners.clone()
{
let any_action = action.as_any();
if action_type == any_action.type_id() {
cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
#[cfg(feature = "profiler")]
self.window_profiler.begin_action_handler(action, cx);
listener(any_action, DispatchPhase::Bubble, self, cx);
#[cfg(feature = "profiler")]
self.window_profiler.end_action_handler();
if !cx.propagate_event {
return;
}
}
}
}
// Bubble phase for global actions.
if let Some(mut global_listeners) = cx
.global_action_listeners
.remove(&action.as_any().type_id())
{
for listener in global_listeners.iter().rev() {
cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
#[cfg(feature = "profiler")]
self.window_profiler.begin_action_handler(action, cx);
listener(action.as_any(), DispatchPhase::Bubble, cx);
#[cfg(feature = "profiler")]
self.window_profiler.end_action_handler();
if !cx.propagate_event {
break;
}
}
global_listeners.extend(
cx.global_action_listeners
.remove(&action.as_any().type_id())
.unwrap_or_default(),
);
cx.global_action_listeners
.insert(action.as_any().type_id(), global_listeners);
}
}
/// Register the given handler to be invoked whenever the global of the given type
/// is updated.
pub fn observe_global<G: Global>(
&mut self,
cx: &mut App,
f: impl Fn(&mut Window, &mut App) + 'static,
) -> Subscription {
let window_handle = self.handle;
let (subscription, activate) = cx.global_observers.insert_pending(
TypeId::of::<G>(),
Box::new(move |cx| {
window_handle
.update(cx, |_, window, cx| f(window, cx))
.is_ok()
}),
);
cx.defer(move |_| activate());
subscription
}
/// Focus the current window and bring it to the foreground at the platform level.
pub fn activate_window(&self) {
self.platform_window.activate();
}
/// Shows a previously hidden window, optionally requesting focus. Returns
/// false if unsupported; otherwise `completed` reports the native result.
pub fn show_window(
&self,
activate: bool,
should_show: impl FnOnce() -> bool + 'static,
completed: impl FnOnce(bool) + 'static,
) -> bool {
self.platform_window.show_window(activate, Box::new(should_show), Box::new(completed))
}
/// Requests that the operating system draw attention to this window.
pub fn request_attention(&self) {
self.platform_window.request_attention();
}
/// Minimize the current window at the platform level.
pub fn minimize_window(&self) {
self.platform_window.minimize();
}
/// Toggle full screen status on the current window at the platform level.
pub fn toggle_fullscreen(&self) {
self.platform_window.toggle_fullscreen();
}
/// Toggle simple (borderless) fullscreen, where the window covers the entire
/// screen including the menu bar and, on notched displays, the area around the
/// notch. Unlike [`Window::toggle_fullscreen`], this does not move the window
/// into its own Mission Control space. Only has an effect on macOS.
pub fn toggle_simple_fullscreen(&self) {
self.platform_window.toggle_simple_fullscreen();
}
/// Updates the IME panel position suggestions for languages like japanese, chinese.
pub fn invalidate_character_coordinates(&self) {
self.on_next_frame(|window, cx| {
if let Some(mut input_handler) = window.platform_window.take_input_handler() {
if let Some(bounds) = input_handler.selected_bounds(window, cx) {
window.platform_window.update_ime_position(bounds);
}
window.platform_window.set_input_handler(input_handler);
}
});
}
/// Present a platform dialog.
/// The provided message will be presented, along with buttons for each answer.
/// When a button is clicked, the returned Receiver will receive the index of the clicked button.
pub fn prompt<T>(
&mut self,
level: PromptLevel,
message: &str,
detail: Option<&str>,
answers: &[T],
cx: &mut App,
) -> oneshot::Receiver<usize>
where
T: Clone + Into<PromptButton>,
{
let prompt_builder = cx.prompt_builder.take();
let Some(prompt_builder) = prompt_builder else {
unreachable!("Re-entrant window prompting is not supported by GPUI");
};
let answers = answers
.iter()
.map(|answer| answer.clone().into())
.collect::<Vec<_>>();
let receiver = match &prompt_builder {
PromptBuilder::Default => self
.platform_window
.prompt(level, message, detail, &answers)
.unwrap_or_else(|| {
self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
}),
PromptBuilder::Custom(_) => {
self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
}
};
cx.prompt_builder = Some(prompt_builder);
receiver
}
fn build_custom_prompt(
&mut self,
prompt_builder: &PromptBuilder,
level: PromptLevel,
message: &str,
detail: Option<&str>,
answers: &[PromptButton],
cx: &mut App,
) -> oneshot::Receiver<usize> {
let (sender, receiver) = oneshot::channel();
let handle = PromptHandle::new(sender);
let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
self.prompt = Some(handle);
receiver
}
/// Returns whether a prompt rendered by GPUI is currently active in this window.
///
/// This is only true for prompts rendered in the window (see
/// [`App::set_prompt_builder`]), not for platform-native prompt dialogs.
pub fn has_active_prompt(&self) -> bool {
self.prompt.is_some()
}
/// Returns the current context stack.
pub fn context_stack(&self) -> Vec<KeyContext> {
let node_id = self.focus_node_id_in_rendered_frame(self.focus);
let dispatch_tree = &self.rendered_frame.dispatch_tree;
dispatch_tree
.dispatch_path(node_id)
.iter()
.filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
.collect()
}
/// Returns all available actions for the focused element.
pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
let node_id = self.focus_node_id_in_rendered_frame(self.focus);
let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
for action_type in cx.global_action_listeners.keys() {
if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
let action = cx.actions.build_action_type(action_type).ok();
if let Some(action) = action {
actions.insert(ix, action);
}
}
}
actions
}
/// Returns key bindings that invoke an action on the currently focused element. Bindings are
/// returned in the order they were added. For display, the last binding should take precedence.
pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
self.rendered_frame
.dispatch_tree
.bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
}
/// Returns the highest precedence key binding that invokes an action on the currently focused
/// element. This is more efficient than getting the last result of `bindings_for_action`.
pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
self.rendered_frame
.dispatch_tree
.highest_precedence_binding_for_action(
action,
&self.rendered_frame.dispatch_tree.context_stack,
)
}
/// Returns the key bindings for an action in a context.
pub fn bindings_for_action_in_context(
&self,
action: &dyn Action,
context: KeyContext,
) -> Vec<KeyBinding> {
let dispatch_tree = &self.rendered_frame.dispatch_tree;
dispatch_tree.bindings_for_action(action, &[context])
}
/// Returns the highest precedence key binding for an action in a context. This is more
/// efficient than getting the last result of `bindings_for_action_in_context`.
pub fn highest_precedence_binding_for_action_in_context(
&self,
action: &dyn Action,
context: KeyContext,
) -> Option<KeyBinding> {
let dispatch_tree = &self.rendered_frame.dispatch_tree;
dispatch_tree.highest_precedence_binding_for_action(action, &[context])
}
/// Returns any bindings that would invoke an action on the given focus handle if it were
/// focused. Bindings are returned in the order they were added. For display, the last binding
/// should take precedence.
pub fn bindings_for_action_in(
&self,
action: &dyn Action,
focus_handle: &FocusHandle,
) -> Vec<KeyBinding> {
let dispatch_tree = &self.rendered_frame.dispatch_tree;
let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
return vec![];
};
dispatch_tree.bindings_for_action(action, &context_stack)
}
/// Returns the highest precedence key binding that would invoke an action on the given focus
/// handle if it were focused. This is more efficient than getting the last result of
/// `bindings_for_action_in`.
pub fn highest_precedence_binding_for_action_in(
&self,
action: &dyn Action,
focus_handle: &FocusHandle,
) -> Option<KeyBinding> {
let dispatch_tree = &self.rendered_frame.dispatch_tree;
let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
}
/// Find the bindings that can follow the current input sequence for the current context stack.
pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
self.rendered_frame
.dispatch_tree
.possible_next_bindings_for_input(input, &self.context_stack())
}
fn context_stack_for_focus_handle(
&self,
focus_handle: &FocusHandle,
) -> Option<Vec<KeyContext>> {
let dispatch_tree = &self.rendered_frame.dispatch_tree;
let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
let context_stack: Vec<_> = dispatch_tree
.dispatch_path(node_id)
.into_iter()
.filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
.collect();
Some(context_stack)
}
/// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
pub fn listener_for<T: 'static, E>(
&self,
view: &Entity<T>,
f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
) -> impl Fn(&E, &mut Window, &mut App) + 'static {
let view = view.downgrade();
move |e: &E, window: &mut Window, cx: &mut App| {
view.update(cx, |view, cx| f(view, e, window, cx)).ok();
}
}
/// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
&self,
entity: &Entity<E>,
f: Callback,
) -> impl Fn(&mut Window, &mut App) + 'static {
let entity = entity.downgrade();
move |window: &mut Window, cx: &mut App| {
entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
}
}
/// Register a callback that can interrupt the closing of the current window based the returned boolean.
/// If the callback returns false, the window won't be closed.
pub fn on_window_should_close(
&self,
cx: &App,
f: impl Fn(&mut Window, &mut App) -> bool + 'static,
) {
let mut cx = self.to_async(cx);
self.platform_window.on_should_close(Box::new(move || {
cx.update(|window, cx| f(window, cx)).unwrap_or(true)
}))
}
/// Register an action listener on this node for the next frame. The type of action
/// is determined by the first parameter of the given listener. When the next frame is rendered
/// the listener will be cleared.
///
/// This is a fairly low-level method, so prefer using action handlers on elements unless you have
/// a specific need to register a listener yourself.
///
/// This method should only be called as part of the paint phase of element drawing.
pub fn on_action(
&mut self,
action_type: TypeId,
listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
) {
self.invalidator.debug_assert_paint();
self.next_frame
.dispatch_tree
.on_action(action_type, Rc::new(listener));
}
/// Register a capturing action listener on this node for the next frame if the condition is true.
/// The type of action is determined by the first parameter of the given listener. When the next
/// frame is rendered the listener will be cleared.
///
/// This is a fairly low-level method, so prefer using action handlers on elements unless you have
/// a specific need to register a listener yourself.
///
/// This method should only be called as part of the paint phase of element drawing.
pub fn on_action_when(
&mut self,
condition: bool,
action_type: TypeId,
listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
) {
self.invalidator.debug_assert_paint();
if condition {
self.next_frame
.dispatch_tree
.on_action(action_type, Rc::new(listener));
}
}
/// Read information about the GPU backing this window.
/// Currently returns None on Mac and Windows.
pub fn gpu_specs(&self) -> Option<GpuSpecs> {
self.platform_window.gpu_specs()
}
/// Perform titlebar double-click action.
/// This is macOS specific.
pub fn titlebar_double_click(&self) {
self.platform_window
.titlebar_double_click(self.is_resizable, self.is_minimizable);
}
/// Gets the window's title at the platform level.
/// This is macOS specific.
pub fn window_title(&self) -> String {
self.platform_window.get_title()
}
/// Returns a list of all tabbed windows and their titles.
/// This is macOS specific.
pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
self.platform_window.tabbed_windows()
}
/// Returns the tab bar visibility.
/// This is macOS specific.
pub fn tab_bar_visible(&self) -> bool {
self.platform_window.tab_bar_visible()
}
/// Merges all open windows into a single tabbed window.
/// This is macOS specific.
pub fn merge_all_windows(&self) {
self.platform_window.merge_all_windows()
}
/// Moves the tab to a new containing window.
/// This is macOS specific.
pub fn move_tab_to_new_window(&self) {
self.platform_window.move_tab_to_new_window()
}
/// Shows or hides the window tab overview.
/// This is macOS specific.
pub fn toggle_window_tab_overview(&self) {
self.platform_window.toggle_window_tab_overview()
}
/// Sets the tabbing identifier for the window.
/// This is macOS specific.
pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
self.platform_window
.set_tabbing_identifier(tabbing_identifier)
}
/// Request the OS to play an alert sound. On some platforms this is associated
/// with the window, for others it's just a simple global function call.
pub fn play_system_bell(&self) {
self.platform_window.play_system_bell()
}
/// Returns whether accessibility support is enabled for this window.
///
/// This is false when the app was created with [`crate::Application::new_inaccessible`].
/// Unlike [`Self::is_a11y_active`], this does not depend on whether assistive
/// technology is currently connected, so it can be used to gate subscriptions
/// that are only needed for accessibility.
pub fn is_a11y_enabled(&self) -> bool {
self.a11y.is_enabled()
}
/// Returns whether accessibility features are active for this frame,
/// i.e. whether assistive technology (such as a screen reader) is
/// connected and an accessibility tree is being built.
///
/// Use this to skip computing data during rendering that is only
/// observable through the accessibility tree. When accessibility is
/// activated, a redraw is forced, so gated work is recomputed before the
/// next tree update is sent to the platform.
///
/// See the [accessibility guide](crate::_accessibility) for an overview.
pub fn is_a11y_active(&self) -> bool {
self.a11y.is_active()
}
/// Debug representation of the last frame's accessibility information.
pub fn debug_a11y_tree_json(&self) -> Option<String> {
self.a11y.debug_tree_json()
}
/// Register a listener for an accessibility action on a specific node.
/// The listener will be called when a screen reader requests the given
/// action on the node identified by `node_id`.
///
/// See the [accessibility guide](crate::_accessibility) for an overview.
pub fn on_a11y_action(
&mut self,
node_id: accesskit::NodeId,
action: accesskit::Action,
listener: impl FnMut(Option<&accesskit::ActionData>, &mut Window, &mut App) + 'static,
) {
self.a11y
.action_listeners
.entry(node_id)
.or_default()
.push((action, Box::new(listener)));
}
#[cfg(not(target_family = "wasm"))]
pub(crate) fn handle_a11y_action(&mut self, request: accesskit::ActionRequest, cx: &mut App) {
// Take listeners out temporarily so the closures can borrow Window
// mutably, then restore them afterward.
if let Some(mut listeners) = self.a11y.action_listeners.remove(&request.target_node) {
let extra_data = request.data.as_ref();
let mut matched = false;
for (action, listener) in &mut listeners {
if *action == request.action {
listener(extra_data, self, cx);
matched = true;
}
}
self.a11y
.action_listeners
.insert(request.target_node, listeners);
if matched {
return;
}
}
// Fall back to built-in action handling.
match request.action {
accesskit::Action::Click => {
if let Some(bounds) = self.a11y.node_bounds.get(&request.target_node).copied() {
let center = bounds.center();
let mouse_down = PlatformInput::MouseDown(crate::MouseDownEvent {
button: MouseButton::Left,
position: center,
modifiers: Modifiers::default(),
click_count: 1,
first_mouse: false,
});
let mouse_up = PlatformInput::MouseUp(MouseUpEvent {
button: MouseButton::Left,
position: center,
modifiers: Modifiers::default(),
click_count: 1,
});
self.dispatch_event(mouse_down, cx);
self.dispatch_event(mouse_up, cx);
}
}
accesskit::Action::Focus => {
if let Some(focus_id) = self.a11y.focus_ids.get(&request.target_node).copied()
&& let Some(handle) = FocusHandle::for_id(focus_id, &cx.focus_handles)
{
self.focus(&handle, cx);
}
}
accesskit::Action::Blur => {
self.blur(cx);
}
_ => {
log::debug!(
"Unhandled a11y action: {:?} on {:?}",
request.action,
request.target_node
);
}
}
}
/// Toggles the inspector mode on this window.
#[cfg(any(feature = "inspector", debug_assertions))]
pub fn toggle_inspector(&mut self, cx: &mut App) {
self.inspector = match self.inspector {
None => Some(cx.new(|_| Inspector::new())),
Some(_) => {
self.rendered_frame.next_inspector_instance_ids = FxHashMap::default();
self.rendered_frame.inspector_hitboxes = FxHashMap::default();
self.next_frame.next_inspector_instance_ids = FxHashMap::default();
self.next_frame.inspector_hitboxes = FxHashMap::default();
None
}
};
self.refresh();
}
/// Returns true if the window is in inspector mode.
pub fn is_inspector_picking(&self, _cx: &App) -> bool {
#[cfg(any(feature = "inspector", debug_assertions))]
{
if let Some(inspector) = &self.inspector {
return inspector.read(_cx).is_picking();
}
}
false
}
/// Executes the provided function with mutable access to an inspector state.
#[cfg(any(feature = "inspector", debug_assertions))]
pub fn with_inspector_state<T: 'static, R>(
&mut self,
inspector_id: Option<&crate::InspectorElementId>,
cx: &mut App,
f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
) -> Option<R> {
let inspector_id = inspector_id?;
let inspector = self.inspector.as_ref()?;
if inspector.read(cx).active_element_id() != Some(inspector_id) {
return None;
}
let inspector = inspector.clone();
Some(inspector.update(cx, |inspector, _cx| {
inspector.with_active_element_state(self, f)
}))
}
#[cfg(any(feature = "inspector", debug_assertions))]
pub(crate) fn inspector_enabled(&self) -> bool {
self.inspector.is_some()
}
#[cfg(any(feature = "inspector", debug_assertions))]
pub(crate) fn build_inspector_element_id(
&mut self,
path: crate::InspectorElementPath,
) -> crate::InspectorElementId {
self.invalidator.debug_assert_paint_or_prepaint();
let path = Rc::new(path);
let next_instance_id = self
.next_frame
.next_inspector_instance_ids
.entry(path.clone())
.or_insert(0);
let instance_id = *next_instance_id;
*next_instance_id += 1;
crate::InspectorElementId { path, instance_id }
}
#[cfg(any(feature = "inspector", debug_assertions))]
fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
if let Some(inspector) = self.inspector.take() {
let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
inspector_element.prepaint_as_root(
point(self.viewport_size.width - inspector_width, px(0.0)),
size(inspector_width, self.viewport_size.height).into(),
self,
cx,
);
self.inspector = Some(inspector);
Some(inspector_element)
} else {
None
}
}
#[cfg(any(feature = "inspector", debug_assertions))]
fn paint_inspector(&mut self, inspector_element: Option<AnyElement>, cx: &mut App) {
if let Some(mut inspector_element) = inspector_element {
inspector_element.paint(self, cx);
};
}
/// Registers a hitbox that can be used for inspector picking mode, allowing users to select and
/// inspect UI elements by clicking on them.
#[cfg(any(feature = "inspector", debug_assertions))]
pub fn insert_inspector_hitbox(
&mut self,
hitbox_id: HitboxId,
inspector_id: Option<&crate::InspectorElementId>,
cx: &App,
) {
self.invalidator.debug_assert_paint_or_prepaint();
if !self.is_inspector_picking(cx) {
return;
}
if let Some(inspector_id) = inspector_id {
self.next_frame
.inspector_hitboxes
.insert(hitbox_id, inspector_id.clone());
}
}
#[cfg(any(feature = "inspector", debug_assertions))]
fn paint_inspector_hitbox(&mut self, cx: &App) {
if let Some(inspector) = self.inspector.as_ref() {
let inspector = inspector.read(cx);
if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
&& let Some(hitbox) = self
.next_frame
.hitboxes
.iter()
.find(|hitbox| hitbox.id == hitbox_id)
{
self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
}
}
}
#[cfg(any(feature = "inspector", debug_assertions))]
fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
let Some(inspector) = self.inspector.clone() else {
return;
};
if event.downcast_ref::<MouseMoveEvent>().is_some() {
inspector.update(cx, |inspector, _cx| {
if let Some((_, inspector_id)) =
self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
{
inspector.hover(inspector_id, self);
}
});
} else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
inspector.update(cx, |inspector, _cx| {
if let Some((_, inspector_id)) =
self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
{
inspector.select(inspector_id, self);
}
});
} else if let Some(event) = event.downcast_ref::<crate::ScrollEvent>() {
// This should be kept in sync with SCROLL_LINES in x11 platform.
const SCROLL_LINES: f32 = 3.0;
const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
let delta_y = event
.delta
.pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
.y;
if let Some(inspector) = self.inspector.clone() {
inspector.update(cx, |inspector, _cx| {
if let Some(depth) = inspector.pick_depth.as_mut() {
*depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
if *depth < 0.0 {
*depth = 0.0;
} else if *depth > max_depth {
*depth = max_depth;
}
if let Some((_, inspector_id)) =
self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
{
inspector.set_active_element_id(inspector_id, self);
}
}
});
}
}
}
#[cfg(any(feature = "inspector", debug_assertions))]
fn hovered_inspector_hitbox(
&self,
inspector: &Inspector,
frame: &Frame,
) -> Option<(HitboxId, crate::InspectorElementId)> {
if let Some(pick_depth) = inspector.pick_depth {
let depth = (pick_depth as i64).try_into().unwrap_or(0);
let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
let skip_count = (depth as usize).min(max_skipped);
for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
return Some((*hitbox_id, inspector_id.clone()));
}
}
}
None
}
/// For testing: set the current modifier keys state.
/// This does not generate any events.
#[cfg(any(test, feature = "test-support"))]
pub fn set_modifiers(&mut self, modifiers: Modifiers) {
self.modifiers = modifiers;
}
/// For testing: simulate a mouse move event to the given position.
/// This dispatches the event through the normal event handling path,
/// which will trigger hover states and tooltips.
#[cfg(any(test, feature = "test-support"))]
pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
let event = PlatformInput::MouseMove(MouseMoveEvent {
position,
modifiers: self.modifiers,
pressed_button: None,
});
let _ = self.dispatch_event(event, cx);
}
#[inline(never)]
fn take_element_state(
&mut self,
global_id: &GlobalElementId,
state_type: TypeId,
) -> ((GlobalElementId, TypeId), Option<ElementStateBox>) {
let key = (global_id.clone(), state_type);
self.next_frame.accessed_element_states.push(key.clone());
let state = self
.next_frame
.element_states
.remove(&key)
.or_else(|| self.rendered_frame.element_states.remove(&key));
(key, state)
}
#[inline(never)]
fn insert_element_state(
&mut self,
key: (GlobalElementId, TypeId),
state: ElementStateBox,
) -> Option<ElementStateBox> {
self.next_frame.element_states.insert(key, state)
}
#[inline(never)]
fn observe_keyed_state<S: 'static>(state: &Entity<S>, current_view: EntityId, cx: &mut App) {
cx.observe(state, move |_, cx| {
cx.notify(current_view);
})
.detach();
}
}
// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
slotmap::new_key_type! {
/// A unique identifier for a window.
pub struct WindowId;
}
impl WindowId {
/// Converts this window ID to a `u64`.
pub fn as_u64(&self) -> u64 {
self.0.as_ffi()
}
}
impl From<u64> for WindowId {
fn from(value: u64) -> Self {
WindowId(slotmap::KeyData::from_ffi(value))
}
}
/// A handle to a window with a specific root view type.
/// Note that this does not keep the window alive on its own.
pub struct WindowHandle<V> {
pub(crate) any_handle: AnyWindowHandle,
state_type: PhantomData<fn(V) -> V>,
}
impl_deref!([V] WindowHandle<V> => mut any_handle: AnyWindowHandle);
impl<V> Debug for WindowHandle<V> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WindowHandle")
.field("any_handle", &self.any_handle.id.as_u64())
.finish()
}
}
impl<V: 'static + Render> WindowHandle<V> {
/// Creates a new handle from a window ID.
/// This does not check if the root type of the window is `V`.
pub fn new(id: WindowId) -> Self {
WindowHandle {
any_handle: AnyWindowHandle {
id,
state_type: TypeId::of::<V>(),
root_entity_type_name: std::any::type_name::<V>(),
},
state_type: PhantomData,
}
}
/// Get the root view out of this window.
///
/// This will fail if the window is closed or if the root view's type does not match `V`.
#[cfg(any(test, feature = "test-support"))]
pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
where
C: AppContext,
{
cx.update_window(self.any_handle, |root_view, _, _| {
root_view
.downcast::<V>()
.map_err(|_| anyhow!("the type of the window's root view has changed"))
})?
}
/// Updates the root view of this window.
///
/// This will fail if the window has been closed or if the root view's type does not match
#[track_caller]
pub fn update<C, R>(
&self,
cx: &mut C,
update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
) -> Result<R>
where
C: AppContext,
{
cx.update_window(self.any_handle, |root_view, window, cx| {
let view = root_view
.downcast::<V>()
.map_err(|_| anyhow!("the type of the window's root view has changed"))?;
Ok(view.update(cx, |view, cx| update(view, window, cx)))
})?
}
/// Read the root view out of this window.
///
/// This will fail if the window is closed or if the root view's type does not match `V`.
pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
let x = cx
.windows
.get(self.id)
.and_then(|window| {
window
.as_deref()
.and_then(|window| window.root.clone())
.map(|root_view| root_view.downcast::<V>())
})
.context("window not found")?
.map_err(|_| anyhow!("the type of the window's root view has changed"))?;
Ok(x.read(cx))
}
/// Read the root view out of this window, with a callback
///
/// This will fail if the window is closed or if the root view's type does not match `V`.
pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
where
C: AppContext,
{
cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
}
/// Read the root view pointer off of this window.
///
/// This will fail if the window is closed or if the root view's type does not match `V`.
pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
where
C: AppContext,
{
cx.read_window(self, |root_view, _cx| root_view)
}
/// Check if this window is 'active'.
///
/// Will return `None` if the window is closed or currently
/// borrowed.
pub fn is_active(&self, cx: &mut App) -> Option<bool> {
cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
.ok()
}
}
impl<V> Copy for WindowHandle<V> {}
impl<V> Clone for WindowHandle<V> {
fn clone(&self) -> Self {
*self
}
}
impl<V> PartialEq for WindowHandle<V> {
fn eq(&self, other: &Self) -> bool {
self.any_handle == other.any_handle
}
}
impl<V> Eq for WindowHandle<V> {}
impl<V> Hash for WindowHandle<V> {
fn hash<H: Hasher>(&self, state: &mut H) {
self.any_handle.hash(state);
}
}
impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
fn from(val: WindowHandle<V>) -> Self {
val.any_handle
}
}
/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct AnyWindowHandle {
pub(crate) id: WindowId,
state_type: TypeId,
root_entity_type_name: &'static str,
}
impl AnyWindowHandle {
/// Get the ID of this window.
pub fn window_id(&self) -> WindowId {
self.id
}
/// Returns the name of the window's declared root entity type.
pub fn root_entity_type_name(&self) -> &'static str {
self.root_entity_type_name
}
/// Attempt to convert this handle to a window handle with a specific root view type.
/// If the types do not match, this will return `None`.
pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
if TypeId::of::<T>() == self.state_type {
Some(WindowHandle {
any_handle: *self,
state_type: PhantomData,
})
} else {
None
}
}
/// Updates the state of the root view of this window.
///
/// This will fail if the window has been closed.
#[track_caller]
pub fn update<C, R>(
self,
cx: &mut C,
update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
) -> Result<R>
where
C: AppContext,
{
cx.update_window(self, update)
}
/// Read the state of the root view of this window.
///
/// This will fail if the window has been closed.
pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
where
C: AppContext,
T: 'static,
{
let view = self
.downcast::<T>()
.context("the type of the window's root view has changed")?;
cx.read_window(&view, read)
}
}
impl HasWindowHandle for Window {
fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
self.platform_window.window_handle()
}
}
impl HasDisplayHandle for Window {
fn display_handle(
&self,
) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
self.platform_window.display_handle()
}
}
/// An identifier for an [`Element`].
///
/// Can be constructed with a string, a number, or both, as well
/// as other internal representations.
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub enum ElementId {
/// The ID of a View element
View(EntityId),
/// An integer ID.
Integer(u64),
/// A string based ID.
Name(SharedString),
/// A UUID.
Uuid(Uuid),
/// An ID that's equated with a focus handle.
FocusHandle(FocusId),
/// A combination of a name and an integer.
NamedInteger(SharedString, u64),
/// A path.
Path(Arc<std::path::Path>),
/// A code location.
CodeLocation(core::panic::Location<'static>),
/// A labeled child of an element.
NamedChild(Arc<ElementId>, SharedString),
/// A byte array ID (used for text-anchors)
OpaqueId([u8; 20]),
}
impl ElementId {
/// Constructs an `ElementId::NamedInteger` from a name and `usize`.
pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
Self::NamedInteger(name.into(), integer as u64)
}
}
impl Display for ElementId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
ElementId::Integer(ix) => write!(f, "{}", ix)?,
ElementId::Name(name) => write!(f, "{}", name)?,
ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
ElementId::Path(path) => write!(f, "{}", path.display())?,
ElementId::CodeLocation(location) => write!(f, "{}", location)?,
ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
ElementId::OpaqueId(opaque_id) => write!(f, "{:x?}", opaque_id)?,
}
Ok(())
}
}
impl TryInto<SharedString> for ElementId {
type Error = anyhow::Error;
fn try_into(self) -> anyhow::Result<SharedString> {
if let ElementId::Name(name) = self {
Ok(name)
} else {
anyhow::bail!("element id is not string")
}
}
}
impl From<u64> for ElementId {
fn from(id: u64) -> Self {
ElementId::Integer(id)
}
}
impl From<usize> for ElementId {
fn from(id: usize) -> Self {
ElementId::Integer(id as u64)
}
}
impl From<i32> for ElementId {
fn from(id: i32) -> Self {
Self::Integer(id as u64)
}
}
impl From<SharedString> for ElementId {
fn from(name: SharedString) -> Self {
ElementId::Name(name)
}
}
impl From<String> for ElementId {
fn from(name: String) -> Self {
ElementId::Name(name.into())
}
}
impl From<Arc<str>> for ElementId {
fn from(name: Arc<str>) -> Self {
ElementId::Name(name.into())
}
}
impl From<Arc<std::path::Path>> for ElementId {
fn from(path: Arc<std::path::Path>) -> Self {
ElementId::Path(path)
}
}
impl From<&'static str> for ElementId {
fn from(name: &'static str) -> Self {
ElementId::Name(SharedString::new_static(name))
}
}
impl<'a> From<&'a FocusHandle> for ElementId {
fn from(handle: &'a FocusHandle) -> Self {
ElementId::FocusHandle(handle.id)
}
}
impl From<(&'static str, EntityId)> for ElementId {
fn from((name, id): (&'static str, EntityId)) -> Self {
ElementId::NamedInteger(SharedString::new_static(name), id.as_u64())
}
}
impl From<(&'static str, usize)> for ElementId {
fn from((name, id): (&'static str, usize)) -> Self {
ElementId::NamedInteger(SharedString::new_static(name), id as u64)
}
}
impl From<(SharedString, usize)> for ElementId {
fn from((name, id): (SharedString, usize)) -> Self {
ElementId::NamedInteger(name, id as u64)
}
}
impl From<(&'static str, u64)> for ElementId {
fn from((name, id): (&'static str, u64)) -> Self {
ElementId::NamedInteger(SharedString::new_static(name), id)
}
}
impl From<Uuid> for ElementId {
fn from(value: Uuid) -> Self {
Self::Uuid(value)
}
}
impl From<(&'static str, u32)> for ElementId {
fn from((name, id): (&'static str, u32)) -> Self {
ElementId::NamedInteger(SharedString::new_static(name), u64::from(id))
}
}
impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
fn from((id, name): (ElementId, T)) -> Self {
ElementId::NamedChild(Arc::new(id), name.into())
}
}
impl From<&'static core::panic::Location<'static>> for ElementId {
fn from(location: &'static core::panic::Location<'static>) -> Self {
ElementId::CodeLocation(*location)
}
}
impl From<[u8; 20]> for ElementId {
fn from(opaque_id: [u8; 20]) -> Self {
ElementId::OpaqueId(opaque_id)
}
}
/// A rectangle to be rendered in the window at the given position and size.
/// Passed as an argument [`Window::paint_quad`].
#[derive(Clone)]
pub struct PaintQuad {
/// The bounds of the quad within the window.
pub bounds: Bounds<Pixels>,
/// The radii of the quad's corners.
pub corner_radii: Corners<Pixels>,
/// The background color of the quad.
pub background: Background,
/// The widths of the quad's borders.
pub border_widths: Edges<Pixels>,
/// The color of the quad's borders.
pub border_color: Hsla,
/// The style of the quad's borders.
pub border_style: BorderStyle,
/// vue-native fork: CSS `corner-shape` of `corner_radii`.
pub corner_shapes: Corners<CornerShape>,
}
/// Options for [`Window::paint_backdrop_blur_rect`].
#[derive(Clone, Copy, Debug)]
pub struct BackdropBlurEffect {
/// Approximate uniform backdrop blur radius in logical pixels, matching the
/// CSS `backdrop-filter: blur(<length>)` radius.
///
/// Non-positive values are treated as zero. Renderers may clamp large radii
/// to a fixed implementation limit.
pub radius: Pixels,
/// Tint color composited over the blurred backdrop.
///
/// CSS models the element's own `background-color` as a separate paint over
/// the filtered backdrop, so callers implementing `backdrop-filter` should
/// leave this transparent and paint a normal quad instead.
pub tint: Hsla,
}
impl BackdropBlurEffect {
/// Create a backdrop blur effect with a uniform CSS-like radius.
///
/// Non-positive values disable blur while still allowing a tint to be painted.
pub fn new(radius: Pixels) -> Self {
Self {
radius,
..Self::default()
}
}
/// Set a tint color composited over the blurred backdrop.
pub fn tint(mut self, tint: impl Into<Hsla>) -> Self {
self.tint = tint.into();
self
}
}
impl Default for BackdropBlurEffect {
fn default() -> Self {
Self {
radius: px(20.),
tint: transparent_black(),
}
}
}
impl PaintQuad {
/// Sets the corner radii of the quad.
pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
PaintQuad {
corner_radii: corner_radii.into(),
..self
}
}
/// Sets the border widths of the quad.
pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
PaintQuad {
border_widths: border_widths.into(),
..self
}
}
/// Sets the border color of the quad.
pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
PaintQuad {
border_color: border_color.into(),
..self
}
}
/// Sets the background color of the quad.
pub fn background(self, background: impl Into<Background>) -> Self {
PaintQuad {
background: background.into(),
..self
}
}
/// vue-native fork: sets the CSS `corner-shape` of the quad's corners.
pub fn corner_shapes(self, corner_shapes: Corners<CornerShape>) -> Self {
PaintQuad {
corner_shapes,
..self
}
}
}
/// vue-native: a host's smaller copy of an image that is about to be drawn
/// well below its own size.
///
/// The sprite atlas keeps one mip level and samples it LINEARLY, so a 1080 px
/// picture drawn at 40 px reads a 2×2 neighbourhood out of every 27×27 block
/// and aliases. [`Window::paint_image`] asks this function first, with the
/// image, the frame, and the size in device pixels the frame is about to be
/// drawn at; `Some` is drawn instead (its frame 0), from its own atlas tile.
/// `None` draws the image as it is. Called during paint, so it must be cheap
/// whenever it says `None`.
pub type ImageResampler =
fn(&Arc<RenderImage>, usize, Size<DevicePixels>) -> Option<Arc<RenderImage>>;
static IMAGE_RESAMPLER: std::sync::OnceLock<ImageResampler> = std::sync::OnceLock::new();
/// vue-native: installs the process's [`ImageResampler`]. The first one
/// installed stays.
pub fn set_image_resampler(resampler: ImageResampler) {
let _ = IMAGE_RESAMPLER.set(resampler);
}
/// Creates a quad with the given parameters.
pub fn quad(
bounds: Bounds<Pixels>,
corner_radii: impl Into<Corners<Pixels>>,
background: impl Into<Background>,
border_widths: impl Into<Edges<Pixels>>,
border_color: impl Into<Hsla>,
border_style: BorderStyle,
) -> PaintQuad {
PaintQuad {
bounds,
corner_radii: corner_radii.into(),
background: background.into(),
border_widths: border_widths.into(),
border_color: border_color.into(),
border_style,
corner_shapes: Corners::default(),
}
}
/// Creates a filled quad with the given bounds and background color.
pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
PaintQuad {
bounds: bounds.into(),
corner_radii: (0.).into(),
background: background.into(),
border_widths: (0.).into(),
border_color: transparent_black(),
border_style: BorderStyle::default(),
corner_shapes: Corners::default(),
}
}
/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
pub fn outline(
bounds: impl Into<Bounds<Pixels>>,
border_color: impl Into<Hsla>,
border_style: BorderStyle,
) -> PaintQuad {
PaintQuad {
bounds: bounds.into(),
corner_radii: (0.).into(),
background: transparent_black().into(),
border_widths: (1.).into(),
border_color: border_color.into(),
border_style,
corner_shapes: Corners::default(),
}
}
/// vue-native fork: [`Shadow::inset`] for an outer shadow drawn outside the
/// element's border box only (CSS). The shaders cut the element out of it.
pub(crate) const SHADOW_OUTSIDE_BOX: u32 = 0;
/// vue-native fork: [`Shadow::inset`] for an inset shadow.
pub(crate) const SHADOW_INSET: u32 = 1;
/// vue-native fork: [`Shadow::inset`] for an outer shadow that also fills the
/// area under the border box ([`Window::paint_drop_shadows_under_box`]).
pub(crate) const SHADOW_UNDER_BOX: u32 = 2;
/// vue-native fork: an outer shadow's corner radius for a border-box corner of
/// radius `radius` and a spread of `spread` (CSS Backgrounds 3 §7.1.1). A
/// positive spread grows a rounded corner by the spread, and a corner rounded
/// by less than the spread by less, so a square corner stays square. A
/// negative spread shrinks it, down to 0.
fn spread_shadow_radius(radius: Pixels, spread: Pixels) -> Pixels {
if spread <= Pixels::ZERO {
return (radius + spread).max(Pixels::ZERO);
}
let ratio = radius / spread;
if ratio >= 1.0 {
radius + spread
} else {
radius + spread * (1.0 + (ratio - 1.0).powi(3))
}
}
#[inline(never)]
fn with_element_arena_erased(callback: &mut dyn FnMut(&mut Arena)) -> Result<(), AccessError> {
if let Some(arena_pointer) = CURRENT_ELEMENT_ARENA.try_with(Cell::get)? {
// SAFETY: The pointer is valid for the duration of the draw operation
// that set it, and we're being called during that same draw.
let arena_cell = unsafe { &*arena_pointer };
callback(&mut arena_cell.borrow_mut());
Ok(())
} else {
ELEMENT_ARENA.try_with(|arena| callback(&mut arena.borrow_mut()))
}
}
#[cfg(test)]
mod tests {
use std::{
cell::{Cell, RefCell},
path::PathBuf,
rc::Rc,
time::Duration,
};
use crate::{
AnyWindowHandle, AppContext as _, BackGestureEvent, BackGesturePhase, Bounds, ContentMask,
Context, CursorStyle, DispatchPhase, DragMoveEvent, Empty, ExternalDragPayload,
ExternalPaths, FileDragPaths, FileDropEvent, FocusHandle, InputEvent as _,
InteractiveElement as _, IntoElement, KeyDownEvent, Keystroke, LongPressEvent, MouseButton,
MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, PlatformInput, Point,
Render, RequestFrameOptions, ScaledPixels, StatefulInteractiveElement as _, Styled,
TestAppContext, ThermalState, TouchDragEvent, TouchEvent, TouchId, TouchPhase, Underline,
UnderlineStyle, Window, WindowAppearance, WindowOptions, canvas, div, hsla, point, px,
size,
};
#[gpui::test]
async fn test_focus_handle_release(cx: &mut TestAppContext) {
let (handle, survivor) = cx.update(|cx| (cx.focus_handle(), cx.focus_handle()));
let handle_id = handle.id;
let weak_handle = handle.downgrade();
let retained = handle.clone();
drop(handle);
cx.update(|_| {});
cx.read(|cx| {
let handles = cx.focus_handles.read();
assert_eq!(handles.handles.len(), 2);
assert!(handles.dropped_handles.is_empty());
});
assert_eq!(weak_handle.upgrade().as_ref(), Some(&retained));
cx.background_spawn(async move { drop(retained) }).await;
assert_eq!(weak_handle.upgrade(), None);
cx.read(|cx| {
assert_eq!(cx.focus_handles.read().dropped_handles, [handle_id]);
});
cx.update(|_| {});
cx.read(|cx| {
let handles = cx.focus_handles.read();
assert_eq!(handles.handles.keys().collect::<Vec<_>>(), [survivor.id]);
assert!(handles.dropped_handles.is_empty());
});
let replacements = cx.update(|cx| [cx.focus_handle(), cx.focus_handle()]);
assert_eq!(weak_handle.upgrade(), None);
cx.update(|cx| {
drop(replacements);
cx.defer(move |_| drop(survivor));
});
cx.read(|cx| {
let handles = cx.focus_handles.read();
assert_eq!(handles.handles.len(), 0);
assert!(handles.dropped_handles.is_empty());
});
}
#[gpui::test]
fn test_dropped_focus_handle_blurs_only_its_windows(cx: &mut TestAppContext) {
let windows = [
cx.add_window(|_, _| EmptyView),
cx.add_window(|_, _| EmptyView),
cx.add_window(|_, _| EmptyView),
cx.add_window(|_, _| EmptyView),
cx.add_window(|_, _| EmptyView),
];
let (handle, other_handle, survivor) =
cx.update(|cx| (cx.focus_handle(), cx.focus_handle(), cx.focus_handle()));
for window in &windows[..2] {
window
.update(cx, |_, window, cx| window.focus(&handle, cx))
.expect("window exists");
}
windows[2]
.update(cx, |_, window, cx| window.focus(&other_handle, cx))
.expect("window exists");
windows[3]
.update(cx, |_, window, cx| window.focus(&survivor, cx))
.expect("window exists");
cx.update(|cx| {
for _ in 0..1_000 {
drop(cx.focus_handle());
}
drop((handle, other_handle));
});
for window in &windows[..3] {
window
.update(cx, |_, window, _| assert_eq!(window.focus, None))
.expect("window exists");
}
windows[3]
.update(cx, |_, window, cx| {
assert_eq!(window.focused(cx).as_ref(), Some(&survivor));
assert_eq!(window.focus_generation, 1);
})
.expect("window exists");
windows[4]
.update(cx, |_, window, _| {
assert_eq!(window.focus, None);
assert_eq!(window.focus_generation, 0);
})
.expect("window exists");
}
#[gpui::test]
fn test_native_close_defers_app_access(cx: &mut TestAppContext) {
let window = cx.add_window(|_, _| EmptyView);
let platform_window = cx.test_window(window.into());
{
let app = cx.app.borrow_mut();
platform_window.simulate_close();
assert!(app.windows.contains_key(window.window_id()));
}
cx.run_until_parked();
assert!(!cx.app.borrow().windows.contains_key(window.window_id()));
}
#[cfg(feature = "profiler")]
#[gpui::test]
fn test_frame_requests_and_skips_are_journaled(cx: &mut TestAppContext) {
use crate::FrameRequestSource;
use crate::profiler::journal::{
self, ForegroundJournalEntry, FrameSkipReason, IntervalBoundary,
};
use scheduler::Instant;
cx.app.borrow_mut().mode = crate::app::GpuiMode::Production;
let window = cx.add_window(|_, _| EmptyView);
let platform_window = cx.test_window(window.into());
platform_window.simulate_frame_request(RequestFrameOptions::default());
let (journal, _guard) = journal::install_test_foreground_journal(64, 4);
let mut collector = journal.collector();
for (signal_at, source) in [
(Some(Instant::now()), FrameRequestSource::NativeCallback),
(Some(Instant::now()), FrameRequestSource::LocalSchedule),
(None, FrameRequestSource::NativeCallback),
] {
platform_window.simulate_frame_request(RequestFrameOptions {
signal_at,
signal_source: source,
require_presentation: true,
..Default::default()
});
let entries = collector.collect_unseen().entries;
let signal_index = entries
.iter()
.position(|entry| {
matches!(
entry,
ForegroundJournalEntry::PlatformSignal(signal)
if signal.window_id == window.window_id()
&& signal.signal_at == signal_at
&& signal.source == source
&& signal_at.is_none_or(|at| signal.handled_at >= at)
)
})
.expect("frame request metadata");
let skip_index = entries
.iter()
.position(|entry| {
matches!(
entry,
ForegroundJournalEntry::Boundary(IntervalBoundary::FrameSkipped(skipped))
if skipped.window_id == window.window_id()
&& skipped.reason == FrameSkipReason::NoRenderNeeded
)
})
.expect("completed no-render boundary");
assert!(signal_index < skip_index);
}
}
#[cfg(feature = "profiler")]
#[gpui::test]
fn test_frame_demand_survives_throttling(cx: &mut TestAppContext) {
use crate::profiler::journal::{
self, ForegroundJournalEntry, FrameSkipReason, IntervalBoundary,
};
use scheduler::Instant;
// Test mode draws during effect flushing, bypassing platform frame throttling.
cx.app.borrow_mut().mode = crate::app::GpuiMode::Production;
let (journal, _guard) = journal::install_test_foreground_journal(256, 4);
let mut collector = journal.collector();
for (initially_dirty, schedule_callback) in [(true, false), (false, true)] {
// Keep the throttle closed without depending on short wall-clock deadlines.
let window = cx
.app
.borrow_mut()
.open_window(
WindowOptions {
inactive_frame_interval: Some(Duration::from_secs(3600)),
..Default::default()
},
|_, cx| cx.new(|_| EmptyView),
)
.expect("open inactive test window");
let platform_window = cx.test_window(window.into());
platform_window.simulate_active_status_change(false);
platform_window.simulate_frame_request(RequestFrameOptions::default());
let callback_ran = Rc::new(Cell::new(false));
let draws_before = window
.update(cx, |_, window, _| {
let draws_before = window
.frame_duration_snapshot()
.draw_duration_histogram
.len();
if initially_dirty {
window.refresh();
}
if schedule_callback {
window.on_next_frame({
let callback_ran = callback_ran.clone();
move |window, _| {
callback_ran.set(true);
window.refresh();
}
});
}
draws_before
})
.expect("schedule throttled frame");
// Skips only seal retained work, so give the throttled skip some.
let input_at = Instant::now();
journal::record_input(journal::InputTiming {
kind: "test",
start: input_at,
end: input_at,
caused_invalidation: false,
});
collector.collect_unseen();
let wakes_before = platform_window.frame_wake_count();
platform_window.simulate_frame_request(RequestFrameOptions {
signal_at: Some(Instant::now()),
..Default::default()
});
window
.update(cx, |_, window, _| {
assert_eq!(
window
.frame_duration_snapshot()
.draw_duration_histogram
.len(),
draws_before,
);
})
.expect("inspect deferred frame");
assert!(!callback_ran.get());
assert!(platform_window.frame_scheduled());
assert!(platform_window.frame_wake_count() > wakes_before);
assert!(collector.collect_unseen().entries.iter().any(|entry| {
matches!(
entry,
ForegroundJournalEntry::Boundary(IntervalBoundary::FrameSkipped(skipped))
if skipped.window_id == window.window_id()
&& skipped.reason == FrameSkipReason::InactiveFrameRateLimit
)
}));
platform_window.simulate_frame_request(RequestFrameOptions {
signal_at: Some(Instant::now()),
require_presentation: true,
..Default::default()
});
window
.update(cx, |_, window, _| {
assert_eq!(
window
.frame_duration_snapshot()
.draw_duration_histogram
.len(),
draws_before + 1,
);
})
.expect("inspect presented frame");
assert_eq!(callback_ran.get(), schedule_callback);
}
}
/// A stale cache is only visible if the snapshot reports GPUI's cached
/// value separately from what the platform reports now.
#[gpui::test]
fn test_debug_state_reports_cached_and_platform_values(cx: &mut TestAppContext) {
use crate::WindowVisibility;
let window = cx.add_window(|_, _| EmptyView);
let window_id = window.window_id().as_u64();
let window_state = |cx: &mut TestAppContext| {
let state = cx.update(|cx| cx.debug_state());
state["windows"]
.as_array()
.and_then(|windows| windows.iter().find(|window| window["id"] == window_id))
.cloned()
.expect("the open window is listed")
};
let state = window_state(cx);
assert_eq!(state["visibility"]["cached"], "Visible");
assert_eq!(state["visibility"]["platform"], "Visible");
cx.test_window(window.into())
.simulate_visibility_change(WindowVisibility::Hidden);
let state = window_state(cx);
assert_eq!(state["visibility"]["cached"], "Hidden");
assert_eq!(state["visibility"]["platform"], "Hidden");
}
/// Visibility transitions reach observers exactly once each, with the new
/// state already stored on the window, and never wake the platform for a
/// frame: the platform requests one itself when it resumes presenting.
#[gpui::test]
fn test_window_visibility(cx: &mut TestAppContext) {
use crate::WindowVisibility;
let window = cx.add_window(|_, _| EmptyView);
let observed = Rc::new(RefCell::new(Vec::new()));
let _subscription = window
.update(cx, {
let observed = observed.clone();
move |_, window, _| {
assert_eq!(window.visibility(), WindowVisibility::Visible);
assert!(window.is_visible());
window.observe_window_visibility(move |visibility, window, _| {
assert_eq!(window.visibility(), visibility);
observed.borrow_mut().push(visibility);
})
}
})
.unwrap();
let test_window = cx.test_window(window.into());
let frame_wake_count = test_window.frame_wake_count();
test_window.simulate_visibility_change(WindowVisibility::Hidden);
assert_eq!(*observed.borrow(), [WindowVisibility::Hidden]);
window
.update(cx, |_, window, _| assert!(!window.is_visible()))
.unwrap();
// Platforms may report the same state again; observers only see changes.
test_window.simulate_visibility_change(WindowVisibility::Hidden);
assert_eq!(observed.borrow().len(), 1);
test_window.simulate_visibility_change(WindowVisibility::Visible);
assert_eq!(
*observed.borrow(),
[WindowVisibility::Hidden, WindowVisibility::Visible]
);
window
.update(cx, |_, window, _| assert!(window.is_visible()))
.unwrap();
assert_eq!(test_window.frame_wake_count(), frame_wake_count);
}
/// App learns display state from the platform's display notifications,
/// and a window from the platform's report of which display it is on.
#[gpui::test]
fn test_display_tracking(cx: &mut TestAppContext) {
use crate::{DisplayChanges, DisplayEvent, DisplayId, Subscription};
let sixty_hertz = Duration::from_secs(1) / 60;
let one_hundred_twenty_hertz = Duration::from_secs(1) / 120;
let one_hundred_forty_four_hertz = Duration::from_secs(1) / 144;
let display_events = Rc::new(RefCell::new(Vec::new()));
let _display_subscription = cx.update({
let display_events = display_events.clone();
move |cx| cx.observe_displays(move |event, _| display_events.borrow_mut().push(event))
});
let window = cx.add_window(|window, cx| DisplayTracker {
refresh_intervals: Vec::new(),
_subscription: cx.observe_window_display(
window,
|tracker: &mut DisplayTracker, window, cx| {
tracker.refresh_intervals.push(window.refresh_interval(cx));
},
),
});
let window_notifications = Rc::new(RefCell::new(Vec::new()));
let _window_subscription = window
.update(cx, {
let window_notifications = window_notifications.clone();
move |_, window, cx| {
assert_eq!(window.refresh_interval(cx), Some(sixty_hertz));
window.observe_window_display(move |window, cx| {
window_notifications
.borrow_mut()
.push((window.display_id, window.refresh_interval(cx)));
})
}
})
.unwrap();
let test_window = cx.test_window(window.into());
// The window may hear that it moved before App hears the display was
// connected. App learns about the display before the window's
// observers run, and the platform's later notification changes
// nothing.
cx.test_platform()
.connect_display(DisplayId(2), Some(one_hundred_twenty_hertz));
test_window.simulate_move_to_display(DisplayId(2));
assert_eq!(
window_notifications.take(),
[(Some(DisplayId(2)), Some(one_hundred_twenty_hertz))]
);
assert_eq!(display_events.take(), [DisplayEvent::Added(DisplayId(2))]);
cx.simulate_display_refresh_interval_change(DisplayId(2), Some(one_hundred_twenty_hertz));
assert!(window_notifications.borrow().is_empty());
// Platforms may report a move that isn't one.
test_window.simulate_move_to_display(DisplayId(2));
assert!(window_notifications.borrow().is_empty());
cx.simulate_display_refresh_interval_change(
DisplayId(2),
Some(one_hundred_forty_four_hertz),
);
assert_eq!(
window_notifications.take(),
[(Some(DisplayId(2)), Some(one_hundred_forty_four_hertz))]
);
// Changes to a display the window isn't on don't notify it.
cx.simulate_display_refresh_interval_change(DisplayId(1), Some(one_hundred_twenty_hertz));
cx.simulate_display_removed(DisplayId(1));
assert!(window_notifications.borrow().is_empty());
assert_eq!(
display_events.take(),
[
DisplayEvent::Changed {
id: DisplayId(2),
changes: DisplayChanges::REFRESH_INTERVAL,
},
DisplayEvent::Changed {
id: DisplayId(1),
changes: DisplayChanges::REFRESH_INTERVAL,
},
DisplayEvent::Removed(DisplayId(1)),
]
);
window
.update(cx, |tracker, _, _| {
assert_eq!(
tracker.refresh_intervals,
[
Some(one_hundred_twenty_hertz),
Some(one_hundred_forty_four_hertz)
]
);
})
.unwrap();
struct DisplayTracker {
refresh_intervals: Vec<Option<Duration>>,
_subscription: Subscription,
}
impl Render for DisplayTracker {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
Empty
}
}
}
#[gpui::test]
fn test_window_opened_from_bounds_observer_uses_new_bounds(cx: &mut TestAppContext) {
use crate::Subscription;
struct BoundsObserver {
_subscription: Subscription,
}
impl Render for BoundsObserver {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
Empty
}
}
let opened_window = Rc::new(Cell::new(None));
let window = cx.add_window({
let opened_window = opened_window.clone();
move |window, cx| BoundsObserver {
_subscription: cx.observe_window_bounds(window, move |_, _, cx| {
let handle = cx
.open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
.unwrap();
opened_window.set(Some(AnyWindowHandle::from(handle)));
}),
}
});
window
.update(cx, |_, window, _| window.activate_window())
.unwrap();
let new_size = size(px(400.), px(300.));
cx.simulate_window_resize(window.into(), new_size);
let opened_window = opened_window
.take()
.expect("bounds observer should have opened a window");
let opened_size = opened_window
.update(cx, |_, window, _| window.bounds().size)
.unwrap();
assert_eq!(opened_size, new_size);
}
#[gpui::test]
fn test_fully_visible_bounds_preserve_layout_viewport(cx: &mut TestAppContext) {
let window = cx.add_window(|_, _| EmptyView);
let mut platform_window = cx.test_window(window.into());
platform_window.simulate_resize(size(px(400.), px(800.)));
window
.update(cx, |_, window, _| {
assert_eq!(
window.visual_viewport_bounds(),
Bounds::new(Point::default(), size(px(400.), px(800.)))
);
assert_eq!(
window.fully_visible_bounds(),
window.visual_viewport_bounds()
);
})
.unwrap();
platform_window.simulate_frame_request(RequestFrameOptions::default());
let wakes = platform_window.frame_wake_count();
let visual_bounds = Bounds::new(point(px(10.), px(40.)), size(px(380.), px(460.)));
platform_window.simulate_visual_viewport_change(visual_bounds);
assert!(platform_window.frame_wake_count() > wakes);
platform_window.simulate_frame_request(RequestFrameOptions::default());
let wakes = platform_window.frame_wake_count();
let insets = crate::WindowInsets {
safe_area: crate::Edges {
top: px(60.),
right: px(20.),
bottom: px(30.),
left: px(-10.),
},
ime: crate::Edges {
bottom: px(350.),
..Default::default()
},
..Default::default()
};
platform_window.simulate_insets_change(insets.clone());
assert!(platform_window.frame_wake_count() > wakes);
window
.update(cx, |_, window, cx| {
let focus = cx.focus_handle();
window.focus(&focus, cx);
assert_eq!(window.insets(), insets);
assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
assert_eq!(window.visual_viewport_bounds(), visual_bounds);
assert_eq!(
window.fully_visible_bounds(),
Bounds::new(point(px(10.), px(60.)), size(px(370.), px(390.)))
);
window.request_virtual_keyboard();
window.dismiss_virtual_keyboard();
assert!(focus.is_focused(window));
assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
})
.unwrap();
assert_eq!(platform_window.virtual_keyboard_requests(), 1);
assert_eq!(platform_window.virtual_keyboard_dismissals(), 1);
platform_window.simulate_insets_change(crate::WindowInsets {
safe_area: crate::Edges {
top: px(900.),
left: px(500.),
..Default::default()
},
..Default::default()
});
window
.update(cx, |_, window, _| {
assert_eq!(
window.fully_visible_bounds().size,
size(Pixels::ZERO, Pixels::ZERO)
);
})
.unwrap();
// Some backends update geometry snapshots without delivering inset callbacks.
use crate::PlatformWindow as _;
platform_window.on_insets_changed(Box::new(|_| {}));
platform_window.simulate_insets_change(crate::WindowInsets::default());
window
.update(cx, |_, window, _| {
assert_eq!(window.insets(), crate::WindowInsets::default());
})
.unwrap();
}
#[test]
fn frame_throttle_tracks_display_refreshes() {
let start = super::Instant::now();
for (elapsed, interval) in [
(Duration::from_micros(16_666), Duration::from_micros(16_667)),
(Duration::from_micros(33_332), Duration::from_micros(33_333)),
] {
let mut pacer = super::FramePacer::default();
assert!(!pacer.should_defer(start, Some(interval)));
assert!(pacer.should_defer(start + elapsed / 2, Some(interval)));
assert!(!pacer.should_defer(start + elapsed, Some(interval)));
}
}
#[test]
fn frame_throttle_preserves_cadence_without_catching_up_after_stalls() {
let start = super::Instant::now();
let interval = Duration::from_micros(33_333);
let mut pacer = super::FramePacer::default();
assert!(!pacer.should_defer(start, Some(interval)));
let delayed_frame = start + interval + Duration::from_millis(5);
assert!(!pacer.should_defer(delayed_frame, Some(interval)));
assert!(pacer.should_defer(start + interval + interval / 2, Some(interval)));
assert!(!pacer.should_defer(start + interval * 2, Some(interval)));
// Even a stall just short of another full interval must not cause a burst.
let after_stall = start + interval * 4 - Duration::from_millis(1);
assert!(!pacer.should_defer(after_stall, Some(interval)));
assert!(pacer.should_defer(after_stall + interval / 2, Some(interval)));
assert!(!pacer.should_defer(after_stall + interval, Some(interval)));
// Mandatory presentation bypasses the limit and establishes a fresh cadence.
let mandatory_frame = after_stall + interval + Duration::from_millis(2);
assert!(!pacer.should_defer(mandatory_frame, None));
assert!(pacer.should_defer(mandatory_frame + interval / 2, Some(interval)));
}
#[test]
fn power_modes_preserve_frame_limits() {
let options = WindowOptions::default();
for (power_mode, active_interval, thermal_interval) in [
(
crate::PowerMode::LowPower,
Some(Duration::from_micros(33_333)),
Duration::from_micros(33_333),
),
(
crate::PowerMode::Unknown,
None,
Duration::from_micros(16_667),
),
(
crate::PowerMode::Balanced,
None,
Duration::from_micros(16_667),
),
(
crate::PowerMode::HighPower,
None,
Duration::from_micros(16_667),
),
] {
assert_eq!(
super::minimum_frame_interval(
true,
false,
options.inactive_frame_interval,
options.low_power_frame_interval,
options.thermal_frame_interval,
ThermalState::Nominal,
power_mode,
),
active_interval,
);
assert_eq!(
super::minimum_frame_interval(
true,
false,
options.inactive_frame_interval,
options.low_power_frame_interval,
options.thermal_frame_interval,
ThermalState::Serious,
power_mode,
),
Some(thermal_interval),
);
}
}
#[test]
fn frame_limits_combine_enabled_intervals() {
let short = Some(Duration::from_millis(10));
let long = Some(Duration::from_millis(100));
for (inactive, low_power, thermal, expected) in [
(long, short, short, long),
(short, long, short, long),
(short, short, long, long),
(long, None, None, long),
(None, long, None, long),
(None, None, long, long),
(None, None, None, None),
] {
assert_eq!(
super::minimum_frame_interval(
true,
true,
inactive,
low_power,
thermal,
ThermalState::Critical,
crate::PowerMode::LowPower,
),
expected,
);
}
assert_eq!(
super::minimum_frame_interval(
false,
true,
long,
long,
long,
ThermalState::Critical,
crate::PowerMode::LowPower,
),
None,
);
}
struct EmptyView;
impl Render for EmptyView {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div()
}
}
struct OpensWindowOnPaint {
opened: Rc<Cell<bool>>,
}
impl Render for OpensWindowOnPaint {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let opened = self.opened.clone();
div()
.size_full()
.child(canvas(
|_, _, _| {},
move |_, _, _window, cx| {
if !opened.replace(true) {
cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
.unwrap();
}
},
))
// Siblings painted after the canvas: their elements were
// allocated in the arena before the nested draw, so they detect
// a mid-draw arena clear when painted afterwards.
.child(div().child("after"))
}
}
/// Opening a window synchronously draws it and requests an element arena
/// clear. When that happens from within another window's draw (here: from
/// an element's paint), the clear must be deferred until the outer draw
/// finishes, or the outer draw's arena-allocated elements would be freed
/// out from under it.
#[test]
fn test_window_opened_during_draw_defers_arena_clear() {
let mut cx = TestAppContext::single();
let opened = Rc::new(Cell::new(false));
// add_window draws once, which runs the nested open_window mid-draw.
let window = cx.add_window({
let opened = opened.clone();
move |_, _| OpensWindowOnPaint { opened }
});
assert!(opened.get());
assert_eq!(cx.windows().len(), 2);
// The deferred clear must actually run once the outer draw unwinds:
// subsequent draws of both windows work against a fresh arena.
cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
.unwrap();
}
#[test]
fn test_scale_factor_change_preserves_bounds_and_survives_resize() {
let mut cx = TestAppContext::single();
let window = cx.add_window(|_, _| EmptyView);
let handle: AnyWindowHandle = window.into();
let window_state = |cx: &mut TestAppContext| {
cx.update_window(handle, |_, window, _| {
(
window.scale_factor(),
window.bounds(),
window.viewport_size(),
)
})
.unwrap()
};
let (scale_factor, mut expected_bounds, _) = window_state(&mut cx);
assert_eq!(scale_factor, 2.0);
for (scale_factor, resized_size) in [
(1.0, size(px(800.), px(600.))),
(1.25, size(px(640.), px(480.))),
(2.0, size(px(1024.), px(768.))),
] {
cx.simulate_window_scale_factor_change(handle, scale_factor);
assert_eq!(
window_state(&mut cx),
(scale_factor, expected_bounds, expected_bounds.size)
);
cx.simulate_window_resize(handle, resized_size);
expected_bounds.size = resized_size;
assert_eq!(
window_state(&mut cx),
(scale_factor, expected_bounds, resized_size)
);
}
}
#[gpui::test]
fn test_fullscreen_toggle_reports_current_bounds(cx: &mut TestAppContext) {
let window = cx.add_window(|_, _| EmptyView);
let handle = AnyWindowHandle::from(window);
let notifications = Rc::new(Cell::new(0));
window
.update(cx, {
let notifications = notifications.clone();
|_, window, cx| {
cx.observe_window_bounds(window, move |_, _, _| {
notifications.set(notifications.get() + 1)
})
.detach();
}
})
.unwrap();
let window_state = |cx: &mut TestAppContext| {
cx.update_window(handle, |_, window, _| {
(
window.is_fullscreen(),
window.bounds().size,
window.viewport_size(),
)
})
.unwrap()
};
let initial_size = window_state(cx).1;
window
.update(cx, |_, window, _| window.toggle_fullscreen())
.unwrap();
cx.run_until_parked();
assert_eq!(window_state(cx), (true, initial_size, initial_size));
assert_eq!(notifications.get(), 1);
let resized_size = size(px(800.), px(600.));
window
.update(cx, |_, window, _| window.toggle_fullscreen())
.unwrap();
cx.simulate_window_resize(handle, resized_size);
cx.run_until_parked();
assert_eq!(window_state(cx), (false, resized_size, resized_size));
}
/// Platforms that stop requesting frames for idle windows (currently web)
/// rely on the frame waker firing whenever frame demand arises; a demand
/// source that skips the waker shows up there as a window that silently
/// stops repainting until unrelated activity wakes it.
#[gpui::test]
fn test_frame_waker_fires_on_frame_demand(cx: &mut TestAppContext) {
let window = cx.add_window(|_, _| EmptyView);
let test_window = cx.test_window(window.into());
// This test exercises idle wakeups, not the inactive-window frame limit.
test_window.simulate_active_status_change(true);
// Windows start dirty, and that can predate waker installation;
// installing the waker must deliver the pending wake or the first
// frame would never be requested.
assert!(
test_window.frame_wake_count() >= 1,
"opening a window must wake the frame source for the initial frame"
);
// Serve outstanding demand (present the frame drawn by `add_window`).
test_window.simulate_frame_request(RequestFrameOptions::default());
// An idle window must not wake on clean frames or plain updates, or
// the frame source could never stop.
let baseline = test_window.frame_wake_count();
test_window.simulate_frame_request(RequestFrameOptions::default());
window.update(cx, |_, _, _| {}).unwrap();
assert_eq!(
test_window.frame_wake_count(),
baseline,
"clean frames and non-notifying updates must not wake the frame source"
);
// Notifying a view in an idle window is the core demand signal.
window.update(cx, |_, _, cx| cx.notify()).unwrap();
assert!(
test_window.frame_wake_count() > baseline,
"notifying a view in an idle window must wake the frame source"
);
// Serving that demand returns to idle without further wakes.
test_window.simulate_frame_request(RequestFrameOptions::default());
let baseline = test_window.frame_wake_count();
test_window.simulate_frame_request(RequestFrameOptions::default());
assert_eq!(
test_window.frame_wake_count(),
baseline,
"serving demand must return the window to idle"
);
// Next-frame callbacks create demand without dirtying the window.
window
.update(cx, |_, window, _| window.on_next_frame(|_, _| {}))
.unwrap();
assert!(
test_window.frame_wake_count() > baseline,
"scheduling a next-frame callback in an idle window must wake the frame source"
);
}
/// A passive next-frame callback rides along with the next delivered frame
/// but never wakes the frame source, even when it re-arms itself.
#[gpui::test]
fn test_passive_next_frame_callbacks_are_not_demand(cx: &mut TestAppContext) {
fn rearm(window: &mut Window, runs: Rc<Cell<usize>>) {
runs.set(runs.get() + 1);
window.on_next_frame_passive(move |window, _| rearm(window, runs));
}
let window = cx.add_window(|_, _| EmptyView);
let test_window = cx.test_window(window.into());
test_window.simulate_frame_request(RequestFrameOptions::default());
let runs = Rc::new(Cell::new(0));
let baseline = test_window.frame_wake_count();
window
.update(cx, {
let runs = runs.clone();
move |_, window, _| window.on_next_frame_passive(move |window, _| rearm(window, runs))
})
.unwrap();
assert_eq!(test_window.frame_wake_count(), baseline, "queueing a passive callback is not demand");
test_window.simulate_frame_request(RequestFrameOptions { require_presentation: true, ..Default::default() });
test_window.simulate_frame_request(RequestFrameOptions { require_presentation: true, ..Default::default() });
assert_eq!(runs.get(), 2, "a passive callback runs with every delivered frame");
assert_eq!(test_window.frame_wake_count(), baseline, "a re-arming passive pump never wakes the frame source");
// Real demand next to the passive pump still wakes it.
window.update(cx, |_, window, _| window.on_next_frame(|_, _| {})).unwrap();
assert!(test_window.frame_wake_count() > baseline);
}
/// A frame request that arrives while next-frame callbacks are pending
/// must never strand them: either the frame runs them, or (when the
/// inactive-window frame-rate throttle defers the frame) the waker fires
/// so another request is delivered.
#[gpui::test]
fn test_pending_next_frame_callbacks_are_not_stranded(cx: &mut TestAppContext) {
let window = cx.add_window(|_, _| EmptyView);
let test_window = cx.test_window(window.into());
// Establish a recent last-frame time so the inactive-window throttle
// can engage on the next request.
test_window.simulate_frame_request(RequestFrameOptions::default());
let callback_ran = Rc::new(Cell::new(false));
window
.update(cx, {
let callback_ran = callback_ran.clone();
move |_, window, _| {
window.on_next_frame(move |_, _| callback_ran.set(true));
}
})
.unwrap();
let baseline = test_window.frame_wake_count();
test_window.simulate_frame_request(RequestFrameOptions::default());
// The test window is inactive, so this request throttles to ~30fps
// when it lands within the throttle interval of the previous frame
// (the common case here, but timing-dependent): the callback is
// deferred and the waker must re-arm the frame source. On a slow run
// the request instead lands outside the interval and runs the
// callback directly.
assert!(
test_window.frame_wake_count() > baseline || callback_ran.get(),
"a frame request with pending next-frame callbacks must either run them or re-arm the frame source"
);
}
#[gpui::test]
fn test_window_reports_no_raw_handle_instead_of_panicking(cx: &mut TestAppContext) {
use raw_window_handle::{HandleError, HasDisplayHandle as _, HasWindowHandle as _};
let window = cx.add_window(|_, _| EmptyView);
window
.update(cx, |_, window, _| {
assert!(matches!(
window.window_handle(),
Err(HandleError::NotSupported)
));
assert!(matches!(
window.display_handle(),
Err(HandleError::NotSupported)
));
})
.unwrap();
}
#[gpui::test]
fn test_appearance_change_runs_after_app_update(cx: &mut TestAppContext) {
let window = cx.add_window(|_, _| EmptyView);
let observed_appearance = Rc::new(Cell::new(None));
let _subscription = window
.update(cx, {
let observed_appearance = observed_appearance.clone();
move |_, window, _| {
window.observe_window_appearance(move |window, _| {
observed_appearance.set(Some(window.appearance()));
})
}
})
.unwrap();
let test_window = cx.test_window(window.into());
cx.update(|_| {
test_window.simulate_appearance_change(WindowAppearance::Dark);
assert_eq!(observed_appearance.get(), None);
});
cx.run_until_parked();
assert_eq!(observed_appearance.get(), Some(WindowAppearance::Dark));
}
#[gpui::test]
fn queued_frame_callback_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
let window = cx.add_window(|_, _| Empty);
let test_window = cx.test_window(window.into());
assert!(test_window.simulate_scheduled_frame());
assert!(test_window.simulate_scheduled_frame());
assert!(!test_window.frame_scheduled());
cx.update_window(window.into(), |_, window, _| {
window.active.set(true);
window.on_next_frame(|_, _| {});
})
.unwrap();
assert!(
test_window.frame_scheduled(),
"queuing work on a parked window must wake the render loop"
);
assert!(test_window.simulate_scheduled_frame());
assert!(
test_window.frame_scheduled(),
"presenting the frame must await one compositor callback"
);
assert!(test_window.simulate_scheduled_frame());
assert!(!test_window.frame_scheduled());
}
#[gpui::test]
fn pending_presentation_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
let window = cx.add_window(|_, _| Empty);
let test_window = cx.test_window(window.into());
assert!(test_window.simulate_scheduled_frame());
assert!(test_window.simulate_scheduled_frame());
assert!(!test_window.frame_scheduled());
cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
.unwrap();
assert!(
test_window.frame_scheduled(),
"a rendered scene awaiting presentation must wake the render loop"
);
}
#[gpui::test]
fn reentrant_frame_request_preserves_pending_callbacks(cx: &mut TestAppContext) {
let window = cx.add_window(|_, _| Empty);
let test_window = cx.test_window(window.into());
let callback_count = Rc::new(Cell::new(0));
cx.update_window(window.into(), |_, window, _| {
window.active.set(true);
let callback_count = callback_count.clone();
window.on_next_frame(move |window, _| {
callback_count.set(callback_count.get() + 1);
window.on_next_frame(move |_, _| {
callback_count.set(callback_count.get() + 1);
});
});
})
.unwrap();
// Win32 can deliver WM_PAINT from a nested native message loop while
// an input listener or host call still owns the App borrow.
let wake_count = test_window.frame_wake_count();
cx.update(|_| {
test_window.simulate_frame_request(RequestFrameOptions::default());
});
assert_eq!(callback_count.get(), 0);
cx.update_window(window.into(), |_, window, _| {
assert_eq!(window.next_frame_callbacks.borrow().len(), 1);
})
.unwrap();
assert!(
test_window.frame_wake_count() > wake_count,
"a deferred frame callback must wake the frame source for a retry"
);
test_window.simulate_frame_request(RequestFrameOptions::default());
assert_eq!(callback_count.get(), 1);
test_window.simulate_frame_request(RequestFrameOptions::default());
assert_eq!(callback_count.get(), 2);
test_window.simulate_frame_request(RequestFrameOptions::default());
assert_eq!(callback_count.get(), 2);
}
#[gpui::test]
fn callback_queued_during_a_frame_requests_a_follow_up(cx: &mut TestAppContext) {
let window = cx.add_window(|_, _| Empty);
let test_window = cx.test_window(window.into());
let callback_ran = Rc::new(Cell::new(false));
cx.update_window(window.into(), |_, window, _| {
// Inactive windows are frame-rate throttled, which would defer the
// ticks this test drives manually.
window.active.set(true);
let callback_ran = callback_ran.clone();
window.on_next_frame(move |window, _| {
window.on_next_frame(move |_, _| callback_ran.set(true));
});
})
.unwrap();
assert!(test_window.simulate_scheduled_frame());
assert!(!callback_ran.get());
assert!(
test_window.frame_scheduled(),
"a callback queued mid-frame must schedule a follow-up before the loop parks"
);
assert!(test_window.simulate_scheduled_frame());
assert!(callback_ran.get());
}
struct RootView {
explicit_size: bool,
child_bounds: Rc<Cell<Bounds<Pixels>>>,
}
impl Render for RootView {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
let child_bounds = self.child_bounds.clone();
let root = div().flex().flex_col().child(
canvas(
move |bounds, _, _| child_bounds.set(bounds),
|_, _, _, _| {},
)
.size_full(),
);
if self.explicit_size {
root.w(px(300.)).h(px(200.))
} else {
root
}
}
}
#[test]
fn auto_sized_window_root_fills_the_window() {
let mut cx = TestAppContext::single();
let child_bounds = Rc::new(Cell::new(Bounds::default()));
let window = cx.add_window({
let child_bounds = child_bounds.clone();
move |_, _| RootView {
explicit_size: false,
child_bounds,
}
});
let viewport_size = cx
.update_window(window.into(), |_, window, cx| {
window.draw(cx).clear(cx);
window.viewport_size()
})
.unwrap();
assert_eq!(child_bounds.get().size, viewport_size);
}
#[test]
fn explicitly_sized_window_root_keeps_its_size() {
let mut cx = TestAppContext::single();
let child_bounds = Rc::new(Cell::new(Bounds::default()));
let window = cx.add_window({
let child_bounds = child_bounds.clone();
move |_, _| RootView {
explicit_size: true,
child_bounds,
}
});
cx.update_window(window.into(), |_, window, cx| {
window.draw(cx).clear(cx);
})
.unwrap();
assert_eq!(child_bounds.get().size, size(px(300.), px(200.)));
}
struct FileDragView {
path: PathBuf,
observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
observed_drops: Rc<RefCell<Vec<PathBuf>>>,
}
struct FileDropExitView(Rc<Cell<usize>>);
impl Render for FileDropExitView {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div().size_full().on_file_drop_exit({
let observed_file_drop_exit = self.0.clone();
move |_, _, _| observed_file_drop_exit.set(observed_file_drop_exit.get() + 1)
})
}
}
impl Render for FileDragView {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div()
.id("file-drag")
.size_full()
.on_drag(self.path.clone(), |_, _, _, cx| cx.new(|_| Empty))
.external_drag_payload(|path: &PathBuf, _, _| {
Some(ExternalDragPayload::Files(FileDragPaths::new([(
path.clone(),
true,
)])))
})
.on_drag_move({
let observed_drag_moves = self.observed_drag_moves.clone();
move |event: &DragMoveEvent<PathBuf>, _, _| {
observed_drag_moves.borrow_mut().push(event.event.position);
}
})
.on_drop({
let observed_drops = self.observed_drops.clone();
move |path: &PathBuf, _, _| observed_drops.borrow_mut().push(path.clone())
})
}
}
#[gpui::test]
fn file_drag_is_promoted_once_and_restored_in_source_window(cx: &mut TestAppContext) {
struct Drag {
window: AnyWindowHandle,
observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
observed_drops: Rc<RefCell<Vec<PathBuf>>>,
}
fn start_drag(cx: &mut TestAppContext, path: PathBuf, platform_result: bool) -> Drag {
let observed_drag_moves = Rc::new(RefCell::new(Vec::new()));
let observed_drops = Rc::new(RefCell::new(Vec::new()));
let window: AnyWindowHandle = cx
.add_window({
let observed_drag_moves = observed_drag_moves.clone();
let observed_drops = observed_drops.clone();
move |_, _| FileDragView {
path,
observed_drag_moves,
observed_drops,
}
})
.into();
cx.test_window(window)
.set_start_external_drag_result(platform_result);
let update_result = cx.update_window(window, |_, window, cx| {
window.draw(cx).clear(cx);
window.dispatch_event(
MouseDownEvent {
position: point(px(10.), px(10.)),
button: MouseButton::Left,
modifiers: Default::default(),
click_count: 1,
first_mouse: false,
}
.to_platform_input(),
cx,
);
window.dispatch_event(
MouseMoveEvent {
position: point(px(20.), px(20.)),
pressed_button: Some(MouseButton::Left),
modifiers: Default::default(),
}
.to_platform_input(),
cx,
);
assert!(cx.active_drag.is_some());
});
assert!(
update_result.is_ok(),
"failed to start drag: {update_result:?}"
);
assert!(cx.test_window(window).external_drag_files().is_empty());
Drag {
window,
observed_drag_moves,
observed_drops,
}
}
let successful_path = PathBuf::from("/tmp/successful-drag");
let successful = start_drag(cx, successful_path.clone(), true);
let outside_position = point(px(-1.), px(20.));
let update_result = cx.update_window(successful.window, |_, window, cx| {
window.dispatch_event(
MouseMoveEvent {
position: outside_position,
pressed_button: Some(MouseButton::Left),
modifiers: Default::default(),
}
.to_platform_input(),
cx,
);
assert!(cx.active_drag.is_none());
});
assert!(
update_result.is_ok(),
"failed to promote drag: {update_result:?}"
);
assert_eq!(
cx.test_window(successful.window).external_drag_files(),
[(successful_path.clone(), true)]
);
// Views must still see the move that leaves the window, otherwise they never learn to tear
// down the drag state they built up while the pointer was inside.
assert_eq!(
successful.observed_drag_moves.borrow().last(),
Some(&outside_position)
);
let first_destination_exit_count = Rc::new(Cell::new(0));
let first_destination: AnyWindowHandle = cx
.add_window({
let first_destination_exit_count = first_destination_exit_count.clone();
move |_, _| FileDropExitView(first_destination_exit_count)
})
.into();
let second_destination_exit_count = Rc::new(Cell::new(0));
let second_destination: AnyWindowHandle = cx
.add_window({
let second_destination_exit_count = second_destination_exit_count.clone();
move |_, _| FileDropExitView(second_destination_exit_count)
})
.into();
let reentry_position = point(px(30.), px(30.));
let external_paths = || ExternalPaths([successful_path.clone()].into_iter().collect());
let update_result = cx.update_window(first_destination, |_, window, cx| {
window.draw(cx).clear(cx);
window.dispatch_event(
FileDropEvent::Entered {
position: reentry_position,
paths: external_paths(),
}
.to_platform_input(),
cx,
);
assert!(
cx.active_drag
.as_ref()
.is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
);
window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
assert!(cx.active_drag.is_none());
assert_eq!(first_destination_exit_count.get(), 1);
assert_eq!(second_destination_exit_count.get(), 0);
});
assert!(
update_result.is_ok(),
"failed to handle drag in first destination window: {update_result:?}"
);
let update_result = cx.update_window(second_destination, |_, window, cx| {
window.draw(cx).clear(cx);
window.dispatch_event(
PlatformInput::KeyDown(KeyDownEvent {
keystroke: Keystroke::parse("down").expect("valid keystroke"),
is_held: false,
prefer_character_input: false,
}),
cx,
);
window.dispatch_event(
FileDropEvent::Entered {
position: reentry_position,
paths: external_paths(),
}
.to_platform_input(),
cx,
);
assert!(
cx.active_drag
.as_ref()
.is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
);
assert_eq!(first_destination_exit_count.get(), 1);
assert_eq!(second_destination_exit_count.get(), 0);
window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
assert!(cx.active_drag.is_none());
assert_eq!(first_destination_exit_count.get(), 1);
assert_eq!(second_destination_exit_count.get(), 1);
});
assert!(
update_result.is_ok(),
"failed to handle drag in second destination window: {update_result:?}"
);
let update_result = cx.update_window(successful.window, |_, window, cx| {
window.dispatch_event(
FileDropEvent::Entered {
position: reentry_position,
paths: external_paths(),
}
.to_platform_input(),
cx,
);
assert!(
cx.active_drag
.as_ref()
.is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
);
assert_eq!(
successful.observed_drag_moves.borrow().last(),
Some(&reentry_position)
);
window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
assert!(cx.active_drag.is_none());
window.dispatch_event(
FileDropEvent::Entered {
position: reentry_position,
paths: external_paths(),
}
.to_platform_input(),
cx,
);
assert!(
cx.active_drag
.as_ref()
.is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
);
window.dispatch_event(
FileDropEvent::Submit {
position: reentry_position,
}
.to_platform_input(),
cx,
);
assert_eq!(
successful.observed_drops.borrow().as_slice(),
std::slice::from_ref(&successful_path)
);
assert!(cx.active_drag.is_none());
window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
assert!(cx.active_drag.is_none());
window.dispatch_event(FileDropEvent::Ended.to_platform_input(), cx);
assert!(cx.active_drag.is_none());
window.dispatch_event(
FileDropEvent::Entered {
position: reentry_position,
paths: external_paths(),
}
.to_platform_input(),
cx,
);
assert!(
cx.active_drag
.as_ref()
.is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
);
window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
});
assert!(
update_result.is_ok(),
"failed to restore drag in source window: {update_result:?}"
);
let cancelled_path = PathBuf::from("/tmp/cancelled-drag");
let cancelled = start_drag(cx, cancelled_path.clone(), true);
let update_result = cx.update_window(cancelled.window, |_, window, cx| {
window.dispatch_event(
MouseMoveEvent {
position: outside_position,
pressed_button: Some(MouseButton::Left),
modifiers: Default::default(),
}
.to_platform_input(),
cx,
);
assert!(cx.active_drag.is_none());
window.dispatch_event(
FileDropEvent::Entered {
position: reentry_position,
paths: ExternalPaths([cancelled_path].into_iter().collect()),
}
.to_platform_input(),
cx,
);
assert!(
cx.active_drag
.as_ref()
.is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
);
assert!(cx.stop_active_drag(window));
assert!(cx.active_drag.is_none());
});
assert!(
update_result.is_ok(),
"failed to cancel restored drag: {update_result:?}"
);
assert!(!cx.update(|cx| cx.end_platform_drag(cancelled.window.window_id())));
let removed_path = PathBuf::from("/tmp/removed-window-drag");
let removed = start_drag(cx, removed_path, true);
let removed_window_id = removed.window.window_id();
let update_result = cx.update_window(removed.window, |_, window, cx| {
window.dispatch_event(
MouseMoveEvent {
position: outside_position,
pressed_button: Some(MouseButton::Left),
modifiers: Default::default(),
}
.to_platform_input(),
cx,
);
assert!(cx.active_drag.is_none());
window.remove_window();
});
assert!(
update_result.is_ok(),
"failed to remove drag source window: {update_result:?}"
);
assert!(!cx.update(|cx| cx.end_platform_drag(removed_window_id)));
let failed_path = PathBuf::from("/tmp/failed-drag");
let failed = start_drag(cx, failed_path.clone(), false);
let update_result = cx.update_window(failed.window, |_, window, cx| {
for x_position in [-1., -2.] {
window.dispatch_event(
MouseMoveEvent {
position: point(px(x_position), px(20.)),
pressed_button: Some(MouseButton::Left),
modifiers: Default::default(),
}
.to_platform_input(),
cx,
);
}
assert!(cx.active_drag.is_some());
});
assert!(
update_result.is_ok(),
"failed to retain drag after platform failure: {update_result:?}"
);
assert_eq!(
cx.test_window(failed.window).external_drag_files(),
[(failed_path, true)]
);
}
struct FocusForwarder {
a: FocusHandle,
b: FocusHandle,
}
impl Render for FocusForwarder {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div()
.size_full()
.child(div().w(px(50.)).h(px(50.)).track_focus(&self.a))
.child(div().w(px(50.)).h(px(50.)).track_focus(&self.b))
}
}
/// When a focus listener moves focus again (e.g. a dock forwarding focus to its
/// active panel), the resulting focus events must be dispatched without waiting
/// for an unrelated redraw of the window.
#[gpui::test]
fn test_focus_moved_by_focus_listener_is_dispatched(cx: &mut TestAppContext) {
let b_focus_count = Rc::new(Cell::new(0));
let window = cx.add_window({
let b_focus_count = b_focus_count.clone();
move |window, cx| {
let a = cx.focus_handle();
let b = cx.focus_handle();
cx.on_focus(&a, window, |this: &mut FocusForwarder, window, cx| {
let b = this.b.clone();
window.focus(&b, cx);
})
.detach();
cx.on_focus(&b, window, move |_, _, _| {
b_focus_count.set(b_focus_count.get() + 1);
})
.detach();
FocusForwarder { a, b }
}
});
window
.update(cx, |_, window, _| window.activate_window())
.unwrap();
cx.executor().run_until_parked();
window
.update(cx, |this, window, cx| {
let a = this.a.clone();
window.focus(&a, cx);
})
.unwrap();
cx.executor().run_until_parked();
window
.update(cx, |this, window, _| {
assert!(this.b.is_focused(window));
})
.unwrap();
assert_eq!(b_focus_count.get(), 1);
}
#[gpui::test]
fn claimed_touch_drag_receives_movement_and_release(cx: &mut TestAppContext) {
let events = Rc::new(RefCell::new(Vec::new()));
let window = cx.add_window({
let events = events.clone();
move |_, _| TouchDragListener { events }
});
let touch = TouchId(1);
dispatch_touch(window, cx, touch, TouchPhase::Started, 10.);
dispatch_touch(window, cx, touch, TouchPhase::Moved, 30.);
dispatch_touch(window, cx, touch, TouchPhase::Ended, 40.);
assert_eq!(
events.borrow().as_slice(),
[
(TouchPhase::Started, px(10.)),
(TouchPhase::Moved, px(30.)),
(TouchPhase::Ended, px(40.)),
]
);
}
#[gpui::test]
fn back_gesture_is_claimed_by_the_innermost_listener(cx: &mut TestAppContext) {
let claims = Rc::new(RefCell::new(Vec::new()));
let window = cx.add_window({
let claims = claims.clone();
move |_, _| BackListeners { claims }
});
let dispatch_back = |cx: &mut TestAppContext, x: f32| {
window
.update(cx, |_, window, cx| {
window
.dispatch_event(
BackGestureEvent {
phase: BackGesturePhase::Started,
start_position: point(px(x), px(10.)),
progress: 0.,
}
.to_platform_input(),
cx,
)
.default_prevented
})
.unwrap()
};
assert!(dispatch_back(cx, 10.));
assert!(dispatch_back(cx, 80.));
assert!(!dispatch_back(cx, 150.));
assert_eq!(claims.borrow().as_slice(), ["inner", "outer"]);
}
struct BackListeners {
claims: Rc<RefCell<Vec<&'static str>>>,
}
impl Render for BackListeners {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let claim = |name: &'static str| {
let claims = self.claims.clone();
move |_: &BackGestureEvent, _: &mut Window, _: &mut crate::App| {
claims.borrow_mut().push(name)
}
};
div().size_full().child(
div()
.w(px(100.))
.h_full()
.on_back_gesture(claim("outer"))
.child(div().w(px(50.)).h_full().on_back_gesture(claim("inner"))),
)
}
}
struct TouchDragListener {
events: Rc<RefCell<Vec<(TouchPhase, Pixels)>>>,
}
impl Render for TouchDragListener {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let events = self.events.clone();
canvas(
|_, _, _| {},
move |_, _, window, _| {
window.on_mouse_event(move |event: &TouchDragEvent, phase, window, _cx| {
if phase != DispatchPhase::Bubble {
return;
}
events.borrow_mut().push((event.phase, event.position.x));
if event.phase == TouchPhase::Started {
window.prevent_default();
}
});
},
)
}
}
#[gpui::test]
fn long_press_is_claimed_only_when_started_prevents_default(cx: &mut TestAppContext) {
for response in [
LongPressResponse::PreventDefault,
LongPressResponse::StopPropagation,
LongPressResponse::None,
] {
let phases = Rc::new(RefCell::new(Vec::new()));
let window = cx.add_window({
let phases = phases.clone();
move |_, _| LongPressListener { phases, response }
});
dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
cx.executor().advance_clock(Duration::from_millis(501));
cx.executor().run_until_parked();
window
.update(cx, |_, window, _| {
assert_eq!(
window.long_press_capture.is_some(),
response == LongPressResponse::PreventDefault
);
})
.unwrap();
dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
dispatch_touch(window, cx, TouchId(1), TouchPhase::Ended, 2.);
window
.update(cx, |_, window, _| {
assert!(window.long_press_capture.is_none());
})
.unwrap();
let phases = phases.borrow();
if response == LongPressResponse::PreventDefault {
assert_eq!(
phases.as_slice(),
[TouchPhase::Started, TouchPhase::Moved, TouchPhase::Ended]
);
} else {
assert_eq!(phases.as_slice(), [TouchPhase::Started]);
}
}
}
#[gpui::test]
fn stale_default_prevention_does_not_claim_long_press(cx: &mut TestAppContext) {
let phases = Rc::new(RefCell::new(Vec::new()));
let window = cx.add_window({
let phases = phases.clone();
move |_, _| LongPressListener {
phases,
response: LongPressResponse::None,
}
});
window
.update(cx, |_, window, _| {
window.prevent_default();
})
.unwrap();
dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
cx.executor().advance_clock(Duration::from_millis(501));
cx.executor().run_until_parked();
dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
}
#[gpui::test]
fn resolved_touch_cancels_scheduled_long_press(cx: &mut TestAppContext) {
for (phase, position) in [
(TouchPhase::Ended, 0.),
(TouchPhase::Cancelled, 0.),
(TouchPhase::Moved, 20.),
] {
let phases = Rc::new(RefCell::new(Vec::new()));
let window = cx.add_window({
let phases = phases.clone();
move |_, _| LongPressListener {
phases,
response: LongPressResponse::PreventDefault,
}
});
dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
dispatch_touch(window, cx, TouchId(1), phase, position);
cx.executor().advance_clock(Duration::from_millis(501));
cx.executor().run_until_parked();
assert!(phases.borrow().is_empty(), "{phase:?} allowed long press");
}
}
#[gpui::test]
fn stale_long_press_timer_cannot_affect_replacement_touch(cx: &mut TestAppContext) {
let phases = Rc::new(RefCell::new(Vec::new()));
let window = cx.add_window({
let phases = phases.clone();
move |_, _| LongPressListener {
phases,
response: LongPressResponse::PreventDefault,
}
});
let first_touch = TouchId(1);
dispatch_touch(window, cx, first_touch, TouchPhase::Started, 0.);
cx.executor().advance_clock(Duration::from_millis(250));
dispatch_touch(window, cx, first_touch, TouchPhase::Cancelled, 0.);
dispatch_touch(window, cx, TouchId(2), TouchPhase::Started, 10.);
cx.executor().advance_clock(Duration::from_millis(251));
cx.executor().run_until_parked();
assert!(phases.borrow().is_empty());
cx.executor().advance_clock(Duration::from_millis(250));
cx.executor().run_until_parked();
assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
}
#[gpui::test]
fn test_underline_exclusions_preserve_device_geometry(cx: &mut TestAppContext) {
test_underline_paint_at_scales(cx, |window| {
let (numerator, denominator) = match window.scale_factor() {
1.0 => (1, 1),
1.25 => (5, 4),
1.5 => (3, 2),
2.0 => (2, 1),
3.0 => (3, 1),
scale => panic!("unexpected scale {scale}"),
};
let snap = |quarters: i32| {
let scaled = quarters * numerator;
let divisor = 4 * denominator;
let rounded =
scaled.abs() / divisor + i32::from(2 * (scaled.abs() % divisor) > divisor);
ScaledPixels((scaled.signum() * rounded) as f32)
};
let stroke = |quarters| {
if quarters == 0 {
ScaledPixels(0.)
} else {
snap(quarters).max(ScaledPixels(1.))
}
};
for origin in [-101, -3, -2, -1, 0, 1, 2, 3, 101] {
for width in [0, 1, 3, 84] {
for thickness in [0, 1, 4, 7] {
for wavy in [false, true] {
let style = UnderlineStyle {
thickness: px(thickness as f32 / 4.),
color: Some(hsla(0.25, 0.5, 0.75, 0.5)),
wavy,
offset: px(0.),
};
let bounds = Bounds::new(
point(snap(origin), snap(-origin)),
size(
stroke(width),
stroke(thickness) * if wavy { 3. } else { 1. },
),
);
let origin = point(px(origin as f32 / 4.), px(-origin as f32 / 4.));
let width = px(width as f32 / 4.);
assert_eq!(window.underline_bounds(origin, width, &style), bounds);
let original = paint_test_underlines(window, |window| {
window.paint_underline(origin, width, &style);
})
.to_vec();
assert_eq!(original.len(), usize::from(!bounds.is_empty()));
if let Some(underline) = original.first() {
assert_eq!(underline.bounds, bounds);
assert_eq!(underline.thickness, stroke(thickness));
assert_eq!(underline.wavy, wavy.into());
assert_eq!(underline.color, hsla(0.25, 0.5, 0.75, 0.5));
}
let underlines = paint_test_underlines(window, |window| {
window.paint_underline_with_exclusions(origin, width, &style, &[]);
});
assert_eq!(underlines.len(), original.len());
for (actual, original) in underlines.iter().zip(&original) {
assert_same_underline_geometry(actual, original);
assert_eq!(actual.content_mask, original.content_mask);
}
let left = bounds.left().0 as i32;
let right = bounds.right().0 as i32;
let exclusions = [
(15, 25),
(3, 7),
(5, 10),
(10, 12),
(0, 0),
(4, 2),
(-50, -1),
(70, 100),
]
.map(|(start, end)| {
ScaledPixels((left + start) as f32)
..ScaledPixels((left + end) as f32)
});
let underlines = paint_test_underlines(window, |window| {
window.paint_underline_with_exclusions(
origin,
width,
&style,
&exclusions,
);
});
let expected = (left..right)
.filter(|column| {
!bounds.is_empty()
&& !exclusions.iter().any(|span| {
span.contains(&ScaledPixels(*column as f32))
})
})
.collect::<Vec<_>>();
assert_eq!(underline_device_columns(underlines), expected);
for underline in underlines {
assert_same_underline_geometry(underline, &original[0]);
}
}
}
}
}
});
}
#[gpui::test]
fn test_underline_exclusions_preserve_helvetica_warning_edge(cx: &mut TestAppContext) {
test_underline_paint_at_scales(cx, |window| {
if window.scale_factor() != 2.0 {
return;
}
let style = UnderlineStyle {
thickness: px(1.),
color: None,
wavy: true,
offset: px(0.),
};
let origin = point(px(2.888_183_8), px(15.357_917));
let width = px(23.848_145) - origin.x;
let original = paint_test_underlines(window, |window| {
window.paint_underline(origin, width, &style);
})[0];
assert_eq!(original.bounds.left(), ScaledPixels(6.));
assert_eq!(original.bounds.right(), ScaledPixels(48.));
let point_bounds = window.underline_bounds(origin, px(10.829_102), &style);
assert_eq!(point_bounds.left(), ScaledPixels(6.));
assert_eq!(point_bounds.right(), ScaledPixels(28.));
let underlines = paint_test_underlines(window, |window| {
window.paint_underline_with_exclusions(
origin,
width,
&style,
&[point_bounds.left()..point_bounds.right()],
);
});
assert_eq!(underlines.len(), 1);
assert_same_underline_geometry(&underlines[0], &original);
assert_eq!(
underline_device_columns(underlines),
(28..48).collect::<Vec<_>>()
);
});
}
#[gpui::test]
fn test_underline_exclusions_preserve_content_mask_and_opacity(cx: &mut TestAppContext) {
test_underline_paint_at_scales(cx, |window| {
let scale = window.scale_factor();
let original_mask = window.content_mask();
let original_opacity = window.element_opacity();
let mask = ContentMask {
bounds: Bounds::from_corners(point(px(4.), px(10.)), point(px(16.), px(12.))),
..Default::default()
};
let style = UnderlineStyle {
thickness: px(2.),
color: Some(hsla(0.25, 0.5, 0.75, 0.5)),
wavy: true,
offset: px(0.),
};
let origin = point(px(-1.25), px(9.25));
let width = px(24.);
window.with_content_mask(Some(mask), |window| {
window.with_element_opacity(Some(0.5), |window| {
window.with_element_opacity(Some(0.5), |window| {
let original = paint_test_underlines(window, |window| {
window.paint_underline(origin, width, &style);
})[0];
assert_eq!(original.color, hsla(0.25, 0.5, 0.75, 0.125));
let underlines = paint_test_underlines(window, |window| {
window.paint_underline_with_exclusions(
origin,
width,
&style,
&[ScaledPixels(6. * scale)..ScaledPixels(8. * scale)],
);
});
assert_eq!(underlines.len(), 2);
let expected = [(4. * scale, 6. * scale), (8. * scale, 16. * scale)].map(
|(left, right)| {
Bounds::from_corners(
point(ScaledPixels(left), ScaledPixels((10. * scale).floor())),
point(ScaledPixels(right), ScaledPixels((12. * scale).ceil())),
)
},
);
assert_eq!(
underlines
.iter()
.map(|underline| underline.content_mask.bounds)
.collect::<Vec<_>>(),
expected
);
for underline in underlines {
assert_same_underline_geometry(underline, &original);
}
});
});
});
assert_eq!(window.content_mask(), original_mask);
assert_eq!(window.element_opacity(), original_opacity);
});
}
#[gpui::test]
fn test_underline_exclusions_adversarial_permutations(cx: &mut TestAppContext) {
test_underline_paint_at_scales(cx, |window| {
let style = UnderlineStyle {
thickness: px(1.),
color: None,
wavy: true,
offset: px(0.),
};
let origin = point(px(-4.), px(-1.));
let width = px(8.);
let left = (-4. * window.scale_factor()) as i32;
let right = (4. * window.scale_factor()) as i32;
let endpoints = [-16, -8, -1, 0, 1, 8, 16];
for first_start in endpoints {
for first_end in endpoints {
for second_start in endpoints {
for second_end in endpoints {
let exclusions = [first_start..first_end, second_start..second_end];
let expected = (left..right)
.filter(|column| {
!exclusions.iter().any(|span| span.contains(column))
})
.collect::<Vec<_>>();
let exclusions = exclusions.map(|span| {
ScaledPixels(span.start as f32)..ScaledPixels(span.end as f32)
});
let underlines = paint_test_underlines(window, |window| {
window.paint_underline_with_exclusions(
origin,
width,
&style,
&exclusions,
);
});
assert_eq!(
underline_device_columns(underlines),
expected,
"{exclusions:?}"
);
}
}
}
}
});
}
#[derive(Clone, Copy, PartialEq)]
enum LongPressResponse {
PreventDefault,
StopPropagation,
None,
}
struct LongPressListener {
phases: Rc<RefCell<Vec<TouchPhase>>>,
response: LongPressResponse,
}
impl Render for LongPressListener {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let entity = cx.entity();
let phases = self.phases.clone();
let response = self.response;
canvas(
|_, _, _| {},
move |_, _, window, _| {
window.on_mouse_event(move |event: &LongPressEvent, phase, window, cx| {
if phase != DispatchPhase::Bubble {
return;
}
phases.borrow_mut().push(event.phase);
match response {
LongPressResponse::PreventDefault => {
window.capture_long_press(&entity);
window.prevent_default();
}
LongPressResponse::StopPropagation => cx.stop_propagation(),
LongPressResponse::None => {}
}
});
},
)
}
}
struct UnderlineTestView(Rc<dyn Fn(&mut Window)>);
impl Render for UnderlineTestView {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
let paint = self.0.clone();
canvas(
|_, _, _| {},
move |_, _, window, _| {
window.content_mask_stack.push(ContentMask::rect(Bounds::from_corners(
point(px(-1000.), px(-1000.)),
point(px(1000.), px(1000.)),
)));
paint(window);
window.content_mask_stack.pop();
},
)
.size_full()
}
}
fn test_underline_paint_at_scales(
cx: &mut TestAppContext,
paint: impl Fn(&mut Window) + 'static,
) {
let window = cx.add_window(move |_, _| UnderlineTestView(Rc::new(paint)));
for scale in [1., 1.25, 1.5, 2., 3.] {
cx.simulate_window_scale_factor_change(window.into(), scale);
cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
.unwrap();
}
}
fn paint_test_underlines(window: &mut Window, paint: impl FnOnce(&mut Window)) -> &[Underline] {
window.next_frame.scene.clear();
paint(window);
&window.next_frame.scene.underlines
}
fn assert_same_underline_geometry(actual: &Underline, expected: &Underline) {
assert_eq!(actual.bounds, expected.bounds);
assert_eq!(actual.thickness, expected.thickness);
assert_eq!(actual.wavy, expected.wavy);
assert_eq!(actual.color, expected.color);
assert_eq!(actual.pad, expected.pad);
}
fn underline_device_columns(underlines: &[Underline]) -> Vec<i32> {
underlines
.iter()
.flat_map(|underline| {
let bounds = underline.bounds.intersect(&underline.content_mask.bounds);
bounds.left().0 as i32..bounds.right().0 as i32
})
.collect()
}
actions!(window_test, [StandaloneModifierAction]);
struct StandaloneModifierView {
focus_handle: FocusHandle,
action_count: usize,
}
impl Render for StandaloneModifierView {
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div()
.key_context("StandaloneModifier")
.track_focus(&self.focus_handle)
.on_action(cx.listener(|this, _: &StandaloneModifierAction, _, _| {
this.action_count += 1;
}))
}
}
#[gpui::test]
fn test_standalone_modifier_sequence_timeout_and_recovery(cx: &mut TestAppContext) {
use crate::{KeyBinding, Modifiers};
cx.update(|cx| {
cx.bind_keys([KeyBinding::new(
"shift shift",
StandaloneModifierAction,
Some("StandaloneModifier"),
)]);
});
let (view, cx) = cx.add_window_view(|window, cx| {
let focus_handle = cx.focus_handle();
window.focus(&focus_handle, cx);
StandaloneModifierView {
focus_handle,
action_count: 0,
}
});
let shift = Modifiers {
shift: true,
..Modifiers::default()
};
cx.simulate_modifiers_change(shift);
cx.simulate_modifiers_change(Modifiers::default());
cx.update(|window, _| {
assert_eq!(
window.pending_input_keystrokes(),
Some([Keystroke::parse("shift").expect("valid keystroke")].as_slice())
);
});
cx.background_executor.advance_clock(Duration::from_secs(2));
cx.run_until_parked();
cx.update(|window, cx| {
assert!(!window.has_pending_keystrokes());
assert_eq!(view.read(cx).action_count, 0);
});
cx.simulate_modifiers_change(shift);
cx.simulate_modifiers_change(Modifiers::default());
cx.update(|window, cx| {
assert!(window.has_pending_keystrokes());
assert_eq!(view.read(cx).action_count, 0);
});
cx.simulate_modifiers_change(shift);
cx.simulate_modifiers_change(Modifiers::default());
cx.update(|window, cx| {
assert!(!window.has_pending_keystrokes());
assert_eq!(view.read(cx).action_count, 1);
});
}
#[gpui::test]
fn test_standalone_modifier_sequence_dispatches_before_timeout(cx: &mut TestAppContext) {
use crate::{KeyBinding, Modifiers};
cx.update(|cx| {
cx.bind_keys([KeyBinding::new(
"shift shift",
StandaloneModifierAction,
Some("StandaloneModifier"),
)]);
});
let (view, cx) = cx.add_window_view(|window, cx| {
let focus_handle = cx.focus_handle();
window.focus(&focus_handle, cx);
StandaloneModifierView {
focus_handle,
action_count: 0,
}
});
let shift = Modifiers {
shift: true,
..Modifiers::default()
};
cx.simulate_modifiers_change(shift);
cx.simulate_modifiers_change(Modifiers::default());
cx.background_executor
.advance_clock(Duration::from_millis(500));
cx.update(|window, cx| {
assert!(window.has_pending_keystrokes());
assert_eq!(view.read(cx).action_count, 0);
});
cx.simulate_modifiers_change(shift);
cx.simulate_modifiers_change(Modifiers::default());
cx.update(|window, cx| {
assert!(!window.has_pending_keystrokes());
assert_eq!(view.read(cx).action_count, 1);
});
cx.background_executor.advance_clock(Duration::from_secs(2));
cx.run_until_parked();
cx.update(|window, cx| {
assert!(!window.has_pending_keystrokes());
assert_eq!(view.read(cx).action_count, 1);
});
}
fn dispatch_touch<T: 'static>(
window: crate::WindowHandle<T>,
cx: &mut TestAppContext,
id: TouchId,
phase: TouchPhase,
x: f32,
) {
window
.update(cx, |_, window, cx| {
window.dispatch_event(
TouchEvent {
id,
phase,
position: point(px(x), px(0.)),
predicted_position: None,
force: None,
}
.to_platform_input(),
cx,
);
})
.unwrap();
}
#[gpui::test]
fn cached_view_follows_inherited_opacity(cx: &mut TestAppContext) {
struct Child {
renders: usize,
}
impl Render for Child {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
self.renders += 1;
div().size_full().bg(crate::rgb(0xff0000))
}
}
struct Root {
opacity: f32,
width: Pixels,
child: crate::Entity<Child>,
}
impl Render for Root {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div()
.w(self.width)
.h(px(200.))
.opacity(self.opacity)
.hover(|style| style.opacity(1.))
.child(
self.child
.clone()
.cached(crate::StyleRefinement::default().size(px(100.))),
)
}
}
/// Updates the root, draws until no more frames are requested, and returns the
/// child's painted alpha and how many times it has rendered.
fn update_and_draw(
window: crate::WindowHandle<Root>,
child: &crate::Entity<Child>,
cx: &mut TestAppContext,
update: impl FnOnce(&mut Root, &mut Window, &mut Context<Root>),
) -> (f32, usize) {
window
.update(cx, |root, window, cx| {
update(root, window, cx);
cx.notify();
})
.expect("update root");
for _ in 0..3 {
let (alpha, renders, requested_frames) = cx
.update_window(window.into(), |_, window, cx| {
window.draw(cx).clear(cx);
let quads = &window.rendered_frame.scene.quads;
assert_eq!(quads.len(), 1);
let alpha = quads.first().expect("child quad").background.solid.a;
(
alpha,
child.read(cx).renders,
window.simulate_next_frame(cx),
)
})
.expect("draw window");
if requested_frames == 0 {
return (alpha, renders);
}
}
panic!("cached child kept requesting frames");
}
let child = cx.new(|_| Child { renders: 0 });
let window = cx.add_window(|_, _| Root {
opacity: 1.,
width: px(200.),
child: child.clone(),
});
let outside = point(px(500.), px(500.));
let inside = point(px(50.), px(50.));
let beside = point(px(250.), px(50.));
// Changing the wrapper's opacity redraws the child; unchanged opacity reuses it.
let move_outside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
window.simulate_mouse_move(outside, cx)
};
assert_eq!(update_and_draw(window, &child, cx, move_outside), (1., 1));
assert_eq!(update_and_draw(window, &child, cx, |_, _, _| {}), (1., 1));
let fade = |root: &mut Root, _: &mut Window, _: &mut Context<Root>| root.opacity = 0.5;
assert_eq!(update_and_draw(window, &child, cx, fade), (0.5, 2));
assert_eq!(update_and_draw(window, &child, cx, |_, _, _| {}), (0.5, 2));
// Hover opacity applies when the mouse enters and leaves.
let move_inside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
window.simulate_mouse_move(inside, cx)
};
assert_eq!(update_and_draw(window, &child, cx, move_inside).0, 1.);
let move_beside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
window.simulate_mouse_move(beside, cx)
};
assert_eq!(update_and_draw(window, &child, cx, move_beside).0, 0.5);
// Widening the wrapper puts it under a still mouse, so only paint's hit test sees
// the hover.
let widen = |root: &mut Root, _: &mut Window, _: &mut Context<Root>| root.width = px(300.);
assert_eq!(update_and_draw(window, &child, cx, widen).0, 1.);
}
#[gpui::test]
fn test_drag_cursor_applies_before_next_paint(cx: &mut TestAppContext) {
struct ResizeHandle;
impl Render for ResizeHandle {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div().size_full().cursor_text().child(
div()
.id("resize-handle")
.w(px(4.))
.h_full()
.cursor_col_resize()
.on_drag((), |_, _, _, cx| cx.new(|_| Empty)),
)
}
}
let window = cx.add_window(|_, _| ResizeHandle);
let handle_position = point(px(1.), px(10.));
let drag_position = point(px(20.), px(10.));
let cursor_observer = cx.clone();
let update_result = cx.update_window(window.into(), |_, window, cx| {
window.hovered.set(true);
window.active.set(true);
window.draw(cx).clear(cx);
window.dispatch_event(
MouseMoveEvent {
position: handle_position,
..Default::default()
}
.to_platform_input(),
cx,
);
window.dispatch_event(
MouseDownEvent {
position: handle_position,
button: MouseButton::Left,
..Default::default()
}
.to_platform_input(),
cx,
);
window.dispatch_event(
MouseMoveEvent {
position: drag_position,
pressed_button: Some(MouseButton::Left),
..Default::default()
}
.to_platform_input(),
cx,
);
assert!(cx.has_active_drag());
// Asserted here because leaving this update flushes effects, which paints a frame.
assert_eq!(
cursor_observer.test_platform().cursor_style(),
CursorStyle::ResizeColumn
);
window.draw(cx).clear(cx);
window.dispatch_event(
MouseUpEvent {
position: drag_position,
button: MouseButton::Left,
..Default::default()
}
.to_platform_input(),
cx,
);
window.draw(cx).clear(cx);
});
assert!(
update_result.is_ok(),
"failed to run drag: {update_result:?}"
);
assert_eq!(
cursor_observer.test_platform().cursor_style(),
CursorStyle::IBeam
);
}
}
#[cfg(all(test, any(feature = "inspector", debug_assertions)))]
mod inspector_tests {
use super::*;
use crate::{
DivInspectorState, InspectorElementId, MouseDownEvent, StyleRefinement, TestAppContext, div,
};
#[gpui::test]
fn inspector_only_tracks_its_open_window(cx: &mut TestAppContext) {
let windows = [
cx.add_window(|_, cx| InspectorTestRoot {
child: cx.new(|_| InspectorTestView::default()),
}),
cx.add_window(|_, cx| InspectorTestRoot {
child: cx.new(|_| InspectorTestView::default()),
}),
];
for window in windows {
assert_closed_inspector(window.into(), cx);
}
for _ in 0..2 {
cx.update_window(windows[0].into(), |root, window, cx| {
let root = root.downcast::<InspectorTestRoot>().expect("test root");
let child_widths = root.read(cx).child.read(cx).child_widths.clone();
window.toggle_inspector(cx);
window.draw(cx).clear(cx);
assert_eq!(child_widths.borrow().as_slice(), &[px(10.); 3]);
let path = window
.rendered_frame
.next_inspector_instance_ids
.iter()
.find_map(|(path, count)| (*count == 3).then(|| path.clone()))
.expect("anonymous siblings share an inspector path");
let selected_id = InspectorElementId {
path,
instance_id: 1,
};
let position = window
.rendered_frame
.hitboxes
.iter()
.find(|hitbox| {
window.rendered_frame.inspector_hitboxes.get(&hitbox.id)
== Some(&selected_id)
})
.expect("middle sibling is pickable")
.bounds
.center();
window.simulate_mouse_move(position, cx);
window.dispatch_event(
PlatformInput::MouseDown(MouseDownEvent {
position,
button: MouseButton::Left,
modifiers: Modifiers::default(),
click_count: 1,
first_mouse: false,
}),
cx,
);
window.dispatch_event(
PlatformInput::MouseUp(MouseUpEvent {
position,
button: MouseButton::Left,
modifiers: Modifiers::default(),
click_count: 1,
}),
cx,
);
assert!(!window.is_inspector_picking(cx));
assert_eq!(
window
.inspector
.as_ref()
.expect("open inspector")
.read(cx)
.active_element_id(),
Some(&selected_id)
);
window.draw(cx).clear(cx);
window.with_inspector_state::<DivInspectorState, _>(
Some(&selected_id),
cx,
|state, _| {
let state = state.as_mut().expect("selected div has style state");
assert_eq!(
state.base_style.size.width,
Some(crate::Length::from(px(10.)))
);
state.base_style.size.width = Some(crate::Length::from(px(25.)));
},
);
window.refresh();
window.draw(cx).clear(cx);
assert_eq!(
child_widths.borrow().as_slice(),
&[px(10.), px(25.), px(10.)]
);
})
.expect("pick and edit a cached child");
assert_closed_inspector(windows[1].into(), cx);
windows[0]
.update(cx, |_, window, cx| window.toggle_inspector(cx))
.expect("close inspector");
assert_closed_inspector(windows[0].into(), cx);
}
}
struct InspectorTestRoot {
child: Entity<InspectorTestView>,
}
impl Render for InspectorTestRoot {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
self.child
.clone()
.cached(StyleRefinement::default().size(px(100.)))
}
}
#[derive(Default)]
struct InspectorTestView {
child_widths: Rc<RefCell<Vec<Pixels>>>,
}
impl Render for InspectorTestView {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let child_widths = self.child_widths.clone();
div()
.on_children_prepainted(move |bounds, _, _| {
*child_widths.borrow_mut() =
bounds.iter().map(|bounds| bounds.size.width).collect();
})
.with_dynamic_prepaint_order(|_, _| SmallVec::from_iter([2, 0, 1]))
.id("inspector-root")
.flex()
.children((0..3).map(|_| div().size(px(10.)).flex_shrink_0()))
}
}
fn assert_closed_inspector(window: AnyWindowHandle, cx: &mut TestAppContext) {
cx.update_window(window, |root, window, cx| {
window.draw(cx).clear(cx);
window.draw(cx).clear(cx);
let root = root.downcast::<InspectorTestRoot>().expect("test root");
assert_eq!(
root.read(cx)
.child
.read(cx)
.child_widths
.borrow()
.as_slice(),
&[px(10.); 3]
);
for frame in [&window.rendered_frame, &window.next_frame] {
assert_eq!(frame.next_inspector_instance_ids.capacity(), 0);
assert_eq!(frame.inspector_hitboxes.capacity(), 0);
}
})
.expect("closed inspector has no bookkeeping and no style overrides");
}
}
/// vue-native fork: `Window::set_assume_active`.
#[cfg(test)]
mod vn_assume_active_tests {
use crate::{
Context, FocusHandle, Render, Subscription, TestAppContext, Window, div, prelude::*, px,
size,
};
use std::{cell::Cell, rc::Rc};
struct Focusable {
handle: FocusHandle,
_on_focus: Subscription,
}
impl Render for Focusable {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().size_full().track_focus(&self.handle)
}
}
#[gpui::test]
fn an_assumed_active_window_runs_focus_and_ignores_the_os(cx: &mut TestAppContext) {
let focused = Rc::new(Cell::new(0u32));
let counter = focused.clone();
let window = cx.open_window(size(px(200.), px(200.)), move |window, cx| {
let handle = cx.focus_handle();
let on_focus = cx.on_focus(&handle, window, move |_, _, _| counter.set(counter.get() + 1));
Focusable { handle, _on_focus: on_focus }
});
let platform = cx.test_window(window.into());
platform.simulate_active_status_change(false);
cx.run_until_parked();
// An inactive window's focus events carry no path, so nothing hears
// the focus move.
window
.update(cx, |view, window, cx| window.focus(&view.handle, cx))
.unwrap();
cx.run_until_parked();
assert_eq!(focused.get(), 0, "no focus event without activation");
// Assumed active: the focused element hears it on the next frame.
window
.update(cx, |_, window, _| window.set_assume_active(true))
.unwrap();
cx.run_until_parked();
assert_eq!(focused.get(), 1, "the focus event carries the path");
let active = |cx: &mut TestAppContext| {
window
.update(cx, |_, window, _| window.is_window_active())
.unwrap()
};
assert!(active(cx));
// The OS's activation changes are ignored while it is set.
platform.simulate_active_status_change(false);
cx.run_until_parked();
assert!(active(cx), "still active after the OS says otherwise");
// Off: back to what the platform reports (a test window: inactive).
window
.update(cx, |_, window, _| window.set_assume_active(false))
.unwrap();
assert!(!active(cx));
}
}
/// vue-native fork: rounded content masks, `ContentMask::intersect`'s corner
/// rule, `contains` and `transform_mask`.
/// vue-native fork: outer shadows are cut out of the border box
/// ([`Window::paint_drop_shadows`]), with CSS's spread radii.
#[cfg(test)]
mod vn_shadow_tests {
use super::{SHADOW_INSET, SHADOW_OUTSIDE_BOX, SHADOW_UNDER_BOX, spread_shadow_radius};
use crate::{
BoxShadow, Context, Hsla, TestAppContext, Window, div, point, prelude::*, px, size,
};
#[test]
fn a_spread_grows_a_rounded_corner_and_keeps_a_square_one_square() {
// A focus ring: rounded-md (6px) and a 3px spread.
assert_eq!(spread_shadow_radius(px(6.), px(3.)), px(9.));
assert_eq!(spread_shadow_radius(px(0.), px(3.)), px(0.));
// Rounded by less than the spread: 1 + (r/s - 1)^3 of the spread.
assert_eq!(spread_shadow_radius(px(1.5), px(3.)), px(1.5 + 3. * 0.875));
assert_eq!(spread_shadow_radius(px(6.), px(0.)), px(6.));
assert_eq!(spread_shadow_radius(px(6.), px(-2.)), px(4.));
assert_eq!(spread_shadow_radius(px(1.), px(-2.)), px(0.));
}
struct Ring {
under_box: bool,
}
impl Render for Ring {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let shadow = |inset: bool| BoxShadow {
color: Hsla::white().opacity(0.5),
offset: point(px(0.), px(0.)),
blur_radius: px(0.),
spread_radius: px(3.),
inset,
};
let mut d = div()
.w(px(100.))
.h(px(36.))
.rounded_md()
.shadow(vec![shadow(false), shadow(true)]);
d.style().vn_shadow_under_box = Some(self.under_box);
d
}
}
/// The frame's shadows as (kind, top-left radius, element top-left radius), in device px.
fn paint(under_box: bool, cx: &mut TestAppContext) -> (Vec<(u32, f32, f32)>, f32) {
let window = cx.open_window(size(px(300.), px(300.)), move |_, _| Ring { under_box });
cx.run_until_parked();
window
.update(cx, |_, window, _| {
let shadows = window
.rendered_frame
.scene
.shadows
.iter()
.map(|s| (s.inset, s.shape_corner_radii.top_left.0, s.corner_radii.top_left.0))
.collect();
(shadows, window.scale_factor())
})
.unwrap()
}
#[gpui::test]
fn an_outer_shadow_is_cut_out_of_the_border_box_unless_it_stands_in_for_the_box(
cx: &mut TestAppContext,
) {
let (shadows, scale) = paint(false, cx);
let outer = shadows.iter().find(|s| s.0 != SHADOW_INSET).expect("the outer shadow");
assert_eq!(outer.0, SHADOW_OUTSIDE_BOX, "the shaders cut the border box out of it");
assert_eq!(outer.1, 9. * scale, "6px corner + 3px spread");
assert_eq!(outer.2, 6. * scale, "the cut-out is the border box itself");
assert!(shadows.iter().any(|s| s.0 == SHADOW_INSET), "the inset shadow is unchanged");
let (shadows, _) = paint(true, cx);
let outer = shadows.iter().find(|s| s.0 != SHADOW_INSET).expect("the outer shadow");
assert_eq!(outer.0, SHADOW_UNDER_BOX);
}
}
#[cfg(test)]
mod vn_rounded_mask_tests {
use super::transform_mask;
use crate::{Bounds, ContentMask, Corners, TransformationMatrix, point, px, size};
fn mask(x: f32, y: f32, w: f32, h: f32, radius: f32) -> ContentMask<crate::Pixels> {
ContentMask {
bounds: Bounds::new(point(px(x), px(y)), size(px(w), px(h))),
corner_radii: Corners::all(px(radius)),
..Default::default()
}
}
#[test]
fn rectangles_intersect_exactly_and_stay_square() {
let a = mask(0., 0., 100., 100., 0.);
let b = mask(50., 20., 100., 30., 0.);
let both = a.intersect(&b);
assert_eq!(both.bounds, Bounds::new(point(px(50.), px(20.)), size(px(50.), px(30.))));
assert!(!both.is_rounded());
}
#[test]
fn a_corner_keeps_the_radius_of_the_mask_it_belongs_to() {
// A rounded card and the square scroller that fills it.
let card = mask(10., 10., 200., 160., 24.);
let scroller = mask(10., 10., 200., 160., 0.);
assert_eq!(scroller.intersect(&card).corner_radii, Corners::all(px(24.)));
assert_eq!(card.intersect(&scroller).corner_radii, Corners::all(px(24.)));
// A rect that shares only the card's top edge: its top corners are
// the card's, its bottom ones are its own.
let header = mask(10., 10., 200., 60., 0.);
let clipped = header.intersect(&card);
assert_eq!(clipped.corner_radii.top_left, px(24.));
assert_eq!(clipped.corner_radii.top_right, px(24.));
assert_eq!(clipped.corner_radii.bottom_left, px(0.));
assert_eq!(clipped.corner_radii.bottom_right, px(0.));
// Two rounded corners at one point nest; the larger radius is the
// smaller region.
let inner = mask(10., 10., 200., 160., 8.);
assert_eq!(inner.intersect(&card).corner_radii, Corners::all(px(24.)));
// A rect inside the card's straight span is square, which is exact.
let row = mask(40., 60., 100., 20., 0.);
assert!(!row.intersect(&card).is_rounded());
// The radii still fit the result.
let sliver = mask(10., 10., 200., 10., 0.);
let clipped = sliver.intersect(&card);
assert_eq!(clipped.corner_radii.top_left, px(5.));
}
#[test]
fn contains_follows_the_curve() {
let avatar = mask(0., 0., 64., 64., 32.);
assert!(avatar.contains(&point(px(32.), px(32.))));
assert!(avatar.contains(&point(px(32.), px(1.))), "the top edge's middle");
assert!(!avatar.contains(&point(px(2.), px(2.))), "outside the curve");
assert!(!avatar.contains(&point(px(62.), px(62.))));
assert!(avatar.contains(&point(px(10.), px(10.))), "inside the curve");
assert!(!avatar.contains(&point(px(70.), px(32.))), "outside the rect");
assert!(mask(0., 0., 64., 64., 0.).contains(&point(px(1.), px(1.))));
}
#[test]
fn a_transform_keeps_the_radii_only_while_corners_stay_round() {
let card = mask(0., 0., 100., 100., 10.);
let moved = TransformationMatrix {
rotation_scale: [[1., 0.], [0., 1.]],
translation: [5., 7.],
};
assert_eq!(transform_mask(moved, card, 1.).corner_radii, Corners::all(px(10.)));
let scaled = TransformationMatrix {
rotation_scale: [[2., 0.], [0., 3.]],
translation: [0., 0.],
};
assert_eq!(
transform_mask(scaled, card, 1.).corner_radii,
Corners::all(px(20.)),
"the smaller factor"
);
let rotated = TransformationMatrix {
rotation_scale: [[0., 1.], [-1., 0.]],
translation: [0., 0.],
};
assert!(!transform_mask(rotated, card, 1.).is_rounded());
}
}
/// vue-native fork: `Window::pointer_inside`.
#[cfg(test)]
mod vn_pointer_inside_tests {
use crate::{
Context, Modifiers, MouseExitEvent, MouseMoveEvent, PlatformInput, Render,
TestAppContext, Window, div, point, prelude::*, px, size,
};
use std::{cell::Cell, rc::Rc};
struct Hoverable {
hovered: Rc<Cell<bool>>,
}
impl Render for Hoverable {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let hovered = self.hovered.clone();
div()
.id("box")
.size_full()
.on_hover(move |is_hovered, _, _| hovered.set(*is_hovered))
}
}
#[gpui::test]
fn a_pointer_outside_the_window_hovers_nothing(cx: &mut TestAppContext) {
let hovered = Rc::new(Cell::new(false));
let state = hovered.clone();
let window = cx.open_window(size(px(200.), px(200.)), move |_, _| Hoverable {
hovered: state,
});
let mut platform = cx.test_window(window.into());
let draw = |cx: &mut TestAppContext| {
window.update(cx, |_, window, _| window.refresh()).unwrap();
cx.run_until_parked();
};
let at = |x: f32, y: f32| point(px(x), px(y));
let moved = |x: f32, y: f32| {
PlatformInput::MouseMove(MouseMoveEvent {
position: at(x, y),
pressed_button: None,
modifiers: Modifiers::default(),
})
};
// The test platform reports the cursor at (0, 0), inside the box, as
// Windows reports wherever the cursor projects. No pointer input has
// reached the window, so nothing is hovered.
draw(cx);
assert!(!hovered.get(), "a cursor that never entered hovers nothing");
platform.simulate_input(moved(50., 50.));
draw(cx);
assert!(hovered.get(), "a move into the box hovers it");
// The platform says the pointer left (`WM_MOUSELEAVE`). The position
// is still inside the box, and the next frame's hit test still finds
// it there.
platform.simulate_hover_status_change(false);
draw(cx);
assert!(!hovered.get(), "a pointer that left hovers nothing");
platform.simulate_input(moved(60., 60.));
draw(cx);
assert!(hovered.get(), "back in");
platform.simulate_input(PlatformInput::MouseExited(MouseExitEvent {
position: at(60., 60.),
pressed_button: None,
modifiers: Modifiers::default(),
}));
draw(cx);
assert!(!hovered.get(), "MouseExited");
}
struct Shaded {
effect: bool,
renders: Rc<Cell<usize>>,
}
impl Render for Shaded {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
self.renders.set(self.renders.get() + 1);
let mut element = div().size_full();
if self.effect {
let mut spec = crate::EffectSpec::NONE;
spec.id = 0;
spec.pointer_param = Some(4);
element.style().vn_effect = Some(spec);
}
element
}
}
#[gpui::test]
fn only_a_pointer_effect_repaints_when_the_pointer_moves(cx: &mut TestAppContext) {
let open = |cx: &mut TestAppContext, effect: bool| {
let renders = Rc::new(Cell::new(0));
let counted = renders.clone();
let window = cx.open_window(size(px(200.), px(100.)), move |_, _| Shaded {
effect,
renders: counted,
});
cx.run_until_parked();
(window, cx.test_window(window.into()), renders)
};
let moved = |x: f32, y: f32| {
PlatformInput::MouseMove(MouseMoveEvent {
position: point(px(x), px(y)),
pressed_button: None,
modifiers: Modifiers::default(),
})
};
let (_, mut platform, renders) = open(cx, false);
platform.simulate_input(moved(10., 10.));
cx.run_until_parked();
let before = renders.get();
platform.simulate_input(moved(20., 20.));
cx.run_until_parked();
assert_eq!(renders.get(), before, "no pointer effect, no repaint");
let (shaded, mut platform, renders) = open(cx, true);
platform.simulate_input(moved(10., 10.));
cx.run_until_parked();
let before = renders.get();
platform.simulate_input(moved(150., 25.));
cx.run_until_parked();
assert!(renders.get() > before, "a pointer effect repaints");
let params = shaded
.update(cx, |_, window, _| {
window.rendered_frame.scene.effect_quads[0].params
})
.unwrap();
assert!((params[4] - 0.75).abs() < 1e-4 && (params[5] - 0.25).abs() < 1e-4);
}
struct Spinning {
speed: Rc<Cell<f32>>,
}
impl Render for Spinning {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let mut spec = crate::EffectSpec::NONE;
spec.id = 0;
spec.animated_param = Some(0);
spec.params[0] = self.speed.get();
let mut element = div().id("spinning").size_full();
element.style().vn_effect = Some(spec);
element
}
}
#[gpui::test]
fn a_speed_change_continues_the_phase_instead_of_rescaling_the_clock(
cx: &mut TestAppContext,
) {
let speed = Rc::new(Cell::new(1.));
let shared = speed.clone();
let window = cx.open_window(size(px(200.), px(100.)), move |_, _| Spinning {
speed: shared,
});
cx.run_until_parked();
let repaint = |cx: &mut TestAppContext| {
window.update(cx, |_, window, _| window.refresh()).unwrap();
cx.run_until_parked();
window
.update(cx, |_, window, _| {
let quad = window.rendered_frame.scene.effect_quads[0];
(quad.params[0] * quad.time, quad.time)
})
.unwrap()
};
// A rescale is only visible once the clock is away from zero.
std::thread::sleep(std::time::Duration::from_millis(200));
let (before, then) = repaint(cx);
assert!((before - then).abs() < 1e-3, "an unchanged speed is `speed * time`");
speed.set(8.);
let (after, now) = repaint(cx);
let advanced = after - before;
assert!(
advanced >= -1e-3 && advanced <= 8. * (now - then) + 1e-3,
"the phase moved by {advanced} in {}s",
now - then
);
}
}
#[cfg(test)]
mod vn_tagged_transform_tests {
use crate::{
AnyElement, App, Bounds, Context, Element, GlobalElementId, InspectorElementId,
IntoElement, LayoutId, Pixels, Render, TestAppContext, TransformLength, TransformSpec,
Window, div, prelude::*, px, size,
};
use std::{cell::RefCell, rc::Rc};
type Seen = Rc<RefCell<Vec<(u32, Bounds<Pixels>, Bounds<Pixels>)>>>;
/// What an embedder's per-node probe does: tag the subtree, prepaint it,
/// take the node's transform, and map its layout box through it.
struct Probe {
tag: u32,
inner: AnyElement,
seen: Seen,
}
impl Element for Probe {
type RequestLayoutState = ();
type PrepaintState = ();
fn id(&self) -> Option<crate::ElementId> {
None
}
fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
None
}
fn request_layout(
&mut self,
_: Option<&GlobalElementId>,
_: Option<&InspectorElementId>,
window: &mut Window,
cx: &mut App,
) -> (LayoutId, ()) {
(self.inner.request_layout(window, cx), ())
}
fn prepaint(
&mut self,
_: Option<&GlobalElementId>,
_: Option<&InspectorElementId>,
bounds: Bounds<Pixels>,
_: &mut (),
window: &mut Window,
cx: &mut App,
) {
let ancestors = window.element_transform();
let (_, own) =
window.with_hitbox_tag(self.tag, |window| self.inner.prepaint(window, cx));
let seen = window.transformed_bounds(own.unwrap_or(ancestors), bounds);
self.seen.borrow_mut().push((self.tag, bounds, seen));
}
fn paint(
&mut self,
_: Option<&GlobalElementId>,
_: Option<&InspectorElementId>,
_: Bounds<Pixels>,
_: &mut (),
_: &mut (),
window: &mut Window,
cx: &mut App,
) {
self.inner.paint(window, cx);
}
}
fn moved(x: TransformLength, y: TransformLength, scale: f32) -> TransformSpec {
TransformSpec { translate: (x, y), scale: (scale, scale), ..TransformSpec::IDENTITY }
}
/// A popper wrapper laid out at (0, 0) and moved by `translate`, a button
/// inside it, and a third box scaled inside that.
struct Popper {
seen: Seen,
}
impl Render for Popper {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
let probe = |tag, inner: AnyElement| Probe { tag, inner, seen: self.seen.clone() };
let mut wrapper = div().w(px(100.)).h(px(80.));
wrapper.style().vn_transform =
Some(moved(TransformLength::Pixels(300.), TransformLength::Pixels(200.), 1.0));
let mut scaled = div().w(px(20.)).h(px(10.));
scaled.style().vn_transform =
Some(moved(TransformLength::ZERO, TransformLength::ZERO, 2.0));
// Built inside the button under the button's tag, like a
// `::before` box: its own transform is not the button's.
let mut pseudo = div().w(px(4.)).h(px(4.));
pseudo.style().vn_transform =
Some(moved(TransformLength::Pixels(50.), TransformLength::ZERO, 1.0));
let button = div()
.ml(px(10.))
.w(px(30.))
.h(px(20.))
.child(probe(3, scaled.into_any_element()))
.child(pseudo);
div().size_full().child(probe(
1,
wrapper.child(probe(2, button.into_any_element())).into_any_element(),
))
}
}
#[gpui::test]
fn a_probe_sees_its_node_where_the_transforms_put_it(cx: &mut TestAppContext) {
let seen: Seen = Rc::default();
let state = seen.clone();
let window =
cx.open_window(size(px(800.), px(600.)), move |_, _| Popper { seen: state });
window.update(cx, |_, window, _| window.refresh()).unwrap();
cx.run_until_parked();
let seen = seen.borrow();
let at = |tag: u32| *seen.iter().rev().find(|s| s.0 == tag).expect("probed");
let b = |x: f32, y: f32, w: f32, h: f32| {
Bounds::new(crate::point(px(x), px(y)), size(px(w), px(h)))
};
// Its own translate moves the wrapper; the layout box stays at 0, 0.
assert_eq!(at(1).1, b(0., 0., 100., 80.));
assert_eq!(at(1).2, b(300., 200., 100., 80.));
// A child with no transform of its own moves with its ancestor, and
// not with the one a box built inside it has.
assert_eq!(at(2).1, b(10., 0., 30., 20.));
assert_eq!(at(2).2, b(310., 200., 30., 20.));
// Its own scale (about its centre) composes with the ancestor's move.
assert_eq!(at(3).1, b(10., 0., 20., 10.));
assert_eq!(at(3).2, b(300., 195., 40., 20.));
}
}