neomacs 0.0.2

Standalone Rust binary for Neomacs (no C dependency)
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
//! Neomacs — standalone Rust binary
//!
//! Uses the neovm-core Elisp evaluator with a GNU Emacs-compatible command
//! loop.  The evaluator's `recursive_edit()` drives the main event loop:
//!
//!   read_char() → key-binding → command-execute → redisplay
//!
//! All editing commands, keybindings, and user customizations come from Elisp
//! (loaded .el files), just like GNU Emacs.  Only the core command loop and
//! low-level primitives are implemented in Rust.

mod args;
mod input_bridge;
mod tty_frontend;

use std::collections::HashMap;
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::time::{Duration, Instant};

use neomacs_display_runtime::render_thread::{
    RenderEventLoopProxy, RenderUserEvent, SharedImageDimensions, SharedMonitorInfo,
    build_render_event_loop, run_render_loop_current_thread,
};
use neomacs_display_runtime::thread_comm::{
    EmacsComms, InputEvent as DisplayInputEvent, RenderCommand, ThreadComms,
};
use neomacs_layout_engine::font_metrics::FontMetricsService;
use neomacs_layout_engine::fontconfig::face_height_to_pixels;
use neomacs_layout_engine::gui_chrome::{collect_gui_menu_bar_items, collect_gui_tool_bar_items};

use neovm_core::buffer::BufferId;
use neovm_core::emacs_core::Value;
use neovm_core::emacs_core::builtins::set_neomacs_monitor_info;
use neovm_core::emacs_core::display::gui_window_system_symbol;
use neovm_core::emacs_core::eval::{
    FontResolveRequest, FontSpecResolveRequest, GuiFrameHostSize, ImageResolveRequest,
    ImageResolveSource, ResolvedFontMatch, ResolvedFontSpecMatch, ResolvedFrameFont, ResolvedImage,
};
use neovm_core::emacs_core::load::LoadupDumpMode;
use neovm_core::emacs_core::load::LoadupStartupSurface;
use neovm_core::emacs_core::load::RuntimeImageRole;
#[cfg(test)]
use neovm_core::emacs_core::print_value_with_eval;
use neovm_core::emacs_core::terminal::pure::{
    TerminalHost, TerminalRuntimeConfig, configure_terminal_runtime, reset_terminal_host,
    reset_terminal_runtime, set_terminal_host,
};
use neovm_core::emacs_core::{Context, DisplayHost, GuiFrameHostRequest};
use neovm_core::face::{FaceHeight, FontSlant, FontWeight, FontWidth};
use neovm_core::heap_types::LispString;
use neovm_core::window::{FrameId, Window};

#[derive(Debug, Clone, PartialEq, Eq)]
enum EarlyCliAction {
    PrintHelp { program: String },
    PrintVersion,
    PrintFingerprint,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FrontendKind {
    Gui,
    Tty,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RuntimeMode {
    Raw,
    BootstrapUse,
    FinalRun,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DumpImageKind {
    Bootstrap,
    Final,
}

impl RuntimeMode {
    pub const fn binary_name(self) -> &'static str {
        match self {
            Self::Raw => "neomacs-temacs",
            Self::BootstrapUse => "bootstrap-neomacs",
            Self::FinalRun => "neomacs",
        }
    }

    pub const fn dump_image_kind(self) -> Option<DumpImageKind> {
        match self {
            Self::Raw => None,
            Self::BootstrapUse => Some(DumpImageKind::Bootstrap),
            Self::FinalRun => Some(DumpImageKind::Final),
        }
    }
}

fn runtime_mode_from_program_name(program: &str) -> RuntimeMode {
    let file_name = Path::new(program)
        .file_name()
        .unwrap_or_else(|| std::ffi::OsStr::new(program))
        .to_string_lossy();
    let file_name = file_name.strip_suffix(".exe").unwrap_or(&file_name);
    match file_name {
        "neomacs-temacs" => RuntimeMode::Raw,
        "bootstrap-neomacs" => RuntimeMode::BootstrapUse,
        _ => RuntimeMode::FinalRun,
    }
}

fn runtime_mode_from_argv<I, S>(args: I) -> RuntimeMode
where
    I: IntoIterator<Item = S>,
    S: AsRef<str>,
{
    args.into_iter()
        .next()
        .map(|arg| runtime_mode_from_program_name(arg.as_ref()))
        .unwrap_or(RuntimeMode::FinalRun)
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct StartupOptions {
    frontend: FrontendKind,
    forwarded_args: Vec<String>,
    terminal_device: Option<String>,
    noninteractive: bool,
    temacs_mode: Option<LoadupDumpMode>,
    dump_file_override: Option<PathBuf>,
    /// Set by `-Q` (peek) and `-x` (consumed). Mirrors GNU
    /// `no_site_lisp` at emacs.c:2126/2135.
    no_site_lisp: bool,
    /// Set by `-nl` / `--no-loadup`. Mirrors GNU `no_loadup` at
    /// emacs.c:2031. Only meaningful in `RuntimeMode::Raw`, where it
    /// suppresses the `-l loadup` splice that would otherwise force
    /// `loadup.el` to run.
    no_loadup: bool,
    /// Set by `-no-build-details` / `--no-build-details`. Mirrors GNU
    /// `build_details` at emacs.c:2037 (where the negation is taken).
    /// When true, build-time strings (e.g. `emacs-build-time`) should
    /// be cleared rather than populated.
    no_build_details: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct BootstrapDisplayConfig {
    frontend: FrontendKind,
    color_cells: i64,
    background_mode: &'static str,
}

const EARLY_HELP_BODY: &str = concat!(
    "Run Neomacs, the extensible, customizable, self-documenting real-time\n",
    "display editor.  The recommended way to start Neomacs for normal editing\n",
    "is with no options at all.\n",
    "\n",
    "Run M-x info RET m emacs RET m emacs invocation RET inside Emacs to\n",
    "read the main documentation for these command-line arguments.\n",
    "\n",
    "Initialization options:\n",
    "\n",
    "--batch                     do not do interactive display; implies -q\n",
    "--chdir DIR                 change to directory DIR\n",
    "--daemon, --bg-daemon[=NAME] start a (named) server in the background\n",
    "--fg-daemon[=NAME]          start a (named) server in the foreground\n",
    "--debug-init                enable Emacs Lisp debugger for init file\n",
    "--display, -d DISPLAY       use X server DISPLAY\n",
    "--no-build-details          do not add build details such as time stamps\n",
    "--no-desktop                do not load a saved desktop\n",
    "--no-init-file, -q          load neither ~/.emacs nor default.el\n",
    "--no-loadup, -nl            do not load loadup.el into bare Emacs\n",
    "--no-site-file              do not load site-start.el\n",
    "--no-x-resources            do not load X resources\n",
    "--no-site-lisp, -nsl        do not add site-lisp directories to load-path\n",
    "--no-splash                 do not display a splash screen on startup\n",
    "--no-window-system, -nw     do not communicate with X, ignoring $DISPLAY\n",
    "--init-directory=DIR        use DIR when looking for the Emacs init files.\n",
    "--quick, -Q                 equivalent to:\n",
    "                              -q --no-site-file --no-site-lisp --no-splash\n",
    "                              --no-x-resources\n",
    "--script FILE               run FILE as an Emacs Lisp script\n",
    "-x                          to be used in #!/usr/bin/emacs -x\n",
    "                              and has approximately the same meaning\n",
    "                              as -Q --script\n",
    "--terminal, -t DEVICE       use DEVICE for terminal I/O\n",
    "--user, -u USER             load ~USER/.emacs instead of your own\n",
    "\n",
    "Action options:\n",
    "\n",
    "FILE                    visit FILE\n",
    "+LINE                   go to line LINE in next FILE\n",
    "+LINE:COLUMN            go to line LINE, column COLUMN, in next FILE\n",
    "--directory, -L DIR     prepend DIR to load-path (with :DIR, append DIR)\n",
    "--eval EXPR             evaluate Emacs Lisp expression EXPR\n",
    "--execute EXPR          evaluate Emacs Lisp expression EXPR\n",
    "--file FILE             visit FILE\n",
    "--find-file FILE        visit FILE\n",
    "--funcall, -f FUNC      call Emacs Lisp function FUNC with no arguments\n",
    "--insert FILE           insert contents of FILE into current buffer\n",
    "--kill                  exit without asking for confirmation\n",
    "--load, -l FILE         load Emacs Lisp FILE using the load function\n",
    "--visit FILE            visit FILE\n",
    "\n",
    "Display options:\n",
    "\n",
    "--background-color, -bg COLOR   window background color\n",
    "--basic-display, -D             disable many display features;\n",
    "                                  used for debugging Emacs\n",
    "--border-color, -bd COLOR       main border color\n",
    "--border-width, -bw WIDTH       width of main border\n",
    "--cursor-color, -cr COLOR       color of the Emacs cursor indicating point\n",
    "--font, -fn FONT                default font; must be fixed-width\n",
    "--foreground-color, -fg COLOR   window foreground color\n",
    "--fullheight, -fh               make the first frame high as the screen\n",
    "--fullscreen, -fs               make the first frame fullscreen\n",
    "--fullwidth, -fw                make the first frame wide as the screen\n",
    "--maximized, -mm                make the first frame maximized\n",
    "--geometry, -g GEOMETRY         window geometry\n",
    "--iconic                        start Neomacs in iconified state\n",
    "--internal-border, -ib WIDTH    width between text and main border\n",
    "--line-spacing, -lsp PIXELS     additional space to put between lines\n",
    "--mouse-color, -ms COLOR        mouse cursor color in Neomacs window\n",
    "--name NAME                     title for initial Neomacs frame\n",
    "--no-blinking-cursor, -nbc      disable blinking cursor\n",
    "--reverse-video, -r, -rv        switch foreground and background\n",
    "--title, -T TITLE               title for initial Neomacs frame\n",
    "--vertical-scroll-bars, -vb     enable vertical scroll bars\n",
    "--xrm XRESOURCES                set additional X resources\n",
    "--parent-id XID                 set parent window\n",
    "--help                          display this help and exit\n",
    "--fingerprint                   output fingerprint and exit\n",
    "--version                       output version information and exit\n",
    "\n",
    "You can generally also specify long option names with a single -; for\n",
    "example, -batch as well as --batch.  You can use any unambiguous\n",
    "abbreviation for a --option.\n",
    "\n",
    "Various environment variables and window system resources also affect\n",
    "the operation of Neomacs.  See the main documentation.\n",
    "\n",
    "Report bugs to https://github.com/eval-exec/neomacs-windows/issues.\n",
);

const BOOTSTRAP_CORE_FEATURES: &[&str] = &["neomacs"];

fn classify_early_cli_action(args: impl IntoIterator<Item = String>) -> Option<EarlyCliAction> {
    let mut args = args.into_iter();
    let program = args.next().unwrap_or_else(|| "neomacs".to_string());
    for arg in args {
        if arg == "--" {
            break;
        }
        match arg.as_str() {
            "--help" | "-help" => {
                return Some(EarlyCliAction::PrintHelp { program });
            }
            "--version" | "-version" => {
                return Some(EarlyCliAction::PrintVersion);
            }
            "--fingerprint" | "-fingerprint" => {
                return Some(EarlyCliAction::PrintFingerprint);
            }
            _ => {}
        }
    }
    None
}

fn render_help_text(program: &str) -> String {
    let mut out = String::new();
    let _ = write!(&mut out, "Usage: {program} [OPTION-OR-FILENAME]...\n\n");
    out.push_str(EARLY_HELP_BODY);
    out
}

fn render_version_text() -> String {
    format!(
        "Neomacs {}\nStandalone Rust binary for Neomacs (no C dependency)\n",
        neomacs_display_runtime::VERSION
    )
}

fn render_fingerprint_text() -> String {
    format!("{}\n", neovm_core::emacs_core::pdump::fingerprint_hex())
}

fn render_startup_image_error(err: &neovm_core::emacs_core::error::EvalError) -> String {
    match err {
        neovm_core::emacs_core::error::EvalError::Signal {
            raw_data: Some(payload),
            ..
        } => payload
            .as_symbol_name()
            .map(str::to_owned)
            .or_else(|| payload.as_utf8_str().map(str::to_owned))
            .unwrap_or_else(|| format!("{err:?}")),
        _ => format!("{err:?}"),
    }
}

fn parse_startup_options(args: impl IntoIterator<Item = String>) -> Result<StartupOptions, String> {
    use args::{ArgMatch, argmatch, sort_args};

    // GNU `argmatch` works on a `(argc, argv)` pair plus a `*skipptr`
    // index that mirrors the consumed cursor in argv. We model the same
    // shape: `parsed[0]` is the program name (matching argv[0]) and
    // `parsed[1..]` are the user-supplied tokens. The `idx` cursor below
    // is `*skipptr` — `argmatch` looks at `parsed[idx + 1]` so an idx of
    // 0 means "look at the first user token".
    let mut parsed: Vec<String> = args.into_iter().collect();

    // GNU emacs.c:1502 — sort_args runs once before the main matching
    // pass so the parser walks argv in canonical priority order. This
    // also has the effect of moving option/value pairs in front of
    // file-name args, matching how lisp/startup.el's `command-line` and
    // `command-line-1` expect to see them regardless of how the user
    // typed them on the command line.
    sort_args(&mut parsed)?;

    let program = parsed
        .first()
        .cloned()
        .unwrap_or_else(|| "neomacs".to_string());
    let mut forwarded_args = vec![program];
    let mut frontend = FrontendKind::Gui;
    let mut terminal_device = None;
    let mut noninteractive = false;
    let mut temacs_mode = None;
    let mut dump_file_override = None;
    let mut no_site_lisp = false;
    let mut no_loadup = false;
    let mut no_build_details = false;
    let mut idx = 0usize;

    while idx + 1 < parsed.len() {
        // GNU walks argv left-to-right inside `main()` after `sort_args`
        // has reordered things. We don't reorder yet (that's Phase 2), so
        // we walk the original token order. Each `argmatch` call looks at
        // `parsed[idx + 1]`; on a match it advances `idx` past the
        // consumed entry/entries. On no-match we drop to the catch-all
        // forwarding branch and bump `idx` ourselves.
        let next = parsed[idx + 1].as_str();

        // `--` is the terminator: every following token is forwarded
        // verbatim and parsing stops here.
        if next == "--" {
            forwarded_args.extend(parsed[idx + 1..].iter().cloned());
            break;
        }

        // -chdir / --chdir DIR (GNU emacs.c:1538-1561). Must run before
        // any later parsing or file resolution: GNU calls chdir() at
        // line 1549, so subsequent file-name args see the new cwd.
        match argmatch(&parsed, &mut idx, "-chdir", Some("--chdir"), 4, true) {
            ArgMatch::Value(dir) => {
                if let Err(e) = std::env::set_current_dir(&dir) {
                    return Err(format!("neomacs: Can't chdir to {dir}: {e}"));
                }
                continue;
            }
            ArgMatch::MissingValue => {
                return Err("neomacs: option `-chdir' requires an argument".to_string());
            }
            ArgMatch::NoMatch => {}
            ArgMatch::Bare => unreachable!(),
        }

        // -nw / --no-window-system / --no-windows
        // (GNU emacs.c:1696-1697; the -nw row in standard_args[] declares
        // both long aliases with minlen 6.)
        match argmatch(
            &parsed,
            &mut idx,
            "-nw",
            Some("--no-window-system"),
            6,
            false,
        ) {
            ArgMatch::Bare => {
                frontend = FrontendKind::Tty;
                continue;
            }
            ArgMatch::NoMatch => {}
            ArgMatch::Value(_) | ArgMatch::MissingValue => unreachable!(),
        }
        match argmatch(&parsed, &mut idx, "-nw", Some("--no-windows"), 6, false) {
            ArgMatch::Bare => {
                frontend = FrontendKind::Tty;
                continue;
            }
            ArgMatch::NoMatch => {}
            ArgMatch::Value(_) | ArgMatch::MissingValue => unreachable!(),
        }

        // -batch / --batch (GNU emacs.c:1702)
        match argmatch(&parsed, &mut idx, "-batch", Some("--batch"), 5, false) {
            ArgMatch::Bare => {
                noninteractive = true;
                frontend = FrontendKind::Tty;
                continue;
            }
            ArgMatch::NoMatch => {}
            ArgMatch::Value(_) | ArgMatch::MissingValue => unreachable!(),
        }

        // -script FILE / --script FILE (GNU emacs.c:1708-1717). GNU
        // sets noninteractive, then rewrites the matched argv slot to
        // -scriptload (an internal flag picked up later by
        // lisp/startup.el's command-line-1) before re-sorting. We do
        // the same: noninteractive + push -scriptload FILE into the
        // forwarded args. Lisp's command-line-1 in startup.el:2841 will
        // pick it up and load FILE.
        match argmatch(&parsed, &mut idx, "-script", Some("--script"), 3, true) {
            ArgMatch::Value(script_file) => {
                noninteractive = true;
                frontend = FrontendKind::Tty;
                forwarded_args.push("-scriptload".to_string());
                forwarded_args.push(script_file);
                continue;
            }
            ArgMatch::MissingValue => {
                return Err("neomacs: option `-script' requires an argument".to_string());
            }
            ArgMatch::NoMatch => {}
            ArgMatch::Bare => unreachable!(),
        }

        // -x (GNU emacs.c:2132-2140). The `-x` form of shebang scripts:
        //   #!/usr/bin/neomacs -x
        // GNU sets noninteractive AND no_site_lisp, then rewrites argv
        // by replacing `-x` with the internal `-scripteval` flag.
        // lisp/startup.el:2841 picks up `-scripteval` and runs the
        // following file as evaluated text rather than loaded code.
        match argmatch(&parsed, &mut idx, "-x", None, 1, false) {
            ArgMatch::Bare => {
                noninteractive = true;
                frontend = FrontendKind::Tty;
                no_site_lisp = true;
                forwarded_args.push("-scripteval".to_string());
                continue;
            }
            ArgMatch::NoMatch => {}
            ArgMatch::Value(_) | ArgMatch::MissingValue => unreachable!(),
        }

        // -nl / --no-loadup (GNU emacs.c:2031-2032). Skip loading
        // loadup.el under RuntimeMode::Raw. Consumed entirely; no
        // forwarding.
        match argmatch(&parsed, &mut idx, "-nl", Some("--no-loadup"), 6, false) {
            ArgMatch::Bare => {
                no_loadup = true;
                continue;
            }
            ArgMatch::NoMatch => {}
            ArgMatch::Value(_) | ArgMatch::MissingValue => unreachable!(),
        }

        // -nsl / --no-site-lisp (GNU emacs.c:2034-2035). Drops site-lisp
        // directories from load-path before lread.c builds it.
        // Consumed entirely; no forwarding.
        match argmatch(&parsed, &mut idx, "-nsl", Some("--no-site-lisp"), 11, false) {
            ArgMatch::Bare => {
                no_site_lisp = true;
                continue;
            }
            ArgMatch::NoMatch => {}
            ArgMatch::Value(_) | ArgMatch::MissingValue => unreachable!(),
        }

        // -no-build-details / --no-build-details (GNU emacs.c:2037-2038).
        // Inverts the GNU `build_details` global; when set, build-time
        // strings (e.g. `emacs-build-time`) should be cleared.
        // Consumed entirely; no forwarding.
        match argmatch(
            &parsed,
            &mut idx,
            "-no-build-details",
            Some("--no-build-details"),
            7,
            false,
        ) {
            ArgMatch::Bare => {
                no_build_details = true;
                continue;
            }
            ArgMatch::NoMatch => {}
            ArgMatch::Value(_) | ArgMatch::MissingValue => unreachable!(),
        }

        // -temacs / --temacs (GNU emacs.c:1364). Forward the original
        // token(s) verbatim so any later consumer (Lisp or another
        // raw_loadup pass) sees the same shape GNU does — emacs.c
        // does NOT rewrite this slot, only the display slot.
        let pre_idx = idx;
        match argmatch(&parsed, &mut idx, "-temacs", Some("--temacs"), 8, true) {
            ArgMatch::Value(value) => {
                temacs_mode = Some(parse_temacs_mode(&value)?);
                for slot in &parsed[pre_idx + 1..=idx] {
                    forwarded_args.push(slot.clone());
                }
                continue;
            }
            ArgMatch::MissingValue => {
                return Err("neomacs: option `-temacs' requires an argument".to_string());
            }
            ArgMatch::NoMatch => {}
            ArgMatch::Bare => unreachable!(),
        }

        // -dump-file / --dump-file (GNU emacs.c:942, 991). Same forward-
        // verbatim treatment as --temacs.
        let pre_idx = idx;
        match argmatch(
            &parsed,
            &mut idx,
            "-dump-file",
            Some("--dump-file"),
            6,
            true,
        ) {
            ArgMatch::Value(value) => {
                dump_file_override = Some(PathBuf::from(&value));
                for slot in &parsed[pre_idx + 1..=idx] {
                    forwarded_args.push(slot.clone());
                }
                continue;
            }
            ArgMatch::MissingValue => {
                return Err("neomacs: option `-dump-file' requires an argument".to_string());
            }
            ArgMatch::NoMatch => {}
            ArgMatch::Bare => unreachable!(),
        }

        // -t / --terminal (GNU emacs.c:1665)
        match argmatch(&parsed, &mut idx, "-t", Some("--terminal"), 4, true) {
            ArgMatch::Value(device) => {
                frontend = FrontendKind::Tty;
                terminal_device = Some(device);
                continue;
            }
            ArgMatch::MissingValue => {
                return Err("neomacs: option `-t' requires an argument".to_string());
            }
            ArgMatch::NoMatch => {}
            ArgMatch::Bare => unreachable!(),
        }

        // -d / --display / -display (GNU emacs.c:2097-2099 — peek + roll
        // back). Our window backend uses winit which reads `DISPLAY` from
        // the environment, so we don't need to act on the value, but we
        // still consume it from argv structurally and re-forward it so
        // Lisp's `command-line-1` sees it where GNU does.
        match argmatch(&parsed, &mut idx, "-d", Some("--display"), 3, true) {
            ArgMatch::Value(value) => {
                forwarded_args.push("-d".to_string());
                forwarded_args.push(value);
                continue;
            }
            ArgMatch::MissingValue => {
                return Err("neomacs: option `-d' requires an argument".to_string());
            }
            ArgMatch::NoMatch => {}
            ArgMatch::Bare => unreachable!(),
        }
        // -display alone (no long form) — GNU emacs.c:2099 has lstr = 0
        // for this row. Use a None lstr to match.
        match argmatch(&parsed, &mut idx, "-display", None, 0, true) {
            ArgMatch::Value(value) => {
                forwarded_args.push("-display".to_string());
                forwarded_args.push(value);
                continue;
            }
            ArgMatch::MissingValue => {
                return Err("neomacs: option `-display' requires an argument".to_string());
            }
            ArgMatch::NoMatch => {}
            ArgMatch::Bare => unreachable!(),
        }

        // No flag matched at this position: forward verbatim.
        forwarded_args.push(parsed[idx + 1].clone());
        idx += 1;
    }

    // -Q / --quick / -quick PEEK (GNU emacs.c:2123-2130). GNU walks
    // argv one more time looking for any of these three spellings; if
    // found, it sets `no_site_lisp = 1` and leaves the flag in argv so
    // lisp/startup.el (`command-line` at lisp/startup.el:1404) can also
    // act on it. Critically the flag is NOT consumed — only `no_site_lisp`
    // is updated as a side effect. This is the only "peek but do not
    // consume" idiom in GNU's parser.
    //
    // We replicate the same scan over `forwarded_args` (the survivors
    // of the consume pass) since that's what the rest of startup will
    // see. Skip if `no_site_lisp` is already set (e.g. by an earlier
    // -nsl or -x), matching GNU's `if (! no_site_lisp)` guard.
    if !no_site_lisp
        && forwarded_args
            .iter()
            .skip(1)
            .any(|a| a == "-Q" || a == "--quick" || a == "-quick")
    {
        no_site_lisp = true;
    }

    Ok(StartupOptions {
        frontend,
        forwarded_args,
        terminal_device,
        noninteractive,
        temacs_mode,
        dump_file_override,
        no_site_lisp,
        no_loadup,
        no_build_details,
    })
}

fn parse_temacs_mode(value: &str) -> Result<LoadupDumpMode, String> {
    match value {
        "pbootstrap" => Ok(LoadupDumpMode::Pbootstrap),
        "pdump" => Ok(LoadupDumpMode::Pdump),
        other => Err(format!("neomacs: invalid --temacs mode `{other}`")),
    }
}

fn bootstrap_display_config(frontend: FrontendKind) -> BootstrapDisplayConfig {
    match frontend {
        FrontendKind::Gui => BootstrapDisplayConfig {
            frontend,
            color_cells: 16777216,
            // GNU `frame--current-background-mode` defaults GUI frames to
            // `light` unless a real background color or terminal default says
            // otherwise.  Live frame-parameter updates recompute this later.
            background_mode: "light",
        },
        FrontendKind::Tty => BootstrapDisplayConfig {
            frontend,
            color_cells: detect_tty_color_cells(),
            background_mode: detect_tty_background_mode(),
        },
    }
}

impl BootstrapDisplayConfig {
    fn window_system_symbol(self) -> Option<&'static str> {
        match self.frontend {
            FrontendKind::Gui => Some(gui_window_system_symbol()),
            FrontendKind::Tty => None,
        }
    }

    fn display_type_symbol(self) -> &'static str {
        if self.color_cells > 0 {
            "color"
        } else {
            "mono"
        }
    }
}

fn detect_tty_type() -> Option<String> {
    std::env::var("TERM").ok().filter(|value| !value.is_empty())
}

fn default_controlling_tty_name() -> &'static str {
    #[cfg(windows)]
    {
        "CONOUT$"
    }
    #[cfg(not(windows))]
    {
        "/dev/tty"
    }
}

fn detect_tty_name(_startup: &StartupOptions) -> String {
    // GNU `init_display_interactive` calls `init_tty(NULL, TERM, ...)` for
    // normal `-nw`; `init_tty` names that controlling terminal DEV_TTY, not
    // `ttyname(0)`.  `-t` device handoff is still not implemented here, so the
    // live Neomacs terminal remains the current controlling tty.
    default_controlling_tty_name().to_string()
}

fn detect_tty_runtime(startup: &StartupOptions) -> TerminalRuntimeConfig {
    TerminalRuntimeConfig::interactive(detect_tty_type(), detect_tty_color_cells())
        .with_name(detect_tty_name(startup))
}

fn detect_tty_color_cells() -> i64 {
    let colorterm = std::env::var("COLORTERM")
        .unwrap_or_default()
        .to_ascii_lowercase();
    if colorterm.contains("truecolor") || colorterm.contains("24bit") {
        return 16777216;
    }

    let term = std::env::var("TERM")
        .unwrap_or_default()
        .to_ascii_lowercase();
    if term.is_empty() || term == "dumb" {
        return 0;
    }
    if term.contains("256color") {
        return 256;
    }
    8
}

fn detect_tty_background_mode() -> &'static str {
    let Some(colorfgbg) = std::env::var("COLORFGBG").ok() else {
        return "dark";
    };
    let Some(background) = colorfgbg
        .split(';')
        .next_back()
        .and_then(|value| value.parse::<i32>().ok())
    else {
        return "dark";
    };

    if (7..=15).contains(&background) {
        "light"
    } else {
        "dark"
    }
}

fn startup_dimensions(frontend: FrontendKind, frame_metrics: BootstrapFrameMetrics) -> (u32, u32) {
    match frontend {
        FrontendKind::Gui => {
            // GNU gui_figure_window_size seeds the first GUI frame from an
            // 80x36 text grid using the default frame font metrics.
            let cols = 80u32;
            let lines = 36u32;
            let width = (cols as f32 * frame_metrics.char_width).round() as u32;
            let height = (lines as f32 * frame_metrics.char_height).round() as u32;
            (width.max(200), height.max(100))
        }
        FrontendKind::Tty => {
            // TTY frames use 1x1 character cells (GNU Emacs frame.c:1184-1185),
            // so frame dimensions are in character cells, not pixels.
            let (cols, rows) = query_terminal_size_cells().unwrap_or((80, 25));
            (cols as u32, rows as u32)
        }
    }
}

#[cfg(unix)]
fn query_terminal_size_cells() -> Option<(u16, u16)> {
    use std::mem::MaybeUninit;

    unsafe {
        let mut winsize = MaybeUninit::<libc::winsize>::uninit();
        if libc::ioctl(libc::STDOUT_FILENO, libc::TIOCGWINSZ, winsize.as_mut_ptr()) == 0 {
            let winsize = winsize.assume_init();
            if winsize.ws_col > 0 && winsize.ws_row > 0 {
                return Some((winsize.ws_col, winsize.ws_row));
            }
        }
    }
    None
}

#[cfg(not(unix))]
fn query_terminal_size_cells() -> Option<(u16, u16)> {
    None
}

enum FrontendHandle {
    /// Single-thread TTY path: input reader only, rendering via TtyRif on eval thread.
    TtyRifInput(tty_frontend::TtyInputReader),
    Batch,
}

impl FrontendHandle {
    fn join(self) {
        match self {
            Self::TtyRifInput(handle) => handle.join(),
            Self::Batch => {}
        }
    }
}

#[derive(Clone)]
struct GuiEventLoopWaker {
    proxy: RenderEventLoopProxy,
}

impl GuiEventLoopWaker {
    fn new(proxy: RenderEventLoopProxy) -> Self {
        Self { proxy }
    }

    fn wake(&self) {
        if let Err(err) = self.proxy.send_event(RenderUserEvent::Wake) {
            tracing::debug!("GUI event loop wake dropped after loop closed: {err}");
        }
    }
}

#[derive(Debug, Clone, Copy)]
struct EvaluatorExit {
    exit_code: i32,
    restart: bool,
}

impl EvaluatorExit {
    const OK: Self = Self {
        exit_code: 0,
        restart: false,
    };
}

const GUI_EVALUATOR_THREAD_STACK_SIZE: usize = 64 * 1024 * 1024;

struct PrimaryWindowDisplayHost {
    cmd_tx: crossbeam_channel::Sender<RenderCommand>,
    render_waker: Option<GuiEventLoopWaker>,
    primary_window_adopted: bool,
    primary_frame_id: Option<neovm_core::window::FrameId>,
    last_window_titles: Mutex<HashMap<neovm_core::window::FrameId, LispString>>,
    font_metrics: Option<FontMetricsService>,
    primary_window_size: SharedPrimaryWindowSize,
    image_dimensions: SharedImageDimensions,
    resolved_images: Mutex<HashMap<ImageResolveRequest, ResolvedImage>>,
}

struct TtyTerminalHost {
    cmd_tx: crossbeam_channel::Sender<RenderCommand>,
}

impl TerminalHost for TtyTerminalHost {
    fn suspend_tty(&mut self) -> Result<(), String> {
        self.cmd_tx
            .send(RenderCommand::SuspendTty)
            .map_err(|err| format!("failed to suspend tty frontend: {err}"))
    }

    fn resume_tty(&mut self) -> Result<(), String> {
        self.cmd_tx
            .send(RenderCommand::ResumeTty)
            .map_err(|err| format!("failed to resume tty frontend: {err}"))
    }

    fn delete_terminal(&mut self) -> Result<(), String> {
        self.cmd_tx
            .send(RenderCommand::Shutdown)
            .map_err(|err| format!("failed to delete tty terminal frontend: {err}"))
    }
}

fn should_enable_live_tty_io(startup: &StartupOptions) -> bool {
    startup.frontend == FrontendKind::Tty && !startup.noninteractive
}

fn maybe_install_tty_redisplay_callback(evaluator: &mut Context, startup: &StartupOptions) {
    if !should_enable_live_tty_io(startup) {
        return;
    }

    provide_lisp_feature(evaluator, "tty-child-frames");

    let (cols, rows) = query_terminal_size_cells().unwrap_or((80, 25));
    let mut tty_rif = neomacs_display_protocol::tty_rif::TtyRif::new(cols as usize, rows as usize);
    // TTY frames use 1x1 character cell metrics (GNU Emacs
    // frame.c:1184-1185). Drop the layout engine's cosmic-text
    // FontMetricsService so char_advance,
    // status_line_font_metrics, etc. fall back to the
    // char-cell grid.
    LAYOUT_ENGINE.with(|engine| {
        engine.borrow_mut().disable_cosmic_metrics();
    });
    evaluator.redisplay_fn = Some(Box::new(move |eval: &mut Context| {
        eval.setup_thread_locals();
        if let Some((cols, rows)) = query_terminal_size_cells() {
            let cols = usize::from(cols);
            let rows = usize::from(rows);
            if tty_rif.width() != cols || tty_rif.height() != rows {
                tty_rif.resize(cols, rows);
            }
        }
        if let Some((root, children)) = run_tty_layout_tree(eval) {
            run_tty_rif_redisplay(&mut tty_rif, &root, &children);
        }
    }));
}

fn provide_lisp_feature(evaluator: &mut Context, feature: &str) {
    let features = evaluator
        .obarray()
        .symbol_value("features")
        .copied()
        .unwrap_or(Value::NIL);
    let feature_value = Value::symbol(feature);
    let already_present = neovm_core::emacs_core::value::list_to_vec(&features)
        .is_some_and(|items| items.into_iter().any(|item| item == feature_value));
    if !already_present {
        evaluator.set_variable("features", Value::cons(feature_value, features));
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct PrimaryWindowSize {
    width: u32,
    height: u32,
}

type SharedPrimaryWindowSize = Arc<Mutex<PrimaryWindowSize>>;

const HOST_IMAGE_ID_START: u32 = 0x4000_0000;
static HOST_IMAGE_ID_ALLOCATOR: AtomicU32 = AtomicU32::new(HOST_IMAGE_ID_START);

fn next_host_image_id() -> u32 {
    HOST_IMAGE_ID_ALLOCATOR.fetch_add(1, Ordering::Relaxed)
}

fn wait_for_image_dimensions(
    shared: &SharedImageDimensions,
    id: u32,
    timeout: Duration,
) -> Option<(u32, u32)> {
    let (lock, cvar) = &**shared;
    let deadline = Instant::now() + timeout;
    let mut dims = match lock.lock() {
        Ok(guard) => guard,
        Err(poisoned) => poisoned.into_inner(),
    };
    loop {
        if let Some(size) = dims.get(&id).copied() {
            return Some(size);
        }
        let remaining = deadline.checked_duration_since(Instant::now())?;
        match cvar.wait_timeout(dims, remaining) {
            Ok((guard, result)) => {
                dims = guard;
                if result.timed_out() {
                    return dims.get(&id).copied();
                }
            }
            Err(poisoned) => {
                let (guard, _) = poisoned.into_inner();
                dims = guard;
            }
        }
    }
}

fn read_primary_window_size(shared: &SharedPrimaryWindowSize) -> PrimaryWindowSize {
    match shared.lock() {
        Ok(state) => *state,
        Err(poisoned) => *poisoned.into_inner(),
    }
}

fn prime_initial_monitor_snapshot(shared: &SharedMonitorInfo) {
    let (lock, cvar) = &**shared;
    let monitors = match lock.lock() {
        Ok(guard) => {
            if guard.is_empty() {
                match cvar.wait_timeout(guard, Duration::from_secs(2)) {
                    Ok((guard, _)) => guard.clone(),
                    Err(poisoned) => {
                        let (guard, _) = poisoned.into_inner();
                        guard.clone()
                    }
                }
            } else {
                guard.clone()
            }
        }
        Err(poisoned) => poisoned.into_inner().clone(),
    };

    if !monitors.is_empty() {
        set_neomacs_monitor_info(input_bridge::convert_monitor_infos(&monitors));
    }
}

fn record_primary_window_resize(shared: &SharedPrimaryWindowSize, event: &DisplayInputEvent) {
    let DisplayInputEvent::WindowResize {
        width,
        height,
        emacs_frame_id,
    } = event
    else {
        return;
    };

    if *emacs_frame_id != 0 || *width == 0 || *height == 0 {
        return;
    }

    match shared.lock() {
        Ok(mut state) => {
            state.width = *width;
            state.height = *height;
        }
        Err(poisoned) => {
            let mut state = poisoned.into_inner();
            state.width = *width;
            state.height = *height;
        }
    }
}

impl PrimaryWindowDisplayHost {
    fn send_render_command(
        &self,
        command: RenderCommand,
        error_context: &str,
    ) -> Result<(), String> {
        self.cmd_tx
            .send(command)
            .map_err(|err| format!("{error_context}: {err}"))?;
        if let Some(waker) = &self.render_waker {
            waker.wake();
        }
        Ok(())
    }
}

impl DisplayHost for PrimaryWindowDisplayHost {
    fn realize_gui_frame(&mut self, request: GuiFrameHostRequest) -> Result<(), String> {
        let title_string = request.title.as_utf8_str().unwrap_or("Neomacs").to_owned();
        tracing::debug!(
            "PrimaryWindowDisplayHost::realize_gui_frame fid=0x{:x} adopted={} size={}x{} title={}",
            request.frame_id.0,
            self.primary_window_adopted,
            request.width,
            request.height,
            title_string
        );
        if !self.primary_window_adopted {
            self.send_render_command(
                RenderCommand::SetWindowTitle {
                    title: title_string.clone(),
                },
                "failed to update primary window title",
            )?;
            self.send_render_command(
                RenderCommand::SetFrameGeometryHints {
                    emacs_frame_id: 0,
                    geometry_hints: request.geometry_hints,
                },
                "failed to update primary window geometry hints",
            )?;
            // The opening GUI frame adopts the already-existing primary host
            // window. Do not push stale Lisp bootstrap dimensions back into
            // that window during adoption; host resize events remain the
            // source of truth until the window is fully realized.
            self.primary_window_adopted = true;
            self.primary_frame_id = Some(request.frame_id);
        } else {
            self.send_render_command(
                RenderCommand::CreateWindow {
                    emacs_frame_id: request.frame_id.0,
                    width: request.width,
                    height: request.height,
                    title: title_string,
                    geometry_hints: request.geometry_hints,
                },
                "failed to create additional GUI window",
            )?;
        }
        self.last_window_titles
            .lock()
            .map_err(|err| format!("failed to cache GUI frame title: {err}"))?
            .insert(request.frame_id, request.title);
        Ok(())
    }

    fn opening_gui_frame_pending(&self) -> bool {
        !self.primary_window_adopted
    }

    fn resize_gui_frame(&mut self, request: GuiFrameHostRequest) -> Result<(), String> {
        let emacs_frame_id = if self.primary_frame_id == Some(request.frame_id) {
            0
        } else {
            request.frame_id.0
        };
        tracing::debug!(
            "PrimaryWindowDisplayHost::resize_gui_frame fid=0x{:x} route=0x{:x} size={}x{}",
            request.frame_id.0,
            emacs_frame_id,
            request.width,
            request.height
        );
        self.send_render_command(
            RenderCommand::ResizeWindow {
                emacs_frame_id,
                width: request.width,
                height: request.height,
                geometry_hints: request.geometry_hints,
            },
            "failed to resize GUI frame",
        )?;
        Ok(())
    }

    fn set_gui_frame_geometry_hints(
        &mut self,
        frame_id: neovm_core::window::FrameId,
        geometry_hints: neovm_core::window::GuiFrameGeometryHints,
    ) -> Result<(), String> {
        let emacs_frame_id =
            if !self.primary_window_adopted || self.primary_frame_id == Some(frame_id) {
                0
            } else {
                frame_id.0
            };
        self.send_render_command(
            RenderCommand::SetFrameGeometryHints {
                emacs_frame_id,
                geometry_hints,
            },
            "failed to update GUI frame geometry hints",
        )?;
        Ok(())
    }

    fn set_gui_frame_title(
        &mut self,
        frame_id: neovm_core::window::FrameId,
        title: LispString,
    ) -> Result<(), String> {
        let mut cached_titles = self
            .last_window_titles
            .lock()
            .map_err(|err| format!("failed to cache GUI frame title: {err}"))?;
        if cached_titles
            .get(&frame_id)
            .is_some_and(|cached| cached == &title)
        {
            return Ok(());
        }
        cached_titles.insert(frame_id, title.clone());
        drop(cached_titles);

        let title_string = title.as_utf8_str().unwrap_or("Neomacs").to_owned();
        let emacs_frame_id = if self.primary_frame_id == Some(frame_id) {
            0
        } else {
            frame_id.0
        };
        self.send_render_command(
            RenderCommand::SetFrameWindowTitle {
                emacs_frame_id,
                title: title_string,
            },
            "failed to update GUI frame title",
        )?;
        Ok(())
    }

    fn current_primary_window_size(&self) -> Option<GuiFrameHostSize> {
        if self.primary_window_adopted {
            return None;
        }
        let state = read_primary_window_size(&self.primary_window_size);
        Some(GuiFrameHostSize {
            width: state.width,
            height: state.height,
        })
    }

    fn set_cursor_blink(&mut self, enabled: bool, interval_ms: u32) -> Result<(), String> {
        self.send_render_command(
            RenderCommand::SetCursorBlink {
                enabled,
                interval_ms,
            },
            "failed to set cursor blink",
        )
    }

    fn resolve_font_for_char(
        &mut self,
        request: FontResolveRequest,
    ) -> Result<Option<ResolvedFontMatch>, String> {
        let requested_family_storage = request.face.family_runtime_string_owned();
        let requested_family = requested_family_storage.as_deref().unwrap_or("Monospace");
        let requested_weight = request.face.weight.unwrap_or(FontWeight::NORMAL).0;
        let requested_italic = request
            .face
            .slant
            .map(|slant| slant.is_italic())
            .unwrap_or(false);
        let font_size = font_size_px_for_face(&request.face);
        let selected = self
            .font_metrics
            .get_or_insert_with(FontMetricsService::new)
            .select_font_for_char(
                request.character,
                requested_family,
                requested_weight,
                requested_italic,
                font_size,
            );
        tracing::debug!(
            target: "neomacs::font_at",
            character = %request.character,
            requested_family,
            requested_weight,
            requested_italic,
            font_size,
            request_face = ?request.face,
            selected = ?selected,
            "display host resolved font-at request"
        );
        Ok(selected.map(|font| ResolvedFontMatch {
            family: LispString::from_utf8(&font.family),
            foundry: None,
            weight: font.weight,
            slant: font.slant,
            width: font.width,
            postscript_name: font.postscript_name.map(|s| LispString::from_utf8(&s)),
        }))
    }

    fn resolve_frame_font(
        &mut self,
        _frame_id: FrameId,
        face: neovm_core::face::Face,
    ) -> Result<Option<ResolvedFrameFont>, String> {
        let requested_family_storage = face.family_runtime_string_owned();
        let requested_family = requested_family_storage.as_deref().unwrap_or("Monospace");
        let requested_weight = face.weight.unwrap_or(FontWeight::NORMAL).0;
        let requested_italic = face.slant.map(|slant| slant.is_italic()).unwrap_or(false);
        let font_size = font_size_px_for_face(&face);
        let selected = self
            .font_metrics
            .get_or_insert_with(FontMetricsService::new)
            .select_font_for_char(
                'M',
                requested_family,
                requested_weight,
                requested_italic,
                font_size,
            );
        let Some(font) = selected else {
            return Ok(None);
        };
        let metrics = self
            .font_metrics
            .get_or_insert_with(FontMetricsService::new)
            .font_metrics(
                &font.family,
                font.weight.0,
                font.slant.is_italic(),
                font_size,
            );
        Ok(Some(ResolvedFrameFont {
            family: LispString::from_utf8(&font.family),
            foundry: None,
            weight: font.weight,
            slant: font.slant,
            width: font.width,
            postscript_name: font.postscript_name.map(|s| LispString::from_utf8(&s)),
            font_size_px: font_size,
            char_width: metrics.char_width.max(1.0),
            line_height: metrics.line_height.max(1.0),
        }))
    }

    fn resolve_font_for_spec(
        &mut self,
        request: FontSpecResolveRequest,
    ) -> Result<Option<ResolvedFontSpecMatch>, String> {
        let matched = neomacs_layout_engine::fontconfig::find_font_for_spec(
            request.family.as_ref().and_then(|ls| ls.as_utf8_str()),
            request.registry.as_ref().and_then(|ls| ls.as_utf8_str()),
            request.lang.as_ref().and_then(|ls| ls.as_utf8_str()),
            request.weight.map(|weight| weight.0),
            request.slant,
        );
        Ok(matched.map(|font| ResolvedFontSpecMatch {
            family: LispString::from_utf8(&font.family),
            registry: Some(LispString::from_utf8("iso10646-1")),
            weight: font.weight.map(FontWeight),
            slant: Some(font.slant),
            width: font.width,
            spacing: font.spacing,
            postscript_name: font.postscript_name.map(|s| LispString::from_utf8(&s)),
        }))
    }

    fn resolve_image(&self, request: ImageResolveRequest) -> Result<Option<ResolvedImage>, String> {
        let cache = match self.resolved_images.lock() {
            Ok(cache) => cache,
            Err(poisoned) => poisoned.into_inner(),
        };
        if let Some(image) = cache.get(&request) {
            return Ok(Some(image.clone()));
        }
        drop(cache);

        let image_id = next_host_image_id();
        match &request.source {
            ImageResolveSource::File(path) => {
                self.send_render_command(
                    RenderCommand::ImageLoadFile {
                        id: image_id,
                        path: path.as_utf8_str().unwrap_or_default().to_owned(),
                        max_width: request.max_width,
                        max_height: request.max_height,
                        fg_color: request.fg_color,
                        bg_color: request.bg_color,
                    },
                    "failed to queue image load",
                )?;
            }
            ImageResolveSource::Data(data) => {
                self.send_render_command(
                    RenderCommand::ImageLoadData {
                        id: image_id,
                        data: data.clone(),
                        max_width: request.max_width,
                        max_height: request.max_height,
                        fg_color: request.fg_color,
                        bg_color: request.bg_color,
                    },
                    "failed to queue image data load",
                )?;
            }
        }

        let Some((width, height)) =
            wait_for_image_dimensions(&self.image_dimensions, image_id, Duration::from_secs(1))
        else {
            return Ok(None);
        };

        let resolved = ResolvedImage {
            image_id,
            width,
            height,
        };
        match self.resolved_images.lock() {
            Ok(mut cache) => {
                cache.insert(request, resolved.clone());
            }
            Err(poisoned) => {
                let mut cache = poisoned.into_inner();
                cache.insert(request, resolved.clone());
            }
        }
        Ok(Some(resolved))
    }
}

fn frame_host_title(eval: &mut Context, frame_id: FrameId) -> LispString {
    let Some((selected_window_id, buffer_id, fallback_title, target_cols)) =
        eval.frame_manager().get(frame_id).map(|frame| {
            let fallback_title = frame.host_title_lisp_string();
            let buffer_id = match frame.selected_window() {
                Some(Window::Leaf { buffer_id, .. }) => Some(*buffer_id),
                _ => None,
            };
            let target_cols = if frame.char_width > 0.0 {
                ((frame.width as f32) / frame.char_width.max(1.0))
                    .floor()
                    .max(1.0) as usize
            } else {
                frame.width.max(1) as usize
            };
            (
                frame.selected_window,
                buffer_id,
                fallback_title,
                target_cols.max(1),
            )
        })
    else {
        return LispString::from_utf8("Neomacs");
    };

    let format = eval
        .obarray()
        .symbol_value("frame-title-format")
        .copied()
        .unwrap_or(Value::NIL);
    if format.is_nil() {
        return fallback_title;
    }

    let rendered = neovm_core::emacs_core::xdisp::format_mode_line_for_display(
        eval,
        format,
        Value::make_window(selected_window_id.0),
        buffer_id
            .map(|buffer_id| Value::make_buffer(buffer_id))
            .unwrap_or(Value::NIL),
        target_cols,
    );
    rendered.as_lisp_string().cloned().unwrap_or(fallback_title)
}

fn adopt_existing_primary_gui_frame(eval: &mut Context) -> Result<(), String> {
    if eval
        .display_host
        .as_ref()
        .is_none_or(|host| !host.opening_gui_frame_pending())
    {
        return Ok(());
    }
    let Some((frame_id, width, height)) = eval
        .frame_manager()
        .selected_frame()
        .map(|frame| (frame.id, frame.width, frame.height))
    else {
        return Ok(());
    };
    let title = frame_host_title(eval, frame_id);
    let geometry_hints = eval
        .frame_manager()
        .get(frame_id)
        .map(|frame| frame.gui_geometry_hints())
        .ok_or_else(|| "selected GUI frame disappeared before adoption".to_string())?;
    let Some(host) = eval.display_host.as_mut() else {
        return Ok(());
    };
    host.realize_gui_frame(GuiFrameHostRequest {
        frame_id,
        width,
        height,
        title,
        geometry_hints,
    })
}

fn sync_live_gui_frame_titles(eval: &mut Context) {
    let frame_ids = eval.frame_manager().frame_list();
    for frame_id in frame_ids {
        let is_gui_frame = eval
            .frame_manager()
            .get(frame_id)
            .is_some_and(|frame| frame.effective_window_system().is_some());
        if !is_gui_frame {
            continue;
        }
        let title = frame_host_title(eval, frame_id);
        if let Some(host) = eval.display_host.as_mut() {
            let _ = host.set_gui_frame_title(frame_id, title);
        }
    }
}

fn seed_gnu_default_gui_chrome_modes(eval: &mut Context) {
    eval.set_variable("menu-bar-mode", Value::T);
    eval.set_variable("tool-bar-mode", Value::T);
}

fn ensure_gnu_tool_bar_setup(eval: &mut Context) {
    let needs_setup = match eval.eval_str(
        "(and (fboundp 'tool-bar-setup) tool-bar-mode (= 1 (length (default-value 'tool-bar-map))))",
    ) {
        Ok(value) => value.is_truthy(),
        Err(err) => {
            tracing::warn!("failed probing tool-bar setup state: {err}");
            false
        }
    };
    if !needs_setup {
        return;
    }
    if let Err(err) = eval.eval_str("(tool-bar-setup)") {
        tracing::warn!("failed running GNU tool-bar setup: {err}");
    }
}

fn sync_selected_gui_chrome_state(eval: &mut Context) {
    let menu_enabled = !eval
        .obarray()
        .symbol_value("menu-bar-mode")
        .copied()
        .unwrap_or(Value::NIL)
        .is_nil();
    let tool_enabled = !eval
        .obarray()
        .symbol_value("tool-bar-mode")
        .copied()
        .unwrap_or(Value::NIL)
        .is_nil();
    if tool_enabled {
        ensure_gnu_tool_bar_setup(eval);
    }

    let menu_items = if menu_enabled {
        collect_gui_menu_bar_items(eval)
    } else {
        Vec::new()
    };
    let tool_items = if tool_enabled {
        collect_gui_tool_bar_items(eval)
    } else {
        Vec::new()
    };

    let mut geometry_hints = None;
    if let Some(frame) = eval.frame_manager_mut().selected_frame_mut() {
        if frame.effective_window_system().is_none() {
            return;
        }
        frame.set_parameter(
            Value::symbol("menu-bar-lines"),
            Value::fixnum(if menu_items.is_empty() { 0 } else { 1 }),
        );
        frame.set_parameter(
            Value::symbol("tool-bar-lines"),
            Value::fixnum(if tool_items.is_empty() { 0 } else { 1 }),
        );
        frame.sync_menu_bar_height_from_parameters();
        frame.sync_tool_bar_height_from_parameters();
        geometry_hints = Some((frame.id, frame.gui_geometry_hints()));
    }

    if let Some((frame_id, hints)) = geometry_hints
        && let Some(host) = eval.display_host.as_mut()
    {
        let _ = host.set_gui_frame_geometry_hints(frame_id, hints);
    }
}

fn font_size_px_for_face(face: &neovm_core::face::Face) -> f32 {
    let default_font_size = face_height_to_pixels(100);
    match &face.height {
        Some(FaceHeight::Absolute(tenths)) => face_height_to_pixels(*tenths),
        Some(FaceHeight::Relative(scale)) => default_font_size * (*scale as f32),
        None => default_font_size,
    }
}

fn create_startup_evaluator_for_mode(mode: RuntimeMode, startup: &StartupOptions) -> Context {
    match mode {
        RuntimeMode::Raw => {
            let startup_surface = raw_loadup_startup_surface(startup, None);
            neovm_core::emacs_core::load::create_bootstrap_evaluator_with_startup_surface(
                BOOTSTRAP_CORE_FEATURES,
                None,
                Some(&startup_surface),
            )
            .expect("raw bootstrap should succeed")
        }
        RuntimeMode::BootstrapUse => {
            neovm_core::emacs_core::load::load_runtime_image_with_features(
                RuntimeImageRole::Bootstrap,
                BOOTSTRAP_CORE_FEATURES,
                startup.dump_file_override.as_deref(),
            )
            .unwrap_or_else(|err| {
                panic!(
                    "bootstrap image should load: {}",
                    render_startup_image_error(&err)
                )
            })
        }
        RuntimeMode::FinalRun => neovm_core::emacs_core::load::load_runtime_image_with_features(
            RuntimeImageRole::Final,
            BOOTSTRAP_CORE_FEATURES,
            startup.dump_file_override.as_deref(),
        )
        .unwrap_or_else(|err| {
            panic!(
                "final image should load: {}",
                render_startup_image_error(&err)
            )
        }),
    }
}

fn raw_loadup_command_line(
    startup: &StartupOptions,
    dump_mode: Option<LoadupDumpMode>,
) -> Vec<String> {
    let mut args = startup.forwarded_args.clone();
    if args.is_empty() {
        args.push(RuntimeMode::Raw.binary_name().to_string());
    }

    // GNU emacs.c:2578 — `if (!no_loadup) ... loadup.el`. We achieve the
    // same effect at the argv level by skipping the `-l loadup` splice
    // when --no-loadup is set. The `--temacs=...` mode below still
    // appends so that the rest of dump bookkeeping continues to run.
    let has_internal_loadup_marker =
        matches!(args.get(1).map(String::as_str), Some("-l" | "--load"))
            && args.get(2).map(String::as_str) == Some("loadup");
    if !startup.no_loadup && !has_internal_loadup_marker {
        args.splice(1..1, ["-l".to_string(), "loadup".to_string()]);
    }

    if let Some(dump_mode) = dump_mode {
        let has_temacs_mode = args
            .iter()
            .any(|arg| arg == "-temacs" || arg == "--temacs" || arg.starts_with("--temacs="));
        if !has_temacs_mode {
            args.push(format!("--temacs={}", dump_mode.as_gnu_string()));
        }
    }

    args
}

fn raw_loadup_startup_surface(
    startup: &StartupOptions,
    dump_mode: Option<LoadupDumpMode>,
) -> LoadupStartupSurface {
    LoadupStartupSurface {
        command_line_args: raw_loadup_command_line(startup, dump_mode),
        noninteractive: startup.noninteractive || dump_mode.is_some(),
    }
}

fn run_gui_main_thread(
    mode: RuntimeMode,
    startup: StartupOptions,
    width: u32,
    height: u32,
    bootstrap_display: BootstrapDisplayConfig,
) {
    let event_loop = build_render_event_loop().unwrap_or_else(|err| {
        eprintln!("neomacs: failed to build GUI event loop: {err}");
        std::process::exit(1);
    });
    let render_waker = GuiEventLoopWaker::new(event_loop.create_proxy());

    let comms = ThreadComms::new().expect("Failed to create thread comms");
    let (emacs_comms, render_comms) = comms.split();
    let primary_window_size: SharedPrimaryWindowSize =
        Arc::new(Mutex::new(PrimaryWindowSize { width, height }));
    let gui_image_dimensions: SharedImageDimensions =
        Arc::new((Mutex::new(HashMap::new()), Condvar::new()));
    let shared_monitors: SharedMonitorInfo = Arc::new((Mutex::new(Vec::new()), Condvar::new()));

    let evaluator_handle = spawn_gui_evaluator_worker(
        mode,
        startup,
        width,
        height,
        bootstrap_display,
        emacs_comms,
        Arc::clone(&primary_window_size),
        Arc::clone(&gui_image_dimensions),
        Arc::clone(&shared_monitors),
        render_waker.clone(),
    );

    tracing::info!(
        "GUI event loop entering on OS main thread ({}x{})",
        width,
        height
    );
    let render_result = run_render_loop_current_thread(
        event_loop,
        render_comms,
        width,
        height,
        "Neomacs".to_string(),
        Arc::clone(&gui_image_dimensions),
        Arc::clone(&shared_monitors),
    );
    if let Err(err) = &render_result {
        tracing::error!("GUI event loop exited with error: {err}");
    }

    let evaluator_exit = match evaluator_handle.join() {
        Ok(exit) => exit,
        Err(payload) => {
            std::panic::resume_unwind(payload);
        }
    };

    if evaluator_exit.restart {
        tracing::warn!("restart requested via kill-emacs, but restart is not implemented yet");
    }
    if evaluator_exit.exit_code != 0 {
        std::process::exit(evaluator_exit.exit_code);
    }
    if render_result.is_err() {
        std::process::exit(1);
    }
}

fn spawn_gui_evaluator_worker(
    mode: RuntimeMode,
    startup: StartupOptions,
    width: u32,
    height: u32,
    bootstrap_display: BootstrapDisplayConfig,
    emacs_comms: EmacsComms,
    primary_window_size: SharedPrimaryWindowSize,
    gui_image_dimensions: SharedImageDimensions,
    shared_monitors: SharedMonitorInfo,
    render_waker: GuiEventLoopWaker,
) -> std::thread::JoinHandle<EvaluatorExit> {
    let cmd_tx_for_panic = emacs_comms.cmd_tx.clone();
    let render_waker_for_panic = render_waker.clone();
    std::thread::Builder::new()
        .name("neomacs-evaluator".to_string())
        // GNU grows the main C stack before Lisp startup.  In the GUI
        // topology the Lisp evaluator is the Emacs main thread semantically,
        // but it runs on a Rust worker so winit can own the OS main thread.
        // Give that worker an explicit native stack instead of relying on
        // pthread defaults chosen before increase_stack_limit runs.
        .stack_size(GUI_EVALUATOR_THREAD_STACK_SIZE)
        .spawn(move || {
            let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                run_gui_evaluator_worker(
                    mode,
                    startup,
                    width,
                    height,
                    bootstrap_display,
                    emacs_comms,
                    primary_window_size,
                    gui_image_dimensions,
                    shared_monitors,
                    render_waker,
                )
            }));
            match outcome {
                Ok(exit) => exit,
                Err(payload) => {
                    let _ = cmd_tx_for_panic.try_send(RenderCommand::Shutdown);
                    render_waker_for_panic.wake();
                    std::panic::resume_unwind(payload);
                }
            }
        })
        .expect("Failed to spawn GUI evaluator worker")
}

fn run_gui_evaluator_worker(
    mode: RuntimeMode,
    startup: StartupOptions,
    width: u32,
    height: u32,
    bootstrap_display: BootstrapDisplayConfig,
    emacs_comms: EmacsComms,
    primary_window_size: SharedPrimaryWindowSize,
    gui_image_dimensions: SharedImageDimensions,
    shared_monitors: SharedMonitorInfo,
    render_waker: GuiEventLoopWaker,
) -> EvaluatorExit {
    let mut evaluator = create_startup_evaluator_for_mode(mode, &startup);
    evaluator.setup_thread_locals();
    evaluator.set_max_depth(1600);
    reset_terminal_host();
    reset_terminal_runtime();
    evaluator.set_variable("dump-mode", Value::NIL);
    tracing::info!("GUI evaluator context initialized");

    let _bootstrap = bootstrap_buffers(&mut evaluator, width, height, bootstrap_display);
    let frame_id = evaluator
        .frame_manager()
        .selected_frame()
        .expect("No selected frame after bootstrap")
        .id;
    configure_gnu_startup_state(&mut evaluator, frame_id, &startup);
    maybe_install_startup_phase_trace(&mut evaluator);

    evaluator.set_display_host(Box::new(PrimaryWindowDisplayHost {
        cmd_tx: emacs_comms.cmd_tx.clone(),
        render_waker: Some(render_waker.clone()),
        primary_window_adopted: false,
        primary_frame_id: None,
        last_window_titles: Mutex::new(HashMap::new()),
        font_metrics: None,
        primary_window_size: Arc::clone(&primary_window_size),
        image_dimensions: Arc::clone(&gui_image_dimensions),
        resolved_images: Mutex::new(HashMap::new()),
    }));
    adopt_existing_primary_gui_frame(&mut evaluator)
        .expect("bootstrap GUI frame adoption should succeed");

    prime_initial_monitor_snapshot(&shared_monitors);

    let (input_tx, input_rx) = crossbeam_channel::unbounded();
    let display_input_rx = emacs_comms.input_rx;
    let primary_window_size_for_input = Arc::clone(&primary_window_size);
    let quit_requested = Arc::clone(&evaluator.quit_requested);
    std::thread::Builder::new()
        .name("input-bridge".to_string())
        .spawn(move || {
            while let Ok(event) = display_input_rx.recv() {
                tracing::info!("input-bridge: received event");
                record_primary_window_resize(&primary_window_size_for_input, &event);
                if let Some(kb_event) = input_bridge::convert_display_event(event) {
                    tracing::info!("input-bridge: converted to kb event");
                    if let neovm_core::keyboard::InputEvent::KeyPress { key, .. } = &kb_event
                        && key.is_default_quit_char()
                    {
                        quit_requested.store(true, std::sync::atomic::Ordering::Relaxed);
                    }
                    if input_tx.send(kb_event).is_err() {
                        break;
                    }
                }
            }
        })
        .expect("Failed to spawn input bridge thread");

    evaluator.init_input_system(input_rx, emacs_comms.wakeup_read_fd);

    LAYOUT_ENGINE.with(|engine| {
        engine.borrow_mut().enable_cosmic_metrics();
    });
    let frame_tx = emacs_comms.frame_tx;
    let initial_frame_tx = frame_tx.clone();
    let redisplay_waker = render_waker.clone();
    evaluator.redisplay_fn = Some(Box::new(move |eval: &mut Context| {
        publish_gui_frame(eval, &frame_tx, Some(&redisplay_waker));
    }));
    publish_gui_frame(&mut evaluator, &initial_frame_tx, Some(&render_waker));

    if let Some(buf) = evaluator.buffer_manager_mut().current_buffer_mut() {
        let mut ul = buf.get_undo_list();
        neovm_core::buffer::undo_list_boundary(&mut ul);
        buf.set_undo_list(ul);
    }

    neovm_core::emacs_core::load::maybe_run_after_pdump_load_hook(&mut evaluator);
    tracing::info!("Entering GNU command loop on GUI evaluator worker...");
    let exit_status = evaluator.recursive_edit();
    if exit_status.is_ok() {
        tracing::info!("Command loop exited normally");
    } else {
        tracing::warn!("Command loop exited with error");
    }

    tracing::info!("GUI evaluator shutting down render loop...");
    let _ = emacs_comms.cmd_tx.try_send(RenderCommand::Shutdown);
    render_waker.wake();

    if let Some(request) = evaluator.shutdown_request() {
        return EvaluatorExit {
            exit_code: request.exit_code,
            restart: request.restart,
        };
    }

    EvaluatorExit::OK
}

pub fn run(mode: RuntimeMode) {
    // Always enable full backtraces for debugging low-level runtime crashes.
    if std::env::var("RUST_BACKTRACE").is_err() {
        unsafe {
            std::env::set_var("RUST_BACKTRACE", "1");
        }
    }

    // Increase the stack size to 64 MB, matching GNU Emacs which adjusts
    // RLIMIT_STACK in main(). Deep Elisp evaluation chains (startup.el →
    // normal-top-level → command-line → init → Doom hooks) can exhaust
    // the default 8 MB stack.
    increase_stack_limit();

    // Handle --help / --version with no logging side effects (so e.g.
    // `NEOMACS_LOG_TO_FILE=1 neomacs --help` does not create a stray
    // neomacs-{pid}.log file).
    if let Some(action) = classify_early_cli_action(std::env::args()) {
        match action {
            EarlyCliAction::PrintHelp { program } => {
                print!("{}", render_help_text(&program));
            }
            EarlyCliAction::PrintVersion => {
                print!("{}", render_version_text());
            }
            EarlyCliAction::PrintFingerprint => {
                print!("{}", render_fingerprint_text());
            }
        }
        return;
    }

    // Parse argv before initializing tracing so we know whether this is a
    // GUI or TTY run — logging policy differs between the two (under TTY
    // any tracing output would smash the alt-screen redisplay engine).
    // `parse_startup_options` emits no tracing events, so delaying init
    // past it costs no diagnostics.
    let startup = parse_startup_options(std::env::args()).unwrap_or_else(|message| {
        eprintln!("{message}");
        std::process::exit(1);
    });

    // Initialize tracing with a writer target appropriate to the
    // binary:
    //
    // - `neomacs-temacs` (RuntimeMode::Raw) and `bootstrap-neomacs`
    //   (RuntimeMode::BootstrapUse) are build-time utilities whose
    //   stdout is captured by the xtask driver — they MUST log to
    //   stdout so the build log shows what they are doing. Frontend
    //   is always `Tty` for them (they run with --batch), but they
    //   have no TUI redisplay engine fighting for the pty, so
    //   stdout logging is safe and useful.
    //
    // - `neomacs` (RuntimeMode::FinalRun) is the user-facing binary.
    //   Under a GUI frontend, stdout is captured to a file by the
    //   calling shell (e.g. `> /tmp/neomacs-gui.log 2>&1`), so
    //   LogTarget::Stdout is fine. Under a TTY frontend (`-nw`,
    //   `--batch`), stdout is the alt-screen pty the redisplay
    //   engine is drawing into, so LogTarget::File routes tracing
    //   to a file instead.
    //
    // In all cases `NEOMACS_LOG_FILE=<path>` overrides the file path
    // (and, for LogTarget::Stdout, also adds a file layer alongside
    // stdout).
    let log_target = match mode {
        RuntimeMode::Raw | RuntimeMode::BootstrapUse => neovm_core::logging::LogTarget::Stdout,
        RuntimeMode::FinalRun => match startup.frontend {
            FrontendKind::Gui => neovm_core::logging::LogTarget::Stdout,
            FrontendKind::Tty => neovm_core::logging::LogTarget::File,
        },
    };
    let _logging_guard = neovm_core::logging::init(log_target);

    if mode == RuntimeMode::Raw
        && let Some(temacs_mode) = startup.temacs_mode
    {
        run_temacs_dump_mode(temacs_mode, &startup);
        return;
    }

    tracing::info!(
        "{} {} starting (pure Rust, backend={}, pid={}, mode={:?}, image={:?})",
        mode.binary_name(),
        neomacs_display_runtime::VERSION,
        neomacs_display_runtime::CORE_BACKEND,
        std::process::id(),
        mode,
        mode.dump_image_kind()
    );
    tracing::info!("Startup frontend: {:?}", startup.frontend);
    if let Some(device) = startup.terminal_device.as_deref() {
        tracing::warn!(
            "terminal device {:?} requested; using current tty until explicit device handoff lands",
            device
        );
    }

    let bootstrap_display = bootstrap_display_config(startup.frontend);
    // For TTY, frame dimensions are in character cells (1x1), so we
    // don't need to scan the system font database for font metrics.
    // This avoids ~500ms of FontMetricsService initialization at
    // startup. GUI mode computes real pixel dimensions from font
    // metrics via bootstrap_frame_metrics().
    let frame_metrics = bootstrap_frame_metrics_for_frontend(startup.frontend);
    let (width, height) = startup_dimensions(startup.frontend, frame_metrics);

    if startup.frontend == FrontendKind::Gui {
        run_gui_main_thread(mode, startup, width, height, bootstrap_display);
        return;
    }

    // 2. Initialize the evaluator from the canonical bootstrap surface.
    //    GNU loads the dumped bootstrap image here, then lets the outer
    //    command loop evaluate `top-level`/`normal-top-level`.
    let mut evaluator = create_startup_evaluator_for_mode(mode, &startup);
    evaluator.setup_thread_locals();
    evaluator.set_max_depth(1600);
    if should_enable_live_tty_io(&startup) {
        reset_terminal_host();
        configure_terminal_runtime(detect_tty_runtime(&startup));
    } else {
        reset_terminal_host();
        reset_terminal_runtime();
    }
    // GNU Emacs does NOT disable GC during startup — GC runs normally.
    // The bc_buf refactor and conservative stack scanning ensure all
    // bytecode VM values are reachable during collection.
    evaluator.set_variable("dump-mode", Value::NIL);
    tracing::info!("Context initialized");

    // 3. Bootstrap the host-side initial frame/buffers.
    let _bootstrap = bootstrap_buffers(&mut evaluator, width, height, bootstrap_display);
    let frame_id = evaluator
        .frame_manager()
        .selected_frame()
        .expect("No selected frame after bootstrap")
        .id;
    configure_gnu_startup_state(&mut evaluator, frame_id, &startup);

    maybe_install_startup_phase_trace(&mut evaluator);

    // 4. Create communication channels before entering GNU's outer
    //    recursive-edit command loop. GNU evaluates `top-level` from that
    //    outer loop, not directly from `main`.
    let comms = ThreadComms::new().expect("Failed to create thread comms");
    let (emacs_comms, render_comms) = comms.split();
    let primary_window_size: SharedPrimaryWindowSize =
        Arc::new(Mutex::new(PrimaryWindowSize { width, height }));
    if should_enable_live_tty_io(&startup) {
        set_terminal_host(Box::new(TtyTerminalHost {
            cmd_tx: emacs_comms.cmd_tx.clone(),
        }));
    }

    // 5. Spawn the frontend loop matching the requested startup mode.
    let frontend = if startup.noninteractive {
        // Batch mode: no terminal I/O, matching GNU which skips
        // init_display() for --batch (emacs.c:1835).
        tracing::info!("TTY batch mode — skipping terminal init");
        FrontendHandle::Batch
    } else {
        // Single-thread TTY path: terminal init here, rendering via TtyRif
        // on the evaluator thread, input reader on a background thread.
        tty_init_terminal();
        let input_reader = tty_frontend::TtyInputReader::spawn(render_comms);
        tracing::info!("TTY frontend spawned (TtyRif single-thread redisplay)");
        FrontendHandle::TtyRifInput(input_reader)
    };

    // 6. Create input bridge: convert display runtime events → keyboard events.
    //
    // GNU Emacs does NOT initialize terminal I/O in --batch mode.
    // The evaluator runs without any input receiver, so
    // `input_rx.is_none()` correctly signals batch mode throughout
    // the keyboard/command-loop code. This prevents blocking on
    // `rx.recv()` in read_char_with_timeout and avoids spawning
    // unnecessary threads.
    if !startup.noninteractive {
        let (input_tx, input_rx) = crossbeam_channel::unbounded();
        let display_input_rx = emacs_comms.input_rx;
        let primary_window_size_for_input = Arc::clone(&primary_window_size);
        // Shared quit-request flag. When the bridge sees `C-g` it flips
        // this so the evaluator's `maybe_quit` can observe it without
        // waiting for `read_char` to drain the channel. Mirrors GNU's
        // synchronous keystroke path (`keyboard.c:3812` sets Vquit_flag
        // immediately); Rust can't longjmp into the evaluator, so we
        // poll an atomic instead.
        let quit_requested = Arc::clone(&evaluator.quit_requested);
        std::thread::Builder::new()
            .name("input-bridge".to_string())
            .spawn(move || {
                while let Ok(event) = display_input_rx.recv() {
                    tracing::info!("input-bridge: received event");
                    record_primary_window_resize(&primary_window_size_for_input, &event);
                    if let Some(kb_event) = input_bridge::convert_display_event(event) {
                        tracing::info!("input-bridge: converted to kb event");
                        if let neovm_core::keyboard::InputEvent::KeyPress { key, .. } = &kb_event {
                            if key.is_default_quit_char() {
                                quit_requested.store(true, std::sync::atomic::Ordering::Relaxed);
                            }
                        }
                        if input_tx.send(kb_event).is_err() {
                            break; // Context dropped
                        }
                    }
                }
            })
            .expect("Failed to spawn input bridge thread");

        // 7. Connect evaluator to input system
        let wakeup_fd = emacs_comms.wakeup_read_fd;
        evaluator.init_input_system(input_rx, wakeup_fd);
    }

    // 8. Set up redisplay callback (layout engine + TTY RIF render).
    maybe_install_tty_redisplay_callback(&mut evaluator, &startup);

    // Add undo boundary after startup so initial content isn't undoable
    if let Some(buf) = evaluator.buffer_manager_mut().current_buffer_mut() {
        let mut ul = buf.get_undo_list();
        neovm_core::buffer::undo_list_boundary(&mut ul);
        buf.set_undo_list(ul);
    }

    // 9. Enter GNU's outer command loop. This mirrors src/emacs.c, which
    //     enters recursive-edit and lets the outer command loop evaluate the
    //     `top-level` startup form before reading interactive input.
    neovm_core::emacs_core::load::maybe_run_after_pdump_load_hook(&mut evaluator);
    tracing::info!("Entering GNU command loop (recursive-edit)...");
    let exit_status = evaluator.recursive_edit();
    if exit_status.is_ok() {
        tracing::info!("Command loop exited normally");
    } else {
        tracing::warn!("Command loop exited with error");
    }

    // 11. Shutdown
    tracing::info!("Shutting down...");
    let _ = emacs_comms
        .cmd_tx
        .try_send(neomacs_display_runtime::thread_comm::RenderCommand::Shutdown);
    frontend.join();
    if should_enable_live_tty_io(&startup) {
        tty_shutdown_terminal();
    }
    tracing::info!("Neomacs exited cleanly");

    if let Some(request) = evaluator.shutdown_request() {
        if request.restart {
            tracing::warn!("restart requested via kill-emacs, but restart is not implemented yet");
        }
        if request.exit_code != 0 {
            std::process::exit(request.exit_code);
        }
    }
}

// ---------------------------------------------------------------------------
// TTY terminal setup/teardown for TtyRif single-thread path
// ---------------------------------------------------------------------------

/// Saved original termios for the TtyRif path. Stored globally so
/// `tty_shutdown_terminal` can restore it even from a panic handler.
#[cfg(unix)]
static TTY_SAVED_TERMIOS: std::sync::Mutex<Option<libc::termios>> = std::sync::Mutex::new(None);

/// Set up the terminal for the TtyRif direct-rendering path:
/// raw mode, alternate screen buffer, hidden cursor.
#[cfg(unix)]
fn tty_init_terminal() {
    use std::io::Write;
    use std::mem::MaybeUninit;

    unsafe {
        let mut original = MaybeUninit::<libc::termios>::uninit();
        if libc::tcgetattr(libc::STDIN_FILENO, original.as_mut_ptr()) != 0 {
            tracing::error!("tty_init_terminal: tcgetattr failed");
            return;
        }
        let original = original.assume_init();

        // Save for later restore
        if let Ok(mut guard) = TTY_SAVED_TERMIOS.lock() {
            *guard = Some(original);
        }

        let mut raw = original;
        // Input: no break, no CR->NL, no parity, no strip, no start/stop
        raw.c_iflag &= !(libc::BRKINT | libc::ICRNL | libc::INPCK | libc::ISTRIP | libc::IXON);
        // Output: disable post-processing
        raw.c_oflag &= !libc::OPOST;
        // Control: 8-bit chars
        raw.c_cflag |= libc::CS8;
        // Local: no echo, no canonical, no signals, no extended
        raw.c_lflag &= !(libc::ECHO | libc::ICANON | libc::ISIG | libc::IEXTEN);
        // Non-blocking reads
        raw.c_cc[libc::VMIN] = 0;
        raw.c_cc[libc::VTIME] = 0;

        if libc::tcsetattr(libc::STDIN_FILENO, libc::TCSAFLUSH, &raw) != 0 {
            tracing::error!("tty_init_terminal: tcsetattr failed");
            return;
        }
    }

    // Enter alternate screen, hide cursor, clear
    let mut stdout = std::io::stdout();
    let _ = stdout.write_all(b"\x1b[?1049h\x1b[?25l\x1b[2J");
    let _ = stdout.flush();
    tracing::info!("TTY terminal initialized (raw mode + alt screen)");
}

#[cfg(not(unix))]
fn tty_init_terminal() {
    tracing::warn!("tty_init_terminal: not implemented on this platform");
}

/// Restore the terminal to its original state: show cursor, leave alt screen,
/// reset SGR, restore saved termios.
#[cfg(unix)]
fn tty_shutdown_terminal() {
    use std::io::Write;

    // Show cursor, reset SGR, leave alternate screen
    let mut stdout = std::io::stdout();
    let _ = stdout.write_all(b"\x1b[0m\x1b[?25h\x1b[?1049l");
    let _ = stdout.flush();

    // Restore termios
    if let Ok(guard) = TTY_SAVED_TERMIOS.lock() {
        if let Some(ref original) = *guard {
            unsafe {
                let _ = libc::tcsetattr(libc::STDIN_FILENO, libc::TCSAFLUSH, original);
            }
        }
    }
    tracing::info!("TTY terminal restored");
}

#[cfg(not(unix))]
fn tty_shutdown_terminal() {
    tracing::warn!("tty_shutdown_terminal: not implemented on this platform");
}

fn run_temacs_dump_mode(dump_mode: LoadupDumpMode, startup: &StartupOptions) {
    // Logging is already initialized by `run()` before this function is
    // called; calling `init()` again here is redundant (it would be a
    // no-op anyway because the global subscriber is set once).
    tracing::info!(
        "{} {} starting raw loadup dump (dump-mode={}, pid={})",
        RuntimeMode::Raw.binary_name(),
        neomacs_display_runtime::VERSION,
        dump_mode.as_gnu_string(),
        std::process::id()
    );

    let startup_surface = raw_loadup_startup_surface(startup, Some(dump_mode));
    let eval = neovm_core::emacs_core::load::create_bootstrap_evaluator_with_startup_surface(
        BOOTSTRAP_CORE_FEATURES,
        Some(dump_mode),
        Some(&startup_surface),
    )
    .expect("temacs bootstrap dump should succeed");

    if let Some(request) = eval.shutdown_request()
        && request.exit_code != 0
    {
        std::process::exit(request.exit_code);
    }
}

#[allow(dead_code)]
fn main() {
    run(runtime_mode_from_argv(std::env::args()));
}

// ---------------------------------------------------------------------------
// Bootstrap helpers
// ---------------------------------------------------------------------------

struct BootstrapResult {
    #[allow(dead_code)]
    scratch_id: BufferId,
    #[allow(dead_code)]
    minibuf_id: BufferId,
}

#[derive(Clone, Copy, Debug)]
struct BootstrapFrameMetrics {
    char_width: f32,
    char_height: f32,
    font_pixel_size: f32,
}

fn font_weight_symbol(weight: FontWeight) -> &'static str {
    match weight.0 {
        0..=150 => "thin",
        151..=250 => "extra-light",
        251..=350 => "light",
        351..=450 => "normal",
        451..=550 => "medium",
        551..=650 => "semi-bold",
        651..=750 => "bold",
        751..=850 => "extra-bold",
        _ => "black",
    }
}

fn startup_font_weight_symbol(weight: FontWeight) -> &'static str {
    match weight.0 {
        351..=450 => "regular",
        _ => font_weight_symbol(weight),
    }
}

fn font_slant_symbol(slant: FontSlant) -> &'static str {
    match slant {
        FontSlant::Normal => "normal",
        FontSlant::Italic => "italic",
        FontSlant::Oblique => "oblique",
        FontSlant::ReverseItalic => "reverse-italic",
        FontSlant::ReverseOblique => "reverse-oblique",
    }
}

fn font_width_symbol(width: FontWidth) -> &'static str {
    match width {
        FontWidth::UltraCondensed => "ultra-condensed",
        FontWidth::ExtraCondensed => "extra-condensed",
        FontWidth::Condensed => "condensed",
        FontWidth::SemiCondensed => "semi-condensed",
        FontWidth::Normal => "normal",
        FontWidth::SemiExpanded => "semi-expanded",
        FontWidth::Expanded => "expanded",
        FontWidth::ExtraExpanded => "extra-expanded",
        FontWidth::UltraExpanded => "ultra-expanded",
    }
}

fn bootstrap_default_font_parameter(font_pixel_size: f32) -> Value {
    let mut metrics_svc = FontMetricsService::new();
    let selected = metrics_svc.select_font_for_char('M', "Monospace", 400, false, font_pixel_size);
    let rounded_pixel_size = font_pixel_size.max(1.0).round() as i64;

    let family = selected
        .as_ref()
        .map(|font| font.family.as_str())
        .unwrap_or("Monospace");
    let weight = selected
        .as_ref()
        .map(|font| startup_font_weight_symbol(font.weight))
        .unwrap_or("regular");
    let slant = selected
        .as_ref()
        .map(|font| font_slant_symbol(font.slant))
        .unwrap_or("normal");
    let width = selected
        .as_ref()
        .map(|font| font_width_symbol(font.width))
        .unwrap_or("normal");

    Value::vector(vec![
        Value::keyword("font-object"),
        Value::keyword("family"),
        Value::string(family),
        Value::keyword("weight"),
        Value::symbol(weight),
        Value::keyword("slant"),
        Value::symbol(slant),
        Value::keyword("width"),
        Value::symbol(width),
        // In GNU font objects, :size is pixel size.  Keep :height in
        // face-attribute units (1/10pt) so face derivation still sees the
        // default-face height rather than a raw pixel count.
        Value::keyword("size"),
        Value::fixnum(rounded_pixel_size),
        Value::keyword("height"),
        Value::fixnum(100),
    ])
}

fn bootstrap_default_font_name(font_pixel_size: f32) -> Value {
    let mut metrics_svc = FontMetricsService::new();
    let selected = metrics_svc.select_font_for_char('M', "Monospace", 400, false, font_pixel_size);
    let rounded_pixel_size = font_pixel_size.max(1.0).round() as i64;

    let family = selected
        .as_ref()
        .map(|font| font.family.as_str())
        .unwrap_or("Monospace");
    let weight = selected
        .as_ref()
        .map(|font| startup_font_weight_symbol(font.weight))
        .unwrap_or("regular");
    let slant = selected
        .as_ref()
        .map(|font| font_slant_symbol(font.slant))
        .unwrap_or("normal");

    Value::string(format!(
        "-*-{family}-{weight}-{slant}-*-*-{rounded_pixel_size}-*-*-*-*-*-*-*"
    ))
}

fn bootstrap_frame_metrics() -> BootstrapFrameMetrics {
    // GNU X backends seed the first GUI frame from a 10pt default font and
    // convert that through the active Xft DPI.
    let font_pixel_size = face_height_to_pixels(100);
    let mut metrics_svc = FontMetricsService::new();
    let metrics = metrics_svc.font_metrics("Monospace", 400, false, font_pixel_size);
    BootstrapFrameMetrics {
        char_width: metrics.char_width.max(1.0),
        char_height: metrics.line_height.max(1.0),
        font_pixel_size,
    }
}

fn bootstrap_frame_metrics_for_frontend(frontend: FrontendKind) -> BootstrapFrameMetrics {
    if frontend == FrontendKind::Tty {
        BootstrapFrameMetrics {
            char_width: 1.0,
            char_height: 1.0,
            font_pixel_size: 16.0,
        }
    } else {
        bootstrap_frame_metrics()
    }
}

fn bootstrap_buffers(
    eval: &mut Context,
    width: u32,
    height: u32,
    display: BootstrapDisplayConfig,
) -> BootstrapResult {
    let frame_metrics = bootstrap_frame_metrics_for_frontend(display.frontend);
    let find_or_create_buffer = |eval: &mut Context, name: &str| {
        eval.buffer_manager()
            .find_buffer_by_name(name)
            .unwrap_or_else(|| eval.buffer_manager_mut().create_buffer(name))
    };

    // Reuse GNU startup buffers instead of creating duplicate names on top of
    // cached bootstrap state.
    let scratch_id = find_or_create_buffer(eval, "*scratch*");
    let _ = eval
        .buffer_manager_mut()
        .clear_buffer_labeled_restrictions(scratch_id);
    if let Some(buf) = eval.buffer_manager_mut().get_mut(scratch_id) {
        buf.widen();
        // Don't insert scratch content here. GNU Emacs populates
        // *scratch* from startup.el:2948 via
        //   (insert (substitute-command-keys initial-scratch-message))
        // which handles \\[...] key-binding expansion and backtick →
        // curly-quote conversion via text-quoting-style. Hardcoding
        // the content in Rust bypassed both of those, producing bare
        // "C-x C-f" instead of quoted "'C-x C-f'".
        buf.goto_byte(buf.point_max());
    }

    // Set *scratch* as the current buffer
    eval.buffer_manager_mut().set_current(scratch_id);

    let msg_id = find_or_create_buffer(eval, "*Messages*");
    let _ = eval
        .buffer_manager_mut()
        .clear_buffer_labeled_restrictions(msg_id);
    if let Some(buf) = eval.buffer_manager_mut().get_mut(msg_id) {
        buf.widen();
        let len = buf.total_bytes();
        if len > 0 {
            buf.delete_region(0, len);
        }
        buf.goto_byte(0);
    }

    let mini_id = find_or_create_buffer(eval, " *Minibuf-0*");
    let _ = eval
        .buffer_manager_mut()
        .clear_buffer_labeled_restrictions(mini_id);
    if let Some(buf) = eval.buffer_manager_mut().get_mut(mini_id) {
        buf.widen();
        buf.goto_byte(0);
    }

    let frame_id = {
        let frame_manager = eval.frame_manager();
        let selected = frame_manager.selected_frame().map(|frame| frame.id);
        let should_reuse_existing = selected.is_some() && frame_manager.frame_list().len() == 1;
        (selected, should_reuse_existing)
    };
    let frame_id = if frame_id.1 {
        let frame_id = frame_id.0.expect("selected startup frame");
        tracing::info!(
            "Reusing existing startup frame {:?} as bootstrap frame ({}x{})",
            frame_id,
            width,
            height
        );
        frame_id
    } else {
        let frame_id = eval
            .frame_manager_mut()
            .create_frame("F1", width, height, scratch_id);
        tracing::info!(
            "Created frame {:?} ({}x{}) with *scratch*={:?}",
            frame_id,
            width,
            height,
            scratch_id
        );
        frame_id
    };
    let _ = eval.frame_manager_mut().select_frame(frame_id);

    // Seed frame parameters so GNU Lisp startup sees the correct host surface.
    let initial_tty_frame = display.frontend == FrontendKind::Tty
        && eval
            .obarray()
            .symbol_value("noninteractive")
            .is_some_and(|value| value.is_truthy());
    if let Some(frame) = eval.frame_manager_mut().get_mut(frame_id) {
        // Font parameter resolution creates a FontMetricsService which
        // scans the system font database (~500ms). Skip for TTY where
        // font parameters are unused — TTY uses 1x1 character cells.
        let (default_font, default_font_name) = if display.frontend == FrontendKind::Tty {
            (Value::NIL, Value::string("fixed"))
        } else {
            (
                bootstrap_default_font_parameter(frame_metrics.font_pixel_size),
                bootstrap_default_font_name(frame_metrics.font_pixel_size),
            )
        };
        // Reused startup frames must be normalized back to GNU's initial-frame
        // surface: generated name (e.g. "F1"), nil title, nil icon-name.
        frame.set_generated_name_value(frame.generated_name_value());
        frame.clear_title();
        frame.icon_name = Value::NIL;
        frame.initial = initial_tty_frame;
        frame.width = width;
        frame.height = height;
        frame.visible = true;
        if let Some(window_system) = display.window_system_symbol() {
            frame.set_window_system(Some(Value::symbol(window_system)));
            frame.set_parameter(Value::symbol("foreground-color"), Value::string("black"));
            frame.set_parameter(Value::symbol("background-color"), Value::string("white"));
        } else {
            frame.set_window_system(None);
        }
        frame.set_parameter(
            Value::symbol("display-type"),
            Value::symbol(display.display_type_symbol()),
        );
        frame.set_parameter(
            Value::symbol("background-mode"),
            Value::symbol(display.background_mode),
        );
        frame.set_parameter(Value::symbol("font"), default_font_name);
        frame.set_parameter(Value::symbol("font-parameter"), default_font);
        // GNU frame.c: initial frame title is NULL (unset). The %F
        // mode-line construct falls through to frame->name ("F1") when
        // title is unset. Don't set a title here — let %F show the
        // frame name, matching GNU behaviour.

        frame.font_pixel_size = frame_metrics.font_pixel_size;
        if display.frontend == FrontendKind::Tty {
            // TTY frames use 1x1 character cell metrics
            // (GNU Emacs frame.c:1184-1185: column_width=1, line_height=1).
            frame.char_width = 1.0;
            frame.char_height = 1.0;
            // The minibuffer was created with a pixel height (16.0) in Frame::new.
            // For TTY, resize it to 1 row (char_height=1.0) before sync.
            if let Some(mini) = frame.minibuffer_leaf.as_mut() {
                let b = *mini.bounds();
                mini.set_bounds(neovm_core::window::Rect::new(b.x, b.y, b.width, 1.0));
            }
        } else {
            frame.char_width = frame_metrics.char_width;
            frame.char_height = frame_metrics.char_height;
        }
        frame.sync_tab_bar_height_from_parameters();
        // Match GNU `frame.c:1307-1309` (TTY frame init):
        //   FRAME_MENU_BAR_LINES (f) = NILP (Vmenu_bar_mode) ? 0 : 1;
        // On TTY frames neomacs has no per-frame default-frame-alist
        // bridge yet, so seed the parameter directly here when the
        // frontend is TTY before calling `sync_menu_bar_height_from_parameters`.
        // The GUI path has its own menu bar pipeline (see
        // `neomacs-display-runtime`) and never goes through this code,
        // so we only need to set the parameter for `FrontendKind::Tty`.
        if display.frontend == FrontendKind::Tty {
            frame.set_parameter(
                neovm_core::emacs_core::Value::symbol("menu-bar-lines"),
                neovm_core::emacs_core::Value::fixnum(1),
            );
        }
        frame.sync_menu_bar_height_from_parameters();
        frame.sync_tool_bar_height_from_parameters();
        if let Window::Leaf {
            buffer_id,
            window_start,
            point,
            ..
        } = &mut frame.root_window
        {
            *buffer_id = scratch_id;
            *window_start = 0;
            *point = 0;
        }
    }
    if display.frontend == FrontendKind::Gui {
        seed_gnu_default_gui_chrome_modes(eval);
        sync_selected_gui_chrome_state(eval);
    } else {
        eval.set_face_attribute(
            "default",
            ":foreground",
            neovm_core::face::FaceAttrValue::Unspecified,
        );
        eval.set_face_attribute(
            "default",
            ":background",
            neovm_core::face::FaceAttrValue::Unspecified,
        );
    }

    if display.window_system_symbol().is_some() {
        neovm_core::emacs_core::font::seed_live_frame_default_face_from_font_parameter(
            eval, frame_id,
        );
    }

    // Fix window geometry: root window takes frame height minus minibuffer.
    if let Some(frame) = eval.frame_manager_mut().get_mut(frame_id) {
        let mini_h = frame.char_height.max(1.0);
        let mini_y = height as f32 - mini_h;
        if let Window::Leaf { bounds, .. } = &mut frame.root_window {
            bounds.height = mini_y;
        }
        if let Some(mini_leaf) = &mut frame.minibuffer_leaf {
            if let Window::Leaf {
                buffer_id,
                window_start,
                point,
                bounds,
                ..
            } = mini_leaf
            {
                *buffer_id = mini_id;
                *window_start = 0;
                *point = 0;
                bounds.y = mini_y;
                bounds.height = mini_h;
                bounds.width = width as f32;
            }
        }
    }

    BootstrapResult {
        scratch_id,
        minibuf_id: mini_id,
    }
}

fn configure_gnu_startup_state(eval: &mut Context, frame_id: FrameId, startup: &StartupOptions) {
    let argv_strings = startup.forwarded_args.iter().cloned().collect::<Vec<_>>();
    let argv = argv_strings
        .iter()
        .cloned()
        .map(Value::string)
        .collect::<Vec<_>>();
    let argv_left = argv_strings
        .iter()
        .skip(1)
        .cloned()
        .map(Value::string)
        .collect::<Vec<_>>();
    let invocation_directory = std::env::current_exe()
        .ok()
        .and_then(|path| path.parent().map(|parent| parent.to_path_buf()))
        .unwrap_or_else(|| PathBuf::from("/"));
    let invocation_name = std::env::current_exe()
        .ok()
        .and_then(|path| {
            path.file_name()
                .map(|name| name.to_string_lossy().to_string())
        })
        .unwrap_or_else(|| "neomacs".to_string());
    let invocation_directory = ensure_dir_string(&invocation_directory);

    eval.set_variable("command-line-args", Value::list(argv));
    eval.set_variable("command-line-args-left", Value::list(argv_left));
    eval.set_variable("command-line-processed", Value::NIL);
    eval.set_variable(
        "noninteractive",
        if startup.noninteractive {
            Value::T
        } else {
            Value::NIL
        },
    );
    // Mirror GNU's C-side `no_site_lisp` / `build_details` globals as
    // Lisp variables. GNU itself does not expose them as Lisp vars (the
    // load-path / version code reads the C globals directly), but
    // surfacing them here lets oracle tests verify the parsed value
    // and lets future load-path or version code observe the choice
    // without re-walking argv. Defaults match GNU: no_site_lisp=false
    // means site-lisp is included; build-details=t means build-time
    // strings are populated.
    eval.set_variable(
        "no-site-lisp",
        if startup.no_site_lisp {
            Value::T
        } else {
            Value::NIL
        },
    );
    eval.set_variable(
        "build-details",
        if startup.no_build_details {
            Value::NIL
        } else {
            Value::T
        },
    );
    let (terminal_frame, frame_initial_frame, default_minibuffer_frame) = match startup.frontend {
        FrontendKind::Gui => {
            let terminal_frame_id = ensure_gnu_startup_terminal_frame(eval, frame_id);
            let window_system = Value::symbol(gui_window_system_symbol());
            eval.set_variable("window-system", window_system);
            eval.set_variable("initial-window-system", window_system);
            eval.set_variable(
                "frame-initial-frame-alist",
                opening_frame_initial_alist(eval, window_system),
            );
            (
                Value::make_frame(terminal_frame_id.0),
                Value::make_frame(frame_id.0),
                Value::make_frame(frame_id.0),
            )
        }
        FrontendKind::Tty => {
            eval.set_variable("window-system", Value::NIL);
            eval.set_variable("initial-window-system", Value::NIL);
            if should_enable_live_tty_io(startup) {
                seed_live_tty_frame_parameters(eval, frame_id, startup);
            }
            (Value::make_frame(frame_id.0), Value::NIL, Value::NIL)
        }
    };
    eval.set_variable("invocation-name", Value::string(invocation_name));
    eval.set_variable(
        "invocation-directory",
        Value::unibyte_string(invocation_directory),
    );
    let cwd = std::env::current_dir()
        .map(|p| ensure_dir_string(&p))
        .unwrap_or_else(|_| "/".to_string());
    eval.set_variable("default-directory", Value::unibyte_string(cwd));
    eval.set_variable("terminal-frame", terminal_frame);
    eval.set_variable("frame-initial-frame", frame_initial_frame);
    eval.set_variable("default-minibuffer-frame", default_minibuffer_frame);
    // Skip the splash screen — its fill-region is extremely slow through
    // with_mirrored_evaluator.  Users who want it can set this to nil in
    // their init file.
    eval.set_variable("inhibit-startup-screen", Value::T);
}

fn seed_live_tty_frame_parameters(eval: &mut Context, frame_id: FrameId, startup: &StartupOptions) {
    let tty_name = detect_tty_name(startup);
    let tty_type = detect_tty_type();
    if let Some(frame) = eval.frame_manager_mut().get_mut(frame_id) {
        frame.set_parameter(Value::symbol("tty"), Value::string(tty_name));
        if let Some(tty_type) = tty_type {
            frame.set_parameter(Value::symbol("tty-type"), Value::string(tty_type));
        } else {
            frame.remove_parameter(Value::symbol("tty-type"));
        }
    }
}

fn ensure_gnu_startup_terminal_frame(eval: &mut Context, opening_frame_id: FrameId) -> FrameId {
    if let Some(existing) = eval
        .frame_manager()
        .frame_list()
        .into_iter()
        .find(|candidate| {
            *candidate != opening_frame_id
                && eval.frame_manager().get(*candidate).is_some_and(|frame| {
                    !frame.visible && frame.effective_window_system().is_none()
                })
        })
    {
        return existing;
    }

    let seed_buffer_id = if let Some(id) = eval.buffer_manager().current_buffer_id() {
        id
    } else if let Some(id) = eval.buffer_manager().find_buffer_by_name("*scratch*") {
        id
    } else {
        eval.buffer_manager_mut().create_buffer("*scratch*")
    };
    let (width, height, environment) = eval
        .frame_manager()
        .get(opening_frame_id)
        .map(|frame| {
            (
                frame.width.max(1),
                frame.height.max(1),
                frame.parameter("environment"),
            )
        })
        .unwrap_or((80, 25, None));
    let terminal_frame_id =
        eval.frame_manager_mut()
            .create_frame("Fstartup-tty", width, height, seed_buffer_id);
    if let Some(frame) = eval.frame_manager_mut().get_mut(terminal_frame_id) {
        frame.visible = false;
        frame.set_window_system(None);
        frame.remove_parameter(Value::symbol("display-type"));
        frame.remove_parameter(Value::symbol("background-mode"));
        if let Some(environment) = environment {
            frame.set_parameter(Value::symbol("environment"), environment);
        }
    }
    terminal_frame_id
}

fn opening_frame_initial_alist(eval: &Context, window_system: Value) -> Value {
    let mut params = vec![Value::cons(Value::symbol("window-system"), window_system)];
    for symbol_name in ["initial-frame-alist", "default-frame-alist"] {
        if let Some(value) = eval.obarray().symbol_value(symbol_name)
            && let Some(items) = neovm_core::emacs_core::value::list_to_vec(value)
        {
            params.extend(items);
        }
    }
    Value::list(params)
}

#[cfg(test)]
fn run_gnu_startup(eval: &mut Context) {
    increase_stack_limit();
    stacker::grow(64 * 1024 * 1024, || run_gnu_startup_inner(eval));
}

#[cfg(test)]
fn run_gnu_startup_inner(eval: &mut Context) {
    eval.setup_thread_locals();
    let _ = std::fs::write("/tmp/neomacs-startup-phases.trace", "");
    maybe_install_startup_phase_trace(eval);
    eval.eval_str(
        r#"
        (progn
          (defun neomacs--test-exit-startup-recursive-edit ()
            (remove-hook 'window-setup-hook
                         #'neomacs--test-exit-startup-recursive-edit)
            (exit-recursive-edit))
          (add-hook 'window-setup-hook
                    #'neomacs--test-exit-startup-recursive-edit))
        "#,
    )
    .expect("startup exit helper should install");
    let top_level = eval.obarray().symbol_value("top-level").cloned();
    tracing::info!("top-level variable before startup: {:?}", top_level);

    let (_tx, rx) = crossbeam_channel::unbounded();

    let mut wake_pipe = [0; 2];
    let pipe_result = unsafe { libc::pipe(wake_pipe.as_mut_ptr()) };
    assert_eq!(pipe_result, 0, "pipe should initialize");
    eval.init_input_system(rx, wake_pipe[0]);

    let result = eval.recursive_edit();
    unsafe {
        libc::close(wake_pipe[0]);
        libc::close(wake_pipe[1]);
    }

    if let Err(other) = result {
        let last_phase = eval
            .obarray()
            .symbol_value("neomacs--startup-last-phase")
            .cloned()
            .map(|value| print_value_with_eval(eval, &value));
        let last_call = eval
            .obarray()
            .symbol_value("neomacs--startup-last-call")
            .cloned()
            .map(|value| print_value_with_eval(eval, &value));
        panic!(
            "GNU startup via recursive_edit failed: {other} last-phase={last_phase:?} last-call={last_call:?}"
        );
    }
}

fn maybe_install_startup_phase_trace(eval: &mut Context) {
    if !cfg!(test) && std::env::var("NEOMACS_TRACE_STARTUP_PHASES").unwrap_or_default() != "1" {
        return;
    }
    let source = r#"
        (progn
          (defvar neomacs--startup-last-phase nil)
          (defvar neomacs--startup-last-call nil)
          (defvar neomacs--startup-trace-active nil)
          (with-temp-buffer
            (write-region (point-min) (point-max)
                          "/tmp/neomacs-startup-phases.trace" nil 'silent))
          (defun neomacs--startup-trace-around (name orig &rest args)
            (if neomacs--startup-trace-active
                (apply orig args)
              (let ((neomacs--startup-trace-active t))
                (setq neomacs--startup-last-phase name)
                (setq neomacs--startup-last-call (cons name args))
                (with-temp-buffer
                  (insert (format "enter %S %S\n" name args))
                  (append-to-file (point-min) (point-max)
                                  "/tmp/neomacs-startup-phases.trace"))
                (prog1
                    (apply orig args)
                  (with-temp-buffer
                    (insert (format "leave %S\n" name))
                    (append-to-file (point-min) (point-max)
                                    "/tmp/neomacs-startup-phases.trace"))))))
          (dolist (fn '(set-locale-environment
                        handle-args-function
                        x-handle-args
                        x-open-connection
                        create-default-fontset
                        create-fontset-from-fontset-spec
                        create-fontset-from-x-resource
                        neomacs--setup-cursor-blink
                        neomacs--setup-animations
                        pixel-scroll-precision-mode
                        frame-initialize
                        startup--setup-quote-display
                        normal-erase-is-backspace-setup-frame
                        tty-register-default-colors
                        startup--load-user-init-file
                        custom-reevaluate-setting
                        tty-run-terminal-initialization
                        display-startup-echo-area-message
                        command-line-1
                        display-startup-screen
                        frame-notice-user-settings))
            (when (fboundp fn)
              (advice-add fn :around
                          (eval `(lambda (orig &rest args)
                                   (apply #'neomacs--startup-trace-around
                                          ',fn orig args)))))))
    "#;
    if let Err(err) = eval.eval_str(source) {
        tracing::warn!("startup trace helper install failed: {err:?}");
    }
}

fn ensure_dir_string(path: &Path) -> String {
    let mut dir = path.to_string_lossy().to_string();
    if !dir.ends_with('/') {
        dir.push('/');
    }
    dir
}

fn current_layout_frame_id(evaluator: &Context) -> Option<FrameId> {
    evaluator
        .frame_manager()
        .selected_frame()
        .map(|frame| frame.id)
}

fn publish_gui_frame(
    evaluator: &mut Context,
    frame_tx: &crossbeam_channel::Sender<neomacs_display_protocol::glyph_matrix::FrameDisplayState>,
    render_waker: Option<&GuiEventLoopWaker>,
) {
    evaluator.setup_thread_locals();
    sync_selected_gui_chrome_state(evaluator);
    run_layout(evaluator);
    sync_live_gui_frame_titles(evaluator);

    // Take the complete FrameDisplayState produced by the layout engine's
    // GlyphMatrixBuilder and hand it to the render thread.
    let display_state =
        LAYOUT_ENGINE.with(|engine| engine.borrow_mut().last_frame_display_state.take());
    let Some(display_state) = display_state else {
        return;
    };
    if frame_tx.try_send(display_state).is_ok() {
        if let Some(waker) = render_waker {
            waker.wake();
        }
    }
}

thread_local! {
    // Start without font metrics to avoid the ~500ms cosmic-text
    // font database scan on first access. The GUI path enables
    // cosmic metrics explicitly; the TTY path leaves it as None.
    static LAYOUT_ENGINE: std::cell::RefCell<neomacs_display_runtime::layout::LayoutEngine> =
        std::cell::RefCell::new(neomacs_display_runtime::layout::LayoutEngine::new_without_font_metrics());
}

/// Run the layout engine on the selected live frame.
fn run_layout(evaluator: &mut Context) {
    let Some(frame_id) = current_layout_frame_id(evaluator) else {
        tracing::warn!("run_layout: no selected live frame");
        return;
    };

    LAYOUT_ENGINE.with(|engine| {
        engine.borrow_mut().layout_frame_rust(evaluator, frame_id);
    });
}

fn layout_frame_display_state(
    evaluator: &mut Context,
    frame_id: FrameId,
) -> Option<neomacs_display_protocol::glyph_matrix::FrameDisplayState> {
    LAYOUT_ENGINE.with(|engine| {
        let mut engine = engine.borrow_mut();
        engine.layout_frame_rust(evaluator, frame_id);
        engine.last_frame_display_state.take()
    })
}

fn frame_origin_in_root(evaluator: &Context, frame_id: FrameId) -> (f32, f32) {
    let mut x = 0_i64;
    let mut y = 0_i64;
    let mut current = Some(frame_id);
    let mut seen = std::collections::HashSet::new();
    while let Some(fid) = current {
        if !seen.insert(fid) {
            break;
        }
        let Some(frame) = evaluator.frame_manager().get(fid) else {
            break;
        };
        x += frame.left_pos;
        y += frame.top_pos;
        current = evaluator.frame_manager().frame_parent_id(fid);
    }
    (x as f32, y as f32)
}

fn run_tty_layout_tree(
    evaluator: &mut Context,
) -> Option<(
    neomacs_display_protocol::glyph_matrix::FrameDisplayState,
    Vec<neomacs_display_protocol::glyph_matrix::FrameDisplayState>,
)> {
    let selected = current_layout_frame_id(evaluator)?;
    let root_id = evaluator
        .frame_manager()
        .root_frame_id(selected)
        .unwrap_or(selected);
    let frame_order = evaluator
        .frame_manager()
        .frames_in_reverse_z_order(root_id, true);

    let mut root_state = layout_frame_display_state(evaluator, root_id)?;
    root_state.parent_id = 0;
    root_state.parent_x = 0.0;
    root_state.parent_y = 0.0;

    let mut child_states = Vec::new();
    for frame_id in frame_order {
        if frame_id == root_id {
            continue;
        }
        let Some(mut state) = layout_frame_display_state(evaluator, frame_id) else {
            continue;
        };
        let (x, y) = frame_origin_in_root(evaluator, frame_id);
        state.parent_id = root_state.frame_id;
        state.parent_x = x;
        state.parent_y = y;
        child_states.push(state);
    }

    Some((root_state, child_states))
}

/// Rasterize the display state into a `TtyRif` and write ANSI output to stdout.
fn run_tty_rif_redisplay(
    tty_rif: &mut neomacs_display_protocol::tty_rif::TtyRif,
    root: &neomacs_display_protocol::glyph_matrix::FrameDisplayState,
    children: &[neomacs_display_protocol::glyph_matrix::FrameDisplayState],
) {
    tty_rif.rasterize_frame_tree(root, children);
    tty_rif.diff_and_render();
    let output = tty_rif.take_output();
    tracing::debug!("tty_rif: output {} bytes", output.len());
    if !output.is_empty() {
        use std::io::Write;
        let _ = std::io::stdout().write_all(&output);
        let _ = std::io::stdout().flush();
    }
}

/// Increase the process stack size limit, matching GNU Emacs's behavior
/// in emacs.c main() which adjusts RLIMIT_STACK.
#[cfg(unix)]
fn increase_stack_limit() {
    const TARGET_STACK_MB: u64 = 128;
    let target = TARGET_STACK_MB * 1024 * 1024;
    unsafe {
        let mut rlim = std::mem::MaybeUninit::<libc::rlimit>::uninit();
        if libc::getrlimit(libc::RLIMIT_STACK, rlim.as_mut_ptr()) == 0 {
            let mut rlim = rlim.assume_init();
            if rlim.rlim_cur < target as libc::rlim_t {
                rlim.rlim_cur = std::cmp::min(target as libc::rlim_t, rlim.rlim_max);
                let _ = libc::setrlimit(libc::RLIMIT_STACK, &rlim);
            }
        }
    }
}

#[cfg(not(unix))]
fn increase_stack_limit() {}

#[cfg(test)]
#[path = "main_test.rs"]
mod tests;