pixel8-console 0.1.0

Pixel8: a PICO-8-like fantasy console for Rust games
Documentation
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
//! The console shell: boot screen, command prompt, mode switching, the
//! run loop, build orchestration and error screens. If Pixel8 has a
//! personality, it lives here.

use crate::{
    builder::{spawn_build, BuildJob},
    editor::{
        code::CodeEditor,
        file_picker::{FilePicker, PickerAction},
        map::MapEditor,
        music::MusicEditor,
        sfx::SfxEditor,
        sprite::SpriteEditor,
    },
    ui::{self, Mouse},
    watch::{FileChange, FileWatch, SourceTreeWatch},
};
use anyhow::{anyhow, bail, Result};
use pixel8_runtime::{
    assets::Assets,
    audio::AudioHandle,
    cart::{self, Cart},
    clipboard::Pasted,
    fb::Framebuffer,
    font,
    palette::col,
    project::{decode_assets, encode_assets, Project},
    storage::Storage,
    vm::{GameVm, RuntimeError, UI_FPS},
};
use std::{
    collections::VecDeque,
    path::PathBuf,
    time::{Duration, Instant, SystemTime},
};

pub const VERSION: &str = env!("CARGO_PKG_VERSION");

/// Keys as the shell sees them, decoupled from the windowing library.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Key {
    Char(char),
    Left,
    Right,
    Up,
    Down,
    Backspace,
    Delete,
    Enter,
    Tab,
    Escape,
    Home,
    End,
    PageUp,
    PageDown,
    /// F6: capture the screen as the cart label while running.
    CaptureLabel,
    /// F1: toggle the resource-usage overlay (CPU, memory, fps).
    ToggleStats,
}

#[derive(Debug, Clone, Copy, Default)]
pub struct Mods {
    pub ctrl: bool,
    pub shift: bool,
    pub alt: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
    Console,
    Run,
    Code,
    Sprite,
    Map,
    Sfx,
    Music,
}

/// The editor tabs, in tab-bar order.
pub const EDITOR_MODES: [Mode; 5] = [Mode::Code, Mode::Sprite, Mode::Map, Mode::Sfx, Mode::Music];

/// What is currently loaded into the console.
enum Loaded {
    None,
    /// A project directory: full edit/build/run workflow.
    Project(Project),
    /// A PNG cart loaded directly: runs as-is; source (if any) is shown
    /// read-only until imported into a project with `import`.
    Cart {
        cart: Cart,
        path: PathBuf,
    },
}

fn assets_of(loaded: &mut Loaded) -> Option<&mut Assets> {
    match loaded {
        Loaded::None => None,
        Loaded::Project(p) => Some(&mut p.assets),
        Loaded::Cart { cart, .. } => Some(&mut cart.assets),
    }
}

fn assets_ref(loaded: &Loaded) -> Option<&Assets> {
    match loaded {
        Loaded::None => None,
        Loaded::Project(p) => Some(&p.assets),
        Loaded::Cart { cart, .. } => Some(&cart.assets),
    }
}

/// Disk watchers for the currently-loaded *project*: the two files pixel8
/// mirrors in memory plus the crate's source tree for build triggering.
struct ProjectWatch {
    code: FileWatch,
    assets: FileWatch,
    source_tree: SourceTreeWatch,
}

impl ProjectWatch {
    fn new(p: &Project) -> Self {
        let assets_baseline = encode_assets(&p.assets).unwrap_or_default();
        Self {
            code: FileWatch::new(p.dir.join("src/lib.rs"), p.code.clone().into_bytes()),
            assets: FileWatch::new(p.dir.join("assets.pixel8.json"), assets_baseline),
            source_tree: SourceTreeWatch::new(&p.dir),
        }
    }

    /// Re-baseline every watcher to the project's current in-memory state and
    /// the current source tree (after pixel8 saved the files itself).
    fn sync(&mut self, p: &Project) {
        self.code.mark_synced(p.code.clone().into_bytes());
        self.assets
            .mark_synced(encode_assets(&p.assets).unwrap_or_default());
        self.source_tree.sync();
    }
}

/// Disk watcher for a loaded PNG cart: re-parses on external change and
/// reconciles its assets against any in-console edits.
struct CartWatch {
    path: PathBuf,
    synced_mtime: Option<SystemTime>,
    /// Encoded assets as of the last sync (the editable, comparable part).
    baseline: Vec<u8>,
}

impl CartWatch {
    fn new(path: PathBuf, baseline: Vec<u8>) -> Self {
        let synced_mtime = std::fs::metadata(&path).and_then(|m| m.modified()).ok();
        Self {
            path,
            synced_mtime,
            baseline,
        }
    }

    /// Re-baseline after pixel8 wrote the cart itself (save), so our own write
    /// is not seen as an external change.
    fn mark_synced(&mut self, baseline: Vec<u8>) {
        self.baseline = baseline;
        self.synced_mtime = std::fs::metadata(&self.path)
            .and_then(|m| m.modified())
            .ok();
    }

    /// The new mtime if the file advanced past the last sync, else `None`.
    fn advanced(&mut self) -> Option<SystemTime> {
        let mtime = std::fs::metadata(&self.path)
            .and_then(|m| m.modified())
            .ok()?;
        let advanced = self.synced_mtime.map(|prev| mtime > prev).unwrap_or(true);
        if advanced {
            // Absorb the mtime now; a transiently-corrupt PNG mid-write is
            // ignored until the next write rather than retried every poll.
            self.synced_mtime = Some(mtime);
            Some(mtime)
        } else {
            None
        }
    }
}

/// Color a budget fraction: green with headroom, yellow from 70%, red above
/// 90%.
fn stat_color(frac: f32) -> u8 {
    if frac < 0.7 {
        col::GREEN
    } else if frac <= 0.9 {
        col::YELLOW
    } else {
        col::RED
    }
}

/// Color the fps reading by how close it is to the cart's target rate.
fn fps_color(measured: f32, target: u32) -> u8 {
    let ratio = if target > 0 {
        measured / target as f32
    } else {
        1.0
    };
    if ratio >= 0.95 {
        col::GREEN
    } else if ratio >= 0.8 {
        col::YELLOW
    } else {
        col::RED
    }
}

/// Draw the resource-usage overlay in the top-right: CPU (update and draw),
/// memory and measured fps, color-coded by how close each is to its budget.
/// `used` is the cart's committed-memory high-water in bytes; it shows as KB
/// and as a fraction of the 128 K cap (see `GameVm::mem_used_bytes`). Columns
/// are aligned: the memory KB sits under the per-call CPU labels and every
/// percentage lines up. A solid black panel keeps it legible over any cart
/// output; it draws in screen space and accepts whatever camera the cart left
/// active (carts reset it each draw).
fn stats_overlay(fb: &mut Framebuffer, cpu_u: f32, cpu_d: f32, used: u32, fps: f32, target: u32) {
    let used_frac = used as f32 / 131_072.0;
    let lines = [
        format!("CPU U   {:>5.1}%", cpu_u * 100.0),
        format!("CPU D   {:>5.1}%", cpu_d * 100.0),
        format!(
            "MEM {:<4}{:>5.1}%",
            format!("{}K", used / 1024),
            used_frac * 100.0
        ),
        format!("FPS    {:>6.1}", fps),
    ];
    let colors = [
        stat_color(cpu_u),
        stat_color(cpu_d),
        stat_color(used_frac),
        fps_color(fps, target),
    ];
    let w = lines.iter().map(|l| l.len()).max().unwrap_or(0) as i32 * 4 + 1;
    let x0 = 127 - w;
    fb.rectfill(x0, 0, 127, 4 * 7, col::BLACK);
    for (i, (line, &color)) in lines.iter().zip(colors.iter()).enumerate() {
        fb.print(line, x0 + 1, 1 + i as i32 * 7, color);
    }
}

/// How long the F6 camera-flash overlay lasts, in frames (~0.1s at 60fps).
const CAPTURE_FLASH_FRAMES: u32 = 6;

/// Paint the camera-flash feedback over the running cart's screen: a bright
/// full-screen white pop, like a camera shutter. `cls` is used deliberately —
/// it ignores any camera offset or clip the cart left active, so the flash
/// always covers the whole screen and touches no cart-visible state.
fn capture_flash_overlay(fb: &mut Framebuffer) {
    fb.cls(col::WHITE);
}

enum ConsoleLine {
    Text {
        text: String,
        color: u8,
    },
    /// Decorative palette stripe shown at boot.
    Stripe,
}

pub struct Shell {
    pub mode: Mode,
    last_editor: Mode,
    loaded: Loaded,
    vm: Option<GameVm>,
    audio: AudioHandle,
    fb: Framebuffer,
    frame: u64,

    // Console state.
    lines: VecDeque<ConsoleLine>,
    input: String,
    cursor: usize,
    history: Vec<String>,
    history_pos: Option<usize>,
    scroll_back: usize,

    // Build state.
    build: Option<BuildJob>,
    run_after_build: bool,
    /// Transient feedback shown in the editor bottom bar:
    /// (text, color, frame it expires at).
    toast: Option<(String, u8, u64)>,

    // Hot reload.
    wasm_mtime: Option<SystemTime>,

    // Disk watching for external-edit live-reload.
    project_watch: Option<ProjectWatch>,
    cart_watch: Option<CartWatch>,

    // Mouse, shared with editors.
    pub mouse: Mouse,

    // Editors.
    code_ed: CodeEditor,
    file_picker: FilePicker,
    /// The file edited just before the current one, for the picker's default
    /// selection (alt-tab style).
    previous_file: Option<String>,
    sprite_ed: SpriteEditor,
    map_ed: MapEditor,
    sfx_ed: SfxEditor,
    music_ed: MusicEditor,

    pub want_exit: bool,
    /// Where `new` creates projects and `ls` looks: the host working dir.
    cwd: PathBuf,
    sdk_path: PathBuf,
    /// Cart save files land under this directory instead of the user's
    /// cache directory when set. Tests use it to stay hermetic.
    storage_root: Option<PathBuf>,

    /// F1 toggles the CPU/memory/fps resource overlay.
    show_stats: bool,
    // Wall-clock fps, measured over a moving window, shown in the overlay.
    fps_frames: u32,
    fps_t0: Instant,
    fps_val: f32,

    /// Frames remaining of the camera-flash overlay shown after an F6 capture.
    capture_flash: u32,

    /// Suppress the software mouse cursor. The windowed console draws its own
    /// pixel-art cursor and hides the OS one; a terminal frontend can't hide
    /// the terminal's mouse pointer, so it hides this one instead to avoid a
    /// distracting double cursor.
    hide_cursor: bool,
}

const TEXT_COLS: usize = 31;
const PROMPT_COL: u8 = col::WHITE;

impl Shell {
    pub fn new(audio: AudioHandle, sdk_path: PathBuf) -> Self {
        let mut shell = Self {
            mode: Mode::Console,
            last_editor: Mode::Code,
            loaded: Loaded::None,
            vm: None,
            audio,
            fb: Framebuffer::new(),
            frame: 0,
            lines: VecDeque::new(),
            input: String::new(),
            cursor: 0,
            history: Vec::new(),
            history_pos: None,
            scroll_back: 0,
            build: None,
            run_after_build: false,
            toast: None,
            wasm_mtime: None,
            project_watch: None,
            cart_watch: None,
            mouse: Mouse::default(),
            code_ed: CodeEditor::new(),
            file_picker: FilePicker::new(),
            previous_file: None,
            sprite_ed: SpriteEditor::new(),
            map_ed: MapEditor::new(),
            sfx_ed: SfxEditor::new(),
            music_ed: MusicEditor::new(),
            want_exit: false,
            cwd: std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
            sdk_path,
            storage_root: None,
            show_stats: false,
            fps_frames: 0,
            fps_t0: Instant::now(),
            fps_val: 0.0,
            capture_flash: 0,
            hide_cursor: false,
        };
        shell.boot();
        shell
    }

    /// Hide the console's software mouse cursor (used by frontends that show
    /// the host's own pointer, like the terminal, to avoid a double cursor).
    pub fn set_hide_cursor(&mut self, hide: bool) {
        self.hide_cursor = hide;
    }

    fn boot(&mut self) {
        self.lines.push_back(ConsoleLine::Stripe);
        self.say(&format!("Pixel8 {VERSION}"), col::WHITE);
        self.say("A fantasy console for Rust", col::LIGHT_GREY);
        self.say("", col::WHITE);
        self.say("Type help for help", col::LIGHT_GREY);
        self.say("", col::WHITE);
    }

    /// Print a (wrapped) line to the console.
    pub fn say(&mut self, text: &str, color: u8) {
        if text.is_empty() {
            self.push_line(String::new(), color);
            return;
        }
        for raw in text.split('\n') {
            let mut rest = raw;
            loop {
                let take = rest
                    .char_indices()
                    .nth(TEXT_COLS)
                    .map(|(i, _)| i)
                    .unwrap_or(rest.len());
                self.push_line(rest[..take].to_string(), color);
                rest = &rest[take..];
                if rest.is_empty() {
                    break;
                }
            }
        }
    }

    /// Flash a message in the editor bottom bar for `secs` seconds.
    fn toast(&mut self, text: &str, color: u8, secs: f32) {
        self.toast = Some((text.to_string(), color, self.frame + (secs * 30.0) as u64));
    }

    fn push_line(&mut self, text: String, color: u8) {
        self.lines.push_back(ConsoleLine::Text { text, color });
        while self.lines.len() > 300 {
            self.lines.pop_front();
        }
        self.scroll_back = 0;
    }

    // -----------------------------------------------------------------
    // Loaded-state helpers
    // -----------------------------------------------------------------

    pub fn assets(&self) -> Option<&Assets> {
        match &self.loaded {
            Loaded::None => None,
            Loaded::Project(p) => Some(&p.assets),
            Loaded::Cart { cart, .. } => Some(&cart.assets),
        }
    }

    pub fn assets_mut(&mut self) -> Option<&mut Assets> {
        match &mut self.loaded {
            Loaded::None => None,
            Loaded::Project(p) => Some(&mut p.assets),
            Loaded::Cart { cart, .. } => Some(&mut cart.assets),
        }
    }

    fn code(&self) -> Option<&str> {
        match &self.loaded {
            Loaded::None => None,
            Loaded::Project(p) => Some(&p.code),
            Loaded::Cart { cart, .. } => cart.source.as_deref(),
        }
    }

    fn set_code(&mut self, code: String) {
        match &mut self.loaded {
            Loaded::None => {}
            Loaded::Project(p) => p.code = code,
            Loaded::Cart { cart, .. } => cart.source = Some(code),
        }
    }

    fn project_file_names(&self) -> Vec<String> {
        match &self.loaded {
            Loaded::Project(p) => p.file_names(),
            _ => Vec::new(),
        }
    }

    fn current_file_name(&self) -> String {
        match &self.loaded {
            Loaded::Project(p) => p.current.clone(),
            _ => String::new(),
        }
    }

    fn run_picker_action(&mut self, action: PickerAction) {
        match action {
            PickerAction::Switch(name) => self.select_file(&name),
            PickerAction::Create(name) => self.create_file_in_project(&name),
        }
    }

    /// Open the file picker for the current project, pre-selecting the most
    /// likely target (the previously edited file, else the first non-current).
    fn open_file_picker(&mut self) {
        let files = self.project_file_names();
        let refs: Vec<&str> = files.iter().map(String::as_str).collect();
        let current = self.current_file_name();
        self.file_picker
            .open(&refs, &current, self.previous_file.as_deref());
    }

    /// Persist the open file, switch to `name`, and re-point the code watcher.
    /// If saving the open file fails, surface the error and stay put rather than
    /// dropping the unsaved buffer.
    fn select_file(&mut self, name: &str) {
        enum R {
            NoOp,
            Err(String),
            Ok(String, PathBuf, String),
        }
        let r = match &mut self.loaded {
            Loaded::Project(p) if p.current != name => {
                let previous = p.current.clone();
                match p.save() {
                    Err(e) => R::Err(format!("could not save {previous}: {e}")),
                    Ok(()) => match p.switch_to(name) {
                        Ok(()) => R::Ok(p.code.clone(), p.dir.join("src").join(name), previous),
                        Err(e) => R::Err(format!("{e}")),
                    },
                }
            }
            _ => R::NoOp,
        };
        match r {
            R::Ok(code, path, previous) => {
                self.previous_file = Some(previous);
                self.code_ed.set_text(&code);
                if let Some(w) = &mut self.project_watch {
                    w.code = FileWatch::new(path, code.into_bytes());
                    // Saving the previous file bumped its mtime; absorb it so a
                    // plain file switch does not trigger a rebuild.
                    w.source_tree.sync();
                }
            }
            R::Err(msg) => {
                self.say(&msg, col::RED);
                self.toast(&msg, col::RED, 3.0);
            }
            R::NoOp => {}
        }
    }

    /// Create a new module, open it, and re-point the code watcher.
    fn create_file_in_project(&mut self, name: &str) {
        enum R {
            Err(String),
            Ok(String, PathBuf, String),
        }
        let r = match &mut self.loaded {
            Loaded::Project(p) => {
                let previous = p.current.clone();
                match p.save() {
                    Err(e) => R::Err(format!("could not save {previous}: {e}")),
                    Ok(()) => match p.create_file(name) {
                        Ok(new) => R::Ok(p.code.clone(), p.dir.join("src").join(&new), previous),
                        Err(e) => R::Err(format!("{e}")),
                    },
                }
            }
            _ => return,
        };
        match r {
            R::Ok(code, path, previous) => {
                self.previous_file = Some(previous);
                self.code_ed.set_text(&code);
                if let Some(w) = &mut self.project_watch {
                    w.code = FileWatch::new(path, code.into_bytes());
                    // We wrote lib.rs + the new file ourselves; absorb the bump.
                    w.source_tree.sync();
                }
            }
            R::Err(msg) => {
                self.say(&msg, col::RED);
                self.toast(&msg, col::RED, 3.0);
            }
        }
    }

    fn cart_name(&self) -> String {
        self.assets()
            .map(|a| a.meta.name.clone())
            .unwrap_or_else(|| "no cart".into())
    }

    /// The OS window title: the loaded cart's name plus the console name, or
    /// just the console name when nothing is loaded.
    pub fn window_title(&self) -> String {
        match &self.loaded {
            Loaded::None => "Pixel8".into(),
            _ => format!("{} - Pixel8", self.cart_name()),
        }
    }

    // -----------------------------------------------------------------
    // Input
    // -----------------------------------------------------------------

    /// Feed a game button (host already mapped keys to buttons 0..6).
    pub fn set_button(&mut self, b: usize, down: bool) {
        if let Some(vm) = &mut self.vm {
            vm.state_mut().input.set_button(b, down);
        }
    }

    pub fn key(&mut self, key: Key, mods: Mods) {
        // The file picker, when open, captures all keys.
        if self.file_picker.is_open() {
            let files = self.project_file_names();
            let refs: Vec<&str> = files.iter().map(String::as_str).collect();
            if let Some(action) = self.file_picker.key(key, mods, &refs) {
                self.run_picker_action(action);
            }
            return;
        }
        // Global shortcuts.
        if key == Key::ToggleStats {
            self.show_stats = !self.show_stats;
            return;
        }
        if mods.ctrl {
            match key {
                Key::Char('r') => {
                    self.cmd_run();
                    return;
                }
                Key::Char('s') => {
                    self.cmd_save_quiet();
                    return;
                }
                Key::Char('o') => {
                    if self.mode == Mode::Code && matches!(self.loaded, Loaded::Project(_)) {
                        self.open_file_picker();
                    }
                    return;
                }
                _ => {}
            }
        }

        match self.mode {
            Mode::Run => {
                if key == Key::Escape {
                    self.stop_run("");
                } else if key == Key::CaptureLabel {
                    self.capture_label();
                }
            }
            Mode::Console => self.console_key(key, mods),
            _ => self.editor_key(key, mods),
        }
    }

    fn editor_key(&mut self, key: Key, mods: Mods) {
        if key == Key::Escape {
            self.mode = Mode::Console;
            return;
        }
        // Alt+Left/Right cycles editor tabs.
        if mods.alt {
            let cur = EDITOR_MODES
                .iter()
                .position(|m| *m == self.mode)
                .unwrap_or(0);
            match key {
                Key::Left => {
                    self.switch_editor(
                        EDITOR_MODES[(cur + EDITOR_MODES.len() - 1) % EDITOR_MODES.len()],
                    );
                    return;
                }
                Key::Right => {
                    self.switch_editor(EDITOR_MODES[(cur + 1) % EDITOR_MODES.len()]);
                    return;
                }
                _ => {}
            }
        }
        // Ctrl+C/X/V move data through the system clipboard for every editor, including
        // the map (its tile region uses the native format).
        if mods.ctrl {
            match key {
                Key::Char('c')
                    if matches!(
                        self.mode,
                        Mode::Sprite | Mode::Sfx | Mode::Music | Mode::Code | Mode::Map
                    ) =>
                {
                    self.cmd_copy();
                    return;
                }
                Key::Char('x') if matches!(self.mode, Mode::Code | Mode::Map) => {
                    self.cmd_cut();
                    return;
                }
                Key::Char('v')
                    if matches!(
                        self.mode,
                        Mode::Sprite | Mode::Sfx | Mode::Music | Mode::Code | Mode::Map
                    ) =>
                {
                    self.cmd_paste();
                    return;
                }
                _ => {}
            }
        }
        if self.loaded_none() {
            return;
        }
        let audio = self.audio.clone();
        match self.mode {
            Mode::Code => {
                let mut code = self.code().unwrap_or_default().to_string();
                self.code_ed.key(key, mods, &mut code);
                self.set_code(code);
            }
            Mode::Sprite => {
                if let Some(a) = assets_of(&mut self.loaded) {
                    self.sprite_ed.key(key, mods, a);
                }
            }
            Mode::Map => {
                if let Some(a) = assets_of(&mut self.loaded) {
                    self.map_ed.key(key, mods, a);
                }
            }
            Mode::Sfx => {
                if let Some(a) = assets_of(&mut self.loaded) {
                    self.sfx_ed.key(key, mods, a, &audio);
                }
            }
            Mode::Music => {
                if let Some(a) = assets_of(&mut self.loaded) {
                    self.music_ed.key(key, mods, a, &audio);
                }
            }
            _ => {}
        }
    }

    pub fn switch_editor(&mut self, mode: Mode) {
        self.file_picker.close();
        // Abandon any in-progress map-editor drag so it can't commit a stale
        // selection or move once the editor regains focus.
        self.map_ed.cancel_drag();
        if self.loaded_none() {
            self.say("No cart loaded. Try: new mygame", col::RED);
            self.mode = Mode::Console;
            return;
        }
        if mode == Mode::Code {
            let code = self.code().unwrap_or_default().to_string();
            self.code_ed.set_text(&code);
        }
        self.mode = mode;
        self.last_editor = mode;
    }

    fn loaded_none(&self) -> bool {
        matches!(self.loaded, Loaded::None)
    }

    fn console_key(&mut self, key: Key, _mods: Mods) {
        match key {
            Key::Char(c) => {
                self.input.insert(self.byte_at(self.cursor), c);
                self.cursor += 1;
            }
            Key::Backspace => {
                if self.cursor > 0 {
                    self.cursor -= 1;
                    let at = self.byte_at(self.cursor);
                    self.input.remove(at);
                }
            }
            Key::Delete => {
                if self.cursor < self.input.chars().count() {
                    let at = self.byte_at(self.cursor);
                    self.input.remove(at);
                }
            }
            Key::Left => self.cursor = self.cursor.saturating_sub(1),
            Key::Right => self.cursor = (self.cursor + 1).min(self.input.chars().count()),
            Key::Home => self.cursor = 0,
            Key::End => self.cursor = self.input.chars().count(),
            Key::Up => {
                if !self.history.is_empty() {
                    let pos = match self.history_pos {
                        None => self.history.len() - 1,
                        Some(p) => p.saturating_sub(1),
                    };
                    self.history_pos = Some(pos);
                    self.input = self.history[pos].clone();
                    self.cursor = self.input.chars().count();
                }
            }
            Key::Down => {
                if let Some(p) = self.history_pos {
                    if p + 1 < self.history.len() {
                        self.history_pos = Some(p + 1);
                        self.input = self.history[p + 1].clone();
                    } else {
                        self.history_pos = None;
                        self.input.clear();
                    }
                    self.cursor = self.input.chars().count();
                }
            }
            Key::PageUp => self.scroll_back = (self.scroll_back + 5).min(self.lines.len()),
            Key::PageDown => self.scroll_back = self.scroll_back.saturating_sub(5),
            Key::Enter => {
                let cmd = self.input.clone();
                self.say(&format!("> {cmd}"), col::LIGHT_GREY);
                if !cmd.trim().is_empty() {
                    self.history.push(cmd.clone());
                }
                self.history_pos = None;
                self.input.clear();
                self.cursor = 0;
                self.exec(&cmd);
            }
            Key::Escape => {
                if !self.loaded_none() {
                    self.switch_editor(self.last_editor);
                }
            }
            Key::Tab | Key::CaptureLabel | Key::ToggleStats => {}
        }
    }

    fn byte_at(&self, char_idx: usize) -> usize {
        self.input
            .char_indices()
            .nth(char_idx)
            .map(|(i, _)| i)
            .unwrap_or(self.input.len())
    }

    // -----------------------------------------------------------------
    // Commands
    // -----------------------------------------------------------------

    fn exec(&mut self, cmd: &str) {
        let parts: Vec<&str> = cmd.split_whitespace().collect();
        let Some(&verb) = parts.first() else { return };
        let args = &parts[1..];
        let result = match verb.to_ascii_lowercase().as_str() {
            "help" => {
                self.cmd_help(args);
                Ok(())
            }
            "new" => self.cmd_new(args),
            "load" => self.cmd_load(args),
            "reload" => self.cmd_reload(),
            "save" => self.cmd_save(args),
            "run" => {
                self.cmd_run();
                Ok(())
            }
            "export" => self.cmd_export(args),
            "import" => self.cmd_import(args),
            "import-pico8" | "importp8" => self.cmd_import_pico8(args),
            "info" => {
                self.cmd_info();
                Ok(())
            }
            "ls" | "dir" => self.cmd_ls(),
            "cls" => {
                self.lines.clear();
                Ok(())
            }
            "title" => self.cmd_meta(args, |a, v| a.meta.name = v),
            "author" => self.cmd_meta(args, |a, v| a.meta.author = v),
            "code" => {
                self.switch_editor(Mode::Code);
                Ok(())
            }
            "sprite" | "gfx" => {
                self.switch_editor(Mode::Sprite);
                Ok(())
            }
            "map" => {
                self.switch_editor(Mode::Map);
                Ok(())
            }
            "sfx" => {
                self.switch_editor(Mode::Sfx);
                Ok(())
            }
            "music" => {
                self.switch_editor(Mode::Music);
                Ok(())
            }
            "keys" => {
                self.cmd_keys();
                Ok(())
            }
            "reboot" => {
                self.vm = None;
                self.audio.stop_all();
                self.loaded = Loaded::None;
                self.lines.clear();
                self.boot();
                Ok(())
            }
            "exit" | "quit" | "shutdown" => {
                self.want_exit = true;
                Ok(())
            }
            other => Err(anyhow!("Syntax error: {other}\nType help for help")),
        };
        if let Err(e) = result {
            self.say(&e.to_string(), col::RED);
        }
    }

    fn cmd_help(&mut self, args: &[&str]) {
        if args.first() == Some(&"keys") {
            self.cmd_keys();
            return;
        }
        for (c, d) in [
            ("new <name>", "Create a project"),
            ("load <dir|cart.png>", "Load a cart"),
            ("reload", "Re-read from disk, drop edits"),
            ("save", "Save project to disk"),
            ("run", "Build + run (esc stops)"),
            ("export <f.png|f.html>", "Export cart (PNG or web)"),
            ("import <f.png> <dir>", "Cart -> project"),
            ("import-pico8 <f> [dir]", "PICO-8 cart -> new project"),
            (
                "import-pico8 <f> --into ...",
                "Append assets to loaded project",
            ),
            ("info", "Cart metadata"),
            ("title/author <text>", "Set metadata"),
            ("code/sprite/map/sfx/music", "Editors (esc)"),
            ("ls, cls, keys, reboot, exit", ""),
        ] {
            self.say(c, col::WHITE);
            if !d.is_empty() {
                self.say(&format!("  {d}"), col::LIGHT_GREY);
            }
        }
    }

    fn cmd_keys(&mut self) {
        for (k, d) in [
            ("esc", "Console <-> editor / stop"),
            ("ctrl+r", "Run cart"),
            ("ctrl+s", "Save + build check"),
            ("ctrl+z / ctrl+y", "Undo / redo (in editors)"),
            ("alt+left/right", "Switch editor"),
            ("arrows + z/x", "Game buttons"),
            ("f1", "Toggle resource stats"),
            ("f6", "Capture label (running)"),
        ] {
            self.say(&format!("{k:14} {d}"), col::LIGHT_GREY);
        }
    }

    fn cmd_new(&mut self, args: &[&str]) -> Result<()> {
        let Some(name) = args.first() else {
            bail!("Usage: new <name>");
        };
        let dir = self.cwd.join(name);
        let project = Project::create(&dir, name)?;
        self.say(&format!("Created ./{name}"), col::GREEN);
        self.code_ed.set_text(&project.code);
        self.project_watch = Some(ProjectWatch::new(&project));
        self.cart_watch = None;
        self.loaded = Loaded::Project(project);
        Ok(())
    }

    /// Load a cart/project given on the command line at boot.
    pub fn startup_load(&mut self, path: &str) {
        if let Err(e) = self.cmd_load(&[path]) {
            self.say(&e.to_string(), col::RED);
        }
    }

    /// Run the cart/project loaded at boot, as if the user typed `run`. Used by
    /// the `pixel8 run <path>` launch mode. A cart enters Run mode immediately; a
    /// project spawns its build and enters Run mode once it succeeds.
    pub fn startup_run(&mut self) {
        self.cmd_run();
    }

    fn cmd_load(&mut self, args: &[&str]) -> Result<()> {
        let Some(path) = args.first() else {
            bail!("Usage: load <dir|cart.png>");
        };
        let path = self.cwd.join(path);
        if path.extension().is_some_and(|e| e == "png") {
            let cart = cart::load_png(&path)?;
            let name = cart.assets.meta.name.clone();
            let has_src = cart.source.is_some();
            self.code_ed.set_text(
                cart.source
                    .as_deref()
                    .unwrap_or("// No source in this cart"),
            );
            self.project_watch = None;
            let cart_baseline = encode_assets(&cart.assets).unwrap_or_default();
            self.cart_watch = Some(CartWatch::new(path.clone(), cart_baseline));
            self.loaded = Loaded::Cart { cart, path };
            self.say(&format!("Loaded cart: {name}"), col::GREEN);
            if !has_src {
                self.say("(Playable cart, no source)", col::LIGHT_GREY);
            }
        } else {
            let project = Project::load(&path)?;
            self.code_ed.set_text(&project.code);
            self.say(&format!("Loaded {}", project.name), col::GREEN);
            self.project_watch = Some(ProjectWatch::new(&project));
            self.cart_watch = None;
            self.loaded = Loaded::Project(project);
        }
        Ok(())
    }

    /// Re-read the current project/cart from disk, discarding in-console edits.
    /// Resolves a conflict in favour of the external version.
    fn cmd_reload(&mut self) -> Result<()> {
        let path = match &self.loaded {
            Loaded::None => bail!("Nothing loaded"),
            Loaded::Project(p) => p.dir.clone(),
            Loaded::Cart { path, .. } => path.clone(),
        };
        let path_str = path.to_string_lossy().into_owned();
        self.cmd_load(&[&path_str])
    }

    fn cmd_save(&mut self, _args: &[&str]) -> Result<()> {
        let message = match &mut self.loaded {
            Loaded::None => bail!("Nothing to save"),
            Loaded::Project(p) => {
                p.save()?;
                "Saved".to_string()
            }
            Loaded::Cart { cart, path } => {
                cart::save_png(cart, path)?;
                format!("Saved {}", path.display())
            }
        };
        // After saving a project, pixel8's own write must not look external.
        if let (Loaded::Project(p), Some(w)) = (&self.loaded, &mut self.project_watch) {
            w.sync(p);
        }
        // After saving a PNG cart, pixel8's own write must not look external.
        if let (Loaded::Cart { cart, .. }, Some(w)) = (&self.loaded, &mut self.cart_watch) {
            w.mark_synced(encode_assets(&cart.assets).unwrap_or_default());
        }
        self.say(&message, col::GREEN);
        Ok(())
    }

    /// Read the system clipboard, decode a PICO-8 asset blob, and paste it into
    /// the active editor. Any failure shows a short message in the editor's bar.
    fn cmd_paste(&mut self) {
        // Bar messages are short fixed strings so they always fit the 31-char bar.
        let text = match crate::clipboard::read_text() {
            Ok(t) => t,
            Err(_) => return self.set_editor_status("no text on clipboard".into()),
        };
        if self.mode == Mode::Code {
            if self.code().is_none() {
                return self.set_editor_status("load a project first".into());
            }
            let mut code = self.code().unwrap_or_default().to_string();
            self.code_ed.paste_text(&mut code, &text);
            self.set_code(code);
            return;
        }
        match pixel8_runtime::clipboard::parse(&text) {
            Ok(pasted) => self.apply_paste(pasted),
            Err(_) => self.set_editor_status("nothing to paste".into()),
        }
    }

    /// Encode the active editor's current item and put it on the system clipboard.
    fn cmd_copy(&mut self) {
        let blob = match self.mode {
            Mode::Code => {
                if self.code().is_none() {
                    return self.set_editor_status("load a project first".into());
                }
                let code = self.code().unwrap_or_default().to_string();
                self.code_ed.copy(&code)
            }
            Mode::Sprite | Mode::Sfx | Mode::Music | Mode::Map => {
                let Some(a) = assets_of(&mut self.loaded) else {
                    return self.set_editor_status("load a project first".into());
                };
                match self.mode {
                    Mode::Sprite => Some(self.sprite_ed.copy(a)),
                    Mode::Sfx => Some(self.sfx_ed.copy(a)),
                    Mode::Music => Some(self.music_ed.copy(a)),
                    Mode::Map => self.map_ed.copy_selection(a, false),
                    _ => unreachable!(),
                }
            }
            _ => None,
        };
        if let Some(text) = blob {
            if crate::clipboard::write_text(&text).is_err() {
                self.set_editor_status("clipboard unavailable".into());
            }
        }
    }

    /// Cut the current selection to the system clipboard (code text or map tiles).
    fn cmd_cut(&mut self) {
        let blob = match self.mode {
            Mode::Code => {
                if self.code().is_none() {
                    return self.set_editor_status("load a project first".into());
                }
                let mut code = self.code().unwrap_or_default().to_string();
                let cut = self.code_ed.cut(&mut code);
                if cut.is_some() {
                    self.set_code(code);
                }
                cut
            }
            Mode::Map => {
                let Some(a) = assets_of(&mut self.loaded) else {
                    return self.set_editor_status("load a project first".into());
                };
                self.map_ed.copy_selection(a, true)
            }
            _ => None,
        };
        if let Some(text) = blob {
            if crate::clipboard::write_text(&text).is_err() {
                self.set_editor_status("clipboard unavailable".into());
            }
        }
    }

    /// Dispatch a decoded clipboard blob to the active editor. Separated from
    /// the clipboard read so it can be tested without a display server.
    fn apply_paste(&mut self, pasted: Pasted) {
        let Some(a) = assets_of(&mut self.loaded) else {
            return self.set_editor_status("load a project first".into());
        };
        match self.mode {
            Mode::Sprite => self.sprite_ed.paste(&pasted, a),
            Mode::Sfx => self.sfx_ed.paste(&pasted, a),
            Mode::Music => self.music_ed.paste(&pasted, a),
            Mode::Map => self.map_ed.paste(&pasted),
            _ => {}
        }
    }

    /// Show a transient message in the active editor's bottom bar.
    fn set_editor_status(&mut self, msg: String) {
        match self.mode {
            Mode::Sprite => self.sprite_ed.set_status(msg),
            Mode::Sfx => self.sfx_ed.set_status(msg),
            Mode::Music => self.music_ed.set_status(msg),
            Mode::Code => self.code_ed.set_status(msg),
            Mode::Map => self.map_ed.set_status(msg),
            _ => {}
        }
    }

    /// Ctrl+S: save, flash feedback where the user is looking, and (for
    /// projects) start a background build so compile errors show up
    /// while editing instead of at `run` time.
    fn cmd_save_quiet(&mut self) {
        if let Err(e) = self.cmd_save(&[]) {
            let msg = e.to_string();
            self.say(&msg, col::RED);
            self.toast(&msg, col::RED, 3.0);
            return;
        }
        self.toast("Saved", col::GREEN, 1.5);
        if self.build.is_none() {
            if let Loaded::Project(p) = &self.loaded {
                let dir = p.dir.clone();
                self.build = Some(spawn_build(&dir));
                self.run_after_build = false;
            }
        }
    }

    pub fn cmd_run(&mut self) {
        self.audio.stop_all();
        self.vm = None;
        match &self.loaded {
            Loaded::None => self.say("No cart loaded", col::RED),
            Loaded::Cart { .. } => match self.start_vm_from_loaded() {
                Ok(()) => {}
                Err(e) => self.show_error("boot", &e.to_string()),
            },
            Loaded::Project(p) => {
                let dir = p.dir.clone();
                if self.build.is_some() {
                    self.say("Already compiling...", col::ORANGE);
                    self.toast("Already building...", col::ORANGE, 1.5);
                    return;
                }
                // Pick up external edits and flush in-console edits without
                // clobbering either. Abort the run on an unresolved conflict.
                if !self.reconcile_for_build() {
                    self.say("Disk & editor both changed", col::ORANGE);
                    self.say("Save or reload to resolve", col::ORANGE);
                    self.toast("Conflict: save or reload", col::ORANGE, 3.0);
                    return;
                }
                self.mode = Mode::Console;
                self.say("Compiling...", col::LIGHT_GREY);
                self.build = Some(spawn_build(&dir));
                self.run_after_build = true;
            }
        }
    }

    /// Reconcile a project's disk and in-memory copies in preparation for a
    /// build. Adopts clean external changes, flushes in-console edits to disk,
    /// and returns `false` (build should abort) on an unresolved conflict.
    fn reconcile_for_build(&mut self) -> bool {
        let Loaded::Project(_) = &self.loaded else {
            return true;
        };
        // Snapshot the in-memory bytes to feed the watchers.
        let (code_mem, assets_mem) = match &self.loaded {
            Loaded::Project(p) => (
                p.code.clone().into_bytes(),
                encode_assets(&p.assets).unwrap_or_default(),
            ),
            _ => return true,
        };
        let Some(w) = &mut self.project_watch else {
            return true;
        };
        // Adopt external changes first (clean memory), or bail on conflict.
        let code_change = w.code.poll(&code_mem);
        let assets_change = w.assets.poll(&assets_mem);
        // Absorb the source-tree high-water mark so the flush below + the build
        // it triggers are not re-detected as an external change next poll.
        w.source_tree.poll();
        // Bail on a conflict — including a *standing* one from an earlier poll.
        // A later poll returns `None` once the mtime is absorbed, so the latch
        // is what keeps `run` from flushing the stale copy over disk until the
        // user resolves it with `save` (keep mine) or `reload` (take disk).
        if matches!(code_change, FileChange::Conflict)
            || matches!(assets_change, FileChange::Conflict)
            || w.code.in_conflict()
            || w.assets.in_conflict()
        {
            return false;
        }
        if let FileChange::Adopt(bytes) = code_change {
            let text = String::from_utf8_lossy(&bytes).into_owned();
            self.code_ed.set_text(&text);
            if let Loaded::Project(p) = &mut self.loaded {
                p.code = text;
            }
        }
        if let FileChange::Adopt(bytes) = assets_change {
            match decode_assets(&bytes) {
                Ok(assets) => {
                    if let Loaded::Project(p) = &mut self.loaded {
                        p.assets = assets;
                    }
                }
                // Malformed disk file: re-sync the watcher to the current
                // in-memory encoding so we do not flush over it.
                Err(_) => self.resync_assets_watcher(),
            }
        }
        // Flush any in-console edits that are not yet on disk, so cargo builds
        // exactly what the editors show. (No-op when nothing is dirty.)
        let needs_flush = match (&self.loaded, &self.project_watch) {
            (Loaded::Project(p), Some(w)) => {
                p.code.as_bytes() != w.code.baseline()
                    || encode_assets(&p.assets).unwrap_or_default() != w.assets.baseline()
            }
            _ => false,
        };
        if needs_flush {
            if let Loaded::Project(p) = &self.loaded {
                let _ = p.save();
            }
            if let (Loaded::Project(p), Some(w)) = (&self.loaded, &mut self.project_watch) {
                w.sync(p);
            }
        }
        true
    }

    /// Re-baseline the assets watcher to the current in-memory encoding. Used
    /// when an external `assets.pixel8.json` is unreadable, so we neither flush over
    /// it nor keep re-detecting it.
    fn resync_assets_watcher(&mut self) {
        if let (Loaded::Project(p), Some(w)) = (&self.loaded, &mut self.project_watch) {
            w.assets
                .mark_synced(encode_assets(&p.assets).unwrap_or_default());
        }
    }

    fn start_vm_from_loaded(&mut self) -> Result<()> {
        // Drop any previous VM first: dropping saves its storage, and the
        // new VM must load the freshest save from disk.
        self.vm = None;
        let (wasm, assets) = match &self.loaded {
            Loaded::None => bail!("No cart loaded"),
            Loaded::Cart { cart, .. } => (cart.wasm.clone(), cart.assets.clone()),
            Loaded::Project(p) => {
                let path = p.wasm_path();
                let wasm = std::fs::read(&path)
                    .map_err(|_| anyhow!("Cart not built yet ({})", path.display()))?;
                self.wasm_mtime = std::fs::metadata(&path).and_then(|m| m.modified()).ok();
                (wasm, p.assets.clone())
            }
        };
        let storage = match &self.storage_root {
            Some(root) => Storage::for_cart_in(root, &assets.meta.name),
            None => Storage::for_cart(&assets.meta.name),
        };
        let vm = GameVm::load(&wasm, &assets, self.audio.clone(), storage)?;
        self.vm = Some(vm);
        self.mode = Mode::Run;
        Ok(())
    }

    fn cmd_export(&mut self, args: &[&str]) -> Result<()> {
        let mut include_source = true;
        let mut file = None;
        for a in args {
            if *a == "-nosrc" {
                include_source = false;
            } else {
                file = Some(*a);
            }
        }
        let file = file
            .map(|f| f.to_string())
            .unwrap_or_else(|| format!("{}.png", self.cart_name()));
        let out = self.cwd.join(&file);
        if file.ends_with(".html") {
            // Web export: one self-contained playable page.
            let cart = self.make_cart(false)?;
            self.say("Exporting for web...", col::LIGHT_GREY);
            let web_dir = crate::webexport::web_crate_dir(&self.sdk_path);
            crate::webexport::export_html(&cart, &out, &web_dir)?;
        } else {
            let cart = self.make_cart(include_source)?;
            cart::save_png(&cart, &out)?;
        }
        self.say(&format!("Exported {file}"), col::GREEN);
        Ok(())
    }

    fn make_cart(&self, include_source: bool) -> Result<Cart> {
        match &self.loaded {
            Loaded::None => bail!("No cart loaded"),
            Loaded::Cart { cart, .. } => Ok(Cart {
                wasm: cart.wasm.clone(),
                assets: cart.assets.clone(),
                source: if include_source {
                    cart.source.clone()
                } else {
                    None
                },
            }),
            Loaded::Project(p) => {
                let wasm = std::fs::read(p.wasm_path())
                    .map_err(|_| anyhow!("Cart not built yet. Type run first"))?;
                Ok(Cart {
                    wasm,
                    assets: p.assets.clone(),
                    source: include_source.then(|| p.lib_source()),
                })
            }
        }
    }

    fn cmd_import(&mut self, args: &[&str]) -> Result<()> {
        let (Some(png), Some(dir)) = (args.first(), args.get(1)) else {
            bail!("Usage: import <cart.png> <dir>");
        };
        let cart = cart::load_png(&self.cwd.join(png))?;
        let Some(source) = &cart.source else {
            bail!("Cart has no source (playable-only)");
        };
        let dir = self.cwd.join(dir);
        let mut project = Project::create(&dir, &cart.assets.meta.name)?;
        project.code = source.clone();
        project.assets = cart.assets.clone();
        project.save()?;
        self.say(&format!("Imported into {}", dir.display()), col::GREEN);
        self.code_ed.set_text(&project.code);
        self.loaded = Loaded::Project(project);
        if let Loaded::Project(p) = &self.loaded {
            self.project_watch = Some(ProjectWatch::new(p));
        }
        self.cart_watch = None;
        Ok(())
    }

    /// Import a PICO-8 cart's assets into a fresh project. Only the graphics,
    /// map, sound and music transfer; the cart's Lua code is ignored.
    fn cmd_import_pico8(&mut self, args: &[&str]) -> Result<()> {
        if args.contains(&"--into") {
            return self.cmd_import_pico8_into(args);
        }
        let Some(src) = args.first() else {
            bail!("Usage: import-pico8 <cart.p8|cart.p8.png> [dir]");
        };
        let src = self.cwd.join(src);
        // The destination defaults to the cart's name when omitted.
        let dir = match args.get(1) {
            Some(d) => self.cwd.join(d),
            None => self.cwd.join(pixel8_runtime::pico8::default_dir_name(&src)),
        };
        let project = pixel8_runtime::pico8::import_project(&src, &dir)?;
        self.say(
            &format!("Imported assets into {}", dir.display()),
            col::GREEN,
        );
        self.code_ed.set_text(&project.code);
        self.loaded = Loaded::Project(project);
        if let Loaded::Project(p) = &self.loaded {
            self.project_watch = Some(ProjectWatch::new(p));
        }
        self.cart_watch = None;
        Ok(())
    }

    /// Append selected PICO-8 assets into the currently-loaded project.
    /// `import-pico8 <src> --into [--sprites R] [--sfx R] [--music R]`.
    fn cmd_import_pico8_into(&mut self, args: &[&str]) -> Result<()> {
        let (mut src, mut sprites, mut sfx, mut music) = (None, None, None, None);
        let mut it = args.iter();
        while let Some(&a) = it.next() {
            match a {
                "--into" => {} // marks additive mode; the target is the loaded project.
                "--sprites" => sprites = Some(flag_value(it.next(), "--sprites")?),
                "--sfx" => sfx = Some(flag_value(it.next(), "--sfx")?),
                "--music" => music = Some(flag_value(it.next(), "--music")?),
                flag if flag.starts_with("--") => bail!("unknown flag {flag}"),
                pos if src.is_none() => src = Some(pos),
                pos => bail!("unexpected argument {pos}"),
            }
        }
        let Some(src) = src else {
            bail!("Usage: import-pico8 <cart> --into [--sprites R] [--sfx R] [--music R]");
        };
        let sel = pixel8_runtime::pico8::Selection::parse(sprites, sfx, music)?;

        let report = {
            let Loaded::Project(project) = &mut self.loaded else {
                bail!("import-pico8 --into needs a project loaded; use `new` or `load` first");
            };
            let assets = pixel8_runtime::pico8::parse_file(&self.cwd.join(src))?;
            let report =
                pixel8_runtime::pico8::append_pico8_assets(&mut project.assets, &assets, &sel)?;
            project.save()?;
            report
        };
        // The save rewrote src/lib.rs too; re-baseline the whole watcher (code +
        // assets + source tree) so pixel8's own write isn't seen as an external edit.
        if let (Loaded::Project(p), Some(w)) = (&self.loaded, &mut self.project_watch) {
            w.sync(p);
        }
        for line in report.summary_lines() {
            self.say(&format!("Imported {line}"), col::GREEN);
        }
        for w in &report.warnings {
            self.say(w, col::YELLOW);
        }
        Ok(())
    }

    fn cmd_info(&mut self) {
        match self.assets() {
            None => self.say("No cart loaded", col::RED),
            Some(a) => {
                let (name, author, version) = (
                    a.meta.name.clone(),
                    a.meta.author.clone(),
                    a.meta.version.clone(),
                );
                let label = if a.label.is_some() {
                    "Captured"
                } else {
                    "Default"
                };
                let kind = match &self.loaded {
                    Loaded::Project(p) => format!("Project {}", p.dir.display()),
                    Loaded::Cart { path, .. } => format!("Cart {}", path.display()),
                    Loaded::None => unreachable!(),
                };
                self.say(&format!("Title:   {name}"), col::WHITE);
                self.say(&format!("Author:  {author}"), col::WHITE);
                self.say(&format!("Version: {version}"), col::WHITE);
                self.say(&format!("Label:   {label}"), col::LIGHT_GREY);
                self.say(&kind, col::LIGHT_GREY);
            }
        }
    }

    fn cmd_ls(&mut self) -> Result<()> {
        let mut entries: Vec<_> = std::fs::read_dir(&self.cwd)?
            .filter_map(|e| e.ok())
            .map(|e| {
                let name = e.file_name().to_string_lossy().into_owned();
                let is_dir = e.file_type().map(|t| t.is_dir()).unwrap_or(false);
                (name, is_dir)
            })
            .filter(|(n, _)| !n.starts_with('.'))
            .collect();
        entries.sort();
        for (name, is_dir) in entries.into_iter().take(40) {
            if is_dir {
                self.say(&format!("{name}/"), col::BLUE);
            } else if name.ends_with(".png") {
                self.say(&name, col::PINK);
            } else {
                self.say(&name, col::LIGHT_GREY);
            }
        }
        Ok(())
    }

    fn cmd_meta(&mut self, args: &[&str], set: impl FnOnce(&mut Assets, String)) -> Result<()> {
        if args.is_empty() {
            bail!("Missing text");
        }
        let value = args.join(" ");
        match self.assets_mut() {
            None => bail!("No cart loaded"),
            Some(a) => {
                set(a, value);
                self.say("OK", col::GREEN);
                Ok(())
            }
        }
    }

    fn capture_label(&mut self) {
        let Some(vm) = &self.vm else { return };
        let pixels = vm.state().fb.pixels().to_vec();
        if let Some(a) = self.assets_mut() {
            a.label = Some(pixels);
        }
        // A brief on-screen camera flash, plus a console line for the record.
        self.capture_flash = CAPTURE_FLASH_FRAMES;
        self.say("Label captured", col::GREEN);
    }

    fn stop_run(&mut self, message: &str) {
        self.vm = None;
        self.audio.stop_all();
        self.mode = Mode::Console;
        if !message.is_empty() {
            self.say(message, col::RED);
        }
    }

    fn show_error(&mut self, phase: &str, message: &str) {
        self.stop_run("");
        self.say("", col::WHITE);
        self.say(&format!("** Error in {phase} **"), col::RED);
        for line in message.lines().take(12) {
            self.say(line, col::ORANGE);
        }
    }

    fn runtime_error(&mut self, e: RuntimeError) {
        self.show_error(e.phase, &e.message);
    }

    // -----------------------------------------------------------------
    // Per-frame logic
    // -----------------------------------------------------------------

    /// The rate the host should tick at: a running cart's frame rate (30 or
    /// 60), else 30. Running the whole Run-mode tick at the cart's rate is
    /// what gets the display to refresh at 60 too.
    pub fn tick_fps(&self) -> u32 {
        match (self.mode, &self.vm) {
            (Mode::Run, Some(vm)) => vm.fps(),
            _ => UI_FPS,
        }
    }

    pub fn tick(&mut self) {
        self.frame += 1;

        // Poll the background build.
        if let Some(job) = &self.build {
            if let Some(result) = job.poll() {
                self.build = None;
                if result.success {
                    let msg = format!("Build ok ({:.1}s)", result.duration.as_secs_f32());
                    self.say(&msg, col::GREEN);
                    self.toast(&msg, col::GREEN, 2.0);
                    for w in &result.warnings {
                        self.say(w, col::ORANGE);
                    }
                    if self.run_after_build {
                        self.run_after_build = false;
                        if let Err(e) = self.start_vm_from_loaded() {
                            self.show_error("boot", &e.to_string());
                        }
                    }
                } else {
                    self.run_after_build = false;
                    // A failed build must never pass silently: whether it was
                    // kicked off from an editor or by an external edit while a
                    // cart is running, drop straight back to the console (and
                    // stop the now-stale cart) so the whole error list is on
                    // screen, rather than relying on a toast that the editor
                    // clips off the right edge of the screen.
                    self.stop_run("");
                    let n = result
                        .errors
                        .iter()
                        .filter(|l| l.starts_with("error"))
                        .count();
                    self.say(&format!("Build failed ({n} errors)"), col::RED);
                    for line in &result.errors {
                        let color = if line.starts_with("error") {
                            col::RED
                        } else {
                            col::ORANGE
                        };
                        self.say(line, color);
                    }
                }
            }
        }

        self.poll_project_watch();
        self.poll_cart_watch();
        self.check_hot_reload();

        match self.mode {
            Mode::Run => {
                if self.vm.is_some() {
                    let fps_val = self.fps_val;
                    let (logs, result) = {
                        let vm = self.vm.as_mut().unwrap();
                        vm.state_mut().set_measured_fps(fps_val);
                        let logs = std::mem::take(&mut vm.state_mut().logs);
                        let r = vm.call_update().and_then(|()| vm.call_draw());
                        (logs, r)
                    };
                    for l in logs {
                        self.say(&l, col::LIGHT_GREY);
                    }
                    if let Err(e) = result {
                        self.runtime_error(e);
                    }
                } else {
                    self.mode = Mode::Console;
                }
            }
            Mode::Console => {}
            _ => {
                // Tab bar clicks work in every editor (but not while the picker is open).
                if !self.file_picker.is_open() {
                    if let Some(target) = ui::tab_bar_click(&self.mouse) {
                        self.switch_editor(EDITOR_MODES[target]);
                    }
                }
                let mouse = self.mouse;
                let audio = self.audio.clone();
                match self.mode {
                    Mode::Code => {
                        if self.file_picker.is_open() {
                            let files = self.project_file_names();
                            let refs: Vec<&str> = files.iter().map(String::as_str).collect();
                            if let Some(action) = self.file_picker.tick(&mouse, &refs) {
                                self.run_picker_action(action);
                            }
                        } else if !self.loaded_none() {
                            // Click the top-left filename to open the picker (projects only).
                            if ui::filename_clicked(&mouse, &self.current_file_name())
                                && matches!(self.loaded, Loaded::Project(_))
                            {
                                self.open_file_picker();
                            } else {
                                let code = self.code().unwrap_or_default().to_string();
                                self.code_ed.tick(&mouse, &code);
                            }
                        }
                    }
                    Mode::Sprite => {
                        if let Some(a) = assets_of(&mut self.loaded) {
                            self.sprite_ed.tick(&mouse, a);
                        }
                    }
                    Mode::Map => {
                        if let Some(a) = assets_of(&mut self.loaded) {
                            self.map_ed.tick(&mouse, a);
                        }
                    }
                    Mode::Sfx => {
                        if let Some(a) = assets_of(&mut self.loaded) {
                            self.sfx_ed.tick(&mouse, a, &audio);
                        }
                    }
                    Mode::Music => {
                        if let Some(a) = assets_of(&mut self.loaded) {
                            self.music_ed.tick(&mouse, a, &audio);
                        }
                        // The pencil on a channel jumps to that SFX for editing.
                        if let Some(n) = self.music_ed.take_edit_request() {
                            self.sfx_ed.select(n);
                            self.switch_editor(Mode::Sfx);
                        }
                    }
                    _ => {}
                }
            }
        }
        self.mouse.end_frame();
    }

    fn check_hot_reload(&mut self) {
        if !self.frame.is_multiple_of(30) {
            return;
        }
        let Loaded::Project(p) = &self.loaded else {
            return;
        };
        let Ok(meta) = std::fs::metadata(p.wasm_path()) else {
            return;
        };
        let Ok(mtime) = meta.modified() else {
            return;
        };
        match self.wasm_mtime {
            Some(prev) if mtime > prev => {
                self.wasm_mtime = Some(mtime);
                // Only swap the running VM; in other modes the fresh wasm is
                // simply ready for the next run.
                if self.mode == Mode::Run {
                    match self.start_vm_from_loaded() {
                        Ok(()) => self.say("Hot reloaded", col::GREEN),
                        Err(e) => self.show_error("reload", &e.to_string()),
                    }
                }
            }
            Some(_) => {}
            None => self.wasm_mtime = Some(mtime),
        }
    }

    /// Poll project watchers and react to external edits: adopt clean changes,
    /// warn on conflicts, and kick off a rebuild (code/source) or VM reload
    /// (assets). Runs on a 30-frame cadence; skipped while a build is in flight.
    fn poll_project_watch(&mut self) {
        if !self.frame.is_multiple_of(30) || self.build.is_some() {
            return;
        }
        let (code_mem, assets_mem) = match &self.loaded {
            Loaded::Project(p) => (
                p.code.clone().into_bytes(),
                encode_assets(&p.assets).unwrap_or_default(),
            ),
            _ => return,
        };
        let Some(w) = &mut self.project_watch else {
            return;
        };
        let assets_change = w.assets.poll(&assets_mem);
        let code_change = w.code.poll(&code_mem);
        let source_changed = w.source_tree.poll();
        let code_conflicted = w.code.in_conflict();

        // Assets: no rebuild needed; adopt and reload the running VM.
        match assets_change {
            FileChange::Adopt(bytes) => match decode_assets(&bytes) {
                Ok(assets) => {
                    if let Loaded::Project(p) = &mut self.loaded {
                        p.assets = assets;
                    }
                    self.say("Assets reloaded from disk", col::GREEN);
                    if self.mode == Mode::Run {
                        if let Err(e) = self.start_vm_from_loaded() {
                            self.show_error("reload", &e.to_string());
                        }
                    }
                }
                // Malformed disk file: re-sync so we do not loop on it.
                Err(_) => {
                    self.resync_assets_watcher();
                    self.say("assets.pixel8.json on disk is unreadable", col::ORANGE);
                }
            },
            FileChange::Conflict => {
                self.say("assets.pixel8.json changed on disk;", col::ORANGE);
                self.say("You have unsaved edits", col::ORANGE);
            }
            FileChange::None => {}
        }

        // Code: adopt into the editor; build is driven by source_changed below.
        match code_change {
            FileChange::Adopt(bytes) => {
                let text = String::from_utf8_lossy(&bytes).into_owned();
                self.code_ed.set_text(&text);
                if let Loaded::Project(p) = &mut self.loaded {
                    p.code = text;
                }
            }
            FileChange::Conflict => {
                self.say(
                    &format!("src/{} changed on disk;", self.current_file_name()),
                    col::ORANGE,
                );
                self.say("Save or reload to resolve", col::ORANGE);
            }
            FileChange::None => {}
        }

        // Any source change (lib.rs or another module) rebuilds — unless the
        // mirrored code is in an unresolved conflict (we must not build a state
        // the user has not chosen).
        if source_changed && !code_conflicted {
            let dir = match &self.loaded {
                Loaded::Project(p) => p.dir.clone(),
                _ => return,
            };
            self.say("Source changed, rebuilding...", col::LIGHT_GREY);
            self.toast("Rebuilding...", col::LIGHT_GREY, 1.5);
            self.build = Some(spawn_build(&dir));
            // Re-run from the console or while already running; stay put if the
            // user is in an editor.
            self.run_after_build = matches!(self.mode, Mode::Run | Mode::Console);
        }
    }

    /// Poll a loaded PNG cart's file: on external change re-parse and adopt it
    /// (when there are no in-console asset edits), else warn about a conflict.
    fn poll_cart_watch(&mut self) {
        if !self.frame.is_multiple_of(30) {
            return;
        }
        let (path, in_memory, baseline) = match (&self.loaded, &mut self.cart_watch) {
            (Loaded::Cart { cart, .. }, Some(w)) => {
                if w.advanced().is_none() {
                    return;
                }
                (
                    w.path.clone(),
                    encode_assets(&cart.assets).unwrap_or_default(),
                    w.baseline.clone(),
                )
            }
            _ => return,
        };
        let new_cart = match cart::load_png(&path) {
            Ok(c) => c,
            Err(e) => {
                self.show_error("reload", &e.to_string());
                return;
            }
        };
        let disk = encode_assets(&new_cart.assets).unwrap_or_default();
        match crate::watch::reconcile(&baseline, &disk, &in_memory) {
            crate::watch::Reconcile::Unchanged => {}
            crate::watch::Reconcile::Adopt(_) => {
                self.code_ed.set_text(
                    new_cart
                        .source
                        .as_deref()
                        .unwrap_or("// No source in this cart"),
                );
                if let Some(w) = &mut self.cart_watch {
                    w.baseline = disk;
                }
                self.loaded = Loaded::Cart {
                    cart: new_cart,
                    path,
                };
                self.say("Cart reloaded from disk", col::GREEN);
                if self.mode == Mode::Run {
                    if let Err(e) = self.start_vm_from_loaded() {
                        self.show_error("reload", &e.to_string());
                    }
                }
            }
            crate::watch::Reconcile::Conflict => {
                // No latch: each new external write re-warns. The `reload`
                // command (next task) takes the disk version to resolve this.
                self.say("Cart changed on disk;", col::ORANGE);
                self.say("You have unsaved edits", col::ORANGE);
            }
        }
    }

    // -----------------------------------------------------------------
    // Drawing
    // -----------------------------------------------------------------

    /// Draw the current mode and return the framebuffer to present.
    /// Count presented frames over ~0.5 s windows for the fps meter. The
    /// cart can't measure this itself — `time()` is a logical clock — so the
    /// host counts real draws against the wall clock.
    fn meter_fps(&mut self) {
        self.fps_frames += 1;
        let elapsed = self.fps_t0.elapsed();
        if elapsed >= Duration::from_millis(500) {
            self.fps_val = self.fps_frames as f32 / elapsed.as_secs_f32();
            self.fps_frames = 0;
            self.fps_t0 = Instant::now();
        }
    }

    pub fn draw(&mut self) -> &Framebuffer {
        self.meter_fps();
        match self.mode {
            Mode::Run => {
                if self.show_stats {
                    let fps = self.fps_val;
                    if let Some(vm) = self.vm.as_mut() {
                        let target = vm.fps();
                        let cpu_u = vm.cpu_update();
                        let cpu_d = vm.cpu_draw();
                        let used = vm.mem_used_bytes();
                        stats_overlay(&mut vm.state_mut().fb, cpu_u, cpu_d, used, fps, target);
                    }
                }
                if self.capture_flash > 0 {
                    if let Some(vm) = self.vm.as_mut() {
                        capture_flash_overlay(&mut vm.state_mut().fb);
                    }
                    self.capture_flash -= 1;
                }
                if let Some(vm) = &self.vm {
                    return &vm.state().fb;
                }
                &self.fb
            }
            Mode::Console => {
                self.draw_console();
                &self.fb
            }
            _ => {
                self.fb.reset_state();
                self.fb.cls(col::DARK_GREY);
                let mouse = self.mouse;
                match self.mode {
                    Mode::Code => {
                        let code = self.code().unwrap_or_default().to_string();
                        self.code_ed.draw(&mut self.fb, &code);
                        if self.file_picker.is_open() {
                            let files = self.project_file_names();
                            let refs: Vec<&str> = files.iter().map(String::as_str).collect();
                            let current = self.current_file_name();
                            self.file_picker.draw(&mut self.fb, &refs, &current);
                        }
                    }
                    Mode::Sprite => {
                        if let Some(a) = assets_ref(&self.loaded) {
                            self.sprite_ed.draw(&mut self.fb, a);
                        }
                    }
                    Mode::Map => {
                        if let Some(a) = assets_ref(&self.loaded) {
                            self.map_ed.draw(&mut self.fb, a);
                        }
                    }
                    Mode::Sfx => {
                        if let Some(a) = assets_ref(&self.loaded) {
                            self.sfx_ed.draw(&mut self.fb, a, &self.audio);
                        }
                    }
                    Mode::Music => {
                        if let Some(a) = assets_ref(&self.loaded) {
                            self.music_ed.draw(&mut self.fb, a, &self.audio);
                        }
                    }
                    _ => {}
                }
                ui::draw_tab_bar(&mut self.fb, self.mode);
                // Per-editor top-left content: the code filename (click to pick
                // a file), the SFX mode buttons, and the sprite/map view buttons.
                match self.mode {
                    Mode::Code => {
                        let name = self.current_file_name();
                        ui::code_filename(&mut self.fb, &name);
                    }
                    Mode::Sfx => ui::mode_buttons(&mut self.fb, self.sfx_ed.is_pitch()),
                    Mode::Sprite => ui::view_buttons(&mut self.fb, self.sprite_ed.is_fullscreen()),
                    Mode::Map => ui::view_buttons(&mut self.fb, self.map_ed.is_fullscreen()),
                    Mode::Music => {
                        ui::mode_buttons(&mut self.fb, !self.music_ed.is_grid());
                        if self.music_ed.is_grid() {
                            ui::pat_sfx_toggle(&mut self.fb, self.music_ed.grid_sfx());
                        }
                    }
                    _ => {}
                }
                self.draw_toast();
                // Name the hovered view in the bottom bar, but not while the
                // file picker is open — its tabs are inert then, so a hint
                // would invite a click that does nothing.
                if !self.file_picker.is_open() {
                    if let Some(i) = ui::tab_bar_hover(&mouse) {
                        ui::status_bar(&mut self.fb, ui::tab_name(i));
                    }
                }
                if !self.hide_cursor {
                    ui::draw_cursor(&mut self.fb, &mouse);
                }
                &self.fb
            }
        }
    }

    /// Bottom-bar feedback in editor modes: a live "building..." while a
    /// build runs, otherwise the most recent toast until it expires.
    fn draw_toast(&mut self) {
        let msg = if self.build.is_some() {
            let dots = ".".repeat(1 + (self.frame as usize / 10) % 3);
            Some((format!("Building{dots}"), col::ORANGE))
        } else {
            match &self.toast {
                Some((text, color, expires)) if self.frame < *expires => {
                    Some((text.clone(), *color))
                }
                _ => {
                    self.toast = None;
                    None
                }
            }
        };
        if let Some((text, color)) = msg {
            self.fb.rectfill(0, 120, 127, 127, col::BLACK);
            self.fb.print(&text, 2, 121, color);
        }
    }

    fn draw_console(&mut self) {
        self.fb.reset_state();
        self.fb.cls(col::BLACK);
        // Lines fit between the top margin and the bottom status line, scaled
        // to the font's line height.
        let rows = ((120 - 2) / font::GLYPH_H) as usize;

        // Gather visible lines: history tail + prompt line.
        let total = self.lines.len();
        let end = total.saturating_sub(self.scroll_back);
        let start = end.saturating_sub(rows);
        let mut y = 2;
        for line in self.lines.iter().skip(start).take(end - start) {
            match line {
                ConsoleLine::Text { text, color } => {
                    self.fb.print(text, 2, y, *color);
                }
                ConsoleLine::Stripe => {
                    for (i, c) in [8u8, 9, 10, 11, 12, 13, 14, 15].iter().enumerate() {
                        self.fb
                            .rectfill(2 + i as i32 * 6, y, 2 + i as i32 * 6 + 4, y + 3, *c);
                    }
                }
            }
            y += font::GLYPH_H;
        }

        // Prompt with blinking cursor (skipped while compiling).
        if self.build.is_some() {
            let dots = ".".repeat(1 + (self.frame as usize / 10) % 3);
            self.fb
                .print(&format!("Compiling{dots}"), 2, y, col::ORANGE);
            return;
        }
        let prompt = format!("> {}", self.input);
        self.fb.print(&prompt, 2, y, PROMPT_COL);
        if (self.frame / 8).is_multiple_of(2) {
            let cx = 2 + (2 + self.cursor as i32) * 4;
            self.fb
                .rectfill(cx, y, cx + 3, y + font::GLYPH_H - 2, col::RED);
        }
    }
}

/// The value following a flag, rejecting a missing value or another flag taken
/// as the value (e.g. `--into --sfx 0`).
fn flag_value<'a>(next: Option<&'a &'a str>, flag: &str) -> Result<&'a str> {
    match next {
        Some(&v) if !v.starts_with("--") => Ok(v),
        _ => bail!("{flag} needs a value"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::Path;

    #[test]
    fn stats_overlay_draws_top_right_panel() {
        let text_pixels = |fb: &Framebuffer, xr: std::ops::Range<i32>| {
            let mut n = 0;
            for y in 0..28 {
                for x in xr.clone() {
                    if fb.pget(x, y) != col::BLACK {
                        n += 1;
                    }
                }
            }
            n
        };
        let mut fb = Framebuffer::new();
        stats_overlay(&mut fb, 0.342, 0.51, 32768, 30.0, 30);
        // With one-decimal CPU the panel widens (12-char rows -> x0=78), so the
        // decimal digit shows colored text in 78..86 — blank with the old
        // integer panel (x0=86). This is what makes the test red-before-green.
        assert!(
            text_pixels(&fb, 78..86) > 0,
            "decimal CPU widened the panel left"
        );
        assert_eq!(
            text_pixels(&fb, 0..60),
            0,
            "overlay leaves the top-left untouched"
        );
    }

    fn test_shell() -> Shell {
        let sdk = Path::new(env!("CARGO_MANIFEST_DIR")).join("../pixel8");
        let mut shell = Shell::new(AudioHandle::dummy(), sdk);
        // Keep cart saves out of the real user cache directory: tests that
        // run carts must be hermetic.
        shell.storage_root =
            Some(std::env::temp_dir().join(format!("pixel8_test_storage_{}", std::process::id())));
        shell
    }

    /// Restarting a cart must save the old VM's storage *before* the new VM
    /// loads its copy from disk — the `self.vm = None` at the top of
    /// `start_vm_from_loaded` is load-bearing. The cart increments a stored
    /// counter in `pixel8_init`; two starts must produce 2, not 1.
    #[test]
    fn restart_saves_storage_before_the_new_vm_loads() {
        use pixel8_runtime::{assets::Assets, cart::Cart, storage::Storage};
        const COUNTER_CART: &str = r#"
            (module
              (import "pixel8" "storage_get" (func $sget (param i32 i32 i32 i32) (result i32)))
              (import "pixel8" "storage_set" (func $sset (param i32 i32 i32 i32) (result i32)))
              (memory (export "memory") 1)
              (data (i32.const 0) "n")
              (func (export "pixel8_init")
                (local $n i32)
                (if (i32.eq (call $sget (i32.const 0) (i32.const 1) (i32.const 8) (i32.const 1))
                            (i32.const 1))
                  (then (local.set $n (i32.sub (i32.load8_u (i32.const 8)) (i32.const 48)))))
                (i32.store8 (i32.const 8) (i32.add (i32.const 49) (local.get $n)))
                (drop (call $sset (i32.const 0) (i32.const 1) (i32.const 8) (i32.const 1))))
              (func (export "pixel8_update"))
              (func (export "pixel8_draw")))
        "#;
        let root = std::env::temp_dir().join(format!("pixel8_restart_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&root);
        let mut shell = test_shell();
        shell.storage_root = Some(root.clone());
        shell.loaded = Loaded::Cart {
            cart: Cart {
                wasm: wat::parse_str(COUNTER_CART).unwrap(),
                assets: Assets::default(),
                source: None,
            },
            path: PathBuf::from("counter.png"),
        };
        shell.start_vm_from_loaded().expect("first start"); // n = 1
        shell.start_vm_from_loaded().expect("restart"); // saves 1, reads it, n = 2
        shell.vm = None; // Final save.
        let s = Storage::for_cart_in(&root, &Assets::default().meta.name);
        assert_eq!(
            s.get_json("n").as_deref(),
            Some("2"),
            "the restart must persist the first run's write before the second reads"
        );
        std::fs::remove_dir_all(&root).unwrap();
    }

    /// Rewrite a freshly-scaffolded project's `pixel8` git dep to a path dep on the
    /// in-tree SDK, so test builds match this host's ABI and stay offline.
    fn point_cart_at_local_sdk(project_dir: &Path) {
        let sdk = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../pixel8")
            .canonicalize()
            .unwrap();
        let manifest_path = project_dir.join("Cargo.toml");
        let manifest = std::fs::read_to_string(&manifest_path).unwrap();
        // A scaffolded project depends on the released SDK; tests must build against the working
        // tree instead. Every workspace crate shares one version, so this crate's major.minor is
        // the requirement the template wrote.
        let dep = format!(
            "version = \"{}.{}\"",
            env!("CARGO_PKG_VERSION_MAJOR"),
            env!("CARGO_PKG_VERSION_MINOR"),
        );
        let patched = manifest.replace(&dep, &format!("path = {:?}", sdk.display().to_string()));
        assert_ne!(patched, manifest, "no `{dep}` to redirect in:\n{manifest}");
        std::fs::write(&manifest_path, patched).unwrap();
    }

    #[test]
    fn window_title_reflects_loaded_cart() {
        let dir = std::env::temp_dir().join(format!("pixel8_title_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let mut shell = test_shell();
        assert_eq!(shell.window_title(), "Pixel8");

        let project_dir = dir.join("game");
        Project::create(&project_dir, "game").unwrap();
        shell
            .cmd_load(&[project_dir.to_str().unwrap()])
            .expect("load project");
        assert_eq!(shell.window_title(), "game - Pixel8");
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// Ctrl+S in an editor saves, flashes feedback, kicks off a real
    /// background build, and reports the result in the bottom bar.
    #[test]
    fn ctrl_s_saves_and_builds_with_feedback() {
        let dir = std::env::temp_dir().join(format!("pixel8_shell_test_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let mut shell = test_shell();
        let project_dir = dir.join("game");
        Project::create(&project_dir, "game").unwrap();
        point_cart_at_local_sdk(&project_dir);

        shell
            .cmd_load(&[project_dir.to_str().unwrap()])
            .expect("load project");
        shell.switch_editor(Mode::Code);

        // Add a comment line at the top (keeping the code valid), then Ctrl+S.
        for c in "//x".chars() {
            shell.key(Key::Char(c), Mods::default());
        }
        shell.key(Key::Enter, Mods::default());
        shell.key(
            Key::Char('s'),
            Mods {
                ctrl: true,
                ..Default::default()
            },
        );

        // Saved to disk, toast shown, build started.
        let code = std::fs::read_to_string(project_dir.join("src/lib.rs")).unwrap();
        assert!(code.starts_with("//x\n"), "edit was saved");
        assert_eq!(shell.toast.as_ref().unwrap().0, "Saved");
        assert!(shell.build.is_some(), "background build spawned");

        // While building, the editor bottom bar shows progress.
        shell.draw();
        assert_eq!(shell.fb.pget(0, 120), col::BLACK, "toast bar drawn");

        // Wait for the real cargo build (template code must compile).
        for _ in 0..(120 * 30) {
            shell.tick();
            if shell.build.is_none() {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(33));
        }
        assert!(shell.build.is_none(), "build finished in time");
        let (text, color, _) = shell.toast.as_ref().unwrap();
        assert!(text.starts_with("Build ok"), "got: {text}");
        assert_eq!(*color, col::GREEN);
        assert!(
            shell.mode == Mode::Code,
            "stays in the editor; no mode switch"
        );
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// A broken cart reports a failing build without leaving the editor.
    #[test]
    fn save_build_failure_is_reported() {
        let dir = std::env::temp_dir().join(format!("pixel8_shell_fail_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let mut shell = test_shell();
        let project_dir = dir.join("game");
        let mut project = Project::create(&project_dir, "game").unwrap();
        project.code = "fn broken( {".into();
        project.save().unwrap();

        shell
            .cmd_load(&[project_dir.to_str().unwrap()])
            .expect("load project");
        shell.switch_editor(Mode::Code);
        shell.key(
            Key::Char('s'),
            Mods {
                ctrl: true,
                ..Default::default()
            },
        );
        assert!(shell.build.is_some());
        for _ in 0..(120 * 30) {
            shell.tick();
            if shell.build.is_none() {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(33));
        }
        // The build-failure summary is now printed to the console buffer (not
        // the toast), and the mode drops back to Console.
        assert_eq!(
            shell.mode,
            Mode::Console,
            "expected console mode after build failure"
        );
        let summary = shell.lines.iter().find_map(|l| match l {
            ConsoleLine::Text { text, color } if text.starts_with("Build failed") => {
                Some((text.clone(), *color))
            }
            _ => None,
        });
        let (text, color) = summary.expect("Build failed summary not found in console lines");
        assert!(text.starts_with("Build failed"), "got: {text}");
        assert_eq!(color, col::RED);
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// `run` after an external edit (clean in-console state) builds the
    /// external version and does NOT overwrite it with the stale in-memory copy.
    #[test]
    fn run_does_not_clobber_external_edits() {
        let dir = std::env::temp_dir().join(format!("pixel8_run_noclobber_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let mut shell = test_shell();
        let project_dir = dir.join("game");
        Project::create(&project_dir, "game").unwrap();
        shell
            .cmd_load(&[project_dir.to_str().unwrap()])
            .expect("load");

        // Simulate an external editor changing src/lib.rs to a still-valid file.
        let lib = project_dir.join("src/lib.rs");
        let original = std::fs::read_to_string(&lib).unwrap();
        let edited = format!("// EXTERNAL EDIT\n{original}");
        // Bump mtime so the watcher sees it as newer than load time.
        std::fs::write(&lib, &edited).unwrap();
        let later = std::time::SystemTime::now() + std::time::Duration::from_secs(10);
        std::fs::OpenOptions::new()
            .write(true)
            .open(&lib)
            .unwrap()
            .set_modified(later)
            .unwrap();

        shell.cmd_run();

        // The on-disk file must still contain the external edit — not be
        // reverted to the stale in-memory copy.
        let after = std::fs::read_to_string(&lib).unwrap();
        assert!(
            after.starts_with("// EXTERNAL EDIT\n"),
            "external edit survived run; got:\n{after}"
        );

        // Let the build finish so we leave no thread dangling.
        for _ in 0..(120 * 30) {
            shell.tick();
            if shell.build.is_none() {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(33));
        }
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// `startup_run` (the `pixel8 run <path>` launch mode) loads-then-runs: on a
    /// project it kicks off the async build and arms the deferred run, exactly
    /// as the in-console `run` verb does.
    #[test]
    fn startup_run_arms_the_deferred_run() {
        let dir = std::env::temp_dir().join(format!("pixel8_startup_run_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let mut shell = test_shell();
        let project_dir = dir.join("game");
        Project::create(&project_dir, "game").unwrap();

        shell.startup_load(project_dir.to_str().unwrap());
        assert_eq!(shell.mode, Mode::Console, "loaded, still at the console");

        shell.startup_run();
        assert!(shell.build.is_some(), "startup_run spawns the build");
        assert!(
            shell.run_after_build,
            "and arms the run to start once it is built"
        );

        // The build runs on a detached thread; don't wait for cargo, just clean up.
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// `new` must arm the disk watcher, otherwise in-console edits are dropped
    /// before the build (reconcile_for_build skips the flush when unwatched).
    #[test]
    fn new_arms_the_project_watcher() {
        let dir = std::env::temp_dir().join(format!("pixel8_new_watch_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let mut shell = test_shell();
        shell.cwd = dir.clone();
        shell.cmd_new(&["game"]).expect("new");
        assert!(shell.project_watch.is_some(), "new should arm the watcher");
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// Editing project source externally while idle at the console triggers an
    /// automatic build and starts the cart running.
    #[test]
    fn external_edit_auto_builds_and_runs() {
        let dir = std::env::temp_dir().join(format!("pixel8_autobuild_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let mut shell = test_shell();
        let project_dir = dir.join("game");
        Project::create(&project_dir, "game").unwrap();
        point_cart_at_local_sdk(&project_dir);

        shell
            .cmd_load(&[project_dir.to_str().unwrap()])
            .expect("load");
        assert_eq!(shell.mode, Mode::Console);

        // External edit, mtime bumped so the watcher sees it.
        let lib = project_dir.join("src/lib.rs");
        let original = std::fs::read_to_string(&lib).unwrap();
        std::fs::write(&lib, format!("// auto\n{original}")).unwrap();
        let later = std::time::SystemTime::now() + std::time::Duration::from_secs(10);
        std::fs::OpenOptions::new()
            .write(true)
            .open(&lib)
            .unwrap()
            .set_modified(later)
            .unwrap();

        // Drive ticks: poll fires on a 30-frame cadence, then the build runs.
        let mut entered_run = false;
        for _ in 0..(180 * 30) {
            shell.tick();
            if shell.mode == Mode::Run {
                entered_run = true;
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(33));
        }
        assert!(entered_run, "external edit should auto-build and run");
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// Re-exporting a loaded PNG cart on disk reloads it (assets adopted) when
    /// there are no in-console edits.
    #[test]
    fn external_png_change_reloads_cart() {
        use pixel8_runtime::cart::{self, Cart};
        let dir = std::env::temp_dir().join(format!("pixel8_pngreload_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let mut shell = test_shell();

        let project_dir = dir.join("game");
        let project = Project::create(&project_dir, "game").unwrap();
        let png = dir.join("game.png");

        // A valid cart needs the 4-byte wasm magic (plus version); the codec
        // checks for it on save and load. The VM never runs here.
        let mut cart = Cart {
            wasm: b"\0asm\x01\0\0\0".to_vec(),
            assets: project.assets.clone(),
            source: Some("// v1".into()),
        };
        cart::save_png(&cart, &png).unwrap();
        shell.cmd_load(&[png.to_str().unwrap()]).expect("load png");
        let before = shell.cart_name();

        // Re-export with a different cart name, bump mtime.
        cart.assets.meta.name = "renamed".into();
        cart::save_png(&cart, &png).unwrap();
        let later = std::time::SystemTime::now() + std::time::Duration::from_secs(10);
        std::fs::OpenOptions::new()
            .write(true)
            .open(&png)
            .unwrap()
            .set_modified(later)
            .unwrap();

        for _ in 0..(60 * 30) {
            shell.tick();
            if shell.cart_name() != before {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(33));
        }
        assert_eq!(shell.cart_name(), "renamed", "external PNG change adopted");
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// Saving a PNG cart re-baselines its watcher, so the next poll does not
    /// mistake pixel8's own write for an external change (no false conflict).
    #[test]
    fn saving_png_does_not_self_conflict() {
        use pixel8_runtime::{
            cart::{self, Cart},
            project::encode_assets,
        };
        let dir = std::env::temp_dir().join(format!("pixel8_pngsave_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let mut shell = test_shell();
        let project = Project::create(&dir.join("game"), "game").unwrap();
        let png = dir.join("game.png");
        let cart = Cart {
            wasm: b"\0asm\x01\0\0\0".to_vec(),
            assets: project.assets.clone(),
            source: Some("// v1".into()),
        };
        cart::save_png(&cart, &png).unwrap();
        shell.cmd_load(&[png.to_str().unwrap()]).expect("load png");

        // Edit the loaded cart's assets in-console, then save.
        if let Some(a) = shell.assets_mut() {
            a.meta.name = "edited".into();
        }
        shell.cmd_save(&[]).expect("save");

        // The watcher baseline must now match the saved in-memory assets.
        let in_mem = encode_assets(shell.assets().unwrap()).unwrap_or_default();
        assert_eq!(
            shell.cart_watch.as_ref().unwrap().baseline,
            in_mem,
            "save re-baselined the cart watcher"
        );

        // Ticking must not flip into a conflict / reload state.
        for _ in 0..(2 * 30) {
            shell.tick();
        }
        assert_eq!(shell.cart_name(), "edited");
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// `reload` discards in-console edits and re-reads the project from disk,
    /// resolving a conflict in favour of the external version.
    #[test]
    fn reload_takes_disk_version() {
        let dir = std::env::temp_dir().join(format!("pixel8_reload_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let mut shell = test_shell();
        let project_dir = dir.join("game");
        Project::create(&project_dir, "game").unwrap();
        shell
            .cmd_load(&[project_dir.to_str().unwrap()])
            .expect("load");

        // External edit on disk.
        let lib = project_dir.join("src/lib.rs");
        std::fs::write(&lib, "// DISK VERSION\n").unwrap();

        shell.cmd_reload().expect("reload");
        let code = shell.code().unwrap_or_default().to_string();
        assert!(
            code.starts_with("// DISK VERSION"),
            "reload took disk; got:\n{code}"
        );
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// A conflict (both disk and editor changed) must abort `run` and keep
    /// aborting on a *second* `run` until resolved — never flushing the stale
    /// in-console copy over the external edit.
    #[test]
    fn run_aborts_on_conflict_and_does_not_clobber() {
        let dir = std::env::temp_dir().join(format!("pixel8_run_conflict_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let mut shell = test_shell();
        let project_dir = dir.join("game");
        Project::create(&project_dir, "game").unwrap();
        shell
            .cmd_load(&[project_dir.to_str().unwrap()])
            .expect("load");

        // In-console edit: make the in-memory copy dirty.
        if let Loaded::Project(p) = &mut shell.loaded {
            p.code = "// IN-CONSOLE EDIT\n".into();
        }
        // External edit on disk, mtime bumped so the watcher sees it.
        let lib = project_dir.join("src/lib.rs");
        std::fs::write(&lib, "// EXTERNAL EDIT\n").unwrap();
        let later = std::time::SystemTime::now() + std::time::Duration::from_secs(10);
        std::fs::OpenOptions::new()
            .write(true)
            .open(&lib)
            .unwrap()
            .set_modified(later)
            .unwrap();

        // First run: conflict → abort, no build, disk keeps the external edit.
        shell.cmd_run();
        assert_eq!(shell.mode, Mode::Console, "first run aborts on conflict");
        assert!(shell.build.is_none(), "no build started on conflict");
        assert_eq!(
            std::fs::read_to_string(&lib).unwrap(),
            "// EXTERNAL EDIT\n",
            "disk untouched after the first run"
        );

        // Second run without resolving: must STILL abort and STILL not clobber.
        shell.cmd_run();
        assert_eq!(shell.mode, Mode::Console, "second run still aborts");
        assert!(shell.build.is_none(), "second run starts no build");
        assert_eq!(
            std::fs::read_to_string(&lib).unwrap(),
            "// EXTERNAL EDIT\n",
            "disk still untouched after the second run"
        );

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn picker_creates_and_switches_files_in_the_shell() {
        let dir = std::env::temp_dir().join(format!("pixel8_pick_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let mut shell = test_shell();
        let project_dir = dir.join("game");
        Project::create(&project_dir, "game").unwrap();
        shell
            .cmd_load(&[project_dir.to_str().unwrap()])
            .expect("load project");
        shell.switch_editor(Mode::Code);

        // Ctrl+O opens the picker; create a new file from it.
        let ctrl = Mods {
            ctrl: true,
            ..Default::default()
        };
        shell.key(Key::Char('o'), ctrl);
        assert!(shell.file_picker.is_open());
        shell.key(Key::Down, Mods::default()); // -> "+ new file"
        shell.key(Key::Enter, Mods::default()); // -> new-file input
        for c in "enemy".chars() {
            shell.key(Key::Char(c), Mods::default());
        }
        shell.key(Key::Enter, Mods::default()); // create

        assert!(!shell.file_picker.is_open());
        assert!(project_dir.join("src/enemy.rs").exists());
        let lib = std::fs::read_to_string(project_dir.join("src/lib.rs")).unwrap();
        // `mod` is wired in after the template's `#![no_std]` inner attribute.
        assert!(lib.starts_with("#![no_std]"), "lib.rs:\n{lib}");
        assert!(lib.contains("\nmod enemy;\n"), "lib.rs:\n{lib}");
        // The new (empty) file is now the open buffer.
        assert_eq!(shell.code().unwrap(), "");

        // Switch back to lib.rs via the picker.
        shell.key(Key::Char('o'), ctrl);
        shell.key(Key::Enter, Mods::default()); // sel 0 == lib.rs
        assert!(shell.code().unwrap().contains("\nmod enemy;\n"));
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn clicking_the_filename_opens_the_picker() {
        let dir = std::env::temp_dir().join(format!("pixel8_fnclick_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let mut shell = test_shell();
        let project_dir = dir.join("game");
        Project::create(&project_dir, "game").unwrap();
        shell
            .cmd_load(&[project_dir.to_str().unwrap()])
            .expect("load project");
        shell.switch_editor(Mode::Code);

        assert!(!shell.file_picker.is_open());
        // A left-press on the top-left filename.
        let name = shell.current_file_name();
        shell.mouse = Mouse {
            x: 3,
            y: 2,
            left_pressed: true,
            ..Default::default()
        };
        assert!(ui::filename_clicked(&shell.mouse, &name));
        shell.tick();
        assert!(
            shell.file_picker.is_open(),
            "filename click opens the picker"
        );
        std::fs::remove_dir_all(&dir).unwrap();
    }

    /// A save failure during a file switch aborts the switch and surfaces the
    /// error via both the console log and the toast bar.
    #[test]
    fn select_file_save_failure_aborts_and_reports() {
        let dir = std::env::temp_dir().join(format!("pixel8_savefail_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let mut shell = test_shell();
        let project_dir = dir.join("game");
        Project::create(&project_dir, "game").unwrap();

        // Write a second source file so there is something to switch to.
        std::fs::write(project_dir.join("src/other.rs"), "").unwrap();

        shell
            .cmd_load(&[project_dir.to_str().unwrap()])
            .expect("load project");
        shell.switch_editor(Mode::Code);

        // Sabotage save: replace src/lib.rs (file) with a directory of the
        // same name so that fs::write fails with EISDIR.
        let lib_path = project_dir.join("src/lib.rs");
        std::fs::remove_file(&lib_path).unwrap();
        std::fs::create_dir(&lib_path).unwrap();

        // Attempt to switch to other.rs — save fails, switch must be aborted.
        shell.select_file("other.rs");

        // The current file must not have changed.
        assert_eq!(
            shell.current_file_name(),
            "lib.rs",
            "switch must be aborted when save fails"
        );

        // The error must be surfaced via the toast bar in red.
        let toast = shell
            .toast
            .as_ref()
            .expect("toast must be set on save error");
        assert_eq!(toast.1, col::RED, "toast must be red");
        assert!(
            toast.0.contains("lib.rs"),
            "toast must name the file that failed to save; got: {}",
            toast.0
        );

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn import_pico8_into_appends_to_loaded_project() {
        let dir = std::env::temp_dir().join(format!("pixel8_shell_into_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();

        // A source cart with sprite 0 pixel (0,0) = 0xc.
        let mut row0 = vec![b'0'; 128];
        row0[0] = b'c';
        let p8 = format!(
            "pico-8 cartridge // http://www.pico-8.com\nversion 41\n__gfx__\n{}\n",
            String::from_utf8(row0).unwrap()
        );
        std::fs::write(dir.join("src.p8"), p8).unwrap();

        let mut shell = test_shell();
        shell.cwd = dir.clone();
        // `new` creates the project under cwd and loads it as the destination.
        shell.cmd_new(&["dest"]).expect("new");
        // Mark sprite 0 of the loaded project as used, so an additive import must
        // land the imported sprite at slot 1 (after the last used slot).
        shell.assets_mut().expect("loaded").sprites.set(0, 0, 5);

        shell.exec("import-pico8 src.p8 --into --sprites 0");

        // The command must append INTO the loaded `dest` project, not replace it
        // with a freshly-created one: the loaded project is still `dest`...
        match &shell.loaded {
            Loaded::Project(p) => assert_eq!(p.name, "dest"),
            _ => panic!("expected the dest project to remain loaded"),
        }
        let assets = shell.assets().expect("a project is loaded");
        // ...the pre-existing sprite 0 is untouched...
        assert_eq!(assets.sprites.get(0, 0), 5);
        // ...and the imported sprite landed at slot 1 (sheet (8, 0)).
        assert_eq!(assets.sprites.get(8, 0), 0xc);

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn additive_import_does_not_trigger_a_rebuild() {
        let dir =
            std::env::temp_dir().join(format!("pixel8_into_norebuild_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();

        let mut row0 = vec![b'0'; 128];
        row0[0] = b'c';
        let p8 = format!(
            "pico-8 cartridge // http://www.pico-8.com\nversion 41\n__gfx__\n{}\n",
            String::from_utf8(row0).unwrap()
        );
        std::fs::write(dir.join("src.p8"), p8).unwrap();

        let mut shell = test_shell();
        shell.cwd = dir.clone();
        shell.cmd_new(&["dest"]).expect("new");

        shell.exec("import-pico8 src.p8 --into --sprites 0");

        // The save rewrote src/lib.rs too; the import must re-baseline the whole
        // watcher. Tick past the source-tree poll interval and confirm no rebuild was
        // triggered and we stayed at the console (no spontaneous run into Run mode).
        for _ in 0..40 {
            shell.tick();
        }
        assert!(
            shell.build.is_none(),
            "additive import must not spawn a build"
        );
        assert_eq!(shell.mode, Mode::Console, "must stay at the console");
        assert!(!shell.run_after_build, "must not arm a run");

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn apply_paste_routes_map_blobs_to_the_map_editor() {
        use pixel8_runtime::clipboard::Pasted;
        let dir = std::env::temp_dir().join(format!("pixel8_mappaste_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();

        let mut shell = test_shell();
        shell.cwd = dir.clone();
        shell.cmd_new(&["dest"]).expect("new");
        shell.mode = Mode::Map;

        shell.apply_paste(Pasted::Map {
            w: 1,
            h: 1,
            tiles: vec![7],
        });
        assert!(shell.map_ed.has_paste_buffer());

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn apply_paste_routes_sfx_to_the_sfx_editor() {
        use pixel8_runtime::clipboard::{Pasted, SfxClip, Slotted};
        let dir = std::env::temp_dir().join(format!("pixel8_paste_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();

        let mut shell = test_shell();
        shell.cwd = dir.clone();
        shell.cmd_new(&["dest"]).expect("new");
        shell.mode = Mode::Sfx; // the SFX editor's slot defaults to 0.

        let mut sfx = pixel8_runtime::assets::Sfx::default();
        sfx.notes[0].pitch = 21;
        sfx.notes[0].volume = 4;
        let clip = SfxClip {
            records: vec![Slotted { src: 0, value: sfx }],
            patterns: vec![],
        };
        shell.apply_paste(Pasted::Sfx(clip));

        let assets = assets_ref(&shell.loaded).unwrap();
        assert_eq!(assets.sfx[0].notes[0].pitch, 21);

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn hide_cursor_suppresses_the_software_cursor() {
        let mut shell = test_shell();
        // An editor mode: the software mouse cursor is drawn there.
        shell.mode = Mode::Sprite;
        shell.mouse.x = 40;
        shell.mouse.y = 40;
        let with_cursor = shell.draw().pixels().to_vec();

        shell.set_hide_cursor(true);
        let hidden = shell.draw().pixels().to_vec();
        assert_ne!(
            with_cursor, hidden,
            "hiding the cursor must change the frame"
        );

        // Hiding the cursor draws exactly what the mouse being off-screen does.
        shell.set_hide_cursor(false);
        shell.mouse = Mouse::default();
        let no_pointer = shell.draw().pixels().to_vec();
        assert_eq!(
            hidden, no_pointer,
            "a hidden cursor leaves no pointer behind"
        );
    }
}