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
use crate::{
Action, ActionBuildError, ActionRegistry, ActivationPolicy, ActivityGuard, Any, AnyView,
AnyWindowHandle, AppContext, AppLifecyclePhase, Arena, ArenaBox, Asset, AssetRegistry,
BackgroundExecutor, Bounds, ClipboardItem, ClipboardReadError, CursorStyle, DispatchPhase,
DisplayChanges, DisplayEvent, DisplayId, EventEmitter, ExternalDragPayload, FocusHandle,
FocusMap, ForegroundExecutor, Global, HapticFeedbackStyle, KeyBinding, KeyContext, Keymap,
Keystroke, LayoutId, Menu, MenuItem, OwnedMenu, PathPromptOptions, Pixels, Platform,
PlatformDisplay, PlatformKeyboardLayout, PlatformKeyboardMapper, Point, Priority,
PromptBuilder, PromptButton, PromptHandle, PromptLevel, Render, RenderImage,
RenderablePromptHandle, Reservation, ScreenCaptureSource, SharedString, SubscriberSet,
Subscription, SvgRenderer, SystemNotification, SystemNotificationResponse, Task,
TextRenderingMode, TextSystem, ThermalState, Window, WindowAppearance, WindowButtonLayout,
WindowHandle, WindowId, WindowInvalidator, WindowingRequest,
colors::{Colors, GlobalColors},
hash,
http_client::{HttpClient, NullHttpClient},
init_app_menus,
};
use anyhow::{Context as _, Result, anyhow};
use collections::{FxHashMap, FxHashSet, HashMap, TypeIdHashMap, TypeIdHashSet, VecDeque};
use derive_more::{Deref, DerefMut};
use futures::{Future, FutureExt, channel::oneshot, future::LocalBoxFuture};
use gpui_util::{ResultExt, debug_panic};
use itertools::Itertools;
use parking_lot::RwLock;
use scheduler::Instant;
use slotmap::SlotMap;
use smallvec::SmallVec;
use std::{
any::{TypeId, type_name},
cell::{BorrowMutError, Cell, Ref, RefCell, RefMut},
ffi::OsString,
marker::PhantomData,
mem,
ops::{Deref, DerefMut},
path::{Path, PathBuf},
rc::{Rc, Weak},
sync::Arc,
time::Duration,
};
#[cfg(any(feature = "inspector", debug_assertions))]
use crate::InspectorElementRegistry;
use crate::asset_cache::CachedLoad;
pub use async_context::*;
#[cfg(feature = "bench-support")]
pub use bench_context::{
BenchAppContext, BenchMeasurement, BenchReport, BenchWindowContext, CountingAllocator,
MetricReport, bench_platform,
};
mod async_context;
#[cfg(feature = "bench-support")]
mod bench_context;
mod context;
mod entity_map;
#[cfg(any(test, feature = "test-support"))]
mod headless_app_context;
#[cfg(any(test, feature = "test-support"))]
mod test_app;
#[cfg(any(test, feature = "test-support"))]
mod test_context;
#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
mod visual_test_context;
pub use context::*;
pub use entity_map::*;
#[cfg(any(test, feature = "test-support"))]
pub use headless_app_context::*;
#[cfg(any(test, feature = "test-support"))]
pub use test_app::*;
#[cfg(any(test, feature = "test-support"))]
pub use test_context::*;
#[cfg(all(target_os = "macos", any(test, feature = "test-support")))]
pub use visual_test_context::*;
/// The duration for which native applications wait for futures returned from
/// [Context::on_app_quit] before fully quitting.
pub const SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(200);
/// Temporary(?) wrapper around [`RefCell<App>`] to help us debug any double borrows.
/// Strongly consider removing after stabilization.
#[doc(hidden)]
pub struct AppCell {
app: RefCell<App>,
}
impl AppCell {
#[doc(hidden)]
#[track_caller]
pub fn borrow(&self) -> AppRef<'_> {
if option_env!("TRACK_THREAD_BORROWS").is_some() {
let thread_id = std::thread::current().id();
eprintln!("borrowed {thread_id:?}");
}
AppRef(self.app.borrow())
}
#[doc(hidden)]
#[track_caller]
pub fn borrow_mut(&self) -> AppRefMut<'_> {
if option_env!("TRACK_THREAD_BORROWS").is_some() {
let thread_id = std::thread::current().id();
eprintln!("borrowed {thread_id:?}");
}
AppRefMut(self.app.borrow_mut())
}
#[doc(hidden)]
#[track_caller]
pub fn try_borrow_mut(&self) -> Result<AppRefMut<'_>, BorrowMutError> {
if option_env!("TRACK_THREAD_BORROWS").is_some() {
let thread_id = std::thread::current().id();
eprintln!("borrowed {thread_id:?}");
}
Ok(AppRefMut(self.app.try_borrow_mut()?))
}
}
#[doc(hidden)]
#[derive(Deref, DerefMut)]
pub struct AppRef<'a>(Ref<'a, App>);
impl Drop for AppRef<'_> {
fn drop(&mut self) {
if option_env!("TRACK_THREAD_BORROWS").is_some() {
let thread_id = std::thread::current().id();
eprintln!("dropped borrow from {thread_id:?}");
}
}
}
#[doc(hidden)]
#[derive(Deref, DerefMut)]
pub struct AppRefMut<'a>(RefMut<'a, App>);
impl Drop for AppRefMut<'_> {
fn drop(&mut self) {
if option_env!("TRACK_THREAD_BORROWS").is_some() {
let thread_id = std::thread::current().id();
eprintln!("dropped {thread_id:?}");
}
}
}
/// The entry point for a GPUI application. Configure it, then call [`Application::run`].
///
/// Get one from `gpui_platform::application()`, which picks the platform for the
/// current target. Configure it with the `with_*` and `on_*` builder methods, then call
/// [`Application::run`] from `main`. The callback you pass to `run` receives the
/// [`App`] once the platform has finished launching. That is where you open windows,
/// bind keys and set globals.
///
/// The `with_*` methods take the application by value and return it, so you can chain
/// them. Call them before [`Application::run`].
///
/// `run` blocks until the app quits on native platforms, so anything after it in
/// `main` runs only after the app exits. Once the app is running, you use [`App`]
/// instead of `Application`.
///
/// # Examples
///
/// ```no_run
/// use gpui::{App, Window, WindowOptions, div, prelude::*};
///
/// struct HelloWorld;
///
/// impl Render for HelloWorld {
/// fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
/// div().child("Hello, world!")
/// }
/// }
///
/// fn main() {
/// gpui_platform::application().run(|cx: &mut App| {
/// cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| HelloWorld))
/// .unwrap();
/// });
/// }
/// ```
///
/// See [the start a project guide](crate::_documentation::guides::start_a_project) for a
/// complete app. `TestApp` runs app code without a display, and is available with the
/// `test-support` feature.
pub struct Application(Rc<AppCell>);
/// A strong handle to an [`Application`] started with [`Application::run_embedded`].
///
/// Dropping this handle releases the app, so an embedder must hold it for as long as the
/// app should run. While held, it is the embedder's entry point back into GPUI each time
/// the external run loop gives it control.
pub struct ApplicationHandle {
app: Rc<AppCell>,
}
impl ApplicationHandle {
/// Runs `f` with the app context, from outside the platform's run loop.
///
/// Call this each time the external run loop gives GPUI control. Effects queued by `f`,
/// such as deferred callbacks, run before this returns. Don't call it from
/// inside an update on the same app: the app state is a `RefCell`, so a re-entrant
/// call panics with a double borrow.
pub fn update<R>(&self, f: impl FnOnce(&mut App) -> R) -> R {
let cx = &mut *self.app.borrow_mut();
cx.update(f)
}
/// Returns an [`AsyncApp`] for use across await points.
///
/// The [`AsyncApp`] holds the app weakly. This handle must stay alive for the
/// [`AsyncApp`] to do anything useful.
pub fn to_async(&self) -> AsyncApp {
self.update(|cx| cx.to_async())
}
}
impl Application {
/// Creates an application that uses a platform implementation you provide.
///
/// Most apps should use `gpui_platform::application()`, which chooses the platform
/// for you. Use this when you want a custom or test platform. The app starts with
/// an empty [`AssetRegistry`], an HTTP client that fails every request, and
/// [`QuitMode::Default`].
///
/// # Panics
///
/// Panics if called from a thread other than the main thread.
pub fn with_platform(platform: Rc<dyn Platform>) -> Self {
Self(App::new_app(
platform,
AssetRegistry::default().into(),
Arc::new(NullHttpClient),
))
}
/// Builds an app with accessibility (AccessKit) integration forcibly
/// disabled.
///
/// In this mode, accessibility APIs (e.g.
/// [`div().role()`][crate::StatefulInteractiveElement::role]) silently
/// no-op.
///
/// See the [accessibility guide](crate::_documentation::guides::accessibility) for the
/// features this disables.
pub fn new_inaccessible(platform: Rc<dyn Platform>) -> Self {
let this = Self::with_platform(platform);
this.0.borrow_mut().accessibility_force_disabled = true;
this
}
/// Build every window's accessibility tree every frame, even when no
/// assistive technology is connected.
///
/// For automation and tree inspection: [`crate::Window::debug_a11y_tree_json`]
/// otherwise reports nothing until a screen reader activates the platform
/// adapter. [`Application::new_inaccessible`] still wins when both are set.
pub fn with_accessibility_forced(self) -> Self {
self.0.borrow_mut().accessibility_forced = true;
self
}
/// Sets the source of assets (images, fonts and SVGs) that the app loads by path.
///
/// The registry is returned by [`App::assets`], and the SVG renderer is rebuilt to
/// read from it. Set it before you open windows that load assets.
pub fn with_assets(self, assets: impl Into<AssetRegistry>) -> Self {
let mut context_lock = self.0.borrow_mut();
let asset_registry = Arc::new(assets.into());
context_lock.asset_registry = asset_registry.clone();
context_lock.svg_renderer = SvgRenderer::new(asset_registry);
drop(context_lock);
self
}
/// Sets the command-line arguments that [`App::restart`] passes to the new process.
pub fn with_restart_arguments(self, arguments: Vec<OsString>) -> Self {
self.0.borrow_mut().restart_arguments = arguments;
self
}
/// Sets the HTTP client that [`App::http_client`] returns.
///
/// The default fails every request. Pass a real client to let the app fetch URLs,
/// for example for remote images.
pub fn with_http_client(self, http_client: Arc<dyn HttpClient>) -> Self {
let mut context_lock = self.0.borrow_mut();
context_lock.http_client = http_client;
drop(context_lock);
self
}
/// Sets when the app quits on its own. See [`QuitMode`] for the choices.
///
/// Defaults to [`QuitMode::Default`]. You can also change it at runtime with
/// [`App::set_quit_mode`].
pub fn with_quit_mode(self, mode: QuitMode) -> Self {
self.0.borrow_mut().quit_mode = mode;
self
}
/// Sets the activation policy for the application (macOS only).
///
/// This determines how the application appears in the system:
/// - `Regular`: Normal app with Dock icon and menu bar
/// - `Accessory`: Background app without Dock icon (LSUIElement)
/// - `Prohibited`: Runs in background, no UI allowed
///
/// This must be called before the application finishes launching to take effect.
/// The method exists only on macOS, so cross-platform code calls it behind
/// `#[cfg(target_os = "macos")]`.
#[cfg(target_os = "macos")]
pub fn with_activation_policy(self, policy: ActivationPolicy) -> Self {
self.0.borrow().platform.set_activation_policy(policy);
self
}
/// Starts the event loop and calls `on_finish_launching` once the app has launched.
///
/// The callback runs on the main thread with the [`App`], and runs once. Open your
/// first window there. On native platforms this method blocks until the app quits,
/// so code after it runs only after the app exits. On the web it returns right away,
/// and the app keeps running in the page.
///
/// See the [`Application`] example for a complete `main`.
/// Sets the windowing mode the app starts in. See [`App::request_windowing`].
///
/// Defaults to windowed. On Linux, the default environment is the process's own, and the app
/// starts headless if that names no allowed display server. On macOS, headless means the app
/// starts without a Dock icon or menu bar ([`ActivationPolicy::Accessory`]). Has no effect on
/// other platforms.
pub fn with_windowing(self, request: WindowingRequest) -> Self {
self.0.borrow().platform.set_initial_windowing(request);
self
}
/// Start the application. The provided callback will be called once the
/// app is fully launched.
///
/// On WebAssembly, this returns immediately and retains the app for the lifetime
/// of the Wasm instance. Use [`Self::run_embedded`] to control its lifetime explicitly.
pub fn run<F>(self, on_finish_launching: F)
where
F: 'static + FnOnce(&mut App),
{
#[cfg(all(
feature = "hot-patching",
debug_assertions,
not(target_family = "wasm")
))]
dioxus_devtools::connect_subsecond();
let this = self.0.clone();
let platform = self.0.borrow().platform.clone();
platform.run(Box::new(move || {
let cx = &mut *this.borrow_mut();
// Some platforms only connect to their display server in `run`.
cx.displays_changed();
on_finish_launching(cx);
}));
// Native platform run loops block until shutdown, keeping `self` alive for the
// application's lifetime. The web platform schedules startup and returns
// immediately, so retain the application until the browser tears down the page.
#[cfg(target_family = "wasm")]
std::mem::forget(self);
}
/// Start the application for an embedder that drives the run loop itself.
///
/// On ordinary platforms `Platform::run` blocks for the lifetime of the app, and the
/// app state is kept alive by [`Application::run`]'s stack frame. Embedded platforms —
/// where the run loop belongs to someone else, e.g. GPUI compiled into a Wasm guest,
/// or a GPUI view hosted inside a foreign native application — implement
/// `Platform::run` to invoke the launch callback and return immediately. This method
/// supports that shape: it returns an [`ApplicationHandle`] that keeps the app alive
/// and lets the embedder re-enter it whenever the external run loop yields control.
pub fn run_embedded<F>(self, on_finish_launching: F) -> ApplicationHandle
where
F: 'static + FnOnce(&mut App),
{
let this = self.0.clone();
let platform = self.0.borrow().platform.clone();
platform.run(Box::new(move || {
let cx = &mut *this.borrow_mut();
// Some platforms only connect to their display server in `run`.
cx.displays_changed();
on_finish_launching(cx);
}));
ApplicationHandle { app: self.0 }
}
/// Registers a handler for URLs that the user asks the app to open.
///
/// The handler receives the URLs as strings. Register a scheme with
/// [`App::register_url_scheme`] so the platform routes links with that scheme to
/// the app.
pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
where
F: 'static + FnMut(Vec<String>),
{
self.0.borrow().platform.on_open_urls(Box::new(callback));
self
}
/// Registers a handler for a second launch while the app is already running.
///
/// On macOS this happens when the user clicks the app icon in the Dock or in
/// Finder. A common response is to open a window if none is visible. The handler
/// receives the [`App`].
pub fn on_reopen<F>(&self, mut callback: F) -> &Self
where
F: 'static + FnMut(&mut App),
{
let this = Rc::downgrade(&self.0);
self.0.borrow_mut().platform.on_reopen(Box::new(move || {
if let Some(app) = this.upgrade() {
callback(&mut app.borrow_mut());
}
}));
self
}
/// Returns the executor for `Send` futures. See [`BackgroundExecutor`] for platform behavior.
pub fn background_executor(&self) -> BackgroundExecutor {
self.0.borrow().background_executor.clone()
}
/// Returns the executor for futures that run on the foreground thread.
pub fn foreground_executor(&self) -> ForegroundExecutor {
self.0.borrow().foreground_executor.clone()
}
/// Returns a shared handle to the app's [`TextSystem`], which shapes and rasterizes text.
pub fn text_system(&self) -> Arc<TextSystem> {
self.0.borrow().text_system.clone()
}
/// Returns the path to a helper executable named `name` that ships with the app.
///
/// Use this to launch a companion binary, such as a CLI or a helper process. It
/// returns an error if the platform cannot find the executable.
pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
self.0.borrow().path_for_auxiliary_executable(name)
}
}
type Handler = Box<dyn FnMut(&mut App) -> bool + 'static>;
type AppLifecycleHandler = Box<dyn FnMut(AppLifecyclePhase, &mut App) -> bool + 'static>;
type DisplayHandler = Box<dyn FnMut(DisplayEvent, &mut App) -> bool + 'static>;
/// The properties of a display that GPUI reports changes to.
#[derive(Clone, Copy, PartialEq)]
struct DisplayState {
bounds: Bounds<Pixels>,
refresh_interval: Option<Duration>,
}
impl DisplayState {
fn changes_from(&self, previous: &DisplayState) -> DisplayChanges {
let mut changes = DisplayChanges::empty();
changes.set(DisplayChanges::BOUNDS, self.bounds != previous.bounds);
changes.set(
DisplayChanges::REFRESH_INTERVAL,
self.refresh_interval != previous.refresh_interval,
);
changes
}
}
fn read_displays(platform: &dyn Platform) -> HashMap<DisplayId, DisplayState> {
platform
.displays()
.into_iter()
.map(|display| {
let state = DisplayState {
bounds: display.bounds(),
refresh_interval: display.refresh_interval(),
};
(display.id(), state)
})
.collect()
}
/// The events that turn one snapshot of the connected displays into the next.
fn display_events(
previous: &HashMap<DisplayId, DisplayState>,
current: &HashMap<DisplayId, DisplayState>,
) -> Vec<DisplayEvent> {
let removed = previous
.keys()
.filter(|id| !current.contains_key(id))
.map(|id| DisplayEvent::Removed(*id));
let added_or_changed = current.iter().filter_map(|(id, state)| {
let Some(previous_state) = previous.get(id) else {
return Some(DisplayEvent::Added(*id));
};
let changes = state.changes_from(previous_state);
(!changes.is_empty()).then_some(DisplayEvent::Changed { id: *id, changes })
});
removed.chain(added_or_changed).collect()
}
type Listener = Box<dyn FnMut(&dyn Any, &mut App) -> bool + 'static>;
pub(crate) type KeystrokeObserver =
Box<dyn FnMut(&KeystrokeEvent, &mut Window, &mut App) -> bool + 'static>;
type QuitHandler = Box<dyn FnOnce(&mut App) -> LocalBoxFuture<'static, ()> + 'static>;
type WindowClosedHandler = Box<dyn FnMut(&mut App, WindowId)>;
type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut App) + 'static>;
type NewEntityListener = Box<dyn FnMut(AnyEntity, &mut Option<&mut Window>, &mut App) + 'static>;
/// Controls whether the app quits on its own when its last window closes.
///
/// The check runs each time a window closes. With [`QuitMode::LastWindowClosed`], the
/// app quits as soon as no windows remain. With [`QuitMode::Explicit`], closing the
/// last window leaves the app running until you call [`App::quit`].
///
/// # Examples
///
/// ```
/// # use gpui::QuitMode;
/// assert_eq!(QuitMode::default(), QuitMode::Default);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum QuitMode {
/// Behaves like [`QuitMode::LastWindowClosed`] on Linux and Windows, and like
/// [`QuitMode::Explicit`] on macOS, where closing the last window is normal.
#[default]
Default,
/// Quit automatically when the last window is closed.
LastWindowClosed,
/// Quit only when requested via [`App::quit`].
Explicit,
}
/// Controls when GPUI hides the mouse cursor in response to keyboard input.
///
/// GPUI decides when to hide the cursor. The platform shows it again on mouse motion.
/// Set the mode with [`App::set_cursor_hide_mode`].
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub enum CursorHideMode {
/// Never hide the cursor automatically.
Never,
/// Hide on character-producing key presses (typing).
OnTyping,
/// Hide on character-producing key presses, *and* when a key binding
/// resolves to an action that consumes the keystroke.
#[default]
OnTypingAndAction,
}
/// A tab in a group of native window tabs. Used by [`SystemWindowTabController`].
#[doc(hidden)]
#[derive(Clone, PartialEq, Eq)]
pub struct SystemWindowTab {
/// The ID of the window this tab shows.
pub id: WindowId,
/// The title shown on the tab.
pub title: SharedString,
/// The handle to the window.
pub handle: AnyWindowHandle,
/// When the tab was last active. Used to choose which tab in a group to show.
pub last_active_at: Instant,
}
impl SystemWindowTab {
/// Creates a tab for a window, with its current time as the last-active time.
pub fn new(title: SharedString, handle: AnyWindowHandle) -> Self {
Self {
id: handle.id,
title,
handle,
last_active_at: Instant::now(),
}
}
}
/// A global that tracks which windows are grouped into native window tabs.
///
/// Stored as a [`Global`]. Call [`SystemWindowTabController::init`] once at startup.
/// The methods that take `cx` read and update this global.
#[derive(Default)]
pub struct SystemWindowTabController {
visible: Option<bool>,
tab_groups: FxHashMap<usize, Vec<SystemWindowTab>>,
}
impl Global for SystemWindowTabController {}
impl SystemWindowTabController {
/// Creates an empty controller with no tab groups and tabs hidden.
pub fn new() -> Self {
Self {
visible: None,
tab_groups: FxHashMap::default(),
}
}
/// Sets the global [`SystemWindowTabController`] to a new, empty controller.
pub fn init(cx: &mut App) {
cx.set_global(SystemWindowTabController::new());
}
/// Returns every tab group, keyed by group ID.
pub fn tab_groups(&self) -> &FxHashMap<usize, Vec<SystemWindowTab>> {
&self.tab_groups
}
/// Returns the handle of the window in the tab group that follows the group containing `id`
/// in the iteration order of `tab_groups`. That order is arbitrary.
///
/// The window chosen is the most recently active tab in that group. Returns `None`
/// if `id` is not in a group.
pub fn get_next_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
let controller = cx.global::<SystemWindowTabController>();
let current_group = controller
.tab_groups
.iter()
.find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
let current_group = current_group?;
// TODO: `.keys()` returns arbitrary order, what does "next" mean?
let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
let idx = group_ids.iter().position(|g| *g == current_group)?;
let next_idx = (idx + 1) % group_ids.len();
controller
.tab_groups
.get(group_ids[next_idx])
.and_then(|tabs| {
tabs.iter()
.max_by_key(|tab| tab.last_active_at)
.or_else(|| tabs.first())
.map(|tab| &tab.handle)
})
}
/// Returns the handle of the window in the tab group that precedes the group containing `id`
/// in the iteration order of `tab_groups`. That order is arbitrary.
///
/// The window chosen is the most recently active tab in that group. Returns `None`
/// if `id` is not in a group.
pub fn get_prev_tab_group_window(cx: &mut App, id: WindowId) -> Option<&AnyWindowHandle> {
let controller = cx.global::<SystemWindowTabController>();
let current_group = controller
.tab_groups
.iter()
.find_map(|(group, tabs)| tabs.iter().find(|tab| tab.id == id).map(|_| group));
let current_group = current_group?;
// TODO: `.keys()` returns arbitrary order, what does "previous" mean?
let mut group_ids: Vec<_> = controller.tab_groups.keys().collect();
let idx = group_ids.iter().position(|g| *g == current_group)?;
let prev_idx = if idx == 0 {
group_ids.len() - 1
} else {
idx - 1
};
controller
.tab_groups
.get(group_ids[prev_idx])
.and_then(|tabs| {
tabs.iter()
.max_by_key(|tab| tab.last_active_at)
.or_else(|| tabs.first())
.map(|tab| &tab.handle)
})
}
/// Returns the tabs in the group that contains the window `id`, or `None` if it has none.
pub fn tabs(&self, id: WindowId) -> Option<&Vec<SystemWindowTab>> {
self.tab_groups
.values()
.find(|tabs| tabs.iter().any(|tab| tab.id == id))
}
/// Sets tab visibility to `visible`, but only if it has not been set yet.
pub fn init_visible(cx: &mut App, visible: bool) {
let mut controller = cx.global_mut::<SystemWindowTabController>();
if controller.visible.is_none() {
controller.visible = Some(visible);
}
}
/// Returns whether window tabs are shown. Defaults to `false` until set.
pub fn is_visible(&self) -> bool {
self.visible.unwrap_or(false)
}
/// Shows or hides window tabs.
pub fn set_visible(cx: &mut App, visible: bool) {
let mut controller = cx.global_mut::<SystemWindowTabController>();
controller.visible = Some(visible);
}
/// Records that the window `id` is now the active tab, for ordering tab groups.
pub fn update_last_active(cx: &mut App, id: WindowId) {
let mut controller = cx.global_mut::<SystemWindowTabController>();
for windows in controller.tab_groups.values_mut() {
for tab in windows.iter_mut() {
if tab.id == id {
tab.last_active_at = Instant::now();
}
}
}
}
/// Moves the tab for window `id` to index `ix` within its group.
///
/// Does nothing if `ix` is out of range or the tab is already there.
pub fn update_tab_position(cx: &mut App, id: WindowId, ix: usize) {
let mut controller = cx.global_mut::<SystemWindowTabController>();
for (_, windows) in controller.tab_groups.iter_mut() {
if let Some(current_pos) = windows.iter().position(|tab| tab.id == id) {
if ix < windows.len() && current_pos != ix {
let window_tab = windows.remove(current_pos);
windows.insert(ix, window_tab);
}
break;
}
}
}
/// Sets the title of the tab for window `id`. Does nothing if the title is unchanged.
pub fn update_tab_title(cx: &mut App, id: WindowId, title: SharedString) {
let controller = cx.global::<SystemWindowTabController>();
let tab = controller
.tab_groups
.values()
.flat_map(|windows| windows.iter())
.find(|tab| tab.id == id);
if tab.map_or(true, |t| t.title == title) {
return;
}
let mut controller = cx.global_mut::<SystemWindowTabController>();
for windows in controller.tab_groups.values_mut() {
for tab in windows.iter_mut() {
if tab.id == id {
tab.title = title;
return;
}
}
}
}
/// Adds the window `id` to the group that holds the other tabs in `tabs`.
///
/// If no existing group holds exactly the other tabs, `tabs` becomes a new group.
/// Does nothing if `tabs` does not contain `id`.
pub fn add_tab(cx: &mut App, id: WindowId, tabs: Vec<SystemWindowTab>) {
let mut controller = cx.global_mut::<SystemWindowTabController>();
let Some(tab) = tabs.iter().find(|tab| tab.id == id).cloned() else {
return;
};
let mut expected_tab_ids: Vec<_> = tabs
.iter()
.filter(|tab| tab.id != id)
.map(|tab| tab.id)
.sorted()
.collect();
let mut tab_group_id = None;
for (group_id, group_tabs) in &controller.tab_groups {
let tab_ids: Vec<_> = group_tabs.iter().map(|tab| tab.id).sorted().collect();
if tab_ids == expected_tab_ids {
tab_group_id = Some(*group_id);
break;
}
}
if let Some(tab_group_id) = tab_group_id {
if let Some(tabs) = controller.tab_groups.get_mut(&tab_group_id) {
tabs.push(tab);
}
} else {
let new_group_id = controller.tab_groups.keys().max().map_or(0, |id| id + 1);
controller.tab_groups.insert(new_group_id, tabs);
}
}
/// Removes the tab for window `id` from its group and returns it.
///
/// A group that becomes empty is removed. Returns `None` if `id` is in no group.
pub fn remove_tab(cx: &mut App, id: WindowId) -> Option<SystemWindowTab> {
let mut controller = cx.global_mut::<SystemWindowTabController>();
let mut removed_tab = None;
controller.tab_groups.retain(|_, tabs| {
if let Some(pos) = tabs.iter().position(|tab| tab.id == id) {
removed_tab = Some(tabs.remove(pos));
}
!tabs.is_empty()
});
removed_tab
}
/// Moves the tab for window `id` out of its group into a new group of its own.
pub fn move_tab_to_new_window(cx: &mut App, id: WindowId) {
let mut removed_tab = Self::remove_tab(cx, id);
let mut controller = cx.global_mut::<SystemWindowTabController>();
if let Some(tab) = removed_tab {
let new_group_id = controller.tab_groups.keys().max().map_or(0, |k| k + 1);
controller.tab_groups.insert(new_group_id, vec![tab]);
}
}
/// Merges every tab group into one group, starting with the group that holds `id`.
pub fn merge_all_windows(cx: &mut App, id: WindowId) {
let mut controller = cx.global_mut::<SystemWindowTabController>();
let Some(initial_tabs) = controller.tabs(id) else {
return;
};
let initial_tabs_len = initial_tabs.len();
let mut all_tabs = initial_tabs.clone();
for (_, mut tabs) in controller.tab_groups.drain() {
tabs.retain(|tab| !all_tabs[..initial_tabs_len].contains(tab));
all_tabs.extend(tabs);
}
controller.tab_groups.insert(0, all_tabs);
}
/// Activates the tab after window `id`'s tab in its group, wrapping around at the end.
pub fn select_next_tab(cx: &mut App, id: WindowId) {
let mut controller = cx.global_mut::<SystemWindowTabController>();
let Some(tabs) = controller.tabs(id) else {
return;
};
let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
let next_index = (current_index + 1) % tabs.len();
let _ = &tabs[next_index].handle.update(cx, |_, window, _| {
window.activate();
});
}
/// Activates the tab before window `id`'s tab in its group, wrapping around at the start.
pub fn select_previous_tab(cx: &mut App, id: WindowId) {
let mut controller = cx.global_mut::<SystemWindowTabController>();
let Some(tabs) = controller.tabs(id) else {
return;
};
let current_index = tabs.iter().position(|tab| tab.id == id).unwrap();
let previous_index = if current_index == 0 {
tabs.len() - 1
} else {
current_index - 1
};
let _ = &tabs[previous_index].handle.update(cx, |_, window, _| {
window.activate();
});
}
}
pub(crate) enum GpuiMode {
#[cfg(any(test, feature = "test-support"))]
Test {
skip_drawing: bool,
},
Production,
}
impl GpuiMode {
#[cfg(any(test, feature = "test-support"))]
pub fn test() -> Self {
GpuiMode::Test {
skip_drawing: false,
}
}
#[inline]
pub(crate) fn skip_drawing(&self) -> bool {
match self {
#[cfg(any(test, feature = "test-support"))]
GpuiMode::Test { skip_drawing } => *skip_drawing,
GpuiMode::Production => false,
}
}
}
struct PlatformOwnedDrag {
source_window: WindowId,
state: PlatformOwnedDragState,
}
enum PlatformOwnedDragState {
Suspended(AnyDrag),
// A source-window drop consumes `active_drag` before AppKit ends the dragging session, so this
// marker can outlive the active drag and is cleaned up by `FileDropEvent::Ended`.
RestoredInSourceWindow,
}
/// What a view read while it drew: entities, globals and handle revisions, with the revision
/// each was at.
#[derive(Default)]
pub(crate) struct Dependencies {
entities: Vec<EntityId>,
globals: Vec<(TypeId, u64)>,
revisions: Vec<(Revision, u64)>,
}
impl Dependencies {
pub(crate) fn extend(&mut self, other: Dependencies) {
self.entities.extend(other.entities);
self.entities.sort_unstable();
self.entities.dedup();
self.globals.extend(other.globals);
self.globals.sort_unstable();
self.globals.dedup_by_key(|(global_type, _)| *global_type);
// A later phase saw the later revision, so it wins.
for (revision, seen) in other.revisions {
match self
.revisions
.iter_mut()
.find(|(known, _)| known.same(&revision))
{
Some(entry) => entry.1 = seen,
None => self.revisions.push((revision, seen)),
}
}
}
}
/// A counter for state that lives outside entities, such as a list's scroll position, so the
/// views that read it are drawn again when it changes. The owner bumps it on every mutation.
#[derive(Clone, Debug, Default)]
pub(crate) struct Revision(Rc<Cell<u64>>);
impl Revision {
pub(crate) fn bump(&self) {
self.0.set(self.0.get().wrapping_add(1));
}
fn same(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.0, &other.0)
}
}
/// The state of a running application: its entities, windows, globals and key bindings.
///
/// You get a `&mut App` from the callback passed to [`Application::run`], from
/// `TestApp::update`, and from any [`Context`], which derefs to `App`. Read an
/// entity with [`Entity::read`], and create one with [`AppContext::new`]. Callbacks that
/// run after an `await` can't hold the `App`, so they use an [`AsyncApp`] instead.
///
/// `App` is not `Clone`. Keep one per app, and use the references you are given. It
/// is not `Send`, so it only runs on the main thread.
///
/// # Examples
///
/// ```
/// # use gpui::{AppContext, TestApp};
/// let mut app = TestApp::new();
/// let count = app.update(|cx| cx.new(|_| 1));
/// app.read(|cx| assert_eq!(*count.read(cx), 1));
/// ```
///
/// See [contexts](crate::_documentation::concepts::contexts) for how `App` relates to the
/// other context types.
pub struct App {
pub(crate) this: Weak<AppCell>,
pub(crate) platform: Rc<dyn Platform>,
text_system: Arc<TextSystem>,
pub(crate) actions: Rc<ActionRegistry>,
pub(crate) active_drag: Option<AnyDrag>,
platform_owned_drag: Option<PlatformOwnedDrag>,
pub(crate) background_executor: BackgroundExecutor,
pub(crate) foreground_executor: ForegroundExecutor,
#[cfg(feature = "profiler")]
foreground_journal: crate::profiler::journal::ForegroundJournal,
#[cfg(all(feature = "profiler", not(target_family = "wasm")))]
hang_monitor: Option<crate::profiler::hang::HangMonitor>,
pub(crate) entities: EntityMap,
pub(crate) new_entity_observers: SubscriberSet<TypeId, NewEntityListener>,
pub(crate) windows: SlotMap<WindowId, Option<Box<Window>>>,
pub(crate) window_handles: FxHashMap<WindowId, AnyWindowHandle>,
pub(crate) focus_handles: Arc<RwLock<FocusMap>>,
pub(crate) keymap: Rc<RefCell<Keymap>>,
pub(crate) keyboard_layout: Box<dyn PlatformKeyboardLayout>,
pub(crate) keyboard_mapper: Rc<dyn PlatformKeyboardMapper>,
pub(crate) global_action_listeners:
TypeIdHashMap<Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
pending_effects: VecDeque<Effect>,
pub(crate) observers: SubscriberSet<EntityId, Handler>,
pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,
pub(crate) keystroke_observers: SubscriberSet<(), KeystrokeObserver>,
pub(crate) keystroke_interceptors: SubscriberSet<(), KeystrokeObserver>,
pub(crate) keyboard_layout_observers: SubscriberSet<(), Handler>,
pub(crate) thermal_state_observers: SubscriberSet<(), Handler>,
pub(crate) display_observers: SubscriberSet<(), DisplayHandler>,
/// The connected displays, as of the platform's last display change
/// notification.
displays: HashMap<DisplayId, DisplayState>,
pub(crate) system_sleep_observers: SubscriberSet<(), Handler>,
pub(crate) system_wake_observers: SubscriberSet<(), Handler>,
app_lifecycle_observers: SubscriberSet<(), AppLifecycleHandler>,
memory_warning_observers: SubscriberSet<(), Handler>,
pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
pub(crate) restart_observers: SubscriberSet<(), Handler>,
pub(crate) window_closed_observers: SubscriberSet<(), WindowClosedHandler>,
/// Per-App element arena. This isolates element allocations between different
/// App instances (important for tests where multiple Apps run concurrently).
pub(crate) element_arena: RefCell<Arena>,
/// Per-App event arena.
pub(crate) event_arena: Arena,
// Drop globals last. We need to ensure all tasks owned by entities and
// callbacks are marked cancelled at this point as this will also shutdown
// the tokio runtime. As any task attempting to spawn a blocking tokio task,
// might panic.
pub(crate) globals_by_type: TypeIdHashMap<Box<dyn Any>>,
global_revisions: TypeIdHashMap<u64>,
global_reads: RefCell<Vec<TypeId>>,
revision_reads: RefCell<Vec<Revision>>,
// Entities which are retained until explicitly removed from the app or dropped at end of life-cycle.
// This is an alternative way to define "global" data which uses entities.
// There can be multiple entities of a given type & each `Entity<T>` is stored as `Box<dyn Any>`.
global_entities: Vec<AnyEntity>,
// assets
pub(crate) loading_assets: FxHashMap<(TypeId, u64), Box<dyn Any>>,
asset_registry: Arc<AssetRegistry>,
pub(crate) svg_renderer: SvgRenderer,
http_client: Arc<dyn HttpClient>,
// below is plain data, the drop order is insignificant here
pub(crate) pending_notifications: FxHashSet<EntityId>,
pub(crate) pending_global_notifications: TypeIdHashSet,
pub(crate) restart_path: Option<PathBuf>,
pub(crate) restart_arguments: Vec<OsString>,
pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
pub(crate) propagate_event: bool,
pub(crate) prompt_builder: Option<PromptBuilder>,
pub(crate) window_invalidators_by_entity:
FxHashMap<EntityId, FxHashMap<WindowId, WindowInvalidator>>,
pub(crate) tracked_entities: FxHashMap<WindowId, FxHashSet<EntityId>>,
pub(crate) current_window_by_entity: FxHashMap<EntityId, WindowId>,
#[cfg(any(feature = "inspector", debug_assertions))]
pub(crate) inspector_renderer: Option<crate::InspectorRenderer>,
#[cfg(any(feature = "inspector", debug_assertions))]
pub(crate) inspector_element_registry: InspectorElementRegistry,
#[cfg(any(test, feature = "test-support", debug_assertions))]
pub(crate) name: Option<&'static str>,
pub(crate) text_rendering_mode: Rc<Cell<TextRenderingMode>>,
pub(crate) window_update_stack: Vec<WindowId>,
pub(crate) mode: GpuiMode,
pub(crate) cursor_hide_mode: CursorHideMode,
pub(crate) reduce_motion: bool,
/// Origin of the shared clock that phase-locks synced repeating animations.
pub(crate) synced_animation_epoch: Instant,
/// Whether the app was created by [`Application::new_inaccessible`]. No
/// accesskit APIs will be called when this flag is set.
pub(crate) accessibility_force_disabled: bool,
/// Whether windows build their accessibility tree every frame without an
/// assistive-technology client. See [`Application::with_accessibility_forced`].
pub(crate) accessibility_forced: bool,
pending_updates: usize,
quit_mode: QuitMode,
quitting: bool,
// We need to ensure the leak detector drops last, after all tasks, callbacks and things have been dropped.
// Otherwise it may report false positives.
#[cfg(any(test, gpui_leak_detection))]
_ref_counts: Arc<RwLock<EntityRefCounts>>,
}
impl App {
#[allow(clippy::new_ret_no_self)]
pub(crate) fn new_app(
platform: Rc<dyn Platform>,
asset_registry: Arc<AssetRegistry>,
http_client: Arc<dyn HttpClient>,
) -> Rc<AppCell> {
let background_executor = platform.background_executor();
let foreground_executor = platform.foreground_executor();
assert!(
background_executor.is_main_thread(),
"must construct App on main thread"
);
#[cfg(feature = "profiler")]
let foreground_journal = crate::profiler::journal::install_foreground_journal();
let synced_animation_epoch = background_executor.now();
let text_system = Arc::new(TextSystem::new(platform.text_system()));
let entities = EntityMap::new();
let keyboard_layout = platform.keyboard_layout();
let keyboard_mapper = platform.keyboard_mapper();
#[cfg(any(test, gpui_leak_detection))]
let _ref_counts = entities.ref_counts_drop_handle();
let app = Rc::new_cyclic(|this| AppCell {
app: RefCell::new(App {
this: this.clone(),
platform: platform.clone(),
text_system,
text_rendering_mode: Rc::new(Cell::new(TextRenderingMode::default())),
mode: GpuiMode::Production,
actions: Rc::new(ActionRegistry::default()),
pending_updates: 0,
active_drag: None,
platform_owned_drag: None,
background_executor,
foreground_executor,
#[cfg(feature = "profiler")]
foreground_journal,
#[cfg(all(feature = "profiler", not(target_family = "wasm")))]
hang_monitor: None,
svg_renderer: SvgRenderer::new(asset_registry.clone()),
loading_assets: Default::default(),
asset_registry,
http_client,
globals_by_type: Default::default(),
global_revisions: Default::default(),
global_reads: Default::default(),
revision_reads: Default::default(),
global_entities: Default::default(),
entities,
new_entity_observers: SubscriberSet::new(),
windows: SlotMap::with_key(),
window_update_stack: Vec::new(),
window_handles: FxHashMap::default(),
focus_handles: Arc::new(RwLock::new(FocusMap::default())),
keymap: Rc::new(RefCell::new(Keymap::default())),
keyboard_layout,
keyboard_mapper,
global_action_listeners: Default::default(),
pending_effects: VecDeque::new(),
pending_notifications: FxHashSet::default(),
pending_global_notifications: Default::default(),
observers: SubscriberSet::new(),
tracked_entities: FxHashMap::default(),
window_invalidators_by_entity: FxHashMap::default(),
current_window_by_entity: FxHashMap::default(),
event_listeners: SubscriberSet::new(),
release_listeners: SubscriberSet::new(),
keystroke_observers: SubscriberSet::new(),
keystroke_interceptors: SubscriberSet::new(),
keyboard_layout_observers: SubscriberSet::new(),
thermal_state_observers: SubscriberSet::new(),
display_observers: SubscriberSet::new(),
displays: read_displays(platform.as_ref()),
system_sleep_observers: SubscriberSet::new(),
system_wake_observers: SubscriberSet::new(),
app_lifecycle_observers: SubscriberSet::new(),
memory_warning_observers: SubscriberSet::new(),
global_observers: SubscriberSet::new(),
quit_observers: SubscriberSet::new(),
restart_observers: SubscriberSet::new(),
restart_path: None,
restart_arguments: Vec::new(),
window_closed_observers: SubscriberSet::new(),
layout_id_buffer: Default::default(),
propagate_event: true,
prompt_builder: Some(PromptBuilder::Default),
#[cfg(any(feature = "inspector", debug_assertions))]
inspector_renderer: None,
#[cfg(any(feature = "inspector", debug_assertions))]
inspector_element_registry: InspectorElementRegistry::default(),
quit_mode: QuitMode::default(),
quitting: false,
cursor_hide_mode: CursorHideMode::default(),
reduce_motion: false,
synced_animation_epoch,
accessibility_force_disabled: false,
accessibility_forced: false,
#[cfg(any(test, feature = "test-support", debug_assertions))]
name: None,
element_arena: RefCell::new(Arena::new(1024 * 1024)),
event_arena: Arena::new(1024 * 1024),
#[cfg(any(test, gpui_leak_detection))]
_ref_counts,
}),
});
init_app_menus(platform.as_ref(), &app.borrow());
SystemWindowTabController::init(&mut app.borrow_mut());
#[cfg(feature = "profiler")]
crate::profiler::journal::observe_power(&app.borrow());
platform.on_keyboard_layout_change(Box::new({
let app = Rc::downgrade(&app);
move || {
if let Some(app) = app.upgrade() {
let cx = &mut app.borrow_mut();
cx.keyboard_layout = cx.platform.keyboard_layout();
cx.keyboard_mapper = cx.platform.keyboard_mapper();
cx.keyboard_layout_observers
.clone()
.retain(&(), move |callback| (callback)(cx));
}
}
}));
platform.on_thermal_state_change(Box::new({
let app = Rc::downgrade(&app);
move || {
if let Some(app) = app.upgrade() {
let cx = &mut app.borrow_mut();
cx.thermal_state_observers
.clone()
.retain(&(), move |callback| (callback)(cx));
}
}
}));
platform.on_displays_changed(Box::new({
let app = Rc::downgrade(&app);
move || {
if let Some(app) = app.upgrade() {
app.borrow_mut().displays_changed();
}
}
}));
platform.on_system_sleep(Box::new({
let app = Rc::downgrade(&app);
move || {
if let Some(app) = app.upgrade() {
let cx = &mut app.borrow_mut();
cx.system_sleep_observers
.clone()
.retain(&(), move |callback| (callback)(cx));
}
}
}));
platform.on_system_wake(Box::new({
let app = Rc::downgrade(&app);
move || {
if let Some(app) = app.upgrade() {
let cx = &mut app.borrow_mut();
cx.system_wake_observers
.clone()
.retain(&(), move |callback| (callback)(cx));
}
}
}));
platform.on_app_lifecycle(Box::new({
let app = Rc::downgrade(&app);
move |phase| {
if let Some(app) = app.upgrade() {
app.borrow_mut().update(|cx| {
cx.app_lifecycle_observers
.clone()
.retain(&(), |callback| callback(phase, cx));
});
}
}
}));
platform.on_memory_warning(Box::new({
let app = Rc::downgrade(&app);
move || {
if let Some(app) = app.upgrade() {
app.borrow_mut().update(|cx| {
cx.memory_warning_observers
.clone()
.retain(&(), |callback| callback(cx));
});
}
}
}));
platform.on_quit(Box::new({
let cx = Rc::downgrade(&app);
move || {
let Some(cx) = cx.upgrade() else {
return true;
};
match cx.try_borrow_mut() {
Ok(mut cx) => {
cx.shutdown();
true
}
Err(_) => {
// Quit was requested while the AppCell was borrowed, so we can't shut down synchronously.
// The platform decides how to proceed.
false
}
}
}
}));
app
}
#[doc(hidden)]
pub fn ref_counts_drop_handle(&self) -> impl Sized + use<> {
self.entities.ref_counts_drop_handle()
}
/// Captures a snapshot of all entities that currently have alive handles.
///
/// The returned [`LeakDetectorSnapshot`] can later be passed to
/// [`assert_no_new_leaks`](Self::assert_no_new_leaks) to verify that no
/// entities created after the snapshot are still alive.
#[cfg(any(test, gpui_leak_detection))]
pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
self.entities.leak_detector_snapshot()
}
/// Asserts that no entities created after `snapshot` still have alive handles.
///
/// Entities that were already tracked at the time of the snapshot are ignored,
/// even if they still have handles. Only *new* entities (those whose
/// `EntityId` was not present in the snapshot) are considered leaks.
///
/// # Panics
///
/// Panics if any new entity handles exist. The panic message lists every
/// leaked entity with its type name, and includes allocation-site backtraces
/// when `LEAK_BACKTRACE` is set.
#[cfg(any(test, gpui_leak_detection))]
pub fn assert_no_new_leaks(&self, snapshot: &LeakDetectorSnapshot) {
self.entities.assert_no_new_leaks(snapshot)
}
/// Without leak detection compiled in, this records nothing.
#[cfg(all(feature = "test-support", not(any(test, gpui_leak_detection))))]
pub fn leak_detector_snapshot(&self) -> LeakDetectorSnapshot {
LeakDetectorSnapshot::default()
}
/// Without leak detection compiled in, this checks nothing. Set
/// `GPUI_LEAK_DETECTION` when building to enable it.
#[cfg(all(feature = "test-support", not(any(test, gpui_leak_detection))))]
pub fn assert_no_new_leaks(&self, _snapshot: &LeakDetectorSnapshot) {}
/// Runs the quit handlers, closes every window and flushes pending effects.
///
/// The platform calls this when the app quits. Handlers registered with
/// [`Context::on_app_quit`] run first. Native apps wait up to [`SHUTDOWN_TIMEOUT`]
/// for them to finish and log an error if they don't. On the web the handlers run
/// asynchronously as best-effort cleanup, because the event loop cannot block.
///
/// To quit from your own code, call [`App::quit`] instead.
pub fn shutdown(&mut self) {
// Requested first so the final hang poll overlaps with the quit
// handlers. It's awaited alongside them, within `SHUTDOWN_TIMEOUT`.
#[cfg(all(feature = "profiler", not(target_family = "wasm")))]
let hang_monitor_flush = self
.hang_monitor
.as_ref()
.and_then(|hang_monitor| hang_monitor.request_flush());
let mut futures: Vec<LocalBoxFuture<'static, ()>> = Vec::new();
for observer in self.quit_observers.remove(&()) {
futures.push(observer(self));
}
#[cfg(all(feature = "profiler", not(target_family = "wasm")))]
if let Some(flushed) = hang_monitor_flush {
futures.push(
async move {
if flushed.await.is_err() {
log::warn!("hang monitor exited before flushing");
}
}
.boxed_local(),
);
}
self.windows.clear();
self.window_handles.clear();
self.flush_effects();
self.quitting = true;
let futures = futures::future::join_all(futures);
#[cfg(not(target_family = "wasm"))]
if self
.foreground_executor
.block_with_timeout(SHUTDOWN_TIMEOUT, futures)
.is_err()
{
log::error!("timed out waiting on app_will_quit");
}
#[cfg(target_family = "wasm")]
self.foreground_executor.spawn(futures).detach();
self.quitting = false;
}
/// Returns the keyboard layout that is active now.
///
/// Use it to translate between keystrokes and the characters they produce. The
/// value is updated when the layout changes, which [`App::on_keyboard_layout_change`]
/// reports.
pub fn keyboard_layout(&self) -> &dyn PlatformKeyboardLayout {
self.keyboard_layout.as_ref()
}
/// Returns the keyboard mapper for the active layout.
pub fn keyboard_mapper(&self) -> &Rc<dyn PlatformKeyboardMapper> {
&self.keyboard_mapper
}
/// Calls `callback` each time the user switches the keyboard layout.
///
/// The subscription stays active while you hold it. Drop it to stop receiving
/// calls. By the time the callback runs, [`App::keyboard_layout`] already returns
/// the new layout.
pub fn on_keyboard_layout_change<F>(&self, mut callback: F) -> Subscription
where
F: 'static + FnMut(&mut App),
{
let (subscription, activate) = self.keyboard_layout_observers.insert(
(),
Box::new(move |cx| {
callback(cx);
true
}),
);
activate();
subscription
}
/// Asks the platform to quit the app, the same as choosing Quit from the app menu.
///
/// The quit happens later, not inside this call. The platform then calls
/// [`App::shutdown`], which runs the [`Context::on_app_quit`] handlers and closes
/// the windows. Use this to quit from your own code. [`QuitMode`] controls quits
/// that happen when the last window closes.
pub fn quit(&self) {
self.platform.quit();
}
/// Switches the platform between headless and windowed modes.
///
/// On Linux, headless means no display server: windows opened afterwards lay out and handle
/// input but draw nothing. Windowed, the platform connects to the display server the
/// environment names. On macOS, the modes set the [`ActivationPolicy`]: headless is
/// `Accessory` (no Dock icon or menu bar) and windowed is `Regular`. Switching to windowed
/// doesn't activate the app: call [`App::activate`] for that.
///
/// The returned task resolves once the switch has been applied. It fails if the platform is
/// already in the requested mode (switching to another display server means going headless
/// first), if the platform doesn't allow the mode or can't switch at all, if any window is
/// open (a window belongs to the display server that opened it), or if the display server
/// can't be reached.
pub fn request_windowing(&self, request: WindowingRequest) -> Task<anyhow::Result<()>> {
if !self.windows.is_empty() {
return Task::ready(Err(anyhow::anyhow!(
"cannot switch windowing modes while windows are open"
)));
}
self.platform.request_windowing(request)
}
/// The environment of the display server the platform is connected to, or `None` while
/// headless. Its activation token is always unset, since the connection has used it.
///
/// Programs an app launches inherit this process's environment, which may name another
/// graphical session, or none if the app started headless. Pass them this one with
/// [`GraphicalEnvironment::apply_to`](crate::GraphicalEnvironment::apply_to).
///
/// On macOS, the environment carries nothing, and this is `None` while the activation
/// policy is `Accessory`. Always `None` on platforms that can't switch windowing modes.
pub fn graphical_environment(&self) -> Option<crate::GraphicalEnvironment> {
self.platform.graphical_environment()
}
/// Returns the policy that decides when GPUI hides the cursor while typing.
///
/// Defaults to [`CursorHideMode::OnTypingAndAction`].
pub fn cursor_hide_mode(&self) -> CursorHideMode {
self.cursor_hide_mode
}
/// Sets the policy that decides when GPUI hides the cursor while typing.
///
/// Takes effect for the next keystroke. The cursor reappears when the mouse moves.
pub fn set_cursor_hide_mode(&mut self, mode: CursorHideMode) {
self.cursor_hide_mode = mode;
}
/// Returns whether the cursor is currently visible according to the
/// platform. This will report `false` after a keyboard input has hidden
/// the cursor and the user has not yet moved the mouse to restore it.
///
/// See [`App::set_cursor_hide_mode`].
pub fn is_cursor_visible(&self) -> bool {
self.platform.is_cursor_visible()
}
/// Returns whether non-essential animations should render in a static state.
///
/// Check this before you start a decorative animation, such as a spinner that only
/// looks busy. The app sets it, and it defaults to `false`.
pub fn reduce_motion(&self) -> bool {
self.reduce_motion
}
/// Sets whether non-essential animations should render in a static state.
///
/// Setting a different value redraws all windows. Animations that are needed to
/// show state, such as a progress bar, should keep running.
pub fn set_reduce_motion(&mut self, reduce_motion: bool) {
if self.reduce_motion != reduce_motion {
self.reduce_motion = reduce_motion;
self.refresh_windows();
}
}
/// Redraws every window once the current update finishes.
///
/// Calling it several times in one update still causes a single redraw per window.
/// Use [`Context::notify`] on the entity that changed instead when you can. Use this
/// when state outside any entity changes what is drawn.
pub fn refresh_windows(&mut self) {
self.pending_effects.push_back(Effect::RefreshWindows);
}
#[inline(always)]
pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
self.start_update();
let result = update(self);
self.finish_update();
result
}
pub(crate) fn start_update(&mut self) {
self.pending_updates += 1;
}
#[inline(never)]
pub(crate) fn finish_update(&mut self) {
if self.pending_updates == 1 {
self.flush_effects();
}
self.pending_updates -= 1;
}
/// Calls `on_notify` each time `entity` calls [`Context::notify`].
///
/// The callback receives the entity and the [`App`]. It runs when the update that
/// called `notify` finishes, not during that call. Keep the returned [`Subscription`]
/// alive, because dropping it ends the observation.
///
/// # Examples
///
/// ```
/// # use gpui::{AppContext, TestApp};
/// # use std::{cell::Cell, rc::Rc};
/// # let mut app = TestApp::new();
/// let seen = Rc::new(Cell::new(0));
/// let counter = app.update(|cx| cx.new(|_| 0));
/// let _subscription = app.update(|cx| {
/// cx.observe(&counter, {
/// let seen = seen.clone();
/// move |counter, cx| seen.set(*counter.read(cx))
/// })
/// });
/// app.update(|cx| {
/// counter.update(cx, |count, cx| {
/// *count = 2;
/// cx.notify();
/// })
/// });
/// assert_eq!(seen.get(), 2);
/// ```
///
/// See [ownership and data flow](crate::_documentation::concepts::ownership).
pub fn observe<W>(
&mut self,
entity: &Entity<W>,
mut on_notify: impl FnMut(Entity<W>, &mut App) + 'static,
) -> Subscription
where
W: 'static,
{
self.observe_internal(entity, move |e, cx| {
on_notify(e, cx);
true
})
}
/// Runs `callback` and returns what it read: the entities, and the globals at their
/// current revisions. Reads by nested recordings count for the enclosing ones too.
pub(crate) fn record_dependencies<R>(
&mut self,
callback: impl FnOnce(&mut App) -> R,
) -> (R, Dependencies) {
let entities_start = self.entities.access_log.get_mut().len();
let globals_start = self.global_reads.get_mut().len();
let revisions_start = self.revision_reads.get_mut().len();
*self.entities.recordings.get_mut() += 1;
let result = callback(self);
let recordings = self.entities.recordings.get_mut();
*recordings -= 1;
let outermost = *recordings == 0;
let log = self.entities.access_log.get_mut();
let mut entities = log[entities_start..].to_vec();
entities.sort_unstable();
entities.dedup();
let reads = self.global_reads.get_mut();
let mut globals: Vec<(TypeId, u64)> = reads[globals_start..]
.iter()
.map(|global_type| (*global_type, 0))
.collect();
let revision_reads = self.revision_reads.get_mut();
let mut revisions: Vec<(Revision, u64)> = Vec::new();
for revision in revision_reads.drain(revisions_start..) {
if !revisions.iter().any(|(known, _)| known.same(&revision)) {
let seen = revision.0.get();
revisions.push((revision, seen));
}
}
if !outermost {
// Enclosing recordings depend on these too.
revision_reads.extend(revisions.iter().map(|(revision, _)| revision.clone()));
}
if outermost {
log.clear();
reads.clear();
}
globals.sort_unstable();
globals.dedup();
for (global_type, revision) in &mut globals {
*revision = self.global_revision(*global_type);
}
(
result,
Dependencies {
entities,
globals,
revisions,
},
)
}
/// Counts `dependencies` as read again, as when a view's output is reused.
pub(crate) fn replay_dependencies(&mut self, dependencies: &Dependencies) {
for entity_id in &dependencies.entities {
self.entities.note_access(*entity_id);
}
for (global_type, _) in &dependencies.globals {
self.note_global_read(*global_type);
}
for (revision, _) in &dependencies.revisions {
self.note_revision(revision);
}
}
/// Records that the drawing view read state versioned by `revision`.
pub(crate) fn note_revision(&self, revision: &Revision) {
if self.entities.recordings.get() > 0 {
self.revision_reads.borrow_mut().push(revision.clone());
}
}
/// Returns whether anything in `dependencies` changed: an entity in `dirty`, or a global
/// written since it was read.
pub(crate) fn dependencies_changed(
&self,
dependencies: &Dependencies,
dirty: &FxHashSet<EntityId>,
) -> bool {
dependencies.entities.iter().any(|id| dirty.contains(id))
|| dependencies
.globals
.iter()
.any(|(global_type, revision)| self.global_revision(*global_type) != *revision)
|| dependencies
.revisions
.iter()
.any(|(revision, seen)| revision.0.get() != *seen)
}
fn note_global_read(&self, global_type: TypeId) {
if self.entities.recordings.get() > 0 {
self.global_reads.borrow_mut().push(global_type);
}
}
fn global_revision(&self, global_type: TypeId) -> u64 {
self.global_revisions
.get(&global_type)
.copied()
.unwrap_or(0)
}
fn global_changed(&mut self, global_type: TypeId) {
*self.global_revisions.entry(global_type).or_default() += 1;
self.push_effect(Effect::NotifyGlobalObservers { global_type });
}
pub(crate) fn record_entities_accessed(
&mut self,
window_handle: AnyWindowHandle,
invalidator: WindowInvalidator,
entities: &FxHashSet<EntityId>,
) {
let mut tracked_entities =
std::mem::take(self.tracked_entities.entry(window_handle.id).or_default());
for entity in tracked_entities.iter() {
self.window_invalidators_by_entity
.entry(*entity)
.and_modify(|windows| {
windows.remove(&window_handle.id);
});
}
for entity in entities.iter() {
self.window_invalidators_by_entity
.entry(*entity)
.or_default()
.insert(window_handle.id, invalidator.clone());
self.current_window_by_entity
.insert(*entity, window_handle.id);
}
tracked_entities.clear();
tracked_entities.extend(entities.iter().copied());
self.tracked_entities
.insert(window_handle.id, tracked_entities);
}
pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
let (subscription, activate) = self.observers.insert(key, value);
self.defer(move |_| activate());
subscription
}
pub(crate) fn observe_internal<W>(
&mut self,
entity: &Entity<W>,
mut on_notify: impl FnMut(Entity<W>, &mut App) -> bool + 'static,
) -> Subscription
where
W: 'static,
{
let entity_id = entity.entity_id();
let handle = entity.downgrade();
self.new_observer(
entity_id,
Box::new(move |cx| {
if let Some(entity) = handle.upgrade() {
on_notify(entity, cx)
} else {
false
}
}),
)
}
/// Calls `on_event` each time `entity` emits an event of type `Event`.
///
/// The callback receives the entity, a reference to the event and the [`App`]. The
/// entity emits with [`Context::emit`]. Callbacks run when the update that emitted
/// the event finishes. Keep the returned [`Subscription`] alive, because dropping it
/// ends the subscription. Use [`App::observe`] when the entity only calls
/// [`Context::notify`] and doesn't send a payload.
///
/// # Examples
///
/// ```
/// # use gpui::{AppContext, EventEmitter, TestApp};
/// # use std::{cell::Cell, rc::Rc};
/// struct Counter;
/// struct Incremented(usize);
/// impl EventEmitter<Incremented> for Counter {}
///
/// # let mut app = TestApp::new();
/// let counter = app.update(|cx| cx.new(|_| Counter));
/// let total = Rc::new(Cell::new(0));
/// let _subscription = app.update(|cx| {
/// cx.subscribe(&counter, {
/// let total = total.clone();
/// move |_, event: &Incremented, _| total.set(total.get() + event.0)
/// })
/// });
/// app.update(|cx| counter.update(cx, |_, cx| cx.emit(Incremented(3))));
/// assert_eq!(total.get(), 3);
/// ```
pub fn subscribe<T, Event>(
&mut self,
entity: &Entity<T>,
mut on_event: impl FnMut(Entity<T>, &Event, &mut App) + 'static,
) -> Subscription
where
T: 'static + EventEmitter<Event>,
Event: 'static,
{
self.subscribe_internal(entity, move |entity, event, cx| {
on_event(entity, event, cx);
true
})
}
pub(crate) fn new_subscription(
&mut self,
key: EntityId,
value: (TypeId, Listener),
) -> Subscription {
let (subscription, activate) = self.event_listeners.insert(key, value);
self.defer(move |_| activate());
subscription
}
pub(crate) fn subscribe_internal<T, Evt>(
&mut self,
entity: &Entity<T>,
mut on_event: impl FnMut(Entity<T>, &Evt, &mut App) -> bool + 'static,
) -> Subscription
where
T: 'static + EventEmitter<Evt>,
Evt: 'static,
{
let entity_id = entity.entity_id();
let handle = entity.downgrade();
self.new_subscription(
entity_id,
(
TypeId::of::<Evt>(),
Box::new(move |event, cx| {
let event: &Evt = event.downcast_ref().expect("invalid event type");
if let Some(entity) = handle.upgrade() {
on_event(entity, event, cx)
} else {
false
}
}),
),
)
}
/// Returns handles to every open window.
///
/// Each handle is untyped. [`AnyWindowHandle::downcast`] checks the root type recorded in
/// the handle. If the root may have been replaced, use [`AnyWindowHandle::update`] to
/// inspect the live root; the recorded type does not change with it.
pub fn windows(&self) -> Vec<AnyWindowHandle> {
self.windows
.keys()
.flat_map(|window_id| self.window_handles.get(&window_id).copied())
.collect()
}
/// Returns the window handles ordered by their appearance on screen, front to back.
///
/// The first window in the returned list is the active/topmost window of the application.
///
/// This method returns None if the platform doesn't implement the method yet.
pub fn window_stack(&self) -> Option<Vec<AnyWindowHandle>> {
self.platform.window_stack()
}
/// Sets the GPU device requirements (extra features and limits) for the renderer.
/// Only macOS uses them.
///
/// Call this before opening any window. The argument must be a
/// `gpui_wgpu::WgpuDeviceRequirements` boxed as `Box<dyn Any>`.
pub fn set_gpu_requirements(&self, requirements: Box<dyn std::any::Any>) {
self.platform.set_gpu_requirements(requirements);
}
/// Sets the label applied to credentials stored in the system keyring.
/// Call before writing credentials. Only Linux/FreeBSD apply the label.
pub fn set_keyring_label(&self, label: impl Into<SharedString>) {
self.platform.set_keyring_label(label.into());
}
/// Returns the handle of the window that the platform reports as active, if any.
///
/// Returns `None` when no window of this app has focus, for example when another
/// application is in front.
pub fn active_window(&self) -> Option<AnyWindowHandle> {
self.platform.active_window()
}
/// Opens a window and builds its root view.
///
/// `build_root_view` runs once, with the new [`Window`] and the [`App`], and returns
/// the root entity. The window is drawn once before this method returns. Use the
/// returned [`WindowHandle`] to update or read the root view later.
///
/// In tests, `TestApp::open_window` opens a window without a display.
///
/// # Errors
///
/// Returns an error if the platform cannot create the window. In that case
/// `build_root_view` is not called.
///
/// # Examples
///
/// ```
/// # use gpui::{AppContext, Context, Render, TestApp, Window, WindowOptions, div, prelude::*};
/// struct Hello;
///
/// impl Render for Hello {
/// fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
/// div().child("Hello")
/// }
/// }
///
/// # let mut app = TestApp::new();
/// let window = app.update(|cx| {
/// cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| Hello))
/// .unwrap()
/// });
/// app.read(|cx| assert_eq!(cx.windows().len(), 1));
/// # let _ = window;
/// ```
pub fn open_window<V: 'static + Render>(
&mut self,
options: crate::WindowOptions,
build_root_view: impl FnOnce(&mut Window, &mut App) -> Entity<V>,
) -> anyhow::Result<WindowHandle<V>> {
self.update(|cx| {
let id = cx.windows.insert(None);
let handle = WindowHandle::new(id);
match Window::new(handle.into(), options, cx) {
Ok(mut window) => {
cx.window_update_stack.push(id);
let root_view = build_root_view(&mut window, cx);
cx.window_update_stack.pop();
window.root.replace(root_view.into());
window.defer(cx, |window: &mut Window, cx| window.appearance_changed(cx));
// allow a window to draw at least once before returning
// this didn't cause any issues on non windows platforms as it seems we always won the race to on_request_frame
// on windows we quite frequently lose the race and return a window that has never rendered, which leads to a crash
// where DispatchTree::root_node_id asserts on empty nodes
let clear = window.draw(cx);
clear.clear(cx);
cx.window_handles.insert(id, window.handle);
cx.windows.get_mut(id).unwrap().replace(Box::new(window));
Ok(handle)
}
Err(e) => {
cx.windows.remove(id);
Err(e)
}
}
})
}
/// Brings the app to the front.
///
/// Pass `ignoring_other_apps: true` to activate the app even when another app is in front.
/// Use it sparingly, because it moves the user's focus.
pub fn activate(&self, ignoring_other_apps: bool) {
self.platform.activate(ignoring_other_apps);
}
/// Hides the app, the same as choosing Hide from the app menu.
pub fn hide(&self) {
self.platform.hide();
}
/// Hides all other applications.
pub fn hide_other_apps(&self) {
self.platform.hide_other_apps();
}
/// Shows the applications hidden by [`App::hide_other_apps`].
pub fn unhide_other_apps(&self) {
self.platform.unhide_other_apps();
}
/// Returns the connected displays.
pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
self.platform.displays()
}
/// Returns the primary display, or `None` if the platform reports none.
pub fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
self.platform.primary_display()
}
/// Returns whether [`App::screen_capture_sources`] can return sources on this platform.
pub fn is_screen_capture_supported(&self) -> bool {
self.platform.is_screen_capture_supported()
}
/// Asks the platform for the screens and windows that can be captured.
///
/// The list arrives on the returned channel, so the call doesn't block. The channel
/// yields an error if the platform can't list sources. Check
/// [`App::is_screen_capture_supported`] first.
pub fn screen_capture_sources(
&self,
) -> oneshot::Receiver<Result<Vec<Rc<dyn ScreenCaptureSource>>>> {
self.platform.screen_capture_sources()
}
/// Returns the display with the given [`DisplayId`], or `None` if it is not connected.
pub fn find_display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
self.displays()
.iter()
.find(|display| display.id() == id)
.cloned()
}
/// Returns the system's current [`ThermalState`].
///
/// Check it before heavy work, such as a long animation or a background
/// computation, and reduce the work when the system is hot.
pub fn thermal_state(&self) -> ThermalState {
self.platform.thermal_state()
}
/// Prevents idle sleep while the returned guard is held.
pub fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> {
self.platform.prevent_idle_sleep(reason)
}
/// Calls `callback` when the system's thermal state changes.
///
/// The subscription stays active while you hold it.
pub fn on_thermal_state_change<F>(&self, mut callback: F) -> Subscription
where
F: 'static + FnMut(&mut App),
{
let (subscription, activate) = self.thermal_state_observers.insert(
(),
Box::new(move |cx| {
callback(cx);
true
}),
);
activate();
subscription
}
/// Invokes a handler when the system is about to sleep.
///
/// The platform gives the process only a short time before suspending, so
/// handlers should record state or cancel work rather than start it.
pub fn on_system_sleep<F>(&self, mut callback: F) -> Subscription
where
F: 'static + FnMut(&mut App),
{
let (subscription, activate) = self.system_sleep_observers.insert(
(),
Box::new(move |cx| {
callback(cx);
true
}),
);
activate();
subscription
}
pub(crate) fn displays_changed(&mut self) {
let current = read_displays(self.platform.as_ref());
let events = display_events(&self.displays, ¤t);
self.displays = current;
for event in &events {
let DisplayEvent::Changed { id, .. } = *event else {
continue;
};
for handle in self.windows() {
self.update_window(handle, |_, window, cx| {
if window.display_id == Some(id) {
window.notify_display_observers(cx);
}
})
.log_err();
}
}
for event in events {
self.display_observers
.clone()
.retain(&(), |callback| (callback)(event, self));
}
}
pub(crate) fn knows_display(&self, id: DisplayId) -> bool {
self.displays.contains_key(&id)
}
/// The refresh interval of a connected display, as of the platform's last
/// display change notification.
pub(crate) fn display_refresh_interval(&self, id: DisplayId) -> Option<Duration> {
self.displays.get(&id)?.refresh_interval
}
/// Invokes a handler when a display is connected, disconnected, or its
/// properties change.
pub fn observe_displays<F>(&self, mut callback: F) -> Subscription
where
F: 'static + FnMut(DisplayEvent, &mut App),
{
let (subscription, activate) = self.display_observers.insert(
(),
Box::new(move |event, cx| {
callback(event, cx);
true
}),
);
activate();
subscription
}
/// Calls `callback` when the system wakes from sleep.
///
/// Use it to reconnect to network services or refresh data that went stale
/// while the machine slept. The subscription stays active while you hold it.
pub fn on_system_wake<F>(&self, mut callback: F) -> Subscription
where
F: 'static + FnMut(&mut App),
{
let (subscription, activate) = self.system_wake_observers.insert(
(),
Box::new(move |cx| {
callback(cx);
true
}),
);
activate();
subscription
}
/// Observes mobile application lifecycle changes. Desktop platforms do not
/// emit these events. On iOS these currently describe the single connected
/// scene, not individual windows.
///
/// Save important changes incrementally: neither disconnection nor quit is
/// guaranteed before the system terminates a backgrounded application.
/// Dropping the returned subscription removes the observer.
pub fn on_app_lifecycle(
&self,
mut callback: impl FnMut(AppLifecyclePhase, &mut App) + 'static,
) -> Subscription {
let (subscription, activate) = self.app_lifecycle_observers.insert(
(),
Box::new(move |phase, cx| {
callback(phase, cx);
true
}),
);
activate();
subscription
}
/// Observes mobile memory-pressure warnings so applications can release
/// expendable caches. Dropping the subscription removes the observer.
pub fn on_memory_warning(&self, mut callback: impl FnMut(&mut App) + 'static) -> Subscription {
let (subscription, activate) = self.memory_warning_observers.insert(
(),
Box::new(move |cx| {
callback(cx);
true
}),
);
activate();
subscription
}
/// Returns whether the windows use the light or dark appearance.
///
/// This is the system setting unless [`App::set_window_appearance`] overrides it.
pub fn window_appearance(&self) -> WindowAppearance {
self.platform.window_appearance()
}
/// Overrides the appearance (light/dark) applied to the app's windows, independent of
/// the OS-wide setting. Pass `None` to clear the override and follow the system again.
/// The current value is reported by [`App::window_appearance`].
///
/// On macOS this sets the underlying `NSApplication.appearance`, which controls the
/// native window chrome (the window border and titlebar) of every window. Use this
/// when the app uses a dark theme while the system is in light mode (or vice versa)
/// so the window edges render to match the theme. While an appearance is forced,
/// windows stop tracking system light/dark changes; pass `None` to resume following
/// the system. On other platforms this is a no-op.
pub fn set_window_appearance(&self, appearance: Option<WindowAppearance>) {
self.platform.set_window_appearance(appearance);
}
/// Returns whether [`App::play_haptic_feedback`] does anything on this platform.
pub fn supports_haptic_feedback(&self) -> bool {
self.platform.supports_haptic_feedback()
}
/// Plays a haptic feedback pulse of the given style.
///
/// Call it from the main thread, for example in response to a click or a drop that
/// the user should feel. It does nothing on platforms without haptics. Check
/// [`App::supports_haptic_feedback`] to decide whether to show a haptic option.
/// Styles correspond to
/// [`NSHapticFeedbackPattern`](https://developer.apple.com/documentation/appkit/nshapticfeedbackmanager/feedbackpattern)
/// values on macOS.
pub fn play_haptic_feedback(&self, style: HapticFeedbackStyle) {
self.platform.play_haptic_feedback(style)
}
/// Returns the window button layout (the position of close, minimize and maximize), if the platform reports one.
///
/// Returns `None` when the platform has no custom layout. Use it to draw your own
/// window controls in the same place as the native ones.
pub fn button_layout(&self) -> Option<WindowButtonLayout> {
self.platform.button_layout()
}
/// Reads the current contents of the system clipboard.
///
/// Returns `None` if the clipboard is empty or holds nothing GPUI can read. On
/// the web, use [`App::read_from_clipboard_async`] instead, because this method
/// cannot wait for permission.
pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
self.platform.read_from_clipboard()
}
/// Reads the system clipboard and resolves once the contents are available.
///
/// Prefer this over [`App::read_from_clipboard`] in code that can await. On
/// platforms where clipboard access is asynchronous and permission-gated (such as
/// the web), the synchronous read always returns `None` while this method performs
/// a real read. The task resolves to an error if the read fails.
pub fn read_from_clipboard_async(
&self,
) -> Task<Result<Option<ClipboardItem>, ClipboardReadError>> {
self.platform.read_from_clipboard_async()
}
/// Sets how text is rasterized for every window in the app.
///
/// The default is [`TextRenderingMode::PlatformDefault`]. The new mode applies to
/// text drawn after this call.
pub fn set_text_rendering_mode(&mut self, mode: TextRenderingMode) {
self.text_rendering_mode.set(mode);
}
/// Returns how text is currently rasterized. See [`App::set_text_rendering_mode`].
pub fn text_rendering_mode(&self) -> TextRenderingMode {
self.text_rendering_mode.get()
}
/// Replaces the contents of the system clipboard with `item`.
///
/// # Examples
///
/// ```
/// # use gpui::{AppContext, ClipboardItem, TestApp};
/// # let mut app = TestApp::new();
/// app.update(|cx| cx.write_to_clipboard(ClipboardItem::new_string("copied".into())));
/// app.read(|cx| {
/// let item = cx.read_from_clipboard().unwrap();
/// assert_eq!(item.text().as_deref(), Some("copied"));
/// });
/// ```
pub fn write_to_clipboard(&self, item: ClipboardItem) {
self.platform.write_to_clipboard(item)
}
/// Reads data from the primary selection buffer.
/// Only available on Linux and FreeBSD.
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
pub fn read_from_primary(&self) -> Option<ClipboardItem> {
self.platform.read_from_primary()
}
/// Writes data to the primary selection buffer.
/// Only available on Linux and FreeBSD.
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
pub fn write_to_primary(&self, item: ClipboardItem) {
self.platform.write_to_primary(item)
}
/// Reads data from macOS's "Find" pasteboard.
///
/// Used to share the current search string between apps.
///
/// <https://developer.apple.com/documentation/appkit/nspasteboard/name-swift.struct/find>
#[cfg(target_os = "macos")]
pub fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
self.platform.read_from_find_pasteboard()
}
/// Writes data to macOS's "Find" pasteboard.
///
/// Used to share the current search string between apps.
///
/// <https://developer.apple.com/documentation/appkit/nspasteboard/name-swift.struct/find>
#[cfg(target_os = "macos")]
pub fn write_to_find_pasteboard(&self, item: ClipboardItem) {
self.platform.write_to_find_pasteboard(item)
}
/// Stores a username and password for `url` in the platform keychain.
///
/// The task resolves once the store finishes, or to an error if it fails. Await it
/// from a task spawned with [`App::spawn`].
pub fn write_credentials(
&self,
url: &str,
username: &str,
password: &[u8],
) -> Task<Result<()>> {
self.platform.write_credentials(url, username, password)
}
/// Reads the username and password stored for `url`.
///
/// The task resolves to `None` when nothing is stored for `url`. Use the same `url`
/// that you passed to [`App::write_credentials`].
pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
self.platform.read_credentials(url)
}
/// Removes the credentials stored for `url` from the platform keychain.
pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
self.platform.delete_credentials(url)
}
/// Opens `url` in the platform's default browser or handler.
///
/// The call returns immediately. In tests, `TestApp::opened_url` reports the last
/// URL passed here.
pub fn open_url(&self, url: &str) {
self.platform.open_url(url);
}
/// Registers `scheme` (for example `zed` for `zed://` links) so that links with it open this app.
///
/// Use [`Application::on_open_urls`] to receive the links. On some platforms you
/// declare schemes when you package the app. This method registers them at runtime.
pub fn register_url_scheme(&self, scheme: &str) -> Task<Result<()>> {
self.platform.register_url_scheme(scheme)
}
/// Sets the app's identifier and user-visible name for the operating system.
///
/// The identifier is used for platform identity mechanisms such as the Windows
/// AppUserModelID. The name is shown wherever the operating system presents the app.
pub fn set_app_identity(&self, identifier: &str, name: &str) {
self.platform.set_app_identity(identifier, name);
}
/// Posts a notification to the operating system's notification center.
///
/// Posting a notification whose [`SystemNotification::tag`] matches an
/// earlier one replaces that notification where the platform supports it.
/// No-op on platforms without notification support, or when delivery is
/// unavailable (e.g. authorization was denied).
pub fn show_system_notification(&self, notification: SystemNotification) {
self.platform.show_system_notification(notification);
}
/// Removes the delivered or pending notification with this tag.
///
/// Best-effort: some platforms cannot retract a notification once shown,
/// in which case it ages out of the notification center on its own.
pub fn dismiss_system_notification(&self, tag: &str) {
self.platform.dismiss_system_notification(tag);
}
/// Registers the handler invoked when the user activates a system
/// notification, either by clicking its body or one of its action
/// buttons. Subsequent registrations replace the handler.
pub fn on_system_notification_response<F>(&self, mut callback: F)
where
F: 'static + FnMut(SystemNotificationResponse, &mut App),
{
let this = self.this.clone();
self.platform
.on_system_notification_response(Box::new(move |response| {
if let Some(app) = this.upgrade() {
callback(response, &mut app.borrow_mut());
}
}));
}
/// Returns the full pathname of the current app bundle.
///
/// Returns an error if the app is not being run from a bundle.
pub fn app_path(&self) -> Result<PathBuf> {
self.platform.app_path()
}
/// On Linux, returns the name of the compositor in use. On the web, returns `"Web"`.
///
/// Returns an empty string on other platforms.
pub fn compositor_name(&self) -> &'static str {
self.platform.compositor_name()
}
/// Returns the path to a helper executable named `name` that ships with the app.
///
/// See [`Application::path_for_auxiliary_executable`].
pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
self.platform.path_for_auxiliary_executable(name)
}
/// Shows the platform's file or folder picker and returns the user's choice.
///
/// The result arrives on the returned channel once the user picks paths or cancels.
/// Cancelling yields `Ok(None)`. The picker is shown without blocking the caller.
/// On Linux the channel yields an error if the picker can't be opened.
pub fn prompt_for_paths(
&self,
options: PathPromptOptions,
) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
self.platform.prompt_for_paths(options)
}
/// Shows the platform's save dialog and returns the path the user chose.
///
/// `directory` is the folder the dialog opens in, and `suggested_name` pre-fills the
/// file name. The result arrives on the returned channel. Cancelling yields
/// `Ok(None)`. On Linux the channel yields an error if the dialog can't be opened.
pub fn prompt_for_new_path(
&self,
directory: &Path,
suggested_name: Option<&str>,
) -> oneshot::Receiver<Result<Option<PathBuf>>> {
self.platform.prompt_for_new_path(directory, suggested_name)
}
/// Shows `path` in the platform's file manager, such as Finder on macOS.
pub fn reveal_path(&self, path: &Path) {
self.platform.reveal_path(path)
}
/// Opens `path` with the system's default application for its file type.
pub fn open_with_system(&self, path: &Path) {
self.platform.open_with_system(path)
}
/// Returns whether the user has configured scrollbars to auto-hide at the platform level.
pub fn should_auto_hide_scrollbars(&self) -> bool {
self.platform.should_auto_hide_scrollbars()
}
/// Restarts the app. Runs the handlers from [`App::on_app_restart`], then asks the
/// platform to relaunch it.
///
/// The relaunch uses the path from [`App::set_restart_path`] and the arguments from
/// [`Application::with_restart_arguments`].
pub fn restart(&mut self) {
self.restart_observers
.clone()
.retain(&(), |observer| observer(self));
self.platform.restart(
self.restart_path.take(),
std::mem::take(&mut self.restart_arguments),
)
}
/// Sets the executable path that [`App::restart`] launches. The path is used once, by the next restart.
pub fn set_restart_path(&mut self, path: PathBuf) {
self.restart_path = Some(path);
}
/// Returns the app's HTTP client. See [`Application::with_http_client`].
pub fn http_client(&self) -> Arc<dyn HttpClient> {
self.http_client.clone()
}
/// Replaces the HTTP client that [`App::http_client`] returns.
pub fn set_http_client(&mut self, new_client: Arc<dyn HttpClient>) {
self.http_client = new_client;
}
/// Sets when the app quits on its own. See [`QuitMode`].
///
/// Defaults to [`QuitMode::Default`].
pub fn set_quit_mode(&mut self, mode: QuitMode) {
self.quit_mode = mode;
}
/// Sets whether the application participates in the system's foreground UI.
///
/// Only has an effect on macOS, where [`Self::request_windowing`] normally sets it. Use this
/// for an accessory app that shows windows, such as a menu bar utility. It overrides the
/// policy until the next [`Self::request_windowing`], and the app counts as headless while
/// `Accessory`. After switching to [`ActivationPolicy::Regular`], activate the app yourself
/// with [`Self::activate`]; otherwise its menu bar may not appear until the app is
/// reactivated.
pub fn set_activation_policy(&mut self, policy: ActivationPolicy) {
self.platform.set_activation_policy(policy);
}
/// Returns the SVG renderer that draws the app's SVG assets.
pub fn svg_renderer(&self) -> SvgRenderer {
self.svg_renderer.clone()
}
pub(crate) fn push_effect(&mut self, effect: Effect) {
match &effect {
Effect::Notify { emitter } => {
if !self.pending_notifications.insert(*emitter) {
return;
}
}
Effect::NotifyGlobalObservers { global_type } => {
if !self.pending_global_notifications.insert(*global_type) {
return;
}
}
_ => {}
};
self.pending_effects.push_back(effect);
}
/// Called at the end of [`App::update`] to complete any side effects
/// such as notifying observers, emitting events, etc. Effects can themselves
/// cause effects, so we continue looping until all effects are processed.
fn flush_effects(&mut self) {
loop {
self.release_dropped_entities();
self.release_dropped_focus_handles();
if let Some(effect) = self.pending_effects.pop_front() {
match effect {
Effect::Notify { emitter } => {
self.apply_notify_effect(emitter);
}
Effect::Emit {
emitter,
event_type,
event,
} => self.apply_emit_effect(emitter, event_type, &*event),
Effect::RefreshWindows => {
self.apply_refresh_effect();
}
Effect::NotifyGlobalObservers { global_type } => {
self.apply_notify_global_observers_effect(global_type);
}
Effect::Defer { callback } => {
self.apply_defer_effect(callback);
}
Effect::EntityCreated {
entity,
tid,
window,
} => {
self.apply_entity_created_effect(entity, tid, window);
}
}
} else {
#[cfg(any(test, feature = "test-support"))]
if matches!(self.mode, GpuiMode::Test { .. }) {
for window in self
.windows
.values()
.filter_map(|window| {
let window = window.as_deref()?;
window.invalidator.is_dirty().then_some(window.handle)
})
.collect::<Vec<_>>()
{
self.update_window(window, |_, window, cx| window.draw(cx).clear(cx))
.unwrap();
}
}
if self.pending_effects.is_empty() {
for window in self.windows.values().filter_map(|window| window.as_deref()) {
if window.invalidator.is_dirty()
|| window.needs_present.get()
|| !window.next_frame_callbacks.borrow().is_empty()
{
window.platform_window.schedule_frame();
}
}
self.event_arena.clear();
break;
}
}
}
}
/// Repeatedly called during `flush_effects` to release any entities whose
/// reference count has become zero. We invoke any release observers before dropping
/// each entity.
fn release_dropped_entities(&mut self) {
loop {
let dropped = self.entities.take_dropped();
if dropped.is_empty() {
break;
}
for (entity_id, mut entity) in dropped {
self.observers.remove(&entity_id);
self.event_listeners.remove(&entity_id);
self.window_invalidators_by_entity.remove(&entity_id);
self.current_window_by_entity.remove(&entity_id);
for release_callback in self.release_listeners.remove(&entity_id) {
release_callback(entity.as_mut(), self);
}
}
}
}
/// Repeatedly called during `flush_effects` to handle a focused handle being dropped.
fn release_dropped_focus_handles(&mut self) {
let focus_handles = self.focus_handles.clone();
let mut focus_handles = focus_handles.write();
let FocusMap {
handles,
dropped_handles,
} = &mut *focus_handles;
if dropped_handles.is_empty() {
return;
}
let windows = self
.windows
.values()
.filter_map(|window| {
let window = window.as_ref()?;
dropped_handles
.contains(&window.focus?)
.then_some(window.handle)
})
.collect::<SmallVec<[_; 1]>>();
for handle_id in dropped_handles.drain(..) {
handles.remove(handle_id);
}
drop(focus_handles);
for window_handle in windows {
window_handle
.update(self, |_, window, cx| window.blur(cx))
.ok();
}
}
fn apply_notify_effect(&mut self, emitter: EntityId) {
self.pending_notifications.remove(&emitter);
self.observers
.clone()
.retain(&emitter, |handler| handler(self));
}
fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: &dyn Any) {
self.event_listeners
.clone()
.retain(&emitter, |(stored_type, handler)| {
if *stored_type == event_type {
handler(event, self)
} else {
true
}
});
}
fn apply_refresh_effect(&mut self) {
for window in self.windows.values_mut() {
if let Some(window) = window.as_deref_mut() {
window.refreshing = true;
window.invalidator.set_dirty(true);
}
}
}
fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
self.pending_global_notifications.remove(&type_id);
self.global_observers
.clone()
.retain(&type_id, |observer| observer(self));
}
fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
callback(self);
}
fn apply_entity_created_effect(
&mut self,
entity: AnyEntity,
tid: TypeId,
window: Option<WindowId>,
) {
// Seed the entity's current window from its creation context so
// `with_window` resolves correctly before the entity has ever been
// rendered.
if let Some(id) = window {
self.current_window_by_entity.insert(entity.entity_id(), id);
}
self.new_entity_observers.clone().retain(&tid, |observer| {
if let Some(id) = window {
self.update_window_id(id, {
let entity = entity.clone();
|_, window, cx| (observer)(entity, &mut Some(window), cx)
})
.expect("All windows should be off the stack when flushing effects");
} else {
(observer)(entity.clone(), &mut None, self)
}
true
});
}
/// Runs `f` with the window that most recently drew the entity `entity_id`.
///
/// If the entity has not been drawn yet, the window it was created in is used. The
/// callback receives the [`Window`] and the [`App`]. Returns `None` if the entity has
/// no current window, if that window has closed, or if the window is already being
/// updated higher up the call stack.
#[inline(always)]
pub fn with_window<R>(
&mut self,
entity_id: EntityId,
f: impl FnOnce(&mut Window, &mut App) -> R,
) -> Option<R> {
let window_id = *self.current_window_by_entity.get(&entity_id)?;
self.update_window_id(window_id, |_, window, cx| f(window, cx))
.ok()
}
fn ensure_window(&mut self, entity_id: EntityId, window: WindowId) {
self.current_window_by_entity
.entry(entity_id)
.or_insert(window);
}
#[inline(always)]
pub(crate) fn update_window_id<T, F>(&mut self, id: WindowId, update: F) -> Result<T>
where
F: FnOnce(AnyView, &mut Window, &mut App) -> T,
{
let mut update = Some(update);
let mut result = None;
self.update_window_erased(id, &mut |arguments| {
if let Some((root_view, window, cx)) = arguments {
result = Some(update.take().unwrap()(root_view, window, cx));
} else {
drop(update.take());
drop(result.take());
}
});
result.context("window not found")
}
/// Returns an [`AsyncApp`] that can be held across `await` points.
///
/// The [`AsyncApp`] holds the app weakly, so it does not keep the app alive. Use
/// it in tasks that outlive the current update.
pub fn to_async(&self) -> AsyncApp {
AsyncApp {
app: self.this.clone(),
background_executor: self.background_executor.clone(),
foreground_executor: self.foreground_executor.clone(),
}
}
/// Returns the [`BackgroundExecutor`] for `Send` futures.
///
/// Native backends use worker threads; single-threaded web builds use the main thread.
pub fn background_executor(&self) -> &BackgroundExecutor {
&self.background_executor
}
/// Whether this app runs on the deterministic test scheduler. See
/// [`BackgroundExecutor::is_test`].
pub fn is_test(&self) -> bool {
self.background_executor.is_test()
}
/// Returns the [`ForegroundExecutor`], which runs futures on the main thread.
///
/// # Panics
///
/// Panics if called after the quit handlers have started running (from
/// [`App::on_app_quit`]).
pub fn foreground_executor(&self) -> &ForegroundExecutor {
if self.quitting {
panic!("Can't spawn on main thread after on_app_quit")
};
&self.foreground_executor
}
/// Returns the foreground work journal for this app's foreground thread.
/// Apps constructed on the same thread share the stream.
#[cfg(feature = "profiler")]
pub fn foreground_journal(&self) -> crate::profiler::journal::ForegroundJournal {
self.foreground_journal.clone()
}
/// Starts detecting foreground hangs on a dedicated thread.
///
/// Nothing is spawned unless the app calls this. The thread polls a
/// detector over this app's foreground journal every `config.interval`
/// and passes each poll's incidents, including empty polls, to `on_poll`
/// on that thread. When the app quits, a final poll with
/// [`HangMonitorPollReason::Flush`] runs during shutdown, concurrently
/// with quit handlers and within [`SHUTDOWN_TIMEOUT`], so `on_poll` can
/// deliver batched results.
///
/// # Errors
///
/// Fails if the monitor was already started or its thread can't be
/// spawned.
///
/// [`HangMonitorPollReason::Flush`]: crate::profiler::hang::HangMonitorPollReason::Flush
#[cfg(all(feature = "profiler", not(target_family = "wasm")))]
pub fn start_hang_monitor(
&mut self,
config: crate::profiler::hang::HangMonitorConfig,
on_poll: impl FnMut(crate::profiler::hang::HangMonitorPoll) + Send + 'static,
) -> Result<(), crate::profiler::hang::HangMonitorError> {
use crate::profiler::hang::{HangDetector, HangMonitor, HangMonitorError};
if self.hang_monitor.is_some() {
debug_assert!(false, "the hang monitor was started twice");
return Err(HangMonitorError::AlreadyStarted);
}
let detector = HangDetector::new(
self.foreground_journal(),
config.threshold,
config.frame_budget,
);
let monitor = HangMonitor::spawn(detector, config.interval, on_poll)
.map_err(HangMonitorError::Spawn)?;
self.hang_monitor = Some(monitor);
Ok(())
}
/// Runs an async block on the main thread, with an [`AsyncApp`] for access to app state.
///
/// The closure receives `&mut AsyncApp`. Use it to update entities and windows after
/// an `await`. The future doesn't need to be `Send`, because it stays on the main
/// thread. Dropping the returned [`Task`] cancels it, so store it or call
/// [`Task::detach`] to let it run to completion in the background.
///
/// Use [`App::background_executor`] for CPU-heavy or blocking work, and send the
/// result back to the main thread with a `spawn` task.
///
/// # Panics
///
/// In debug builds this panics if called after the quit handlers have started
/// running. Release builds log a debug message and continue.
///
/// # Examples
///
/// ```
/// # use gpui::{AppContext, TestApp};
/// # use std::{cell::Cell, rc::Rc};
/// # let mut app = TestApp::new();
/// let ran = Rc::new(Cell::new(false));
/// app.update(|cx| {
/// let ran = ran.clone();
/// cx.spawn(async move |_cx| ran.set(true)).detach();
/// });
/// app.read(|_| assert!(ran.get()));
/// ```
///
/// See [async work](crate::_documentation::guides::async_work) for the executors and
/// how to share state across tasks.
#[track_caller]
#[inline(always)]
pub fn spawn<AsyncFn, R>(&self, f: AsyncFn) -> Task<R>
where
AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
R: 'static,
{
let mut cx = self.prepare_spawn();
self.foreground_executor
.spawn(async move { f(&mut cx).await }.boxed_local())
}
/// Like [`App::spawn`], but schedules the task with the given [`Priority`].
pub fn spawn_with_priority<AsyncFn, R>(&self, priority: Priority, f: AsyncFn) -> Task<R>
where
AsyncFn: AsyncFnOnce(&mut AsyncApp) -> R + 'static,
R: 'static,
{
if self.quitting {
debug_panic!("Can't spawn on main thread after on_app_quit")
};
let mut cx = self.to_async();
self.foreground_executor
.spawn_with_priority(priority, async move { f(&mut cx).await }.boxed_local())
}
/// Runs `f` after the current effect cycle finishes, with the [`App`].
///
/// Use it to act on state that is borrowed right now. For example, you can change
/// an entity from inside its own `update`, which would otherwise be a double borrow.
/// The callback runs once the outermost update returns.
///
/// ```
/// # use gpui::{AppContext, TestApp};
/// let mut app = TestApp::new();
/// let count = app.update(|cx| cx.new(|_| 0));
/// app.update(|cx| {
/// let count = count.clone();
/// cx.defer(move |cx| {
/// count.update(cx, |count, _| *count += 1);
/// });
/// });
/// app.read(|cx| assert_eq!(*count.read(cx), 1));
/// ```
pub fn defer(&mut self, f: impl FnOnce(&mut App) + 'static) {
self.push_effect(Effect::Defer {
callback: Box::new(f),
});
}
/// Returns the asset registry that the app loads assets from. See [`Application::with_assets`].
pub fn assets(&self) -> &Arc<AssetRegistry> {
&self.asset_registry
}
/// Returns the app's [`TextSystem`], which shapes and rasterizes text.
pub fn text_system(&self) -> &Arc<TextSystem> {
&self.text_system
}
/// Returns whether a global of type `G` has been set.
pub fn has_global<G: Global>(&self) -> bool {
self.note_global_read(TypeId::of::<G>());
self.globals_by_type.contains_key(&TypeId::of::<G>())
}
/// Returns the global of type `G`.
///
/// # Panics
///
/// Panics if no global of type `G` has been set. Use [`App::try_global`] when the
/// global may be missing.
#[track_caller]
pub fn global<G: Global>(&self) -> &G {
self.note_global_read(TypeId::of::<G>());
self.globals_by_type
.get(&TypeId::of::<G>())
.map(|any_state| any_state.downcast_ref::<G>().unwrap())
.unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
}
/// Returns the global of type `G`, or `None` if it has not been set.
pub fn try_global<G: Global>(&self) -> Option<&G> {
self.note_global_read(TypeId::of::<G>());
self.globals_by_type
.get(&TypeId::of::<G>())
.map(|any_state| any_state.downcast_ref::<G>().unwrap())
}
/// Returns the global of type `G` for mutation, and notifies global observers.
///
/// Observers registered with [`App::observe_global`] run when the current update
/// finishes. The notification happens on every call, even if you don't change the
/// value.
///
/// # Panics
///
/// Panics if no global of type `G` has been set. Use [`App::default_global`] to
/// create one on first use.
#[track_caller]
pub fn global_mut<G: Global>(&mut self) -> &mut G {
let global_type = TypeId::of::<G>();
self.global_changed(global_type);
self.globals_by_type
.get_mut(&global_type)
.and_then(|any_state| any_state.downcast_mut::<G>())
.unwrap_or_else(|| panic!("no state of type {} exists", type_name::<G>()))
}
/// Returns the global of type `G` for mutation, first setting `G::default()` if it is missing.
///
/// Like [`App::global_mut`], this notifies global observers.
pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
let global_type = TypeId::of::<G>();
self.global_changed(global_type);
self.globals_by_type
.entry(global_type)
.or_insert_with(|| Box::<G>::default())
.downcast_mut::<G>()
.unwrap()
}
/// Sets the global of type `G` to `global`, replacing any previous value.
///
/// Notifies global observers when the current update finishes.
///
/// # Examples
///
/// ```
/// # use gpui::{AppContext, Global, TestApp};
/// struct Theme {
/// name: &'static str,
/// }
/// impl Global for Theme {}
///
/// # let mut app = TestApp::new();
/// app.update(|cx| cx.set_global(Theme { name: "dark" }));
/// app.read(|cx| assert_eq!(cx.global::<Theme>().name, "dark"));
/// ```
pub fn set_global<G: Global>(&mut self, global: G) {
let global_type = TypeId::of::<G>();
self.global_changed(global_type);
self.globals_by_type.insert(global_type, Box::new(global));
}
/// Clear all stored globals. Does not notify global observers.
#[cfg(any(test, feature = "test-support"))]
pub fn clear_globals(&mut self) {
self.globals_by_type.drain();
}
/// Removes the global of type `G` and returns it.
///
/// Notifies global observers when the current update finishes.
///
/// # Panics
///
/// Panics if no global of type `G` has been set.
pub fn remove_global<G: Global>(&mut self) -> G {
let global_type = TypeId::of::<G>();
self.global_changed(global_type);
*self
.globals_by_type
.remove(&global_type)
.unwrap_or_else(|| panic!("no global added for {}", type_name::<G>()))
.downcast()
.unwrap()
}
/// Calls `f` each time the global of type `G` is set, changed or removed.
///
/// The observer is active once the current update finishes. Keep the returned
/// [`Subscription`] alive, because dropping it stops the observer.
///
/// # Examples
///
/// ```
/// # use gpui::{AppContext, Global, TestApp};
/// # use std::{cell::Cell, rc::Rc};
/// struct Count(usize);
/// impl Global for Count {}
///
/// # let mut app = TestApp::new();
/// let calls = Rc::new(Cell::new(0));
/// let _subscription = app.update(|cx| {
/// cx.set_global(Count(0));
/// cx.observe_global::<Count>({
/// let calls = calls.clone();
/// move |_| calls.set(calls.get() + 1)
/// })
/// });
/// app.update(|cx| cx.global_mut::<Count>().0 += 1);
/// assert_eq!(calls.get(), 1);
/// ```
pub fn observe_global<G: Global>(
&mut self,
mut f: impl FnMut(&mut Self) + 'static,
) -> Subscription {
let (subscription, activate) = self.global_observers.insert(
TypeId::of::<G>(),
Box::new(move |cx| {
f(cx);
true
}),
);
self.defer(move |_| activate());
subscription
}
/// Move the global of the given type to the stack.
#[track_caller]
pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
GlobalLease::new(
self.globals_by_type
.remove(&TypeId::of::<G>())
.with_context(|| format!("no global registered of type {}", type_name::<G>()))
.unwrap(),
)
}
/// Restore the global of the given type after it is moved to the stack.
pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
let global_type = TypeId::of::<G>();
self.global_changed(global_type);
self.globals_by_type.insert(global_type, lease.global);
}
pub(crate) fn new_entity_observer(
&self,
key: TypeId,
value: NewEntityListener,
) -> Subscription {
let (subscription, activate) = self.new_entity_observers.insert(key, value);
activate();
subscription
}
/// Calls `on_new` each time an entity of type `T` is created.
///
/// The callback receives the new state, the [`Window`] if the entity was created with
/// one, and a [`Context`] for it. Use it to set up behavior for every instance of a
/// type, such as registering an observer. Keep the returned [`Subscription`] alive
/// for the callback to keep running.
pub fn observe_new<T: 'static>(
&self,
on_new: impl 'static + Fn(&mut T, Option<&mut Window>, &mut Context<T>),
) -> Subscription {
self.new_entity_observer(
TypeId::of::<T>(),
Box::new(
move |any_entity: AnyEntity, window: &mut Option<&mut Window>, cx: &mut App| {
any_entity
.downcast::<T>()
.unwrap()
.update(cx, |entity_state, cx| {
on_new(entity_state, window.as_deref_mut(), cx)
})
},
),
)
}
/// Calls `on_release` when the entity behind `handle` is released.
///
/// The callback runs after the entity's last strong handle is dropped, and before the
/// entity's state is dropped. It receives the state as `&mut T`. Keep the returned
/// [`Subscription`] alive for the callback to run.
pub fn observe_release<T>(
&self,
handle: &Entity<T>,
on_release: impl FnOnce(&mut T, &mut App) + 'static,
) -> Subscription
where
T: 'static,
{
let (subscription, activate) = self.release_listeners.insert(
handle.entity_id(),
Box::new(move |entity, cx| {
let entity = entity.downcast_mut().expect("invalid entity type");
on_release(entity, cx)
}),
);
activate();
subscription
}
/// Calls `on_release` when the entity behind `handle` is released, inside `window`.
///
/// Like [`App::observe_release`], but the callback also receives `window`. The
/// callback doesn't run if `window` has already closed when the entity is released.
pub fn observe_release_in<T>(
&self,
handle: &Entity<T>,
window: &Window,
on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
) -> Subscription
where
T: 'static,
{
let window_handle = window.handle;
self.observe_release(handle, move |entity, cx| {
let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
})
}
/// Calls `f` for every keystroke that reaches any window of the app.
///
/// The callback runs after action and event handling has finished, and the event
/// names the action that handled the keystroke, if any. Keystrokes consumed by an
/// interceptor or a raw keyboard event handler are not observed, and a modifier
/// pressed on its own is observed when it is released. Use
/// [`App::intercept_keystrokes`] to see keystrokes before they are dispatched. Keep
/// the returned [`Subscription`] alive.
pub fn observe_keystrokes(
&mut self,
mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
) -> Subscription {
fn inner(
keystroke_observers: &SubscriberSet<(), KeystrokeObserver>,
handler: KeystrokeObserver,
) -> Subscription {
let (subscription, activate) = keystroke_observers.insert((), handler);
activate();
subscription
}
inner(
&self.keystroke_observers,
Box::new(move |event, window, cx| {
f(event, window, cx);
true
}),
)
}
/// Calls `f` for every key-down that reaches any window, before it is dispatched.
///
/// Unlike [`App::observe_keystrokes`], which runs after handling, the interceptor runs
/// first. Calling [`App::stop_propagation`] inside it stops the keystroke from reaching
/// action dispatch. Keep the returned [`Subscription`] alive.
pub fn intercept_keystrokes(
&mut self,
mut f: impl FnMut(&KeystrokeEvent, &mut Window, &mut App) + 'static,
) -> Subscription {
fn inner(
keystroke_interceptors: &SubscriberSet<(), KeystrokeObserver>,
handler: KeystrokeObserver,
) -> Subscription {
let (subscription, activate) = keystroke_interceptors.insert((), handler);
activate();
subscription
}
inner(
&self.keystroke_interceptors,
Box::new(move |event, window, cx| {
f(event, window, cx);
true
}),
)
}
/// Adds key bindings to the app's keymap and redraws the windows.
///
/// A binding maps a keystroke, optionally limited to a [`KeyContext`], to an action.
/// Bindings are matched during key dispatch. Calling this again adds to the existing
/// bindings, and [`App::clear_key_bindings`] removes them all.
///
/// # Examples
///
/// ```standalone_crate
/// use gpui::{AppContext, KeyBinding, Keystroke, TestApp, actions};
///
/// actions!(app_bind_keys, [Save]);
///
/// let mut app = TestApp::new();
/// app.update(|cx| cx.bind_keys([KeyBinding::new("ctrl-s", Save, None)]));
/// app.read(|cx| {
/// let bindings = cx.all_bindings_for_input(&[Keystroke::parse("ctrl-s").unwrap()]);
/// assert_eq!(bindings.len(), 1);
/// assert_eq!(bindings[0].action().name(), "app_bind_keys::Save");
/// });
/// ```
///
/// See [keyboard](crate::_documentation::guides::keyboard) for context rules and
/// [input dispatch](crate::_documentation::concepts::input_dispatch) for how a keystroke
/// picks an action.
pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
self.keymap.borrow_mut().add_bindings(bindings);
self.pending_effects.push_back(Effect::RefreshWindows);
}
/// Removes every key binding from the app's keymap.
pub fn clear_key_bindings(&mut self) {
self.keymap.borrow_mut().clear();
self.pending_effects.push_back(Effect::RefreshWindows);
}
/// Returns the app's keymap, shared with the app.
///
/// Borrow it to inspect bindings. Don't hold the borrow across a call that changes
/// bindings, such as [`App::bind_keys`], because the borrow panics.
pub fn key_bindings(&self) -> Rc<RefCell<Keymap>> {
self.keymap.clone()
}
/// Registers a handler that runs when an action is dispatched. Global handlers run in
/// the bubble phase, after the handlers in the element tree, and only if no earlier
/// handler stopped the propagation. Use it for app-wide
/// commands such as Quit, which should work with no window focused. Dispatch an action
/// with [`App::dispatch_action`].
///
/// # Examples
///
/// ```standalone_crate
/// use gpui::{AppContext, TestApp, actions};
/// use std::{cell::Cell, rc::Rc};
///
/// actions!(app_on_action, [Ping]);
///
/// let mut app = TestApp::new();
/// let pings = Rc::new(Cell::new(0));
/// app.update(|cx| {
/// let pings = pings.clone();
/// cx.on_action(move |_: &Ping, _| pings.set(pings.get() + 1));
/// });
/// app.update(|cx| cx.dispatch_action(&Ping));
/// assert_eq!(pings.get(), 1);
/// ```
pub fn on_action<A: Action>(
&mut self,
listener: impl Fn(&A, &mut Self) + 'static,
) -> &mut Self {
self.global_action_listeners
.entry(TypeId::of::<A>())
.or_default()
.push(Rc::new(move |action, phase, cx| {
if phase == DispatchPhase::Bubble {
let action = action.downcast_ref().unwrap();
listener(action, cx)
}
}));
self
}
/// Stops the current event or action from reaching later handlers.
///
/// Handlers for mouse events further down the z-order, and keyboard handlers higher
/// in the tree, don't run after this. Call [`App::propagate`] to undo it before the
/// effects are flushed.
pub fn stop_propagation(&mut self) {
self.propagate_event = false;
}
/// Lets the current event or action continue to later handlers.
///
/// Use it in a handler to pass the event on to the next handler, for example an
/// action listener on a parent element or a global handler from [`App::on_action`].
/// It cancels an earlier [`App::stop_propagation`] in the same dispatch.
pub fn propagate(&mut self) {
self.propagate_event = true;
}
/// Builds an action by its registered name, from JSON data such as a keymap entry.
///
/// `data` is the action's parameters, or `None` for an action with no parameters.
/// Returns an [`ActionBuildError`] if the name is unknown or the data doesn't match
/// the action's type. Use it to load actions from a keymap file.
pub fn build_action(
&self,
name: &str,
data: Option<serde_json::Value>,
) -> std::result::Result<Box<dyn Action>, ActionBuildError> {
self.actions.build_action(name, data)
}
/// Returns the names of every action type that has been registered.
///
/// Registration makes an action buildable by name with [`App::build_action`]. It
/// does not bind the action to a key or a handler. For that, use [`App::bind_keys`]
/// and [`App::on_action`].
pub fn all_action_names(&self) -> &[&'static str] {
self.actions.all_action_names()
}
/// Returns the bindings that match `input`, ignoring key context.
///
/// The bindings come back in the order they were added. When you show one to the user,
/// use the last one, because it takes precedence.
pub fn all_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
RefCell::borrow(&self.keymap).all_bindings_for_input(input)
}
/// Returns each registered action name with its JSON schema, if it has one.
///
/// Use it to generate editor completions or to validate keymap files.
pub fn action_schemas(
&self,
generator: &mut schemars::SchemaGenerator,
) -> Vec<(&'static str, Option<schemars::Schema>)> {
self.actions.action_schemas(generator)
}
/// Returns the JSON schema for the action named `name`.
///
/// Returns `None` if no action has that name. Returns `Some(None)` if the action
/// exists but has no schema, and `Some(Some(schema))` if it has one.
pub fn action_schema_by_name(
&self,
name: &str,
generator: &mut schemars::SchemaGenerator,
) -> Option<Option<schemars::Schema>> {
self.actions.action_schema_by_name(name, generator)
}
/// Returns a map from each deprecated action name to the name that replaces it.
pub fn deprecated_actions_to_preferred_actions(&self) -> &HashMap<&'static str, &'static str> {
self.actions.deprecated_aliases()
}
/// Returns a map from each deprecated action name to its deprecation message.
pub fn action_deprecation_messages(&self) -> &HashMap<&'static str, &'static str> {
self.actions.deprecation_messages()
}
/// Returns a map from each action name to its documentation string.
pub fn action_documentation(&self) -> &HashMap<&'static str, &'static str> {
self.actions.documentation()
}
/// Calls `on_quit` when the app is about to quit, and waits for the returned future.
///
/// Use it to flush data to disk or close connections. The quit can't be cancelled
/// at this point. Native apps wait up to [`SHUTDOWN_TIMEOUT`] for the futures, so
/// keep the work short. Keep the returned [`Subscription`] alive for the callback to
/// run.
pub fn on_app_quit<Fut>(
&self,
mut on_quit: impl FnMut(&mut App) -> Fut + 'static,
) -> Subscription
where
Fut: 'static + Future<Output = ()>,
{
let (subscription, activate) = self.quit_observers.insert(
(),
Box::new(move |cx| {
let future = on_quit(cx);
future.boxed_local()
}),
);
activate();
subscription
}
/// Calls `on_restart` when the app is about to restart, before any [`App::on_app_quit`] handlers run.
///
/// Keep the returned [`Subscription`] alive for the callback to run.
pub fn on_app_restart(&self, mut on_restart: impl 'static + FnMut(&mut App)) -> Subscription {
let (subscription, activate) = self.restart_observers.insert(
(),
Box::new(move |cx| {
on_restart(cx);
true
}),
);
activate();
subscription
}
/// Calls `on_closed` with the [`WindowId`] each time a window closes.
///
/// The window is no longer accessible when the callback runs. Keep the returned
/// [`Subscription`] alive for the callback to run.
pub fn on_window_closed(
&self,
mut on_closed: impl FnMut(&mut App, WindowId) + 'static,
) -> Subscription {
let (subscription, activate) = self.window_closed_observers.insert((), Box::new(on_closed));
activate();
subscription
}
pub(crate) fn clear_pending_keystrokes(&mut self) {
for window in self.windows() {
window
.update(self, |_, window, cx| {
window.clear_pending_keystrokes(cx);
})
.ok();
}
}
/// Returns whether `action` would be handled if it were dispatched now.
///
/// Checks the active window's focus path and its bindings, then the global listeners
/// from [`App::on_action`]. Use it to enable or disable menu items.
pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
let mut action_available = false;
if let Some(window) = self.active_window()
&& let Ok(window_action_available) =
window.update(self, |_, window, cx| window.is_action_available(action, cx))
{
action_available = window_action_available;
}
action_available
|| self
.global_action_listeners
.contains_key(&action.as_any().type_id())
}
/// Replaces the app's menu bar with `menus`.
///
/// Menu items that name an action show the key bindings from the keymap.
pub fn set_menus(&self, menus: impl IntoIterator<Item = Menu>) {
let menus: Vec<Menu> = menus.into_iter().collect();
self.platform.set_menus(menus, &self.keymap.borrow());
}
/// Returns the menu bar most recently set with [`App::set_menus`], or `None` if none was set.
pub fn get_menus(&self) -> Option<Vec<OwnedMenu>> {
self.platform.get_menus()
}
/// Sets the menu that appears when the user right-clicks the app's Dock icon.
pub fn set_dock_menu(&self, menus: Vec<MenuItem>) {
self.platform.set_dock_menu(menus, &self.keymap.borrow())
}
/// Runs the dock menu item at index `action`, as set with [`App::set_dock_menu`].
///
/// Only Windows uses this path.
pub fn perform_dock_menu_action(&self, action: usize) {
self.platform.perform_dock_menu_action(action);
}
/// On macOS, adds `path` to the recent documents list, which the Dock menu shows.
/// Other platforms do nothing.
///
/// Call this when the user opens a document, so it appears in the recent list next time.
pub fn add_recent_document(&self, path: &Path) {
self.platform.add_recent_document(path);
}
/// Replaces the Windows jump list with `menus` and the recent `entries`.
///
/// Only Windows uses this. It also sets the dock menu.
pub fn update_jump_list(
&self,
menus: Vec<MenuItem>,
entries: Vec<SmallVec<[PathBuf; 2]>>,
) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
self.platform.update_jump_list(menus, entries)
}
/// Dispatches `action` to the active window, or to the global listeners if no window is active.
///
/// In a window, the action follows the focus path, as a keystroke bound to it would.
/// Without an active window, it goes to the listeners from [`App::on_action`]. See
/// [`crate::Action`] for how actions work.
pub fn dispatch_action(&mut self, action: &dyn Action) {
if let Some(active_window) = self.active_window() {
active_window
.update(self, |_, window, cx| {
window.dispatch_action(action.boxed_clone(), cx)
})
.log_err();
} else {
self.dispatch_global_action(action);
}
}
fn dispatch_global_action(&mut self, action: &dyn Action) {
self.propagate_event = true;
if let Some(mut global_listeners) = self
.global_action_listeners
.remove(&action.as_any().type_id())
{
for listener in &global_listeners {
listener(action.as_any(), DispatchPhase::Capture, self);
if !self.propagate_event {
break;
}
}
global_listeners.extend(
self.global_action_listeners
.remove(&action.as_any().type_id())
.unwrap_or_default(),
);
self.global_action_listeners
.insert(action.as_any().type_id(), global_listeners);
}
if self.propagate_event
&& let Some(mut global_listeners) = self
.global_action_listeners
.remove(&action.as_any().type_id())
{
for listener in global_listeners.iter().rev() {
listener(action.as_any(), DispatchPhase::Bubble, self);
if !self.propagate_event {
break;
}
}
global_listeners.extend(
self.global_action_listeners
.remove(&action.as_any().type_id())
.unwrap_or_default(),
);
self.global_action_listeners
.insert(action.as_any().type_id(), global_listeners);
}
}
/// Returns whether a drag is in progress.
pub fn has_active_drag(&self) -> bool {
self.active_drag.is_some()
}
/// Returns the payload of the drag in progress, if any.
pub fn active_drag(&self) -> Option<&AnyDrag> {
self.active_drag.as_ref()
}
/// Returns the cursor style of the drag in progress, if it set one.
pub fn active_drag_cursor_style(&self) -> Option<CursorStyle> {
self.active_drag.as_ref().and_then(|drag| drag.cursor_style)
}
/// Starts a drag with `drag` as its payload. Refresh the windows after calling this, so the drag shows.
///
/// # Panics
///
/// Debug builds panic if a drag is already in progress.
pub fn start_drag(&mut self, drag: AnyDrag) {
debug_assert!(self.active_drag.is_none());
self.active_drag = Some(drag);
}
/// Ends the drag in progress and returns its payload, if there was one.
///
/// Refresh the windows after calling this.
pub fn stop_drag(&mut self, window: &Window) -> Option<Arc<dyn Any>> {
let drag = self.active_drag.take();
if drag.is_some()
&& let Some(platform_drag) = self.platform_owned_drag.as_ref()
{
if platform_drag.source_window == window.window_handle().window_id()
&& matches!(
&platform_drag.state,
PlatformOwnedDragState::RestoredInSourceWindow
)
{
self.platform_owned_drag = None;
}
}
Some(drag?.value)
}
/// Stops active drag and clears any related effects.
pub fn stop_active_drag(&mut self, window: &mut Window) -> bool {
if self.stop_drag(window).is_some() {
window.refresh();
true
} else {
false
}
}
pub(crate) fn hand_active_drag_to_platform(&mut self, source_window: WindowId) -> bool {
let Some(drag) = self.active_drag.take() else {
return false;
};
self.platform_owned_drag = Some(PlatformOwnedDrag {
source_window,
state: PlatformOwnedDragState::Suspended(drag),
});
true
}
pub(crate) fn restore_platform_drag(&mut self, source_window: WindowId) -> bool {
let Some(platform_drag) = self
.platform_owned_drag
.as_mut()
.filter(|drag| drag.source_window == source_window)
else {
return false;
};
let state = std::mem::replace(
&mut platform_drag.state,
PlatformOwnedDragState::RestoredInSourceWindow,
);
let PlatformOwnedDragState::Suspended(drag) = state else {
return false;
};
self.active_drag = Some(drag);
true
}
pub(crate) fn hand_restored_drag_to_platform(&mut self, source_window: WindowId) -> bool {
let Some(platform_drag) = self.platform_owned_drag.as_mut().filter(|drag| {
drag.source_window == source_window
&& matches!(&drag.state, PlatformOwnedDragState::RestoredInSourceWindow)
}) else {
return false;
};
let Some(drag) = self.active_drag.take() else {
return false;
};
platform_drag.state = PlatformOwnedDragState::Suspended(drag);
true
}
pub(crate) fn end_platform_drag(&mut self, source_window: WindowId) -> bool {
if !self
.platform_owned_drag
.as_ref()
.is_some_and(|drag| drag.source_window == source_window)
{
return false;
}
self.platform_owned_drag = None;
self.active_drag = None;
true
}
/// Sets the cursor shown during the active drag. Returns `false` if no drag is in progress.
pub fn set_active_drag_cursor_style(
&mut self,
cursor_style: CursorStyle,
window: &mut Window,
) -> bool {
if let Some(ref mut drag) = self.active_drag {
drag.cursor_style = Some(cursor_style);
window.refresh();
true
} else {
false
}
}
/// Replaces the default and platform prompts with `renderer`.
///
/// The renderer is called for each prompt the app shows. It receives the prompt's
/// level, message, detail and buttons, and returns the handle that the window renders.
/// Use [`App::reset_prompt_builder`] to go back to the default prompts.
pub fn set_prompt_builder(
&mut self,
renderer: impl Fn(
PromptLevel,
&str,
Option<&str>,
&[PromptButton],
PromptHandle,
&mut Window,
&mut App,
) -> RenderablePromptHandle
+ 'static,
) {
self.prompt_builder = Some(PromptBuilder::Custom(Box::new(renderer)));
}
/// Reset the prompt builder to the default implementation.
pub fn reset_prompt_builder(&mut self) {
self.prompt_builder = Some(PromptBuilder::Default);
}
/// Removes the cached result for `source`, so the next [`App::fetch_asset`] loads it again.
pub fn remove_asset<A: Asset>(&mut self, source: &A::Source) {
let asset_id = (TypeId::of::<A>(), hash(source));
self.loading_assets.remove(&asset_id);
}
/// Returns whether `source` is cached for asset type `A`, either loading or loaded.
///
/// This doesn't start a load. Only available in tests and with the `test-support` feature.
#[cfg(any(test, feature = "test-support"))]
pub fn has_asset<A: Asset>(&self, source: &A::Source) -> bool {
let asset_id = (TypeId::of::<A>(), hash(source));
self.loading_assets.contains_key(&asset_id)
}
/// Starts loading an uncached asset and returns its result once available.
///
/// Pending loads and completed results are cached until [`Self::remove_asset`].
/// This method does not subscribe a view to completion notifications.
pub fn fetch_asset<A: Asset>(&mut self, source: &A::Source) -> Option<A::Output> {
self.asset_entry::<A>(source).get()
}
pub(crate) fn asset_entry<A: Asset>(&mut self, source: &A::Source) -> &CachedLoad<A::Output> {
let asset_id = (TypeId::of::<A>(), hash(source));
if !self.loading_assets.contains_key(&asset_id) {
let future = A::load(source.clone(), self);
let entry = CachedLoad::new(future, self);
self.loading_assets.insert(asset_id, Box::new(entry));
}
self.loading_assets
.get(&asset_id)
.and_then(|entry| entry.downcast_ref())
.expect("asset cache entries are keyed by their asset type")
}
/// Creates a new [`FocusHandle`] for tracking keyboard focus.
///
/// Attach the handle to an element with `track_focus`, and move focus to it with
/// [`Window::focus`].
#[track_caller]
pub fn focus_handle(&self) -> FocusHandle {
FocusHandle::new(&self.focus_handles)
}
/// Returns the debugging name of this app, if one was set.
///
/// Only available in tests, with the `test-support` feature, or in debug builds.
#[cfg(any(test, feature = "test-support", debug_assertions))]
pub fn get_name(&self) -> Option<&'static str> {
self.name
}
/// Returns `true` if the platform file picker supports selecting a mix of files and directories.
pub fn can_select_mixed_files_and_dirs(&self) -> bool {
self.platform.can_select_mixed_files_and_dirs()
}
/// Removes an image from the sprite atlas on all windows.
///
/// A window that is being updated is not in `App.windows`, so pass it as `current_window` to
/// remove the image from it too.
/// This is a no-op if the image is not in the sprite atlas.
pub fn drop_image(&mut self, image: Arc<RenderImage>, current_window: Option<&mut Window>) {
// remove the texture from all other windows
for window in self.windows.values_mut().flatten() {
_ = window.drop_image(image.clone());
}
// remove the texture from the current window
if let Some(window) = current_window {
_ = window.drop_image(image);
}
}
/// Sets the renderer for the inspector.
#[cfg(any(feature = "inspector", debug_assertions))]
pub fn set_inspector_renderer(&mut self, f: crate::InspectorRenderer) {
self.inspector_renderer = Some(f);
}
/// Registers a renderer specific to an inspector state.
#[cfg(any(feature = "inspector", debug_assertions))]
pub fn register_inspector_element<T: 'static, R: crate::IntoElement, F>(
&mut self,
factory: impl 'static + Fn(&mut Window, &mut App) -> F,
) where
F: 'static + FnMut(crate::InspectorElementId, &T, &mut Window, &mut App) -> R,
{
self.inspector_element_registry.register(factory);
}
/// Sets the default [`Colors`] global, which `cx.default_colors()` returns.
pub fn init_colors(&mut self) {
self.set_global(GlobalColors(Arc::new(Colors::default())));
}
#[inline(never)]
fn update_window_erased(
&mut self,
window_id: WindowId,
update: &mut dyn FnMut(Option<(AnyView, &mut Window, &mut App)>),
) {
self.update(|cx| {
let Some(mut window) = cx.windows.get_mut(window_id).and_then(Option::take) else {
update(None);
return;
};
let root_view = window.root.clone().unwrap();
cx.window_update_stack.push(window.handle.id);
update(Some((root_view, &mut window, cx)));
fn trail(window_id: WindowId, window: Box<Window>, cx: &mut App) -> Option<()> {
cx.window_update_stack.pop();
if window.removed {
cx.end_platform_drag(window_id);
cx.window_handles.remove(&window_id);
cx.windows.remove(window_id);
if let Some(tracked) = cx.tracked_entities.remove(&window_id) {
for entity_id in tracked {
if let Some(windows) =
cx.window_invalidators_by_entity.get_mut(&entity_id)
{
windows.remove(&window_id);
}
if cx.current_window_by_entity.get(&entity_id) == Some(&window_id) {
cx.current_window_by_entity.remove(&entity_id);
}
}
}
cx.window_closed_observers.clone().retain(&(), |callback| {
callback(cx, window_id);
true
});
let quit_on_empty = match cx.quit_mode {
QuitMode::Explicit => false,
QuitMode::LastWindowClosed => true,
QuitMode::Default => cfg!(not(target_os = "macos")),
};
if quit_on_empty && cx.windows.is_empty() {
cx.quit();
}
} else {
cx.windows.get_mut(window_id)?.replace(window);
}
Some(())
}
if trail(window_id, window, cx).is_none() {
update(None);
}
});
}
#[inline(never)]
fn update_entity_erased(
&mut self,
handle: &AnyEntity,
entity_type: &str,
update: &mut dyn FnMut(&mut dyn Any, &mut App),
) {
self.update(|cx| {
let mut lease = cx.entities.lease_erased(handle, entity_type);
update(lease.entity.as_deref_mut().unwrap(), cx);
cx.entities.end_lease_erased(handle.entity_id, lease);
});
}
#[inline(never)]
#[track_caller]
fn prepare_spawn(&self) -> AsyncApp {
if self.quitting {
debug_panic!("Can't spawn on main thread after on_app_quit")
};
self.to_async()
}
}
impl AppContext for App {
/// Builds an entity that is owned by the application.
///
/// The given function will be invoked with a [`Context`] and must return an object representing the entity. An
/// [`Entity`] handle will be returned, which can be used to access the entity in a context.
fn new<T: 'static>(&mut self, build_entity: impl FnOnce(&mut Context<T>) -> T) -> Entity<T> {
self.update(|cx| {
let slot = cx.entities.reserve();
let handle = slot.clone();
let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
cx.push_effect(Effect::EntityCreated {
entity: handle.into_any(),
tid: TypeId::of::<T>(),
window: cx.window_update_stack.last().cloned(),
});
cx.entities.insert(slot, entity)
})
}
fn reserve_entity<T: 'static>(&mut self) -> Reservation<T> {
Reservation(self.entities.reserve())
}
fn insert_entity<T: 'static>(
&mut self,
reservation: Reservation<T>,
build_entity: impl FnOnce(&mut Context<T>) -> T,
) -> Entity<T> {
self.update(|cx| {
let slot = reservation.0;
let entity = build_entity(&mut Context::new_context(cx, slot.downgrade()));
cx.entities.insert(slot, entity)
})
}
/// Updates the entity referenced by the given handle. The function is passed a mutable reference to the
/// entity along with a `Context` for the entity.
#[inline(always)]
fn update_entity<T: 'static, R>(
&mut self,
handle: &Entity<T>,
update: impl FnOnce(&mut T, &mut Context<T>) -> R,
) -> R {
let mut update = Some(update);
let mut result = None;
self.update_entity_erased(handle, type_name::<T>(), &mut |entity, cx| {
let value = update.take().unwrap()(
entity.downcast_mut::<T>().unwrap(),
&mut Context::new_context(cx, handle.downgrade()),
);
result = Some(value);
});
result.unwrap()
}
fn as_mut<'a, T>(&'a mut self, handle: &Entity<T>) -> GpuiBorrow<'a, T>
where
T: 'static,
{
GpuiBorrow::new(handle.clone(), self)
}
#[inline(always)]
fn read_entity<T, R>(&self, handle: &Entity<T>, read: impl FnOnce(&T, &App) -> R) -> R
where
T: 'static,
{
let entity = self.entities.read(handle);
read(entity, self)
}
fn notify(&mut self, entity_id: EntityId) {
let window_invalidators = mem::take(
self.window_invalidators_by_entity
.entry(entity_id)
.or_default(),
);
// `window_invalidators_by_entity` is monotonic, so an entry alone
// doesn't mean the window is currently rendering the entity. Filter
// through `tracked_entities` to keep invalidation tight to windows
// that actually display this entity right now.
let live_invalidators: SmallVec<[WindowInvalidator; 2]> = window_invalidators
.iter()
.filter(|(window_id, _)| {
self.tracked_entities
.get(window_id)
.is_some_and(|set| set.contains(&entity_id))
})
.map(|(_, invalidator)| invalidator.clone())
.collect();
if live_invalidators.is_empty() {
if self.pending_notifications.insert(entity_id) {
self.pending_effects
.push_back(Effect::Notify { emitter: entity_id });
}
} else {
for invalidator in &live_invalidators {
invalidator.invalidate_view(entity_id, self);
}
}
self.window_invalidators_by_entity
.insert(entity_id, window_invalidators);
}
fn emit<EntityType, EventType>(&mut self, entity: &Entity<EntityType>, event: EventType)
where
EntityType: EventEmitter<EventType>,
EventType: 'static,
{
let event = self
.event_arena
.alloc(|| event)
.map(|it| it as &mut dyn Any);
self.pending_effects.push_back(Effect::Emit {
emitter: entity.entity_id(),
event_type: TypeId::of::<EventType>(),
event,
});
}
fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
where
F: FnOnce(AnyView, &mut Window, &mut App) -> T,
{
self.update_window_id(handle.id, update)
}
fn with_window<R>(
&mut self,
entity_id: EntityId,
f: impl FnOnce(&mut Window, &mut App) -> R,
) -> Option<R> {
App::with_window(self, entity_id, f)
}
fn read_window<T, R>(
&self,
window: &WindowHandle<T>,
read: impl FnOnce(Entity<T>, &App) -> R,
) -> Result<R>
where
T: 'static,
{
let window = self
.windows
.get(window.id)
.context("window not found")?
.as_deref()
.expect("attempted to read a window that is already on the stack");
let root_view = window.root.clone().unwrap();
let view = root_view
.downcast::<T>()
.map_err(|_| anyhow!("root view's type has changed"))?;
Ok(read(view, self))
}
fn background_spawn<R>(&self, future: impl Future<Output = R> + Send + 'static) -> Task<R>
where
R: Send + 'static,
{
self.background_executor.spawn(future)
}
fn read_global<G, R>(&self, callback: impl FnOnce(&G, &App) -> R) -> R
where
G: Global,
{
let mut g = self.global::<G>();
callback(g, self)
}
fn insert_global_entity<T: 'static>(&mut self, entity: Entity<T>) {
let any = entity.into_any();
if !self.global_entities.contains(&any) {
self.global_entities.push(any);
}
}
fn remove_global_entity<T: 'static>(&mut self, entity: &Entity<T>) {
self.global_entities
.retain(|any| any.entity_id() != entity.entity_id());
}
fn global_entities<T: 'static>(&self) -> impl Iterator<Item = Entity<T>> {
let mut iter = self.global_entities.iter();
iter.filter_map(|any| any.clone().downcast::<T>().ok())
}
}
/// These effects are processed at the end of each application update cycle.
pub(crate) enum Effect {
Notify {
emitter: EntityId,
},
Emit {
emitter: EntityId,
event_type: TypeId,
event: ArenaBox<dyn Any>,
},
RefreshWindows,
NotifyGlobalObservers {
global_type: TypeId,
},
Defer {
callback: Box<dyn FnOnce(&mut App) + 'static>,
},
EntityCreated {
entity: AnyEntity,
tid: TypeId,
window: Option<WindowId>,
},
}
impl std::fmt::Debug for Effect {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Effect::Notify { emitter } => write!(f, "Notify({})", emitter),
Effect::Emit { emitter, .. } => write!(f, "Emit({:?})", emitter),
Effect::RefreshWindows => write!(f, "RefreshWindows"),
Effect::NotifyGlobalObservers { global_type } => {
write!(f, "NotifyGlobalObservers({:?})", global_type)
}
Effect::Defer { .. } => write!(f, "Defer(..)"),
Effect::EntityCreated { entity, .. } => write!(f, "EntityCreated({:?})", entity),
}
}
}
/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
pub(crate) struct GlobalLease<G: Global> {
global: Box<dyn Any>,
global_type: PhantomData<G>,
}
impl<G: Global> GlobalLease<G> {
fn new(global: Box<dyn Any>) -> Self {
GlobalLease {
global,
global_type: PhantomData,
}
}
}
impl<G: Global> Deref for GlobalLease<G> {
type Target = G;
fn deref(&self) -> &Self::Target {
self.global.downcast_ref().unwrap()
}
}
impl<G: Global> DerefMut for GlobalLease<G> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.global.downcast_mut().unwrap()
}
}
/// The state of a drag in progress, started by dragging an element in a window.
///
/// Set with [`App::start_drag`]. Read it with [`App::active_drag`]. It is cleared by
/// [`App::stop_drag`] when the drop happens.
#[derive(derive_setters::Setters)]
#[setters(generate = false)]
pub struct AnyDrag {
/// The view that draws the dragged item under the cursor.
pub view: AnyView,
/// The value that the drop target receives.
pub value: Arc<dyn Any>,
/// The offset from the cursor to the drag view, so the view stays under the same point it was grabbed.
#[setters(generate, rename = "offset")]
pub cursor_offset: Point<Pixels>,
/// The cursor shown during the drag, or `None` for the default.
#[setters(generate)]
pub cursor_style: Option<CursorStyle>,
/// Resolves the payload to offer the platform if the drag leaves the window.
/// Invoked at most once per drag gesture, at promotion time.
pub external_payload_source: Option<ExternalDragPayloadSource>,
}
impl AnyDrag {
/// Creates a drag that carries `value` and draws `view` under the cursor.
pub fn new<T: 'static + Sized>(value: T, view: impl Into<AnyView>) -> Self {
Self {
view: view.into(),
value: Arc::new(value),
cursor_offset: Point::default(),
cursor_style: None,
external_payload_source: None,
}
}
/// Sets [`AnyDrag::external_payload_source`]: the closure builds the payload if the drag leaves the window.
pub fn external_payload(
mut self,
predicate: impl FnOnce(&mut Window, &mut App) -> Option<ExternalDragPayload> + 'static,
) -> Self {
self.external_payload_source = Some(Box::new(predicate));
self
}
/// Returns whether the dragged value has type `T`.
pub fn is_type<T: 'static>(&self) -> bool {
self.value.as_ref().type_id() == TypeId::of::<T>()
}
}
/// A closure that builds the payload for a drag that leaves the window.
///
/// It runs when the drag becomes a native drag session, not when the drag starts. Set it
/// with [`AnyDrag::external_payload`].
pub type ExternalDragPayloadSource =
Box<dyn FnOnce(&mut Window, &mut App) -> Option<ExternalDragPayload> + 'static>;
/// The state of a tooltip that is currently shown.
///
/// You need this type only when you implement tooltip behavior on a custom element.
/// Otherwise use [`Interactivity::tooltip`](crate::Interactivity::tooltip).
#[derive(Clone)]
pub struct AnyTooltip {
/// The view that draws the tooltip.
pub view: AnyView,
/// The absolute position of the mouse when the tooltip was shown.
pub mouse_position: Point<Pixels>,
/// Given the bounds of the tooltip, checks whether the tooltip should still be visible and
/// updates its state accordingly. This is needed atop the hovered element's mouse move handler
/// to handle the case where the element is not painted (e.g. via use of `visible_on_hover`).
pub check_visible_and_update: Rc<dyn Fn(Bounds<Pixels>, &mut Window, &mut App) -> bool>,
}
/// Whether a keystroke should prefer character input or key bindings.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum InputPreference {
/// Prefer typing text over triggering key bindings.
CharacterInput,
/// Dispatch key bindings normally, if any match.
KeyBindings,
}
/// A keystroke that reached the app, with the action it resolved to, if any.
///
/// Passed to the callbacks from [`App::observe_keystrokes`] and [`App::intercept_keystrokes`].
#[derive(Debug)]
pub struct KeystrokeEvent {
/// The keystroke that was pressed.
pub keystroke: Keystroke,
/// Whether this keystroke should prefer character input or key bindings.
/// This is [`InputPreference::CharacterInput`] when the platform prefers text for the key
/// (e.g. AltGr on Windows) and the focused input accepts text. Interceptors still receive
/// these keystrokes and can consume them.
///
/// If the keystroke is part of a multi-stroke binding, it still waits as pending input
/// even when this is [`InputPreference::CharacterInput`].
pub input_preference: InputPreference,
/// The action the keystroke resolved to, or `None` if no binding matched. Always
/// `None` in an `intercept_keystrokes` callback.
pub action: Option<Box<dyn Action>>,
/// The key contexts that were active for the keystroke, from the outermost to the focused element.
pub context_stack: Vec<KeyContext>,
}
/// A mutable borrow of an entity's state, taken out of GPUI while the borrow is alive.
pub struct GpuiBorrow<'a, T> {
inner: Option<Lease<T>>,
app: &'a mut App,
}
impl<'a, T: 'static> GpuiBorrow<'a, T> {
fn new(inner: Entity<T>, app: &'a mut App) -> Self {
app.start_update();
let lease = app.entities.lease(&inner);
Self {
inner: Some(lease),
app,
}
}
}
impl<'a, T: 'static> std::borrow::Borrow<T> for GpuiBorrow<'a, T> {
fn borrow(&self) -> &T {
self.inner.as_ref().unwrap().borrow()
}
}
impl<'a, T: 'static> std::borrow::BorrowMut<T> for GpuiBorrow<'a, T> {
fn borrow_mut(&mut self) -> &mut T {
self.inner.as_mut().unwrap().borrow_mut()
}
}
impl<'a, T: 'static> std::ops::Deref for GpuiBorrow<'a, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.inner.as_ref().unwrap()
}
}
impl<'a, T: 'static> std::ops::DerefMut for GpuiBorrow<'a, T> {
fn deref_mut(&mut self) -> &mut T {
self.inner.as_mut().unwrap()
}
}
impl<'a, T> Drop for GpuiBorrow<'a, T> {
fn drop(&mut self) {
let lease = self.inner.take().unwrap();
self.app.notify(lease.id);
self.app.entities.end_lease(lease);
self.app.finish_update();
}
}
#[cfg(test)]
mod test {
use std::{
cell::{Cell, RefCell},
ffi::OsString,
path::PathBuf,
rc::Rc,
};
#[cfg(unix)]
use std::os::unix::ffi::OsStringExt;
use crate::{AppContext, Context, Empty, IntoElement, Render, TestAppContext, Window};
struct RenderCounter(Rc<Cell<usize>>);
impl Render for RenderCounter {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
self.0.set(self.0.get() + 1);
Empty
}
}
#[gpui::test]
fn async_app_refresh_flushes_refresh_effect(cx: &mut TestAppContext) {
let render_count = Rc::new(Cell::new(0));
let _window = cx.add_window({
let render_count = render_count.clone();
move |_, _| RenderCounter(render_count)
});
cx.run_until_parked();
let render_count_before_refresh = render_count.get();
cx.to_async().refresh();
assert_eq!(render_count.get(), render_count_before_refresh + 1);
}
#[test]
fn embedded_update_flushes_effects() {
let cx = TestAppContext::single();
let handle = super::ApplicationHandle { app: cx.app };
let completed = Rc::new(Cell::new(false));
handle.update(|cx| {
cx.defer({
let completed = completed.clone();
move |_| completed.set(true)
});
});
assert!(completed.get());
}
#[gpui::test]
fn nested_update_defers_new_effects_until_current_effect_returns(cx: &mut TestAppContext) {
let order = Rc::new(RefCell::new(Vec::new()));
cx.update({
let order = order.clone();
move |cx| {
cx.defer(move |cx| {
order.borrow_mut().push("outer-start");
cx.update({
let order = order.clone();
|cx| {
cx.defer(move |_| order.borrow_mut().push("nested"));
}
});
order.borrow_mut().push("outer-end");
});
}
});
assert_eq!(*order.borrow(), ["outer-start", "outer-end", "nested"]);
}
#[gpui::test]
fn adding_a_tab_group_after_removal_preserves_other_groups(cx: &mut TestAppContext) {
use super::{SystemWindowTab, SystemWindowTabController};
let windows: Vec<_> = (0..4).map(|_| cx.add_window(|_, _| Empty)).collect();
cx.update(|cx| {
for (ix, window) in windows.iter().take(3).enumerate() {
SystemWindowTabController::add_tab(
cx,
window.window_id(),
vec![SystemWindowTab::new(
format!("Window {ix}").into(),
(*window).into(),
)],
);
}
SystemWindowTabController::remove_tab(cx, windows[0].window_id());
SystemWindowTabController::add_tab(
cx,
windows[3].window_id(),
vec![SystemWindowTab::new("New window".into(), windows[3].into())],
);
let controller = cx.global::<SystemWindowTabController>();
assert_eq!(controller.tab_groups.len(), 3);
for window in &windows[1..] {
assert_eq!(controller.tabs(window.window_id()).unwrap().len(), 1);
}
});
}
#[gpui::test]
fn drag_type_matches_the_payload(cx: &mut TestAppContext) {
cx.update(|cx| {
let view = cx.new(|_| Empty);
let drag = super::AnyDrag::new(String::from("row"), view);
assert!(drag.is_type::<String>());
assert!(!drag.is_type::<usize>());
assert!(!drag.is_type::<std::sync::Arc<dyn std::any::Any>>());
});
}
#[test]
fn test_gpui_borrow() {
let cx = TestAppContext::single();
let observation_count = Rc::new(RefCell::new(0));
let state = cx.update(|cx| {
let state = cx.new(|_| false);
cx.observe(&state, {
let observation_count = observation_count.clone();
move |_, _| {
let mut count = observation_count.borrow_mut();
*count += 1;
}
})
.detach();
state
});
cx.update(|cx| {
// Calling this like this so that we don't clobber the borrow_mut above
*std::borrow::BorrowMut::borrow_mut(&mut state.as_mut(cx)) = true;
});
cx.update(|cx| {
state.write(cx, false);
});
assert_eq!(*observation_count.borrow(), 2);
}
#[gpui::test]
async fn test_restart_preserves_path_and_arguments(cx: &mut TestAppContext) {
#[cfg(unix)]
let user_data_dir = OsString::from_vec(b"/tmp/zed data/\xff".to_vec());
#[cfg(not(unix))]
let user_data_dir = OsString::from("C:\\zed data");
let arguments = vec![OsString::from("--user-data-dir"), user_data_dir];
let restart_path = PathBuf::from("updated-zed");
let _application =
super::Application(cx.app.clone()).with_restart_arguments(arguments.clone());
let restart = cx.expect_restart();
cx.update(|cx| {
cx.set_restart_path(restart_path.clone());
cx.restart();
});
let (path, restart_arguments) = restart.await.expect("restart was not requested");
assert_eq!(path, Some(restart_path));
assert_eq!(restart_arguments, arguments);
}
}