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
#![warn(missing_docs)] // Let's keep `Context` well-documented.

use std::{borrow::Cow, cell::RefCell, panic::Location, sync::Arc, time::Duration};

use ahash::HashMap;
use epaint::{mutex::*, stats::*, text::Fonts, util::OrderedFloat, TessellationOptions, *};

use crate::{
    animation_manager::AnimationManager,
    data::output::PlatformOutput,
    frame_state::FrameState,
    input_state::*,
    layers::GraphicLayers,
    load::{Bytes, Loaders, SizedTexture},
    memory::Options,
    os::OperatingSystem,
    output::FullOutput,
    util::IdTypeMap,
    viewport::ViewportClass,
    TextureHandle, ViewportCommand, *,
};

/// Information given to the backend about when it is time to repaint the ui.
///
/// This is given in the callback set by [`Context::set_request_repaint_callback`].
#[derive(Clone, Copy, Debug)]
pub struct RequestRepaintInfo {
    /// This is used to specify what viewport that should repaint.
    pub viewport_id: ViewportId,

    /// Repaint after this duration. If zero, repaint as soon as possible.
    pub delay: Duration,

    /// The current frame number.
    ///
    /// This can be compared to [`Context::frame_nr`] to see if we've already
    /// triggered the painting of the next frame.
    pub current_frame_nr: u64,
}

// ----------------------------------------------------------------------------

thread_local! {
    static IMMEDIATE_VIEWPORT_RENDERER: RefCell<Option<Box<ImmediateViewportRendererCallback>>> = Default::default();
}

// ----------------------------------------------------------------------------

struct WrappedTextureManager(Arc<RwLock<epaint::TextureManager>>);

impl Default for WrappedTextureManager {
    fn default() -> Self {
        let mut tex_mngr = epaint::textures::TextureManager::default();

        // Will be filled in later
        let font_id = tex_mngr.alloc(
            "egui_font_texture".into(),
            epaint::FontImage::new([0, 0]).into(),
            Default::default(),
        );
        assert_eq!(font_id, TextureId::default());

        Self(Arc::new(RwLock::new(tex_mngr)))
    }
}

// ----------------------------------------------------------------------------

/// Generic event callback.
pub type ContextCallback = Arc<dyn Fn(&Context) + Send + Sync>;

#[derive(Clone)]
struct NamedContextCallback {
    debug_name: &'static str,
    callback: ContextCallback,
}

/// Callbacks that users can register
#[derive(Clone, Default)]
struct Plugins {
    pub on_begin_frame: Vec<NamedContextCallback>,
    pub on_end_frame: Vec<NamedContextCallback>,
}

impl Plugins {
    fn call(ctx: &Context, _cb_name: &str, callbacks: &[NamedContextCallback]) {
        crate::profile_scope!("plugins", _cb_name);
        for NamedContextCallback {
            debug_name: _name,
            callback,
        } in callbacks
        {
            crate::profile_scope!("plugin", _name);
            (callback)(ctx);
        }
    }

    fn on_begin_frame(&self, ctx: &Context) {
        Self::call(ctx, "on_begin_frame", &self.on_begin_frame);
    }

    fn on_end_frame(&self, ctx: &Context) {
        Self::call(ctx, "on_end_frame", &self.on_end_frame);
    }
}

// ----------------------------------------------------------------------------

/// Repaint-logic
impl ContextImpl {
    /// This is where we update the repaint logic.
    fn begin_frame_repaint_logic(&mut self, viewport_id: ViewportId) {
        let viewport = self.viewports.entry(viewport_id).or_default();

        std::mem::swap(
            &mut viewport.repaint.prev_causes,
            &mut viewport.repaint.causes,
        );
        viewport.repaint.causes.clear();

        viewport.repaint.prev_frame_paint_delay = viewport.repaint.repaint_delay;

        if viewport.repaint.outstanding == 0 {
            // We are repainting now, so we can wait a while for the next repaint.
            viewport.repaint.repaint_delay = Duration::MAX;
        } else {
            viewport.repaint.repaint_delay = Duration::ZERO;
            viewport.repaint.outstanding -= 1;
            if let Some(callback) = &self.request_repaint_callback {
                (callback)(RequestRepaintInfo {
                    viewport_id,
                    delay: Duration::ZERO,
                    current_frame_nr: viewport.repaint.frame_nr,
                });
            }
        }
    }

    fn request_repaint(&mut self, viewport_id: ViewportId, cause: RepaintCause) {
        self.request_repaint_after(Duration::ZERO, viewport_id, cause);
    }

    fn request_repaint_after(
        &mut self,
        delay: Duration,
        viewport_id: ViewportId,
        cause: RepaintCause,
    ) {
        let viewport = self.viewports.entry(viewport_id).or_default();

        if delay == Duration::ZERO {
            // Each request results in two repaints, just to give some things time to settle.
            // This solves some corner-cases of missing repaints on frame-delayed responses.
            viewport.repaint.outstanding = 1;
        } else {
            // For non-zero delays, we only repaint once, because
            // otherwise we would just schedule an immediate repaint _now_,
            // which would then clear the delay and repaint again.
            // Hovering a tooltip is a good example of a case where we want to repaint after a delay.
        }

        viewport.repaint.causes.push(cause);

        // We save some CPU time by only calling the callback if we need to.
        // If the new delay is greater or equal to the previous lowest,
        // it means we have already called the callback, and don't need to do it again.
        if delay < viewport.repaint.repaint_delay {
            viewport.repaint.repaint_delay = delay;

            if let Some(callback) = &self.request_repaint_callback {
                (callback)(RequestRepaintInfo {
                    viewport_id,
                    delay,
                    current_frame_nr: viewport.repaint.frame_nr,
                });
            }
        }
    }

    #[must_use]
    fn requested_immediate_repaint_prev_frame(&self, viewport_id: &ViewportId) -> bool {
        self.viewports.get(viewport_id).map_or(false, |v| {
            v.repaint.requested_immediate_repaint_prev_frame()
        })
    }

    #[must_use]
    fn has_requested_repaint(&self, viewport_id: &ViewportId) -> bool {
        self.viewports.get(viewport_id).map_or(false, |v| {
            0 < v.repaint.outstanding || v.repaint.repaint_delay < Duration::MAX
        })
    }
}

// ----------------------------------------------------------------------------

/// Used to store each widget's [Id], [Rect] and [Sense] each frame.
/// Used to check for overlaps between widgets when handling events.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct WidgetRect {
    /// Where the widget is.
    ///
    /// This is after clipping with the parent ui clip rect.
    pub rect: Rect,

    /// The globally unique widget id.
    ///
    /// For interactive widgets, this better be globally unique.
    /// If not there will be weird bugs,
    /// and also big red warning test on the screen in debug builds
    /// (see [`Options::warn_on_id_clash`]).
    ///
    /// You can ensure globally unique ids using [`Ui::push_id`].
    pub id: Id,

    /// How the widget responds to interaction.
    pub sense: Sense,
}

/// Stores the positions of all widgets generated during a single egui update/frame.
///
/// Actually, only those that are on screen.
#[derive(Default, Clone, PartialEq, Eq)]
pub struct WidgetRects {
    /// All widgets, in painting order.
    pub by_layer: HashMap<LayerId, Vec<WidgetRect>>,
}

impl WidgetRects {
    /// Clear the contents while retaining allocated memory.
    pub fn clear(&mut self) {
        for rects in self.by_layer.values_mut() {
            rects.clear();
        }
    }

    /// Insert the given widget rect in the given layer.
    pub fn insert(&mut self, layer_id: LayerId, widget_rect: WidgetRect) {
        if !widget_rect.rect.is_positive() {
            return;
        }

        let layer_widgets = self.by_layer.entry(layer_id).or_default();

        if let Some(last) = layer_widgets.last_mut() {
            if last.id == widget_rect.id {
                // e.g. calling `response.interact(…)` right after interacting.
                last.sense |= widget_rect.sense;
                last.rect = last.rect.union(widget_rect.rect);
                return;
            }
        }

        layer_widgets.push(widget_rect);
    }
}

// ----------------------------------------------------------------------------

/// State stored per viewport
#[derive(Default)]
struct ViewportState {
    /// The type of viewport.
    ///
    /// This will never be [`ViewportClass::Embedded`],
    /// since those don't result in real viewports.
    class: ViewportClass,

    /// The latest delta
    builder: ViewportBuilder,

    /// The user-code that shows the GUI, used for deferred viewports.
    ///
    /// `None` for immediate viewports.
    viewport_ui_cb: Option<Arc<DeferredViewportUiCallback>>,

    input: InputState,

    /// State that is collected during a frame and then cleared
    frame_state: FrameState,

    /// Has this viewport been updated this frame?
    used: bool,

    /// Written to during the frame.
    layer_rects_this_frame: WidgetRects,

    /// Read
    layer_rects_prev_frame: WidgetRects,

    /// State related to repaint scheduling.
    repaint: ViewportRepaintInfo,

    // ----------------------
    // The output of a frame:
    graphics: GraphicLayers,
    // Most of the things in `PlatformOutput` are not actually viewport dependent.
    output: PlatformOutput,
    commands: Vec<ViewportCommand>,
}

/// What called [`Context::request_repaint`]?
#[derive(Clone, Debug)]
pub struct RepaintCause {
    /// What file had the call that requested the repaint?
    pub file: String,

    /// What line number of the the call that requested the repaint?
    pub line: u32,
}

impl RepaintCause {
    /// Capture the file and line number of the call site.
    #[allow(clippy::new_without_default)]
    #[track_caller]
    pub fn new() -> Self {
        let caller = Location::caller();
        Self {
            file: caller.file().to_owned(),
            line: caller.line(),
        }
    }
}

impl std::fmt::Display for RepaintCause {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}:{}", self.file, self.line)
    }
}

/// Per-viewport state related to repaint scheduling.
struct ViewportRepaintInfo {
    /// Monotonically increasing counter.
    frame_nr: u64,

    /// The duration which the backend will poll for new events
    /// before forcing another egui update, even if there's no new events.
    ///
    /// Also used to suppress multiple calls to the repaint callback during the same frame.
    ///
    /// This is also returned in [`crate::ViewportOutput`].
    repaint_delay: Duration,

    /// While positive, keep requesting repaints. Decrement at the start of each frame.
    outstanding: u8,

    /// What caused repaints during this frame?
    causes: Vec<RepaintCause>,

    /// What triggered a repaint the previous frame?
    /// (i.e: why are we updating now?)
    prev_causes: Vec<RepaintCause>,

    /// What was the output of `repaint_delay` on the previous frame?
    ///
    /// If this was zero, we are repainting as quickly as possible
    /// (as far as we know).
    prev_frame_paint_delay: Duration,
}

impl Default for ViewportRepaintInfo {
    fn default() -> Self {
        Self {
            frame_nr: 0,

            // We haven't scheduled a repaint yet.
            repaint_delay: Duration::MAX,

            // Let's run a couple of frames at the start, because why not.
            outstanding: 1,

            causes: Default::default(),
            prev_causes: Default::default(),

            prev_frame_paint_delay: Duration::MAX,
        }
    }
}

impl ViewportRepaintInfo {
    pub fn requested_immediate_repaint_prev_frame(&self) -> bool {
        self.prev_frame_paint_delay == Duration::ZERO
    }
}

// ----------------------------------------------------------------------------

#[derive(Default)]
struct ContextImpl {
    /// Since we could have multiple viewports across multiple monitors with
    /// different `pixels_per_point`, we need a `Fonts` instance for each unique
    /// `pixels_per_point`.
    /// This is because the `Fonts` depend on `pixels_per_point` for the font atlas
    /// as well as kerning, font sizes, etc.
    fonts: std::collections::BTreeMap<OrderedFloat<f32>, Fonts>,
    font_definitions: FontDefinitions,

    memory: Memory,
    animation_manager: AnimationManager,

    plugins: Plugins,

    /// All viewports share the same texture manager and texture namespace.
    ///
    /// In all viewports, [`TextureId::default`] is special, and points to the font atlas.
    /// The font-atlas texture _may_ be different across viewports, as they may have different
    /// `pixels_per_point`, so we do special book-keeping for that.
    /// See <https://github.com/emilk/egui/issues/3664>.
    tex_manager: WrappedTextureManager,

    /// Set during the frame, becomes active at the start of the next frame.
    new_zoom_factor: Option<f32>,

    os: OperatingSystem,

    /// How deeply nested are we?
    viewport_stack: Vec<ViewportIdPair>,

    /// What is the last viewport rendered?
    last_viewport: ViewportId,

    paint_stats: PaintStats,

    request_repaint_callback: Option<Box<dyn Fn(RequestRepaintInfo) + Send + Sync>>,

    viewport_parents: ViewportIdMap<ViewportId>,
    viewports: ViewportIdMap<ViewportState>,

    embed_viewports: bool,

    #[cfg(feature = "accesskit")]
    is_accesskit_enabled: bool,
    #[cfg(feature = "accesskit")]
    accesskit_node_classes: accesskit::NodeClassSet,

    loaders: Arc<Loaders>,
}

impl ContextImpl {
    fn begin_frame_mut(&mut self, mut new_raw_input: RawInput) {
        let viewport_id = new_raw_input.viewport_id;
        let parent_id = new_raw_input
            .viewports
            .get(&viewport_id)
            .and_then(|v| v.parent)
            .unwrap_or_default();
        let ids = ViewportIdPair::from_self_and_parent(viewport_id, parent_id);

        let is_outermost_viewport = self.viewport_stack.is_empty(); // not necessarily root, just outermost immediate viewport
        self.viewport_stack.push(ids);

        self.begin_frame_repaint_logic(viewport_id);

        let viewport = self.viewports.entry(viewport_id).or_default();

        if is_outermost_viewport {
            if let Some(new_zoom_factor) = self.new_zoom_factor.take() {
                let ratio = self.memory.options.zoom_factor / new_zoom_factor;
                self.memory.options.zoom_factor = new_zoom_factor;

                let input = &viewport.input;
                // This is a bit hacky, but is required to avoid jitter:
                let mut rect = input.screen_rect;
                rect.min = (ratio * rect.min.to_vec2()).to_pos2();
                rect.max = (ratio * rect.max.to_vec2()).to_pos2();
                new_raw_input.screen_rect = Some(rect);
                // We should really scale everything else in the input too,
                // but the `screen_rect` is the most important part.
            }
        }
        let pixels_per_point = self.memory.options.zoom_factor
            * new_raw_input
                .viewport()
                .native_pixels_per_point
                .unwrap_or(1.0);

        let all_viewport_ids: ViewportIdSet = self.all_viewport_ids();

        let viewport = self.viewports.entry(self.viewport_id()).or_default();

        self.memory
            .begin_frame(&viewport.input, &new_raw_input, &all_viewport_ids);

        viewport.input = std::mem::take(&mut viewport.input).begin_frame(
            new_raw_input,
            viewport.repaint.requested_immediate_repaint_prev_frame(),
            pixels_per_point,
        );

        viewport.frame_state.begin_frame(&viewport.input);

        // Ensure we register the background area so panels and background ui can catch clicks:
        let screen_rect = viewport.input.screen_rect();
        self.memory.areas_mut().set_state(
            LayerId::background(),
            containers::area::State {
                pivot_pos: screen_rect.left_top(),
                pivot: Align2::LEFT_TOP,
                size: screen_rect.size(),
                interactable: true,
                edges_padded_for_resize: false,
            },
        );

        #[cfg(feature = "accesskit")]
        if self.is_accesskit_enabled {
            crate::profile_scope!("accesskit");
            use crate::frame_state::AccessKitFrameState;
            let id = crate::accesskit_root_id();
            let mut builder = accesskit::NodeBuilder::new(accesskit::Role::Window);
            let pixels_per_point = viewport.input.pixels_per_point();
            builder.set_transform(accesskit::Affine::scale(pixels_per_point.into()));
            let mut node_builders = IdMap::default();
            node_builders.insert(id, builder);
            viewport.frame_state.accesskit_state = Some(AccessKitFrameState {
                node_builders,
                parent_stack: vec![id],
            });
        }

        self.update_fonts_mut();
    }

    /// Load fonts unless already loaded.
    fn update_fonts_mut(&mut self) {
        crate::profile_function!();

        let input = &self.viewport().input;
        let pixels_per_point = input.pixels_per_point();
        let max_texture_side = input.max_texture_side;

        if let Some(font_definitions) = self.memory.new_font_definitions.take() {
            // New font definition loaded, so we need to reload all fonts.
            self.fonts.clear();
            self.font_definitions = font_definitions;
            #[cfg(feature = "log")]
            log::debug!("Loading new font definitions");
        }

        let mut is_new = false;

        let fonts = self
            .fonts
            .entry(pixels_per_point.into())
            .or_insert_with(|| {
                #[cfg(feature = "log")]
                log::trace!("Creating new Fonts for pixels_per_point={pixels_per_point}");

                is_new = true;
                crate::profile_scope!("Fonts::new");
                Fonts::new(
                    pixels_per_point,
                    max_texture_side,
                    self.font_definitions.clone(),
                )
            });

        {
            crate::profile_scope!("Fonts::begin_frame");
            fonts.begin_frame(pixels_per_point, max_texture_side);
        }

        if is_new && self.memory.options.preload_font_glyphs {
            crate::profile_scope!("preload_font_glyphs");
            // Preload the most common characters for the most common fonts.
            // This is not very important to do, but may save a few GPU operations.
            for font_id in self.memory.options.style.text_styles.values() {
                fonts.lock().fonts.font(font_id).preload_common_characters();
            }
        }
    }

    #[cfg(feature = "accesskit")]
    fn accesskit_node_builder(&mut self, id: Id) -> &mut accesskit::NodeBuilder {
        let state = self
            .viewport()
            .frame_state
            .accesskit_state
            .as_mut()
            .unwrap();
        let builders = &mut state.node_builders;
        if let std::collections::hash_map::Entry::Vacant(entry) = builders.entry(id) {
            entry.insert(Default::default());
            let parent_id = state.parent_stack.last().unwrap();
            let parent_builder = builders.get_mut(parent_id).unwrap();
            parent_builder.push_child(id.accesskit_id());
        }
        builders.get_mut(&id).unwrap()
    }

    fn pixels_per_point(&mut self) -> f32 {
        self.viewport().input.pixels_per_point
    }

    /// Return the `ViewportId` of the current viewport.
    ///
    /// For the root viewport this will return [`ViewportId::ROOT`].
    pub(crate) fn viewport_id(&self) -> ViewportId {
        self.viewport_stack.last().copied().unwrap_or_default().this
    }

    /// Return the `ViewportId` of his parent.
    ///
    /// For the root viewport this will return [`ViewportId::ROOT`].
    pub(crate) fn parent_viewport_id(&self) -> ViewportId {
        self.viewport_stack
            .last()
            .copied()
            .unwrap_or_default()
            .parent
    }

    fn all_viewport_ids(&self) -> ViewportIdSet {
        self.viewports
            .keys()
            .copied()
            .chain([ViewportId::ROOT])
            .collect()
    }

    /// The current active viewport
    fn viewport(&mut self) -> &mut ViewportState {
        self.viewports.entry(self.viewport_id()).or_default()
    }

    fn viewport_for(&mut self, viewport_id: ViewportId) -> &mut ViewportState {
        self.viewports.entry(viewport_id).or_default()
    }
}

// ----------------------------------------------------------------------------

/// Your handle to egui.
///
/// This is the first thing you need when working with egui.
/// Contains the [`InputState`], [`Memory`], [`PlatformOutput`], and more.
///
/// [`Context`] is cheap to clone, and any clones refers to the same mutable data
/// ([`Context`] uses refcounting internally).
///
/// ## Locking
/// All methods are marked `&self`; [`Context`] has interior mutability protected by an [`RwLock`].
///
/// To access parts of a `Context` you need to use some of the helper functions that take closures:
///
/// ```
/// # let ctx = egui::Context::default();
/// if ctx.input(|i| i.key_pressed(egui::Key::A)) {
///     ctx.output_mut(|o| o.copied_text = "Hello!".to_string());
/// }
/// ```
///
/// Within such a closure you may NOT recursively lock the same [`Context`], as that can lead to a deadlock.
/// Therefore it is important that any lock of [`Context`] is short-lived.
///
/// These are effectively transactional accesses.
///
/// [`Ui`] has many of the same accessor functions, and the same applies there.
///
/// ## Example:
///
/// ``` no_run
/// # fn handle_platform_output(_: egui::PlatformOutput) {}
/// # fn paint(textures_delta: egui::TexturesDelta, _: Vec<egui::ClippedPrimitive>) {}
/// let mut ctx = egui::Context::default();
///
/// // Game loop:
/// loop {
///     let raw_input = egui::RawInput::default();
///     let full_output = ctx.run(raw_input, |ctx| {
///         egui::CentralPanel::default().show(&ctx, |ui| {
///             ui.label("Hello world!");
///             if ui.button("Click me").clicked() {
///                 // take some action here
///             }
///         });
///     });
///     handle_platform_output(full_output.platform_output);
///     let clipped_primitives = ctx.tessellate(full_output.shapes, full_output.pixels_per_point);
///     paint(full_output.textures_delta, clipped_primitives);
/// }
/// ```
#[derive(Clone)]
pub struct Context(Arc<RwLock<ContextImpl>>);

impl std::fmt::Debug for Context {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Context").finish_non_exhaustive()
    }
}

impl std::cmp::PartialEq for Context {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.0, &other.0)
    }
}

impl Default for Context {
    fn default() -> Self {
        let ctx_impl = ContextImpl {
            embed_viewports: true,
            ..Default::default()
        };
        let ctx = Self(Arc::new(RwLock::new(ctx_impl)));

        // Register built-in plugins:
        crate::debug_text::register(&ctx);
        crate::text_selection::LabelSelectionState::register(&ctx);
        crate::DragAndDrop::register(&ctx);

        ctx
    }
}

impl Context {
    /// Do read-only (shared access) transaction on Context
    fn read<R>(&self, reader: impl FnOnce(&ContextImpl) -> R) -> R {
        reader(&self.0.read())
    }

    /// Do read-write (exclusive access) transaction on Context
    fn write<R>(&self, writer: impl FnOnce(&mut ContextImpl) -> R) -> R {
        writer(&mut self.0.write())
    }

    /// Run the ui code for one frame.
    ///
    /// Put your widgets into a [`SidePanel`], [`TopBottomPanel`], [`CentralPanel`], [`Window`] or [`Area`].
    ///
    /// This will modify the internal reference to point to a new generation of [`Context`].
    /// Any old clones of this [`Context`] will refer to the old [`Context`], which will not get new input.
    ///
    /// You can alternatively run [`Self::begin_frame`] and [`Context::end_frame`].
    ///
    /// ```
    /// // One egui context that you keep reusing:
    /// let mut ctx = egui::Context::default();
    ///
    /// // Each frame:
    /// let input = egui::RawInput::default();
    /// let full_output = ctx.run(input, |ctx| {
    ///     egui::CentralPanel::default().show(&ctx, |ui| {
    ///         ui.label("Hello egui!");
    ///     });
    /// });
    /// // handle full_output
    /// ```
    #[must_use]
    pub fn run(&self, new_input: RawInput, run_ui: impl FnOnce(&Self)) -> FullOutput {
        crate::profile_function!();

        self.begin_frame(new_input);
        run_ui(self);
        self.end_frame()
    }

    /// An alternative to calling [`Self::run`].
    ///
    /// ```
    /// // One egui context that you keep reusing:
    /// let mut ctx = egui::Context::default();
    ///
    /// // Each frame:
    /// let input = egui::RawInput::default();
    /// ctx.begin_frame(input);
    ///
    /// egui::CentralPanel::default().show(&ctx, |ui| {
    ///     ui.label("Hello egui!");
    /// });
    ///
    /// let full_output = ctx.end_frame();
    /// // handle full_output
    /// ```
    pub fn begin_frame(&self, new_input: RawInput) {
        crate::profile_function!();
        self.read(|ctx| ctx.plugins.clone()).on_begin_frame(self);
        self.write(|ctx| ctx.begin_frame_mut(new_input));
    }
}

/// ## Borrows parts of [`Context`]
/// These functions all lock the [`Context`].
/// Please see the documentation of [`Context`] for how locking works!
impl Context {
    /// Read-only access to [`InputState`].
    ///
    /// Note that this locks the [`Context`].
    ///
    /// ```
    /// # let mut ctx = egui::Context::default();
    /// ctx.input(|i| {
    ///     // ⚠️ Using `ctx` (even from other `Arc` reference) again here will lead to a deadlock!
    /// });
    ///
    /// if let Some(pos) = ctx.input(|i| i.pointer.hover_pos()) {
    ///     // This is fine!
    /// }
    /// ```
    #[inline]
    pub fn input<R>(&self, reader: impl FnOnce(&InputState) -> R) -> R {
        self.write(move |ctx| reader(&ctx.viewport().input))
    }

    /// This will create a `InputState::default()` if there is no input state for that viewport
    #[inline]
    pub fn input_for<R>(&self, id: ViewportId, reader: impl FnOnce(&InputState) -> R) -> R {
        self.write(move |ctx| reader(&ctx.viewport_for(id).input))
    }

    /// Read-write access to [`InputState`].
    #[inline]
    pub fn input_mut<R>(&self, writer: impl FnOnce(&mut InputState) -> R) -> R {
        self.input_mut_for(self.viewport_id(), writer)
    }

    /// This will create a `InputState::default()` if there is no input state for that viewport
    #[inline]
    pub fn input_mut_for<R>(&self, id: ViewportId, writer: impl FnOnce(&mut InputState) -> R) -> R {
        self.write(move |ctx| writer(&mut ctx.viewport_for(id).input))
    }

    /// Read-only access to [`Memory`].
    #[inline]
    pub fn memory<R>(&self, reader: impl FnOnce(&Memory) -> R) -> R {
        self.read(move |ctx| reader(&ctx.memory))
    }

    /// Read-write access to [`Memory`].
    #[inline]
    pub fn memory_mut<R>(&self, writer: impl FnOnce(&mut Memory) -> R) -> R {
        self.write(move |ctx| writer(&mut ctx.memory))
    }

    /// Read-only access to [`IdTypeMap`], which stores superficial widget state.
    #[inline]
    pub fn data<R>(&self, reader: impl FnOnce(&IdTypeMap) -> R) -> R {
        self.read(move |ctx| reader(&ctx.memory.data))
    }

    /// Read-write access to [`IdTypeMap`], which stores superficial widget state.
    #[inline]
    pub fn data_mut<R>(&self, writer: impl FnOnce(&mut IdTypeMap) -> R) -> R {
        self.write(move |ctx| writer(&mut ctx.memory.data))
    }

    /// Read-write access to [`GraphicLayers`], where painted [`crate::Shape`]s are written to.
    #[inline]
    pub fn graphics_mut<R>(&self, writer: impl FnOnce(&mut GraphicLayers) -> R) -> R {
        self.write(move |ctx| writer(&mut ctx.viewport().graphics))
    }

    /// Read-only access to [`GraphicLayers`], where painted [`crate::Shape`]s are written to.
    #[inline]
    pub fn graphics<R>(&self, reader: impl FnOnce(&GraphicLayers) -> R) -> R {
        self.write(move |ctx| reader(&ctx.viewport().graphics))
    }

    /// Read-only access to [`PlatformOutput`].
    ///
    /// This is what egui outputs each frame.
    ///
    /// ```
    /// # let mut ctx = egui::Context::default();
    /// ctx.output_mut(|o| o.cursor_icon = egui::CursorIcon::Progress);
    /// ```
    #[inline]
    pub fn output<R>(&self, reader: impl FnOnce(&PlatformOutput) -> R) -> R {
        self.write(move |ctx| reader(&ctx.viewport().output))
    }

    /// Read-write access to [`PlatformOutput`].
    #[inline]
    pub fn output_mut<R>(&self, writer: impl FnOnce(&mut PlatformOutput) -> R) -> R {
        self.write(move |ctx| writer(&mut ctx.viewport().output))
    }

    /// Read-only access to [`FrameState`].
    #[inline]
    pub(crate) fn frame_state<R>(&self, reader: impl FnOnce(&FrameState) -> R) -> R {
        self.write(move |ctx| reader(&ctx.viewport().frame_state))
    }

    /// Read-write access to [`FrameState`].
    #[inline]
    pub(crate) fn frame_state_mut<R>(&self, writer: impl FnOnce(&mut FrameState) -> R) -> R {
        self.write(move |ctx| writer(&mut ctx.viewport().frame_state))
    }

    /// Read-only access to [`Fonts`].
    ///
    /// Not valid until first call to [`Context::run()`].
    /// That's because since we don't know the proper `pixels_per_point` until then.
    #[inline]
    pub fn fonts<R>(&self, reader: impl FnOnce(&Fonts) -> R) -> R {
        self.write(move |ctx| {
            let pixels_per_point = ctx.pixels_per_point();
            reader(
                ctx.fonts
                    .get(&pixels_per_point.into())
                    .expect("No fonts available until first call to Context::run()"),
            )
        })
    }

    /// Read-only access to [`Options`].
    #[inline]
    pub fn options<R>(&self, reader: impl FnOnce(&Options) -> R) -> R {
        self.read(move |ctx| reader(&ctx.memory.options))
    }

    /// Read-write access to [`Options`].
    #[inline]
    pub fn options_mut<R>(&self, writer: impl FnOnce(&mut Options) -> R) -> R {
        self.write(move |ctx| writer(&mut ctx.memory.options))
    }

    /// Read-only access to [`TessellationOptions`].
    #[inline]
    pub fn tessellation_options<R>(&self, reader: impl FnOnce(&TessellationOptions) -> R) -> R {
        self.read(move |ctx| reader(&ctx.memory.options.tessellation_options))
    }

    /// Read-write access to [`TessellationOptions`].
    #[inline]
    pub fn tessellation_options_mut<R>(
        &self,
        writer: impl FnOnce(&mut TessellationOptions) -> R,
    ) -> R {
        self.write(move |ctx| writer(&mut ctx.memory.options.tessellation_options))
    }

    /// If the given [`Id`] has been used previously the same frame at at different position,
    /// then an error will be printed on screen.
    ///
    /// This function is already called for all widgets that do any interaction,
    /// but you can call this from widgets that store state but that does not interact.
    ///
    /// The given [`Rect`] should be approximately where the widget will be.
    /// The most important thing is that [`Rect::min`] is approximately correct,
    /// because that's where the warning will be painted. If you don't know what size to pick, just pick [`Vec2::ZERO`].
    pub fn check_for_id_clash(&self, id: Id, new_rect: Rect, what: &str) {
        let prev_rect = self.frame_state_mut(move |state| state.used_ids.insert(id, new_rect));

        if !self.options(|opt| opt.warn_on_id_clash) {
            return;
        }

        let Some(prev_rect) = prev_rect else { return };

        // it is ok to reuse the same ID for e.g. a frame around a widget,
        // or to check for interaction with the same widget twice:
        let is_same_rect = prev_rect.expand(0.1).contains_rect(new_rect)
            || new_rect.expand(0.1).contains_rect(prev_rect);
        if is_same_rect {
            return;
        }

        let show_error = |widget_rect: Rect, text: String| {
            let screen_rect = self.screen_rect();

            let text = format!("🔥 {text}");
            let color = self.style().visuals.error_fg_color;
            let painter = self.debug_painter();
            painter.rect_stroke(widget_rect, 0.0, (1.0, color));

            let below = widget_rect.bottom() + 32.0 < screen_rect.bottom();

            let text_rect = if below {
                painter.debug_text(
                    widget_rect.left_bottom() + vec2(0.0, 2.0),
                    Align2::LEFT_TOP,
                    color,
                    text,
                )
            } else {
                painter.debug_text(
                    widget_rect.left_top() - vec2(0.0, 2.0),
                    Align2::LEFT_BOTTOM,
                    color,
                    text,
                )
            };

            if let Some(pointer_pos) = self.pointer_hover_pos() {
                if text_rect.contains(pointer_pos) {
                    let tooltip_pos = if below {
                        text_rect.left_bottom() + vec2(2.0, 4.0)
                    } else {
                        text_rect.left_top() + vec2(2.0, -4.0)
                    };

                    painter.error(
                        tooltip_pos,
                        format!("Widget is {} this text.\n\n\
                             ID clashes happens when things like Windows or CollapsingHeaders share names,\n\
                             or when things like Plot and Grid:s aren't given unique id_source:s.\n\n\
                             Sometimes the solution is to use ui.push_id.",
                         if below { "above" } else { "below" })
                    );
                }
            }
        };

        let id_str = id.short_debug_format();

        if prev_rect.min.distance(new_rect.min) < 4.0 {
            show_error(new_rect, format!("Double use of {what} ID {id_str}"));
        } else {
            show_error(prev_rect, format!("First use of {what} ID {id_str}"));
            show_error(new_rect, format!("Second use of {what} ID {id_str}"));
        }
    }

    // ---------------------------------------------------------------------

    /// Use `ui.interact` instead
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn interact(
        &self,
        clip_rect: Rect,
        item_spacing: Vec2,
        layer_id: LayerId,
        id: Id,
        rect: Rect,
        sense: Sense,
        enabled: bool,
    ) -> Response {
        let gap = 0.1; // Just to make sure we don't accidentally hover two things at once (a small eps should be sufficient).

        // Make it easier to click things:
        let interact_rect = rect.expand2(
            (0.5 * item_spacing - Vec2::splat(gap))
                .at_least(Vec2::splat(0.0))
                .at_most(Vec2::splat(5.0)),
        );

        // Respect clip rectangle when interacting:
        let interact_rect = clip_rect.intersect(interact_rect);

        let contains_pointer = self.widget_contains_pointer(layer_id, id, sense, interact_rect);

        #[cfg(debug_assertions)]
        if sense.interactive()
            && interact_rect.is_positive()
            && self.style().debug.show_interactive_widgets
        {
            Self::layer_painter(self, LayerId::debug()).rect(
                interact_rect,
                0.0,
                Color32::YELLOW.additive().linear_multiply(0.005),
                Stroke::new(1.0, Color32::YELLOW.additive().linear_multiply(0.05)),
            );
        }

        self.interact_with_hovered(
            layer_id,
            id,
            rect,
            interact_rect,
            sense,
            enabled,
            contains_pointer,
        )
    }

    /// You specify if a thing is hovered, and the function gives a [`Response`].
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn interact_with_hovered(
        &self,
        layer_id: LayerId,
        id: Id,
        rect: Rect,
        interact_rect: Rect,
        sense: Sense,
        enabled: bool,
        contains_pointer: bool,
    ) -> Response {
        // This is the start - we'll fill in the fields below:
        let mut res = Response {
            ctx: self.clone(),
            layer_id,
            id,
            rect,
            sense,
            enabled,
            contains_pointer,
            hovered: contains_pointer && enabled,
            highlighted: self.frame_state(|fs| fs.highlight_this_frame.contains(&id)),
            clicked: Default::default(),
            double_clicked: Default::default(),
            triple_clicked: Default::default(),
            drag_started: false,
            dragged: false,
            drag_released: false,
            is_pointer_button_down_on: false,
            interact_pointer_pos: None,
            changed: false, // must be set by the widget itself
        };

        if !enabled || !sense.focusable || !layer_id.allow_interaction() {
            // Not interested or allowed input:
            self.memory_mut(|mem| mem.surrender_focus(id));
        }

        if sense.interactive() || sense.focusable {
            self.check_for_id_clash(id, rect, "widget");
        }

        #[cfg(feature = "accesskit")]
        if sense.focusable {
            // Make sure anything that can receive focus has an AccessKit node.
            // TODO(mwcampbell): For nodes that are filled from widget info,
            // some information is written to the node twice.
            self.accesskit_node_builder(id, |builder| res.fill_accesskit_node_common(builder));
        }

        let clicked_elsewhere = res.clicked_elsewhere();
        self.write(|ctx| {
            let viewport = ctx.viewports.entry(ctx.viewport_id()).or_default();

            // We need to remember this widget.
            // `widget_contains_pointer` also does this, but in case of e.g. `Response::interact`,
            // that won't be called.
            // We add all widgets here, even non-interactive ones,
            // because we need this list not only for checking for blocking widgets,
            // but also to know when we have reached the widget we are checking for cover.
            viewport.layer_rects_this_frame.insert(
                layer_id,
                WidgetRect {
                    id,
                    rect: interact_rect,
                    sense,
                },
            );

            let input = &viewport.input;
            let memory = &mut ctx.memory;

            if sense.focusable {
                memory.interested_in_focus(id);
            }

            if sense.click
                && memory.has_focus(res.id)
                && (input.key_pressed(Key::Space) || input.key_pressed(Key::Enter))
            {
                // Space/enter works like a primary click for e.g. selected buttons
                res.clicked[PointerButton::Primary as usize] = true;
            }

            #[cfg(feature = "accesskit")]
            if sense.click && input.has_accesskit_action_request(res.id, accesskit::Action::Default)
            {
                res.clicked[PointerButton::Primary as usize] = true;
            }

            if sense.click || sense.drag {
                let interaction = memory.interaction_mut();

                interaction.click_interest |= contains_pointer && sense.click;
                interaction.drag_interest |= contains_pointer && sense.drag;

                res.is_pointer_button_down_on =
                    interaction.click_id == Some(id) || interaction.drag_id == Some(id);

                if sense.click && sense.drag {
                    // This widget is sensitive to both clicks and drags.
                    // When the mouse first is pressed, it could be either,
                    // so we postpone the decision until we know.
                    res.dragged =
                        interaction.drag_id == Some(id) && input.pointer.is_decidedly_dragging();
                    res.drag_started = res.dragged && input.pointer.started_decidedly_dragging;
                } else if sense.drag {
                    // We are just sensitive to drags, so we can mark ourself as dragged right away:
                    res.dragged = interaction.drag_id == Some(id);
                    // res.drag_started will be filled below if applicable
                }

                for pointer_event in &input.pointer.pointer_events {
                    match pointer_event {
                        PointerEvent::Moved(_) => {}

                        PointerEvent::Pressed { .. } => {
                            if contains_pointer {
                                let interaction = memory.interaction_mut();

                                if sense.click && interaction.click_id.is_none() {
                                    // potential start of a click
                                    interaction.click_id = Some(id);
                                    res.is_pointer_button_down_on = true;
                                }

                                // HACK: windows have low priority on dragging.
                                // This is so that if you drag a slider in a window,
                                // the slider will steal the drag away from the window.
                                // This is needed because we do window interaction first (to prevent frame delay),
                                // and then do content layout.
                                if sense.drag
                                    && (interaction.drag_id.is_none() || interaction.drag_is_window)
                                {
                                    // potential start of a drag
                                    interaction.drag_id = Some(id);
                                    interaction.drag_is_window = false;
                                    memory.set_window_interaction(None); // HACK: stop moving windows (if any)

                                    res.is_pointer_button_down_on = true;

                                    // Again, only if we are ONLY sensitive to drags can we decide that this is a drag now.
                                    if sense.click {
                                        res.dragged = false;
                                        res.drag_started = false;
                                    } else {
                                        res.dragged = true;
                                        res.drag_started = true;
                                    }
                                }
                            }
                        }

                        PointerEvent::Released { click, button } => {
                            res.drag_released = res.dragged;
                            res.dragged = false;

                            if sense.click && res.hovered && res.is_pointer_button_down_on {
                                if let Some(click) = click {
                                    let clicked = res.hovered && res.is_pointer_button_down_on;
                                    res.clicked[*button as usize] = clicked;
                                    res.double_clicked[*button as usize] =
                                        clicked && click.is_double();
                                    res.triple_clicked[*button as usize] =
                                        clicked && click.is_triple();
                                }
                            }

                            res.is_pointer_button_down_on = false;
                        }
                    }
                }
            }

            // is_pointer_button_down_on is false when released, but we want interact_pointer_pos
            // to still work.
            let clicked = res.clicked.iter().any(|c| *c);
            let is_interacted_with = res.is_pointer_button_down_on || clicked || res.drag_released;
            if is_interacted_with {
                res.interact_pointer_pos = input.pointer.interact_pos();
            }

            if input.pointer.any_down() && !res.is_pointer_button_down_on {
                // We don't hover widgets while interacting with *other* widgets:
                res.hovered = false;
            }

            if memory.has_focus(res.id) && clicked_elsewhere {
                memory.surrender_focus(id);
            }

            if res.dragged() && !memory.has_focus(res.id) {
                // e.g.: remove focus from a widget when you drag something else
                memory.stop_text_input();
            }
        });

        res
    }

    /// Get a full-screen painter for a new or existing layer
    pub fn layer_painter(&self, layer_id: LayerId) -> Painter {
        let screen_rect = self.screen_rect();
        Painter::new(self.clone(), layer_id, screen_rect)
    }

    /// Paint on top of everything else
    pub fn debug_painter(&self) -> Painter {
        Self::layer_painter(self, LayerId::debug())
    }

    /// Print this text next to the cursor at the end of the frame.
    ///
    /// If you call this multiple times, the text will be appended.
    ///
    /// This only works if compiled with `debug_assertions`.
    ///
    /// ```
    /// # let ctx = egui::Context::default();
    /// # let state = true;
    /// ctx.debug_text(format!("State: {state:?}"));
    /// ```
    ///
    /// This is just a convenience for calling [`crate::debug_text::print`].
    #[track_caller]
    pub fn debug_text(&self, text: impl Into<WidgetText>) {
        crate::debug_text::print(self, text);
    }

    /// What operating system are we running on?
    ///
    /// When compiling natively, this is
    /// figured out from the `target_os`.
    ///
    /// For web, this can be figured out from the user-agent,
    /// and is done so by [`eframe`](https://github.com/emilk/egui/tree/master/crates/eframe).
    pub fn os(&self) -> OperatingSystem {
        self.read(|ctx| ctx.os)
    }

    /// Set the operating system we are running on.
    ///
    /// If you are writing wasm-based integration for egui you
    /// may want to set this based on e.g. the user-agent.
    pub fn set_os(&self, os: OperatingSystem) {
        self.write(|ctx| ctx.os = os);
    }

    /// Set the cursor icon.
    ///
    /// Equivalent to:
    /// ```
    /// # let ctx = egui::Context::default();
    /// ctx.output_mut(|o| o.cursor_icon = egui::CursorIcon::PointingHand);
    /// ```
    pub fn set_cursor_icon(&self, cursor_icon: CursorIcon) {
        self.output_mut(|o| o.cursor_icon = cursor_icon);
    }

    /// Open an URL in a browser.
    ///
    /// Equivalent to:
    /// ```
    /// # let ctx = egui::Context::default();
    /// # let open_url = egui::OpenUrl::same_tab("http://www.example.com");
    /// ctx.output_mut(|o| o.open_url = Some(open_url));
    /// ```
    pub fn open_url(&self, open_url: crate::OpenUrl) {
        self.output_mut(|o| o.open_url = Some(open_url));
    }

    /// Copy the given text to the system clipboard.
    ///
    /// Empty strings are ignored.
    ///
    /// Equivalent to:
    /// ```
    /// # let ctx = egui::Context::default();
    /// ctx.output_mut(|o| o.copied_text = "Copy this".to_owned());
    /// ```
    pub fn copy_text(&self, text: String) {
        self.output_mut(|o| o.copied_text = text);
    }

    /// Format the given shortcut in a human-readable way (e.g. `Ctrl+Shift+X`).
    ///
    /// Can be used to get the text for [`Button::shortcut_text`].
    pub fn format_shortcut(&self, shortcut: &KeyboardShortcut) -> String {
        let os = self.os();

        let is_mac = matches!(os, OperatingSystem::Mac | OperatingSystem::IOS);

        let can_show_symbols = || {
            let ModifierNames {
                alt,
                ctrl,
                shift,
                mac_cmd,
                ..
            } = ModifierNames::SYMBOLS;

            let font_id = TextStyle::Body.resolve(&self.style());
            self.fonts(|f| {
                let mut lock = f.lock();
                let font = lock.fonts.font(&font_id);
                font.has_glyphs(alt)
                    && font.has_glyphs(ctrl)
                    && font.has_glyphs(shift)
                    && font.has_glyphs(mac_cmd)
            })
        };

        if is_mac && can_show_symbols() {
            shortcut.format(&ModifierNames::SYMBOLS, is_mac)
        } else {
            shortcut.format(&ModifierNames::NAMES, is_mac)
        }
    }

    /// The current frame number for the current viewport.
    ///
    /// Starts at zero, and is incremented at the end of [`Self::run`] or by [`Self::end_frame`].
    ///
    /// Between calls to [`Self::run`], this is the frame number of the coming frame.
    pub fn frame_nr(&self) -> u64 {
        self.frame_nr_for(self.viewport_id())
    }

    /// The current frame number.
    ///
    /// Starts at zero, and is incremented at the end of [`Self::run`] or by [`Self::end_frame`].
    ///
    /// Between calls to [`Self::run`], this is the frame number of the coming frame.
    pub fn frame_nr_for(&self, id: ViewportId) -> u64 {
        self.read(|ctx| ctx.viewports.get(&id).map_or(0, |v| v.repaint.frame_nr))
    }

    /// Call this if there is need to repaint the UI, i.e. if you are showing an animation.
    ///
    /// If this is called at least once in a frame, then there will be another frame right after this.
    /// Call as many times as you wish, only one repaint will be issued.
    ///
    /// To request repaint with a delay, use [`Self::request_repaint_after`].
    ///
    /// If called from outside the UI thread, the UI thread will wake up and run,
    /// provided the egui integration has set that up via [`Self::set_request_repaint_callback`]
    /// (this will work on `eframe`).
    ///
    /// This will repaint the current viewport.
    #[track_caller]
    pub fn request_repaint(&self) {
        self.request_repaint_of(self.viewport_id());
    }

    /// Call this if there is need to repaint the UI, i.e. if you are showing an animation.
    ///
    /// If this is called at least once in a frame, then there will be another frame right after this.
    /// Call as many times as you wish, only one repaint will be issued.
    ///
    /// To request repaint with a delay, use [`Self::request_repaint_after_for`].
    ///
    /// If called from outside the UI thread, the UI thread will wake up and run,
    /// provided the egui integration has set that up via [`Self::set_request_repaint_callback`]
    /// (this will work on `eframe`).
    ///
    /// This will repaint the specified viewport.
    #[track_caller]
    pub fn request_repaint_of(&self, id: ViewportId) {
        let cause = RepaintCause::new();
        self.write(|ctx| ctx.request_repaint(id, cause));
    }

    /// Request repaint after at most the specified duration elapses.
    ///
    /// The backend can chose to repaint sooner, for instance if some other code called
    /// this method with a lower duration, or if new events arrived.
    ///
    /// The function can be multiple times, but only the *smallest* duration will be considered.
    /// So, if the function is called two times with `1 second` and `2 seconds`, egui will repaint
    /// after `1 second`
    ///
    /// This is primarily useful for applications who would like to save battery by avoiding wasted
    /// redraws when the app is not in focus. But sometimes the GUI of the app might become stale
    /// and outdated if it is not updated for too long.
    ///
    /// Let's say, something like a stopwatch widget that displays the time in seconds. You would waste
    /// resources repainting multiple times within the same second (when you have no input),
    /// just calculate the difference of duration between current time and next second change,
    /// and call this function, to make sure that you are displaying the latest updated time, but
    /// not wasting resources on needless repaints within the same second.
    ///
    /// ### Quirk:
    /// Duration begins at the next frame. Let's say for example that it's a very inefficient app
    /// and takes 500 milliseconds per frame at 2 fps. The widget / user might want a repaint in
    /// next 500 milliseconds. Now, app takes 1000 ms per frame (1 fps) because the backend event
    /// timeout takes 500 milliseconds AFTER the vsync swap buffer.
    /// So, it's not that we are requesting repaint within X duration. We are rather timing out
    /// during app idle time where we are not receiving any new input events.
    ///
    /// This repaints the current viewport
    #[track_caller]
    pub fn request_repaint_after(&self, duration: Duration) {
        self.request_repaint_after_for(duration, self.viewport_id());
    }

    /// Request repaint after at most the specified duration elapses.
    ///
    /// The backend can chose to repaint sooner, for instance if some other code called
    /// this method with a lower duration, or if new events arrived.
    ///
    /// The function can be multiple times, but only the *smallest* duration will be considered.
    /// So, if the function is called two times with `1 second` and `2 seconds`, egui will repaint
    /// after `1 second`
    ///
    /// This is primarily useful for applications who would like to save battery by avoiding wasted
    /// redraws when the app is not in focus. But sometimes the GUI of the app might become stale
    /// and outdated if it is not updated for too long.
    ///
    /// Let's say, something like a stopwatch widget that displays the time in seconds. You would waste
    /// resources repainting multiple times within the same second (when you have no input),
    /// just calculate the difference of duration between current time and next second change,
    /// and call this function, to make sure that you are displaying the latest updated time, but
    /// not wasting resources on needless repaints within the same second.
    ///
    /// ### Quirk:
    /// Duration begins at the next frame. Let's say for example that it's a very inefficient app
    /// and takes 500 milliseconds per frame at 2 fps. The widget / user might want a repaint in
    /// next 500 milliseconds. Now, app takes 1000 ms per frame (1 fps) because the backend event
    /// timeout takes 500 milliseconds AFTER the vsync swap buffer.
    /// So, it's not that we are requesting repaint within X duration. We are rather timing out
    /// during app idle time where we are not receiving any new input events.
    ///
    /// This repaints the specified viewport
    #[track_caller]
    pub fn request_repaint_after_for(&self, duration: Duration, id: ViewportId) {
        let cause = RepaintCause::new();
        self.write(|ctx| ctx.request_repaint_after(duration, id, cause));
    }

    /// Was a repaint requested last frame for the current viewport?
    #[must_use]
    pub fn requested_repaint_last_frame(&self) -> bool {
        self.requested_repaint_last_frame_for(&self.viewport_id())
    }

    /// Was a repaint requested last frame for the given viewport?
    #[must_use]
    pub fn requested_repaint_last_frame_for(&self, viewport_id: &ViewportId) -> bool {
        self.read(|ctx| ctx.requested_immediate_repaint_prev_frame(viewport_id))
    }

    /// Has a repaint been requested for the current viewport?
    #[must_use]
    pub fn has_requested_repaint(&self) -> bool {
        self.has_requested_repaint_for(&self.viewport_id())
    }

    /// Has a repaint been requested for the given viewport?
    #[must_use]
    pub fn has_requested_repaint_for(&self, viewport_id: &ViewportId) -> bool {
        self.read(|ctx| ctx.has_requested_repaint(viewport_id))
    }

    /// Why are we repainting?
    ///
    /// This can be helpful in debugging why egui is constantly repainting.
    pub fn repaint_causes(&self) -> Vec<RepaintCause> {
        self.read(|ctx| {
            ctx.viewports
                .get(&ctx.viewport_id())
                .map(|v| v.repaint.causes.clone())
        })
        .unwrap_or_default()
    }

    /// For integrations: this callback will be called when an egui user calls [`Self::request_repaint`] or [`Self::request_repaint_after`].
    ///
    /// This lets you wake up a sleeping UI thread.
    ///
    /// Note that only one callback can be set. Any new call overrides the previous callback.
    pub fn set_request_repaint_callback(
        &self,
        callback: impl Fn(RequestRepaintInfo) + Send + Sync + 'static,
    ) {
        let callback = Box::new(callback);
        self.write(|ctx| ctx.request_repaint_callback = Some(callback));
    }
}

/// Callbacks
impl Context {
    /// Call the given callback at the start of each frame
    /// of each viewport.
    ///
    /// This can be used for egui _plugins_.
    /// See [`crate::debug_text`] for an example.
    pub fn on_begin_frame(&self, debug_name: &'static str, cb: ContextCallback) {
        let named_cb = NamedContextCallback {
            debug_name,
            callback: cb,
        };
        self.write(|ctx| ctx.plugins.on_begin_frame.push(named_cb));
    }

    /// Call the given callback at the end of each frame
    /// of each viewport.
    ///
    /// This can be used for egui _plugins_.
    /// See [`crate::debug_text`] for an example.
    pub fn on_end_frame(&self, debug_name: &'static str, cb: ContextCallback) {
        let named_cb = NamedContextCallback {
            debug_name,
            callback: cb,
        };
        self.write(|ctx| ctx.plugins.on_end_frame.push(named_cb));
    }
}

impl Context {
    /// Tell `egui` which fonts to use.
    ///
    /// The default `egui` fonts only support latin and cyrillic alphabets,
    /// but you can call this to install additional fonts that support e.g. korean characters.
    ///
    /// The new fonts will become active at the start of the next frame.
    pub fn set_fonts(&self, font_definitions: FontDefinitions) {
        crate::profile_function!();

        let pixels_per_point = self.pixels_per_point();

        let mut update_fonts = true;

        self.read(|ctx| {
            if let Some(current_fonts) = ctx.fonts.get(&pixels_per_point.into()) {
                // NOTE: this comparison is expensive since it checks TTF data for equality
                if current_fonts.lock().fonts.definitions() == &font_definitions {
                    update_fonts = false; // no need to update
                }
            }
        });

        if update_fonts {
            self.memory_mut(|mem| mem.new_font_definitions = Some(font_definitions));
        }
    }

    /// The [`Style`] used by all subsequent windows, panels etc.
    pub fn style(&self) -> Arc<Style> {
        self.options(|opt| opt.style.clone())
    }

    /// Mutate the [`Style`] used by all subsequent windows, panels etc.
    ///
    /// Example:
    /// ```
    /// # let mut ctx = egui::Context::default();
    /// ctx.style_mut(|style| {
    ///     style.spacing.item_spacing = egui::vec2(10.0, 20.0);
    /// });
    /// ```
    pub fn style_mut(&self, mutate_style: impl FnOnce(&mut Style)) {
        self.options_mut(|opt| mutate_style(std::sync::Arc::make_mut(&mut opt.style)));
    }

    /// The [`Style`] used by all new windows, panels etc.
    ///
    /// You can also change this using [`Self::style_mut]`
    ///
    /// You can use [`Ui::style_mut`] to change the style of a single [`Ui`].
    pub fn set_style(&self, style: impl Into<Arc<Style>>) {
        self.options_mut(|opt| opt.style = style.into());
    }

    /// The [`Visuals`] used by all subsequent windows, panels etc.
    ///
    /// You can also use [`Ui::visuals_mut`] to change the visuals of a single [`Ui`].
    ///
    /// Example:
    /// ```
    /// # let mut ctx = egui::Context::default();
    /// ctx.set_visuals(egui::Visuals::light()); // Switch to light mode
    /// ```
    pub fn set_visuals(&self, visuals: crate::Visuals) {
        self.options_mut(|opt| std::sync::Arc::make_mut(&mut opt.style).visuals = visuals);
    }

    /// The number of physical pixels for each logical point.
    ///
    /// This is calculated as [`Self::zoom_factor`] * [`Self::native_pixels_per_point`]
    #[inline(always)]
    pub fn pixels_per_point(&self) -> f32 {
        self.input(|i| i.pixels_per_point)
    }

    /// Set the number of physical pixels for each logical point.
    /// Will become active at the start of the next frame.
    ///
    /// This will actually translate to a call to [`Self::set_zoom_factor`].
    pub fn set_pixels_per_point(&self, pixels_per_point: f32) {
        if pixels_per_point != self.pixels_per_point() {
            self.set_zoom_factor(pixels_per_point / self.native_pixels_per_point().unwrap_or(1.0));
        }
    }

    /// The number of physical pixels for each logical point on this monitor.
    ///
    /// This is given as input to egui via [`ViewportInfo::native_pixels_per_point`]
    /// and cannot be changed.
    #[inline(always)]
    pub fn native_pixels_per_point(&self) -> Option<f32> {
        self.input(|i| i.viewport().native_pixels_per_point)
    }

    /// Global zoom factor of the UI.
    ///
    /// This is used to calculate the `pixels_per_point`
    /// for the UI as `pixels_per_point = zoom_fator * native_pixels_per_point`.
    ///
    /// The default is 1.0.
    /// Make larger to make everything larger.
    #[inline(always)]
    pub fn zoom_factor(&self) -> f32 {
        self.options(|o| o.zoom_factor)
    }

    /// Sets zoom factor of the UI.
    /// Will become active at the start of the next frame.
    ///
    /// Note that calling this will not update [`Self::zoom_factor`] until the end of the frame.
    ///
    /// This is used to calculate the `pixels_per_point`
    /// for the UI as `pixels_per_point = zoom_fator * native_pixels_per_point`.
    ///
    /// The default is 1.0.
    /// Make larger to make everything larger.
    ///
    /// It is better to call this than modifying
    /// [`Options::zoom_factor`].
    #[inline(always)]
    pub fn set_zoom_factor(&self, zoom_factor: f32) {
        let cause = RepaintCause::new();
        self.write(|ctx| {
            if ctx.memory.options.zoom_factor != zoom_factor {
                ctx.new_zoom_factor = Some(zoom_factor);
                for viewport_id in ctx.all_viewport_ids() {
                    ctx.request_repaint(viewport_id, cause.clone());
                }
            }
        });
    }

    /// Useful for pixel-perfect rendering
    #[inline]
    pub(crate) fn round_to_pixel(&self, point: f32) -> f32 {
        let pixels_per_point = self.pixels_per_point();
        (point * pixels_per_point).round() / pixels_per_point
    }

    /// Useful for pixel-perfect rendering
    #[inline]
    pub(crate) fn round_pos_to_pixels(&self, pos: Pos2) -> Pos2 {
        pos2(self.round_to_pixel(pos.x), self.round_to_pixel(pos.y))
    }

    /// Useful for pixel-perfect rendering
    #[inline]
    pub(crate) fn round_vec_to_pixels(&self, vec: Vec2) -> Vec2 {
        vec2(self.round_to_pixel(vec.x), self.round_to_pixel(vec.y))
    }

    /// Useful for pixel-perfect rendering
    #[inline]
    pub(crate) fn round_rect_to_pixels(&self, rect: Rect) -> Rect {
        Rect {
            min: self.round_pos_to_pixels(rect.min),
            max: self.round_pos_to_pixels(rect.max),
        }
    }

    /// Allocate a texture.
    ///
    /// This is for advanced users.
    /// Most users should use [`crate::Ui::image`] or [`Self::try_load_texture`]
    /// instead.
    ///
    /// In order to display an image you must convert it to a texture using this function.
    /// The function will hand over the image data to the egui backend, which will
    /// upload it to the GPU.
    ///
    /// ⚠️ Make sure to only call this ONCE for each image, i.e. NOT in your main GUI code.
    /// The call is NOT immediate safe.
    ///
    /// The given name can be useful for later debugging, and will be visible if you call [`Self::texture_ui`].
    ///
    /// For how to load an image, see [`ImageData`] and [`ColorImage::from_rgba_unmultiplied`].
    ///
    /// ```
    /// struct MyImage {
    ///     texture: Option<egui::TextureHandle>,
    /// }
    ///
    /// impl MyImage {
    ///     fn ui(&mut self, ui: &mut egui::Ui) {
    ///         let texture: &egui::TextureHandle = self.texture.get_or_insert_with(|| {
    ///             // Load the texture only once.
    ///             ui.ctx().load_texture(
    ///                 "my-image",
    ///                 egui::ColorImage::example(),
    ///                 Default::default()
    ///             )
    ///         });
    ///
    ///         // Show the image:
    ///         ui.image((texture.id(), texture.size_vec2()));
    ///     }
    /// }
    /// ```
    ///
    /// See also [`crate::ImageData`], [`crate::Ui::image`] and [`crate::Image`].
    pub fn load_texture(
        &self,
        name: impl Into<String>,
        image: impl Into<ImageData>,
        options: TextureOptions,
    ) -> TextureHandle {
        let name = name.into();
        let image = image.into();
        let max_texture_side = self.input(|i| i.max_texture_side);
        crate::egui_assert!(
            image.width() <= max_texture_side && image.height() <= max_texture_side,
            "Texture {:?} has size {}x{}, but the maximum texture side is {}",
            name,
            image.width(),
            image.height(),
            max_texture_side
        );
        let tex_mngr = self.tex_manager();
        let tex_id = tex_mngr.write().alloc(name, image, options);
        TextureHandle::new(tex_mngr, tex_id)
    }

    /// Low-level texture manager.
    ///
    /// In general it is easier to use [`Self::load_texture`] and [`TextureHandle`].
    ///
    /// You can show stats about the allocated textures using [`Self::texture_ui`].
    pub fn tex_manager(&self) -> Arc<RwLock<epaint::textures::TextureManager>> {
        self.read(|ctx| ctx.tex_manager.0.clone())
    }

    // ---------------------------------------------------------------------

    /// Constrain the position of a window/area so it fits within the provided boundary.
    ///
    /// If area is `None`, will constrain to [`Self::available_rect`].
    pub(crate) fn constrain_window_rect_to_area(&self, window: Rect, area: Option<Rect>) -> Rect {
        let mut area = area.unwrap_or_else(|| self.available_rect());

        if window.width() > area.width() {
            // Allow overlapping side bars.
            // This is important for small screens, e.g. mobiles running the web demo.
            let screen_rect = self.screen_rect();
            (area.min.x, area.max.x) = (screen_rect.min.x, screen_rect.max.x);
        }
        if window.height() > area.height() {
            // Allow overlapping top/bottom bars:
            let screen_rect = self.screen_rect();
            (area.min.y, area.max.y) = (screen_rect.min.y, screen_rect.max.y);
        }

        let mut pos = window.min;

        // Constrain to screen, unless window is too large to fit:
        let margin_x = (window.width() - area.width()).at_least(0.0);
        let margin_y = (window.height() - area.height()).at_least(0.0);

        pos.x = pos.x.at_most(area.right() + margin_x - window.width()); // move left if needed
        pos.x = pos.x.at_least(area.left() - margin_x); // move right if needed
        pos.y = pos.y.at_most(area.bottom() + margin_y - window.height()); // move right if needed
        pos.y = pos.y.at_least(area.top() - margin_y); // move down if needed

        pos = self.round_pos_to_pixels(pos);

        Rect::from_min_size(pos, window.size())
    }
}

impl Context {
    /// Call at the end of each frame.
    #[must_use]
    pub fn end_frame(&self) -> FullOutput {
        crate::profile_function!();

        if self.options(|o| o.zoom_with_keyboard) {
            crate::gui_zoom::zoom_with_keyboard(self);
        }

        self.read(|ctx| ctx.plugins.clone()).on_end_frame(self);

        self.write(|ctx| ctx.end_frame())
    }
}

impl ContextImpl {
    fn end_frame(&mut self) -> FullOutput {
        let ended_viewport_id = self.viewport_id();
        let viewport = self.viewports.entry(ended_viewport_id).or_default();
        let pixels_per_point = viewport.input.pixels_per_point;

        viewport.repaint.frame_nr += 1;

        self.memory.end_frame(&viewport.frame_state.used_ids);

        if let Some(fonts) = self.fonts.get(&pixels_per_point.into()) {
            let tex_mngr = &mut self.tex_manager.0.write();
            if let Some(font_image_delta) = fonts.font_image_delta() {
                // A partial font atlas update, e.g. a new glyph has been entered.
                tex_mngr.set(TextureId::default(), font_image_delta);
            }

            if 1 < self.fonts.len() {
                // We have multiple different `pixels_per_point`,
                // e.g. because we have many viewports spread across
                // monitors with different DPI scaling.
                // All viewports share the same texture namespace and renderer,
                // so the all use `TextureId::default()` for the font texture.
                // This is a problem.
                // We solve this with a hack: we always upload the full font atlas
                // every frame, for all viewports.
                // This ensures it is up-to-date, solving
                // https://github.com/emilk/egui/issues/3664
                // at the cost of a lot of performance.
                // (This will override any smaller delta that was uploaded above.)
                crate::profile_scope!("full_font_atlas_update");
                let full_delta = ImageDelta::full(fonts.image(), TextureAtlas::texture_options());
                tex_mngr.set(TextureId::default(), full_delta);
            }
        }

        // Inform the backend of all textures that have been updated (including font atlas).
        let textures_delta = self.tex_manager.0.write().take_delta();

        #[cfg_attr(not(feature = "accesskit"), allow(unused_mut))]
        let mut platform_output: PlatformOutput = std::mem::take(&mut viewport.output);

        #[cfg(feature = "accesskit")]
        {
            crate::profile_scope!("accesskit");
            let state = viewport.frame_state.accesskit_state.take();
            if let Some(state) = state {
                let root_id = crate::accesskit_root_id().accesskit_id();
                let nodes = {
                    state
                        .node_builders
                        .into_iter()
                        .map(|(id, builder)| {
                            (
                                id.accesskit_id(),
                                builder.build(&mut self.accesskit_node_classes),
                            )
                        })
                        .collect()
                };
                let focus_id = self.memory.focus().map_or(root_id, |id| id.accesskit_id());
                platform_output.accesskit_update = Some(accesskit::TreeUpdate {
                    nodes,
                    tree: Some(accesskit::Tree::new(root_id)),
                    focus: focus_id,
                });
            }
        }

        let shapes = viewport.graphics.drain(self.memory.areas().order());

        let mut repaint_needed = false;

        {
            if self.memory.options.repaint_on_widget_change {
                crate::profile_function!("compare-widget-rects");
                if viewport.layer_rects_prev_frame != viewport.layer_rects_this_frame {
                    repaint_needed = true; // Some widget has moved
                }
            }

            std::mem::swap(
                &mut viewport.layer_rects_prev_frame,
                &mut viewport.layer_rects_this_frame,
            );
            viewport.layer_rects_this_frame.clear();
        }

        if repaint_needed || viewport.input.wants_repaint() {
            self.request_repaint(ended_viewport_id, RepaintCause::new());
        }

        //  -------------------

        let all_viewport_ids = self.all_viewport_ids();

        self.last_viewport = ended_viewport_id;

        self.viewports.retain(|&id, viewport| {
            let parent = *self.viewport_parents.entry(id).or_default();

            if !all_viewport_ids.contains(&parent) {
                #[cfg(feature = "log")]
                log::debug!(
                    "Removing viewport {:?} ({:?}): the parent is gone",
                    id,
                    viewport.builder.title
                );

                return false;
            }

            let is_our_child = parent == ended_viewport_id && id != ViewportId::ROOT;
            if is_our_child {
                if !viewport.used {
                    #[cfg(feature = "log")]
                    log::debug!(
                        "Removing viewport {:?} ({:?}): it was never used this frame",
                        id,
                        viewport.builder.title
                    );

                    return false; // Only keep children that have been updated this frame
                }

                viewport.used = false; // reset so we can check again next frame
            }

            true
        });

        // If we are an immediate viewport, this will resume the previous viewport.
        self.viewport_stack.pop();

        // The last viewport is not necessarily the root viewport,
        // just the top _immediate_ viewport.
        let is_last = self.viewport_stack.is_empty();

        let viewport_output = self
            .viewports
            .iter_mut()
            .map(|(&id, viewport)| {
                let parent = *self.viewport_parents.entry(id).or_default();
                let commands = if is_last {
                    // Let the primary immediate viewport handle the commands of its children too.
                    // This can make things easier for the backend, as otherwise we may get commands
                    // that affect a viewport while its egui logic is running.
                    std::mem::take(&mut viewport.commands)
                } else {
                    vec![]
                };

                (
                    id,
                    ViewportOutput {
                        parent,
                        class: viewport.class,
                        builder: viewport.builder.clone(),
                        viewport_ui_cb: viewport.viewport_ui_cb.clone(),
                        commands,
                        repaint_delay: viewport.repaint.repaint_delay,
                    },
                )
            })
            .collect();

        if is_last {
            // Remove dead viewports:
            self.viewports.retain(|id, _| all_viewport_ids.contains(id));
            self.viewport_parents
                .retain(|id, _| all_viewport_ids.contains(id));
        } else {
            let viewport_id = self.viewport_id();
            self.memory.set_viewport_id(viewport_id);
        }

        let active_pixels_per_point: std::collections::BTreeSet<OrderedFloat<f32>> = self
            .viewports
            .values()
            .map(|v| v.input.pixels_per_point.into())
            .collect();
        self.fonts.retain(|pixels_per_point, _| {
            if active_pixels_per_point.contains(pixels_per_point) {
                true
            } else {
                #[cfg(feature = "log")]
                log::trace!(
                    "Freeing Fonts with pixels_per_point={} because it is no longer needed",
                    pixels_per_point.into_inner()
                );
                false
            }
        });

        FullOutput {
            platform_output,
            textures_delta,
            shapes,
            pixels_per_point,
            viewport_output,
        }
    }
}

impl Context {
    /// Tessellate the given shapes into triangle meshes.
    ///
    /// `pixels_per_point` is used for feathering (anti-aliasing).
    /// For this you can use [`FullOutput::pixels_per_point`], [`Self::pixels_per_point`],
    /// or whatever is appropriate for your viewport.
    pub fn tessellate(
        &self,
        shapes: Vec<ClippedShape>,
        pixels_per_point: f32,
    ) -> Vec<ClippedPrimitive> {
        crate::profile_function!();

        // A tempting optimization is to reuse the tessellation from last frame if the
        // shapes are the same, but just comparing the shapes takes about 50% of the time
        // it takes to tessellate them, so it is not a worth optimization.

        self.write(|ctx| {
            let tessellation_options = ctx.memory.options.tessellation_options;
            let texture_atlas = ctx
                .fonts
                .get(&pixels_per_point.into())
                .expect("tessellate called before first call to Context::run()")
                .texture_atlas();
            let (font_tex_size, prepared_discs) = {
                let atlas = texture_atlas.lock();
                (atlas.size(), atlas.prepared_discs())
            };

            let paint_stats = PaintStats::from_shapes(&shapes);
            let clipped_primitives = {
                crate::profile_scope!("tessellator::tessellate_shapes");
                tessellator::Tessellator::new(
                    pixels_per_point,
                    tessellation_options,
                    font_tex_size,
                    prepared_discs,
                )
                .tessellate_shapes(shapes)
            };
            ctx.paint_stats = paint_stats.with_clipped_primitives(&clipped_primitives);
            clipped_primitives
        })
    }

    // ---------------------------------------------------------------------

    /// Position and size of the egui area.
    pub fn screen_rect(&self) -> Rect {
        self.input(|i| i.screen_rect())
    }

    /// How much space is still available after panels has been added.
    ///
    /// This is the "background" area, what egui doesn't cover with panels (but may cover with windows).
    /// This is also the area to which windows are constrained.
    pub fn available_rect(&self) -> Rect {
        self.frame_state(|s| s.available_rect())
    }

    /// How much space is used by panels and windows.
    pub fn used_rect(&self) -> Rect {
        self.write(|ctx| {
            let mut used = ctx.viewport().frame_state.used_by_panels;
            for window in ctx.memory.areas().visible_windows() {
                used = used.union(window.rect());
            }
            used
        })
    }

    /// How much space is used by panels and windows.
    ///
    /// You can shrink your egui area to this size and still fit all egui components.
    pub fn used_size(&self) -> Vec2 {
        self.used_rect().max - Pos2::ZERO
    }

    // ---------------------------------------------------------------------

    /// Is the pointer (mouse/touch) over any egui area?
    pub fn is_pointer_over_area(&self) -> bool {
        let pointer_pos = self.input(|i| i.pointer.interact_pos());
        if let Some(pointer_pos) = pointer_pos {
            if let Some(layer) = self.layer_id_at(pointer_pos) {
                if layer.order == Order::Background {
                    !self.frame_state(|state| state.unused_rect.contains(pointer_pos))
                } else {
                    true
                }
            } else {
                false
            }
        } else {
            false
        }
    }

    /// True if egui is currently interested in the pointer (mouse or touch).
    ///
    /// Could be the pointer is hovering over a [`Window`] or the user is dragging a widget.
    /// If `false`, the pointer is outside of any egui area and so
    /// you may be interested in what it is doing (e.g. controlling your game).
    /// Returns `false` if a drag started outside of egui and then moved over an egui area.
    pub fn wants_pointer_input(&self) -> bool {
        self.is_using_pointer()
            || (self.is_pointer_over_area() && !self.input(|i| i.pointer.any_down()))
    }

    /// Is egui currently using the pointer position (e.g. dragging a slider)?
    ///
    /// NOTE: this will return `false` if the pointer is just hovering over an egui area.
    pub fn is_using_pointer(&self) -> bool {
        self.memory(|m| m.interaction().is_using_pointer())
    }

    /// If `true`, egui is currently listening on text input (e.g. typing text in a [`TextEdit`]).
    pub fn wants_keyboard_input(&self) -> bool {
        self.memory(|m| m.interaction().focus.focused().is_some())
    }

    /// Highlight this widget, to make it look like it is hovered, even if it isn't.
    ///
    /// The highlight takes on frame to take effect if you call this after the widget has been fully rendered.
    ///
    /// See also [`Response::highlight`].
    pub fn highlight_widget(&self, id: Id) {
        self.frame_state_mut(|fs| fs.highlight_next_frame.insert(id));
    }

    /// Is an egui context menu open?
    pub fn is_context_menu_open(&self) -> bool {
        self.data(|d| {
            d.get_temp::<crate::menu::BarState>(menu::CONTEXT_MENU_ID_STR.into())
                .map_or(false, |state| state.has_root())
        })
    }
}

// Ergonomic methods to forward some calls often used in 'if let' without holding the borrow
impl Context {
    /// Latest reported pointer position.
    ///
    /// When tapping a touch screen, this will be `None`.
    #[inline(always)]
    pub fn pointer_latest_pos(&self) -> Option<Pos2> {
        self.input(|i| i.pointer.latest_pos())
    }

    /// If it is a good idea to show a tooltip, where is pointer?
    #[inline(always)]
    pub fn pointer_hover_pos(&self) -> Option<Pos2> {
        self.input(|i| i.pointer.hover_pos())
    }

    /// If you detect a click or drag and wants to know where it happened, use this.
    ///
    /// Latest position of the mouse, but ignoring any [`Event::PointerGone`]
    /// if there were interactions this frame.
    /// When tapping a touch screen, this will be the location of the touch.
    #[inline(always)]
    pub fn pointer_interact_pos(&self) -> Option<Pos2> {
        self.input(|i| i.pointer.interact_pos())
    }

    /// Calls [`InputState::multi_touch`].
    pub fn multi_touch(&self) -> Option<MultiTouchInfo> {
        self.input(|i| i.multi_touch())
    }
}

impl Context {
    /// Move all the graphics at the given layer.
    ///
    /// Can be used to implement drag-and-drop (see relevant demo).
    pub fn translate_layer(&self, layer_id: LayerId, delta: Vec2) {
        if delta != Vec2::ZERO {
            self.graphics_mut(|g| g.entry(layer_id).translate(delta));
        }
    }

    /// Top-most layer at the given position.
    pub fn layer_id_at(&self, pos: Pos2) -> Option<LayerId> {
        self.memory(|mem| {
            mem.layer_id_at(pos, mem.options.style.interaction.resize_grab_radius_side)
        })
    }

    /// Moves the given area to the top in its [`Order`].
    ///
    /// [`Area`]:s and [`Window`]:s also do this automatically when being clicked on or interacted with.
    pub fn move_to_top(&self, layer_id: LayerId) {
        self.memory_mut(|mem| mem.areas_mut().move_to_top(layer_id));
    }

    /// Retrieve the [`LayerId`] of the top level windows.
    pub fn top_layer_id(&self) -> Option<LayerId> {
        self.memory(|mem| mem.areas().top_layer_id(Order::Middle))
    }

    /// Does the given rectangle contain the mouse pointer?
    ///
    /// Will return false if some other area is covering the given layer.
    ///
    /// The given rectangle is assumed to have been clipped by its parent clip rect.
    ///
    /// See also [`Response::contains_pointer`].
    pub fn rect_contains_pointer(&self, layer_id: LayerId, rect: Rect) -> bool {
        if !rect.is_positive() {
            return false;
        }

        let pointer_pos = self.input(|i| i.pointer.interact_pos());
        let Some(pointer_pos) = pointer_pos else {
            return false;
        };

        if !rect.contains(pointer_pos) {
            return false;
        }

        if self.layer_id_at(pointer_pos) != Some(layer_id) {
            return false;
        }

        true
    }

    /// Does the given widget contain the mouse pointer?
    ///
    /// Will return false if some other area is covering the given layer.
    ///
    /// If another widget is covering us and is listening for the same input (click and/or drag),
    /// this will return false.
    ///
    /// The given rectangle is assumed to have been clipped by its parent clip rect.
    ///
    /// See also [`Response::contains_pointer`].
    pub fn widget_contains_pointer(
        &self,
        layer_id: LayerId,
        id: Id,
        sense: Sense,
        interact_rect: Rect,
    ) -> bool {
        if !interact_rect.is_positive() {
            return false; // don't even remember this widget
        }

        let contains_pointer = self.rect_contains_pointer(layer_id, interact_rect);

        let mut blocking_widget = None;

        self.write(|ctx| {
            let viewport = ctx.viewport();

            // We add all widgets here, even non-interactive ones,
            // because we need this list not only for checking for blocking widgets,
            // but also to know when we have reached the widget we are checking for cover.
            viewport.layer_rects_this_frame.insert(
                layer_id,
                WidgetRect {
                    id,
                    rect: interact_rect,
                    sense,
                },
            );

            // Check if any other widget is covering us.
            // Whichever widget is added LAST (=on top) gets the input.
            if contains_pointer {
                let pointer_pos = viewport.input.pointer.interact_pos();
                if let Some(pointer_pos) = pointer_pos {
                    if let Some(rects) = viewport.layer_rects_prev_frame.by_layer.get(&layer_id) {
                        // Iterate backwards, i.e. topmost widgets first.
                        for blocking in rects.iter().rev() {
                            if blocking.id == id {
                                // We've checked all widgets there were added after this one last frame,
                                // which means there are no widgets covering us.
                                break;
                            }
                            if !blocking.rect.contains(pointer_pos) {
                                continue;
                            }
                            if sense.interactive() && !blocking.sense.interactive() {
                                // Only interactive widgets can block other interactive widgets.
                                continue;
                            }

                            // The `prev` widget is covering us - do we care?
                            // We don't want a click-only button to block drag-events to a `ScrollArea`:

                            let sense_only_drags = sense.drag && !sense.click;
                            if sense_only_drags && !blocking.sense.drag {
                                continue;
                            }
                            let sense_only_clicks = sense.click && !sense.drag;
                            if sense_only_clicks && !blocking.sense.click {
                                continue;
                            }

                            if blocking.sense.interactive() {
                                // Another widget is covering us at the pointer position
                                blocking_widget = Some(blocking.rect);
                                break;
                            }
                        }
                    }
                }
            }
        });

        #[cfg(debug_assertions)]
        if let Some(blocking_rect) = blocking_widget {
            if sense.interactive() && self.memory(|m| m.options.style.debug.show_blocking_widget) {
                Self::layer_painter(self, LayerId::debug()).debug_rect(
                    interact_rect,
                    Color32::GREEN,
                    "Covered",
                );
                Self::layer_painter(self, LayerId::debug()).debug_rect(
                    blocking_rect,
                    Color32::LIGHT_BLUE,
                    "On top",
                );
            }
        }

        contains_pointer && blocking_widget.is_none()
    }

    // ---------------------------------------------------------------------

    /// Whether or not to debug widget layout on hover.
    #[cfg(debug_assertions)]
    pub fn debug_on_hover(&self) -> bool {
        self.options(|opt| opt.style.debug.debug_on_hover)
    }

    /// Turn on/off whether or not to debug widget layout on hover.
    #[cfg(debug_assertions)]
    pub fn set_debug_on_hover(&self, debug_on_hover: bool) {
        self.style_mut(|style| style.debug.debug_on_hover = debug_on_hover);
    }
}

/// ## Animation
impl Context {
    /// Returns a value in the range [0, 1], to indicate "how on" this thing is.
    ///
    /// The first time called it will return `if value { 1.0 } else { 0.0 }`
    /// Calling this with `value = true` will always yield a number larger than zero, quickly going towards one.
    /// Calling this with `value = false` will always yield a number less than one, quickly going towards zero.
    ///
    /// The function will call [`Self::request_repaint()`] when appropriate.
    ///
    /// The animation time is taken from [`Style::animation_time`].
    #[track_caller] // To track repaint cause
    pub fn animate_bool(&self, id: Id, value: bool) -> f32 {
        let animation_time = self.style().animation_time;
        self.animate_bool_with_time(id, value, animation_time)
    }

    /// Like [`Self::animate_bool`] but allows you to control the animation time.
    #[track_caller] // To track repaint cause
    pub fn animate_bool_with_time(&self, id: Id, target_value: bool, animation_time: f32) -> f32 {
        let animated_value = self.write(|ctx| {
            ctx.animation_manager.animate_bool(
                &ctx.viewports.entry(ctx.viewport_id()).or_default().input,
                animation_time,
                id,
                target_value,
            )
        });
        let animation_in_progress = 0.0 < animated_value && animated_value < 1.0;
        if animation_in_progress {
            self.request_repaint();
        }
        animated_value
    }

    /// Smoothly animate an `f32` value.
    ///
    /// At the first call the value is written to memory.
    /// When it is called with a new value, it linearly interpolates to it in the given time.
    #[track_caller] // To track repaint cause
    pub fn animate_value_with_time(&self, id: Id, target_value: f32, animation_time: f32) -> f32 {
        let animated_value = self.write(|ctx| {
            ctx.animation_manager.animate_value(
                &ctx.viewports.entry(ctx.viewport_id()).or_default().input,
                animation_time,
                id,
                target_value,
            )
        });
        let animation_in_progress = animated_value != target_value;
        if animation_in_progress {
            self.request_repaint();
        }

        animated_value
    }

    /// Clear memory of any animations.
    pub fn clear_animations(&self) {
        self.write(|ctx| ctx.animation_manager = Default::default());
    }
}

impl Context {
    /// Show a ui for settings (style and tessellation options).
    pub fn settings_ui(&self, ui: &mut Ui) {
        let prev_options = self.options(|o| o.clone());
        let mut options = prev_options.clone();

        options.ui(ui);

        if options != prev_options {
            self.options_mut(move |o| *o = options);
        }
    }

    /// Show the state of egui, including its input and output.
    pub fn inspection_ui(&self, ui: &mut Ui) {
        use crate::containers::*;

        ui.label(format!("Is using pointer: {}", self.is_using_pointer()))
            .on_hover_text(
                "Is egui currently using the pointer actively (e.g. dragging a slider)?",
            );
        ui.label(format!("Wants pointer input: {}", self.wants_pointer_input()))
            .on_hover_text("Is egui currently interested in the location of the pointer (either because it is in use, or because it is hovering over a window).");
        ui.label(format!(
            "Wants keyboard input: {}",
            self.wants_keyboard_input()
        ))
        .on_hover_text("Is egui currently listening for text input?");
        ui.label(format!(
            "Keyboard focus widget: {}",
            self.memory(|m| m.interaction().focus.focused())
                .as_ref()
                .map(Id::short_debug_format)
                .unwrap_or_default()
        ))
        .on_hover_text("Is egui currently listening for text input?");

        let pointer_pos = self
            .pointer_hover_pos()
            .map_or_else(String::new, |pos| format!("{pos:?}"));
        ui.label(format!("Pointer pos: {pointer_pos}"));

        let top_layer = self
            .pointer_hover_pos()
            .and_then(|pos| self.layer_id_at(pos))
            .map_or_else(String::new, |layer| layer.short_debug_format());
        ui.label(format!("Top layer under mouse: {top_layer}"));

        ui.add_space(16.0);

        ui.label(format!(
            "There are {} text galleys in the layout cache",
            self.fonts(|f| f.num_galleys_in_cache())
        ))
        .on_hover_text("This is approximately the number of text strings on screen");
        ui.add_space(16.0);

        CollapsingHeader::new("🔃 Repaint Causes")
            .default_open(false)
            .show(ui, |ui| {
                ui.set_min_height(120.0);
                ui.label("What caused egui to repaint:");
                ui.add_space(8.0);
                let causes = ui.ctx().repaint_causes();
                for cause in causes {
                    ui.label(cause.to_string());
                }
            });

        CollapsingHeader::new("📥 Input")
            .default_open(false)
            .show(ui, |ui| {
                let input = ui.input(|i| i.clone());
                input.ui(ui);
            });

        CollapsingHeader::new("📊 Paint stats")
            .default_open(false)
            .show(ui, |ui| {
                let paint_stats = self.read(|ctx| ctx.paint_stats);
                paint_stats.ui(ui);
            });

        CollapsingHeader::new("🖼 Textures")
            .default_open(false)
            .show(ui, |ui| {
                self.texture_ui(ui);
            });

        CollapsingHeader::new("🔠 Font texture")
            .default_open(false)
            .show(ui, |ui| {
                let font_image_size = self.fonts(|f| f.font_image_size());
                crate::introspection::font_texture_ui(ui, font_image_size);
            });

        CollapsingHeader::new("Label text selection state")
            .default_open(false)
            .show(ui, |ui| {
                ui.label(format!(
                    "{:#?}",
                    crate::text_selection::LabelSelectionState::load(ui.ctx())
                ));
            });
    }

    /// Show stats about the allocated textures.
    pub fn texture_ui(&self, ui: &mut crate::Ui) {
        let tex_mngr = self.tex_manager();
        let tex_mngr = tex_mngr.read();

        let mut textures: Vec<_> = tex_mngr.allocated().collect();
        textures.sort_by_key(|(id, _)| *id);

        let mut bytes = 0;
        for (_, tex) in &textures {
            bytes += tex.bytes_used();
        }

        ui.label(format!(
            "{} allocated texture(s), using {:.1} MB",
            textures.len(),
            bytes as f64 * 1e-6
        ));
        let max_preview_size = vec2(48.0, 32.0);

        ui.group(|ui| {
            ScrollArea::vertical()
                .max_height(300.0)
                .auto_shrink([false, true])
                .show(ui, |ui| {
                    ui.style_mut().override_text_style = Some(TextStyle::Monospace);
                    Grid::new("textures")
                        .striped(true)
                        .num_columns(4)
                        .spacing(vec2(16.0, 2.0))
                        .min_row_height(max_preview_size.y)
                        .show(ui, |ui| {
                            for (&texture_id, meta) in textures {
                                let [w, h] = meta.size;

                                let mut size = vec2(w as f32, h as f32);
                                size *= (max_preview_size.x / size.x).min(1.0);
                                size *= (max_preview_size.y / size.y).min(1.0);
                                ui.image(SizedTexture::new(texture_id, size))
                                    .on_hover_ui(|ui| {
                                        // show larger on hover
                                        let max_size = 0.5 * ui.ctx().screen_rect().size();
                                        let mut size = vec2(w as f32, h as f32);
                                        size *= max_size.x / size.x.max(max_size.x);
                                        size *= max_size.y / size.y.max(max_size.y);
                                        ui.image(SizedTexture::new(texture_id, size));
                                    });

                                ui.label(format!("{w} x {h}"));
                                ui.label(format!("{:.3} MB", meta.bytes_used() as f64 * 1e-6));
                                ui.label(format!("{:?}", meta.name));
                                ui.end_row();
                            }
                        });
                });
        });
    }

    /// Shows the contents of [`Self::memory`].
    pub fn memory_ui(&self, ui: &mut crate::Ui) {
        if ui
            .button("Reset all")
            .on_hover_text("Reset all egui state")
            .clicked()
        {
            self.memory_mut(|mem| *mem = Default::default());
        }

        let (num_state, num_serialized) = self.data(|d| (d.len(), d.count_serialized()));
        ui.label(format!(
            "{num_state} widget states stored (of which {num_serialized} are serialized)."
        ));

        ui.horizontal(|ui| {
            ui.label(format!(
                "{} areas (panels, windows, popups, …)",
                self.memory(|mem| mem.areas().count())
            ));
            if ui.button("Reset").clicked() {
                self.memory_mut(|mem| *mem.areas_mut() = Default::default());
            }
        });
        ui.indent("areas", |ui| {
            ui.label("Visible areas, ordered back to front.");
            ui.label("Hover to highlight");
            let layers_ids: Vec<LayerId> = self.memory(|mem| mem.areas().order().to_vec());
            for layer_id in layers_ids {
                let area = self.memory(|mem| mem.areas().get(layer_id.id).copied());
                if let Some(area) = area {
                    let is_visible = self.memory(|mem| mem.areas().is_visible(&layer_id));
                    if !is_visible {
                        continue;
                    }
                    let text = format!("{} - {:?}", layer_id.short_debug_format(), area.rect(),);
                    // TODO(emilk): `Sense::hover_highlight()`
                    if ui
                        .add(Label::new(RichText::new(text).monospace()).sense(Sense::click()))
                        .hovered
                        && is_visible
                    {
                        ui.ctx()
                            .debug_painter()
                            .debug_rect(area.rect(), Color32::RED, "");
                    }
                }
            }
        });

        ui.horizontal(|ui| {
            ui.label(format!(
                "{} collapsing headers",
                self.data(|d| d.count::<containers::collapsing_header::InnerState>())
            ));
            if ui.button("Reset").clicked() {
                self.data_mut(|d| d.remove_by_type::<containers::collapsing_header::InnerState>());
            }
        });

        ui.horizontal(|ui| {
            ui.label(format!(
                "{} menu bars",
                self.data(|d| d.count::<menu::BarState>())
            ));
            if ui.button("Reset").clicked() {
                self.data_mut(|d| d.remove_by_type::<menu::BarState>());
            }
        });

        ui.horizontal(|ui| {
            ui.label(format!(
                "{} scroll areas",
                self.data(|d| d.count::<scroll_area::State>())
            ));
            if ui.button("Reset").clicked() {
                self.data_mut(|d| d.remove_by_type::<scroll_area::State>());
            }
        });

        ui.horizontal(|ui| {
            ui.label(format!(
                "{} resize areas",
                self.data(|d| d.count::<resize::State>())
            ));
            if ui.button("Reset").clicked() {
                self.data_mut(|d| d.remove_by_type::<resize::State>());
            }
        });

        ui.shrink_width_to_current(); // don't let the text below grow this window wider
        ui.label("NOTE: the position of this window cannot be reset from within itself.");

        ui.collapsing("Interaction", |ui| {
            let interaction = self.memory(|mem| mem.interaction().clone());
            interaction.ui(ui);
        });
    }
}

impl Context {
    /// Edit the active [`Style`].
    pub fn style_ui(&self, ui: &mut Ui) {
        let mut style: Style = (*self.style()).clone();
        style.ui(ui);
        self.set_style(style);
    }
}

/// ## Accessibility
impl Context {
    /// Call the provided function with the given ID pushed on the stack of
    /// parent IDs for accessibility purposes. If the `accesskit` feature
    /// is disabled or if AccessKit support is not active for this frame,
    /// the function is still called, but with no other effect.
    ///
    /// No locks are held while the given closure is called.
    #[allow(clippy::unused_self)]
    #[inline]
    pub fn with_accessibility_parent(&self, _id: Id, f: impl FnOnce()) {
        // TODO(emilk): this isn't thread-safe - another thread can call this function between the push/pop calls
        #[cfg(feature = "accesskit")]
        self.frame_state_mut(|fs| {
            if let Some(state) = fs.accesskit_state.as_mut() {
                state.parent_stack.push(_id);
            }
        });

        f();

        #[cfg(feature = "accesskit")]
        self.frame_state_mut(|fs| {
            if let Some(state) = fs.accesskit_state.as_mut() {
                assert_eq!(state.parent_stack.pop(), Some(_id));
            }
        });
    }

    /// If AccessKit support is active for the current frame, get or create
    /// a node builder with the specified ID and return a mutable reference to it.
    /// For newly created nodes, the parent is the node with the ID at the top
    /// of the stack managed by [`Context::with_accessibility_parent`].
    ///
    /// The `Context` lock is held while the given closure is called!
    ///
    /// Returns `None` if acesskit is off.
    // TODO: consider making both RO and RW versions
    #[cfg(feature = "accesskit")]
    pub fn accesskit_node_builder<R>(
        &self,
        id: Id,
        writer: impl FnOnce(&mut accesskit::NodeBuilder) -> R,
    ) -> Option<R> {
        self.write(|ctx| {
            ctx.viewport()
                .frame_state
                .accesskit_state
                .is_some()
                .then(|| ctx.accesskit_node_builder(id))
                .map(writer)
        })
    }

    /// Enable generation of AccessKit tree updates in all future frames.
    ///
    /// If it's practical for the egui integration to immediately run the egui
    /// application when it is either initializing the AccessKit adapter or
    /// being called by the AccessKit adapter to provide the initial tree update,
    /// then it should do so, to provide a complete AccessKit tree to the adapter
    /// immediately. Otherwise, it should enqueue a repaint and use the
    /// placeholder tree update from [`Context::accesskit_placeholder_tree_update`]
    /// in the meantime.
    #[cfg(feature = "accesskit")]
    pub fn enable_accesskit(&self) {
        self.write(|ctx| ctx.is_accesskit_enabled = true);
    }

    /// Return a tree update that the egui integration should provide to the
    /// AccessKit adapter if it cannot immediately run the egui application
    /// to get a full tree update after running [`Context::enable_accesskit`].
    #[cfg(feature = "accesskit")]
    pub fn accesskit_placeholder_tree_update(&self) -> accesskit::TreeUpdate {
        crate::profile_function!();

        use accesskit::{NodeBuilder, Role, Tree, TreeUpdate};

        let root_id = crate::accesskit_root_id().accesskit_id();
        self.write(|ctx| TreeUpdate {
            nodes: vec![(
                root_id,
                NodeBuilder::new(Role::Window).build(&mut ctx.accesskit_node_classes),
            )],
            tree: Some(Tree::new(root_id)),
            focus: root_id,
        })
    }
}

/// ## Image loading
impl Context {
    /// Associate some static bytes with a `uri`.
    ///
    /// The same `uri` may be passed to [`Ui::image`] later to load the bytes as an image.
    ///
    /// By convention, the `uri` should start with `bytes://`.
    /// Following that convention will lead to better error messages.
    pub fn include_bytes(&self, uri: impl Into<Cow<'static, str>>, bytes: impl Into<Bytes>) {
        self.loaders().include.insert(uri, bytes);
    }

    /// Returns `true` if the chain of bytes, image, or texture loaders
    /// contains a loader with the given `id`.
    pub fn is_loader_installed(&self, id: &str) -> bool {
        let loaders = self.loaders();

        loaders.bytes.lock().iter().any(|l| l.id() == id)
            || loaders.image.lock().iter().any(|l| l.id() == id)
            || loaders.texture.lock().iter().any(|l| l.id() == id)
    }

    /// Add a new bytes loader.
    ///
    /// It will be tried first, before any already installed loaders.
    ///
    /// See [`load`] for more information.
    pub fn add_bytes_loader(&self, loader: Arc<dyn load::BytesLoader + Send + Sync + 'static>) {
        self.loaders().bytes.lock().push(loader);
    }

    /// Add a new image loader.
    ///
    /// It will be tried first, before any already installed loaders.
    ///
    /// See [`load`] for more information.
    pub fn add_image_loader(&self, loader: Arc<dyn load::ImageLoader + Send + Sync + 'static>) {
        self.loaders().image.lock().push(loader);
    }

    /// Add a new texture loader.
    ///
    /// It will be tried first, before any already installed loaders.
    ///
    /// See [`load`] for more information.
    pub fn add_texture_loader(&self, loader: Arc<dyn load::TextureLoader + Send + Sync + 'static>) {
        self.loaders().texture.lock().push(loader);
    }

    /// Release all memory and textures related to the given image URI.
    ///
    /// If you attempt to load the image again, it will be reloaded from scratch.
    pub fn forget_image(&self, uri: &str) {
        use load::BytesLoader as _;

        crate::profile_function!();

        let loaders = self.loaders();

        loaders.include.forget(uri);
        for loader in loaders.bytes.lock().iter() {
            loader.forget(uri);
        }
        for loader in loaders.image.lock().iter() {
            loader.forget(uri);
        }
        for loader in loaders.texture.lock().iter() {
            loader.forget(uri);
        }
    }

    /// Release all memory and textures related to images used in [`Ui::image`] or [`Image`].
    ///
    /// If you attempt to load any images again, they will be reloaded from scratch.
    pub fn forget_all_images(&self) {
        use load::BytesLoader as _;

        crate::profile_function!();

        let loaders = self.loaders();

        loaders.include.forget_all();
        for loader in loaders.bytes.lock().iter() {
            loader.forget_all();
        }
        for loader in loaders.image.lock().iter() {
            loader.forget_all();
        }
        for loader in loaders.texture.lock().iter() {
            loader.forget_all();
        }
    }

    /// Try loading the bytes from the given uri using any available bytes loaders.
    ///
    /// Loaders are expected to cache results, so that this call is immediate-mode safe.
    ///
    /// This calls the loaders one by one in the order in which they were registered.
    /// If a loader returns [`LoadError::NotSupported`][not_supported],
    /// then the next loader is called. This process repeats until all loaders have
    /// been exhausted, at which point this returns [`LoadError::NotSupported`][not_supported].
    ///
    /// # Errors
    /// This may fail with:
    /// - [`LoadError::NotSupported`][not_supported] if none of the registered loaders support loading the given `uri`.
    /// - [`LoadError::Loading`][custom] if one of the loaders _does_ support loading the `uri`, but the loading process failed.
    ///
    /// ⚠ May deadlock if called from within a `BytesLoader`!
    ///
    /// [not_supported]: crate::load::LoadError::NotSupported
    /// [custom]: crate::load::LoadError::Loading
    pub fn try_load_bytes(&self, uri: &str) -> load::BytesLoadResult {
        crate::profile_function!(uri);

        let loaders = self.loaders();
        let bytes_loaders = loaders.bytes.lock();

        // Try most recently added loaders first (hence `.rev()`)
        for loader in bytes_loaders.iter().rev() {
            match loader.load(self, uri) {
                Err(load::LoadError::NotSupported) => continue,
                result => return result,
            }
        }

        Err(load::LoadError::NoMatchingBytesLoader)
    }

    /// Try loading the image from the given uri using any available image loaders.
    ///
    /// Loaders are expected to cache results, so that this call is immediate-mode safe.
    ///
    /// This calls the loaders one by one in the order in which they were registered.
    /// If a loader returns [`LoadError::NotSupported`][not_supported],
    /// then the next loader is called. This process repeats until all loaders have
    /// been exhausted, at which point this returns [`LoadError::NotSupported`][not_supported].
    ///
    /// # Errors
    /// This may fail with:
    /// - [`LoadError::NoImageLoaders`][no_image_loaders] if tbere are no registered image loaders.
    /// - [`LoadError::NotSupported`][not_supported] if none of the registered loaders support loading the given `uri`.
    /// - [`LoadError::Loading`][custom] if one of the loaders _does_ support loading the `uri`, but the loading process failed.
    ///
    /// ⚠ May deadlock if called from within an `ImageLoader`!
    ///
    /// [no_image_loaders]: crate::load::LoadError::NoImageLoaders
    /// [not_supported]: crate::load::LoadError::NotSupported
    /// [custom]: crate::load::LoadError::Loading
    pub fn try_load_image(&self, uri: &str, size_hint: load::SizeHint) -> load::ImageLoadResult {
        crate::profile_function!(uri);

        let loaders = self.loaders();
        let image_loaders = loaders.image.lock();
        if image_loaders.is_empty() {
            return Err(load::LoadError::NoImageLoaders);
        }

        // Try most recently added loaders first (hence `.rev()`)
        for loader in image_loaders.iter().rev() {
            match loader.load(self, uri, size_hint) {
                Err(load::LoadError::NotSupported) => continue,
                result => return result,
            }
        }

        Err(load::LoadError::NoMatchingImageLoader)
    }

    /// Try loading the texture from the given uri using any available texture loaders.
    ///
    /// Loaders are expected to cache results, so that this call is immediate-mode safe.
    ///
    /// This calls the loaders one by one in the order in which they were registered.
    /// If a loader returns [`LoadError::NotSupported`][not_supported],
    /// then the next loader is called. This process repeats until all loaders have
    /// been exhausted, at which point this returns [`LoadError::NotSupported`][not_supported].
    ///
    /// # Errors
    /// This may fail with:
    /// - [`LoadError::NotSupported`][not_supported] if none of the registered loaders support loading the given `uri`.
    /// - [`LoadError::Loading`][custom] if one of the loaders _does_ support loading the `uri`, but the loading process failed.
    ///
    /// ⚠ May deadlock if called from within a `TextureLoader`!
    ///
    /// [not_supported]: crate::load::LoadError::NotSupported
    /// [custom]: crate::load::LoadError::Loading
    pub fn try_load_texture(
        &self,
        uri: &str,
        texture_options: TextureOptions,
        size_hint: load::SizeHint,
    ) -> load::TextureLoadResult {
        crate::profile_function!(uri);

        let loaders = self.loaders();
        let texture_loaders = loaders.texture.lock();

        // Try most recently added loaders first (hence `.rev()`)
        for loader in texture_loaders.iter().rev() {
            match loader.load(self, uri, texture_options, size_hint) {
                Err(load::LoadError::NotSupported) => continue,
                result => return result,
            }
        }

        Err(load::LoadError::NoMatchingTextureLoader)
    }

    /// The loaders of bytes, images, and textures.
    pub fn loaders(&self) -> Arc<Loaders> {
        crate::profile_function!();
        self.read(|this| this.loaders.clone())
    }
}

/// ## Viewports
impl Context {
    /// Return the `ViewportId` of the current viewport.
    ///
    /// If this is the root viewport, this will return [`ViewportId::ROOT`].
    ///
    /// Don't use this outside of `Self::run`, or after `Self::end_frame`.
    pub fn viewport_id(&self) -> ViewportId {
        self.read(|ctx| ctx.viewport_id())
    }

    /// Return the `ViewportId` of his parent.
    ///
    /// If this is the root viewport, this will return [`ViewportId::ROOT`].
    ///
    /// Don't use this outside of `Self::run`, or after `Self::end_frame`.
    pub fn parent_viewport_id(&self) -> ViewportId {
        self.read(|ctx| ctx.parent_viewport_id())
    }

    /// For integrations: Set this to render a sync viewport.
    ///
    /// This will only set the callback for the current thread,
    /// which most likely should be the main thread.
    ///
    /// When an immediate viewport is created with [`Self::show_viewport_immediate`] it will be rendered by this function.
    ///
    /// When called, the integration needs to:
    /// * Check if there already is a window for this viewport id, and if not open one
    /// * Set the window attributes (position, size, …) based on [`ImmediateViewport::builder`].
    /// * Call [`Context::run`] with [`ImmediateViewport::viewport_ui_cb`].
    /// * Handle the output from [`Context::run`], including rendering
    #[allow(clippy::unused_self)]
    pub fn set_immediate_viewport_renderer(
        callback: impl for<'a> Fn(&Self, ImmediateViewport<'a>) + 'static,
    ) {
        let callback = Box::new(callback);
        IMMEDIATE_VIEWPORT_RENDERER.with(|render_sync| {
            render_sync.replace(Some(callback));
        });
    }

    /// If `true`, [`Self::show_viewport_deferred`] and [`Self::show_viewport_immediate`] will
    /// embed the new viewports inside the existing one, instead of spawning a new native window.
    ///
    /// `eframe` sets this to `false` on supported platforms, but the default value is `true`.
    pub fn embed_viewports(&self) -> bool {
        self.read(|ctx| ctx.embed_viewports)
    }

    /// If `true`, [`Self::show_viewport_deferred`] and [`Self::show_viewport_immediate`] will
    /// embed the new viewports inside the existing one, instead of spawning a new native window.
    ///
    /// `eframe` sets this to `false` on supported platforms, but the default value is `true`.
    pub fn set_embed_viewports(&self, value: bool) {
        self.write(|ctx| ctx.embed_viewports = value);
    }

    /// Send a command to the current viewport.
    ///
    /// This lets you affect the current viewport, e.g. resizing the window.
    pub fn send_viewport_cmd(&self, command: ViewportCommand) {
        self.send_viewport_cmd_to(self.viewport_id(), command);
    }

    /// Send a command to a specific viewport.
    ///
    /// This lets you affect another viewport, e.g. resizing its window.
    pub fn send_viewport_cmd_to(&self, id: ViewportId, command: ViewportCommand) {
        self.request_repaint_of(id);

        if command.requires_parent_repaint() {
            self.request_repaint_of(self.parent_viewport_id());
        }

        self.write(|ctx| ctx.viewport_for(id).commands.push(command));
    }

    /// Show a deferred viewport, creating a new native window, if possible.
    ///
    /// The given id must be unique for each viewport.
    ///
    /// You need to call this each frame when the child viewport should exist.
    ///
    /// You can check if the user wants to close the viewport by checking the
    /// [`crate::ViewportInfo::close_requested`] flags found in [`crate::InputState::viewport`].
    ///
    /// The given callback will be called whenever the child viewport needs repainting,
    /// e.g. on an event or when [`Self::request_repaint`] is called.
    /// This means it may be called multiple times, for instance while the
    /// parent viewport (the caller) is sleeping but the child viewport is animating.
    ///
    /// You will need to wrap your viewport state in an `Arc<RwLock<T>>` or `Arc<Mutex<T>>`.
    /// When this is called again with the same id in `ViewportBuilder` the render function for that viewport will be updated.
    ///
    /// You can also use [`Self::show_viewport_immediate`], which uses a simpler `FnOnce`
    /// with no need for `Send` or `Sync`. The downside is that it will require
    /// the parent viewport (the caller) to repaint anytime the child is repainted,
    /// and vice versa.
    ///
    /// If [`Context::embed_viewports`] is `true` (e.g. if the current egui
    /// backend does not support multiple viewports), the given callback
    /// will be called immediately, embedding the new viewport in the current one.
    /// You can check this with the [`ViewportClass`] given in the callback.
    /// If you find [`ViewportClass::Embedded`], you need to create a new [`crate::Window`] for you content.
    ///
    /// See [`crate::viewport`] for more information about viewports.
    pub fn show_viewport_deferred(
        &self,
        new_viewport_id: ViewportId,
        viewport_builder: ViewportBuilder,
        viewport_ui_cb: impl Fn(&Self, ViewportClass) + Send + Sync + 'static,
    ) {
        crate::profile_function!();

        if self.embed_viewports() {
            viewport_ui_cb(self, ViewportClass::Embedded);
        } else {
            self.write(|ctx| {
                ctx.viewport_parents
                    .insert(new_viewport_id, ctx.viewport_id());

                let viewport = ctx.viewports.entry(new_viewport_id).or_default();
                viewport.class = ViewportClass::Deferred;
                viewport.builder = viewport_builder;
                viewport.used = true;
                viewport.viewport_ui_cb = Some(Arc::new(move |ctx| {
                    (viewport_ui_cb)(ctx, ViewportClass::Deferred);
                }));
            });
        }
    }

    /// Show an immediate viewport, creating a new native window, if possible.
    ///
    /// This is the easier type of viewport to use, but it is less performant
    /// at it requires both parent and child to repaint if any one of them needs repainting,
    /// which efficvely produce double work for two viewports, and triple work for three viewports, etc.
    /// To avoid this, use [`Self::show_viewport_deferred`] instead.
    ///
    /// The given id must be unique for each viewport.
    ///
    /// You need to call this each frame when the child viewport should exist.
    ///
    /// You can check if the user wants to close the viewport by checking the
    /// [`crate::ViewportInfo::close_requested`] flags found in [`crate::InputState::viewport`].
    ///
    /// The given ui function will be called immediately.
    /// This may only be called on the main thread.
    /// This call will pause the current viewport and render the child viewport in its own window.
    /// This means that the child viewport will not be repainted when the parent viewport is repainted, and vice versa.
    ///
    /// If [`Context::embed_viewports`] is `true` (e.g. if the current egui
    /// backend does not support multiple viewports), the given callback
    /// will be called immediately, embedding the new viewport in the current one.
    /// You can check this with the [`ViewportClass`] given in the callback.
    /// If you find [`ViewportClass::Embedded`], you need to create a new [`crate::Window`] for you content.
    ///
    /// See [`crate::viewport`] for more information about viewports.
    pub fn show_viewport_immediate<T>(
        &self,
        new_viewport_id: ViewportId,
        builder: ViewportBuilder,
        viewport_ui_cb: impl FnOnce(&Self, ViewportClass) -> T,
    ) -> T {
        crate::profile_function!();

        if self.embed_viewports() {
            return viewport_ui_cb(self, ViewportClass::Embedded);
        }

        IMMEDIATE_VIEWPORT_RENDERER.with(|immediate_viewport_renderer| {
            let immediate_viewport_renderer = immediate_viewport_renderer.borrow();
            let Some(immediate_viewport_renderer) = immediate_viewport_renderer.as_ref() else {
                // This egui backend does not support multiple viewports.
                return viewport_ui_cb(self, ViewportClass::Embedded);
            };

            let ids = self.write(|ctx| {
                let parent_viewport_id = ctx.viewport_id();

                ctx.viewport_parents
                    .insert(new_viewport_id, parent_viewport_id);

                let viewport = ctx.viewports.entry(new_viewport_id).or_default();
                viewport.builder = builder.clone();
                viewport.used = true;
                viewport.viewport_ui_cb = None; // it is immediate

                ViewportIdPair::from_self_and_parent(new_viewport_id, parent_viewport_id)
            });

            let mut out = None;
            {
                let out = &mut out;

                let viewport = ImmediateViewport {
                    ids,
                    builder,
                    viewport_ui_cb: Box::new(move |context| {
                        *out = Some(viewport_ui_cb(context, ViewportClass::Immediate));
                    }),
                };

                immediate_viewport_renderer(self, viewport);
            }

            out.expect(
                "egui backend is implemented incorrectly - the user callback was never called",
            )
        })
    }
}

#[test]
fn context_impl_send_sync() {
    fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<Context>();
}