1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
use crate::nes::{
action::{Debug, DebugInterrupt, DebugStep},
config::Config,
debug::{AddrLabel, LabelKey, Marks},
event::{ConfigEvent, DebugRequest, DebugWrite, EmulationEvent, NesEventProxy, UiEvent},
renderer::gui::{
MessageType,
lib::ViewportOptions,
palette::Palette,
panes::{self, Column, Pane as _},
},
};
use egui::{
CentralPanel, Color32, Context, Grid, Label, Panel, Rect, RichText, ScrollArea, Sense, Ui,
Vec2, ViewportId, text::CCursor,
};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
ops::Range,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
};
use tetanes_core::{
bus::Bus,
cpu::{Cpu, Disasm, IrqFlags, Status, instr::InstrRef},
debug::{
Access, AccessHit, Breakpoint as DeckBreakpoint, Breakpoints as DeckBreakpoints, CallFrame,
FrameKind, RunTo,
expr::{Expr, ParseError},
},
input::{
ExpansionDevice, FourPlayer, JoypadBtn, JoypadBtnState, Player, PortDevice, PowerPad,
Zapper,
},
mapper::MapperOps,
memory::{Memory, PRG_PAGES, Page},
};
use winit::event::ElementState;
/// A range of addresses the console stops at when one is accessed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[must_use]
pub struct Breakpoint {
/// Names this breakpoint for as long as it is listed.
///
/// An address does not, since several breakpoints can cover one - a range and a single
/// address, or two accesses of the same byte under different conditions. Handed out by
/// [`Breakpoints::add`], so one read back from a file is renumbered as it is listed.
#[serde(skip)]
pub id: u32,
/// First address covered.
pub addr: u16,
/// Last address covered, inclusive. Equal to `addr` for a single address.
pub end: u16,
/// Where `addr` sat in the cart arena when the breakpoint was set. See
/// [`DeckBreakpoint::offset`].
pub offset: Option<u32>,
/// Which accesses trip it.
pub access: Access,
/// Cleared to keep a breakpoint in the list without stopping at it.
pub enabled: bool,
/// Cleared to record the access in the list and let the console run on.
pub breaks: bool,
/// An expression that has to hold as well, as typed. Empty to trip on every access.
///
/// Kept as text rather than as a parsed [`Expr`], since the box holds whatever is being typed
/// and half an expression is not one yet.
pub condition: String,
}
impl Breakpoint {
/// A breakpoint on a single address, stopping before it executes.
///
/// `offset` pins it to the bank mapped at `addr` as the window draws it. The id is handed out
/// by [`Breakpoints::add`], so one built here carries a placeholder until it is listed.
pub const fn execute(addr: u16, offset: Option<u32>) -> Self {
Self {
id: 0,
addr,
end: addr,
offset,
access: Access::EXEC,
enabled: true,
breaks: true,
condition: String::new(),
}
}
/// A breakpoint over a range, stopping on any access to it.
///
/// A range is typed rather than clicked, which usually means data, so it watches reads and
/// writes as well as execution.
pub fn range(addr: u16, end: u16, offset: Option<u32>) -> Self {
Self {
end,
access: Access::all(),
..Self::execute(addr, offset)
}
}
/// Whether `addr` falls in this breakpoint's range.
///
/// Says nothing about the bank, which `is_mapped` answers.
pub const fn covers(&self, addr: u16) -> bool {
self.addr <= addr && addr <= self.end
}
/// The range as the list writes it, one address or two.
pub fn range_text(&self) -> String {
if self.addr == self.end {
format!("${:04X}", self.addr)
} else {
format!("${:04X}-${:04X}", self.addr, self.end)
}
}
/// The condition as parsed, or `None` when the box is empty.
pub fn condition(&self) -> Option<Result<Expr, ParseError>> {
let text = self.condition.trim();
(!text.is_empty()).then(|| Expr::parse(text))
}
/// What the console is told, which drops the parts only the list draws.
///
/// `None` for a condition that does not parse. Arming it without the condition would stop on
/// far more than was asked for, so the breakpoint stays listed and unarmed until the
/// expression is one.
fn armed(&self) -> Option<DeckBreakpoint> {
Some(DeckBreakpoint {
start: self.addr,
end: self.end,
offset: self.offset,
access: self.access,
breaks: self.breaks,
condition: self.condition().transpose().ok()?,
})
}
}
/// The Debugger's breakpoints, in address order so the list reads like the disassembly.
///
/// The console is only ever told the enabled addresses, since that is all it can act on. The
/// window draws the rest.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
#[must_use]
pub struct Breakpoints {
list: Vec<Breakpoint>,
/// The next id to hand out, which only ever counts up.
///
/// Reusing the id of a removed breakpoint would let a stale reference - the open editor, a
/// pending row action - land on whatever took its place.
next_id: u32,
}
impl Breakpoints {
/// Add `breakpoint`, naming it and reporting the id it was given.
///
/// Overlap is allowed: one address holds as many breakpoints as are set on it, since a range
/// and a single address, or two conditions on one byte, are different questions.
pub fn add(&mut self, mut breakpoint: Breakpoint) -> Option<u32> {
if self.list.len() >= DeckBreakpoints::MAX {
return None;
}
let id = self.next_id;
self.next_id += 1;
breakpoint.id = id;
let index = self
.list
.partition_point(|other| other.addr < breakpoint.addr);
self.list.insert(index, breakpoint);
Some(id)
}
/// Remove the breakpoint `id` names, reporting whether it was listed.
pub fn remove(&mut self, id: u32) -> bool {
let held = self.list.len();
self.list.retain(|breakpoint| breakpoint.id != id);
self.list.len() != held
}
/// Stop before the instruction at `addr` in the bank at `offset` executes, or clear the
/// breakpoint already on exactly that address.
///
/// A range covering `addr` is left alone. Removing a range by clicking one row inside it
/// would take away far more than the row the click landed on.
pub fn toggle(&mut self, addr: u16, offset: Option<u32>) {
match self.single_at(addr, offset) {
Some(id) => {
self.remove(id);
}
None => {
self.add(Breakpoint::execute(addr, offset));
}
}
}
/// The breakpoint set on exactly `addr` in the bank at `offset`, which is the one a gutter
/// click owns.
pub fn single_at(&self, addr: u16, offset: Option<u32>) -> Option<u32> {
self.list
.iter()
.find(|breakpoint| {
breakpoint.addr == addr && breakpoint.end == addr && breakpoint.offset == offset
})
.map(|breakpoint| breakpoint.id)
}
/// Every breakpoint covering `addr` as `pages` has it mapped, in list order.
///
/// A range covers every row in it, not only the one it starts on.
pub fn covering<'a>(
&'a self,
addr: u16,
pages: &'a [Page; PRG_PAGES],
) -> impl Iterator<Item = &'a Breakpoint> {
self.list
.iter()
.filter(move |breakpoint| breakpoint.covers(addr) && is_mapped(pages, breakpoint))
}
/// Whether another breakpoint would be refused.
pub const fn is_full(&self) -> bool {
self.list.len() >= DeckBreakpoints::MAX
}
/// The breakpoint `id` names, whether or not it is enabled.
pub fn get(&self, id: u32) -> Option<&Breakpoint> {
self.list.iter().find(|breakpoint| breakpoint.id == id)
}
/// The breakpoint `id` names, to edit in place.
pub fn get_mut(&mut self, id: u32) -> Option<&mut Breakpoint> {
self.list.iter_mut().find(|breakpoint| breakpoint.id == id)
}
/// What the console is to act on, which is the enabled ones with an access selected.
pub fn armed(&self) -> Vec<DeckBreakpoint> {
self.list
.iter()
.filter(|breakpoint| breakpoint.enabled && !breakpoint.access.is_empty())
.filter_map(Breakpoint::armed)
.collect()
}
/// The breakpoints in address order, for the window to edit in place.
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut Breakpoint> {
self.list.iter_mut()
}
/// Every breakpoint listed, in address order.
pub fn iter(&self) -> impl Iterator<Item = &Breakpoint> {
self.list.iter()
}
/// Put the list back in address order, so it reads like the disassembly again.
///
/// [`Breakpoints::add`] inserts in order, which an edit to a breakpoint's address moves out
/// from under. Stable, so breakpoints sharing an address keep the order they were added in.
pub fn sort(&mut self) {
self.list.sort_by_key(|breakpoint| breakpoint.addr);
}
/// Drop the breakpoints pinned to a cart, keeping the ones any cart shares.
pub fn retain_without_cart(&mut self) {
self.list.retain(|breakpoint| breakpoint.offset.is_none());
}
/// Whether no breakpoint is listed, enabled or not.
pub const fn is_empty(&self) -> bool {
self.list.is_empty()
}
}
/// A range of the address space shown collapsed and not disassembled.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[must_use]
pub enum BlockKind {
/// Work RAM. Code can run from it, but nothing yet says which bytes are code.
Ram,
/// PPU, APU and IO registers.
Registers,
/// Cart RAM, usually save data.
SaveRam,
/// No cart window is mapped here.
Unmapped,
/// Cart ROM that nothing has shown to be instructions.
Unknown,
}
impl BlockKind {
/// The rendered label for an address block.
pub const fn label(self) -> &'static str {
match self {
Self::Ram => "work ram",
Self::Registers => "registers",
Self::SaveRam => "save ram",
Self::Unmapped => "unmapped",
Self::Unknown => "unknown",
}
}
}
/// A line of the address space view.
#[derive(Debug, Clone)]
#[must_use]
pub enum Row {
/// A disassembled instruction.
Instruction(Disasm),
/// A collapsed range, inclusive of both ends.
Block {
start: u16,
end: u16,
kind: BlockKind,
},
/// The name given to the address the next row starts at, on a line of its own above it.
Label { addr: u16, name: String },
}
impl Row {
/// The address this row starts at.
pub const fn addr(&self) -> u16 {
match self {
Self::Instruction(disasm) => disasm.addr,
Self::Block { start, .. } | Self::Label { addr: start, .. } => *start,
}
}
/// Whether `addr` falls in this row, which for a block is anywhere in its range.
/// A label covers nothing: it sits above the row that owns its address, so PC and the
/// selection mark that row rather than the name over it.
pub const fn covers(&self, addr: u16) -> bool {
match self {
Self::Instruction(disasm) => disasm.addr == addr,
Self::Block { start, end, .. } => *start <= addr && addr <= *end,
Self::Label { .. } => false,
}
}
}
/// Snapshot of the Control Deck CPU state for use by the Debugger.
#[derive(Debug, Clone)]
#[must_use]
pub struct CpuSnapshot {
/// CPU state and registers.
pub cpu: Cpu,
/// CPU stack.
pub stack: Vec<u8>,
/// The calls execution is inside, outermost first, from [`DebugRequest::call_stack`].
pub call_stack: Vec<CallFrame>,
/// Previously executed instructions, oldest first, ending just before PC from
/// [`DebugRequest::history_lines`].
pub history: Vec<Disasm>,
/// The range requested from [`DebugRequest::memory`], if any.
pub memory: Vec<u8>,
/// The address [`CpuSnapshot::memory`] starts at, so its bytes line up with the rows however
/// far behind the window the snapshot is.
pub memory_start: u16,
/// Accesses that breakpoints recorded without stopping, oldest first.
pub access_log: Vec<AccessHit>,
/// What the Watches pane's expressions came to, in the order it listed them.
///
/// `None` where the row holds something that does not parse, so the values line up with the
/// rows whatever is half-written.
pub watches: Vec<Option<i32>>,
/// The PRG page table, which resolves an address to the cart byte currently mapped there.
///
/// Sent every frame while running and after every step, so a breakpoint is pinned to the bank
/// the window was drawing when it was set, and a row draws the mark only while that bank is
/// still in.
pub prg_pages: [Page; PRG_PAGES],
/// The frame the console is on, which scales the cycle count into something readable.
pub frame: u32,
/// What each interrupt line is doing.
pub interrupts: Interrupts,
/// The buttons held on each controller port.
pub joypads: [JoypadBtnState; 4],
/// Which four-player adapter is plugged in, which decides whether ports 3 and 4 exist.
pub four_player: FourPlayer,
/// What is plugged into ports 1 and 2.
pub ports: [PortDevice; 2],
/// What is plugged into the Famicom expansion port.
pub expansion: ExpansionDevice,
/// The Power Pad mat, which a port or the Family Trainer reads.
pub power_pad: PowerPad,
/// The Zapper's aim and trigger.
pub zapper: Zapper,
/// Whether the Zapper is aimed at a bright pixel, from [`Zapper::aims_at_light`].
pub zapper_light: bool,
}
/// The pending interrupts and the sources that drive them, as of a [`CpuSnapshot`].
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
#[must_use]
pub struct Interrupts {
/// The CPU has seen the NMI edge and will take the NMI after the current instruction.
pub nmi_latched: bool,
/// `$2000` bit 7, without which vblank asserts no NMI.
pub nmi_enabled: bool,
/// The APU frame counter is asserting IRQ.
pub frame_irq: bool,
/// The DMC is asserting IRQ.
pub dmc_irq: bool,
/// The cartridge board is asserting IRQ.
pub mapper_irq: bool,
/// The cartridge board has an IRQ at all.
pub mapper_has_irq: bool,
}
impl Interrupts {
/// Read the interrupt state off `bus` without moving anything.
pub fn capture(bus: &Bus) -> Self {
Self {
nmi_latched: bus.cpu.irq_flags.contains(IrqFlags::NMI),
nmi_enabled: bus.ppu.ctrl_nmi_enabled,
frame_irq: bus.apu.frame_counter.irq_pending,
dmc_irq: bus.apu.dmc.irq_pending,
mapper_irq: bus.mapper.irq_pending(),
mapper_has_irq: bus.mapper_ops.contains(MapperOps::IRQ),
}
}
/// Whether any source is asserting IRQ, whether or not the I flag lets it through.
#[must_use]
pub const fn irq_line(&self) -> bool {
self.frame_irq | self.dmc_irq | self.mapper_irq
}
}
impl Default for CpuSnapshot {
fn default() -> Self {
Self {
cpu: Cpu::default(),
stack: Vec::new(),
call_stack: Vec::new(),
history: Vec::new(),
memory: Vec::new(),
memory_start: 0,
access_log: Vec::new(),
watches: Vec::new(),
prg_pages: [Page::UNMAPPED; PRG_PAGES],
frame: 0,
interrupts: Interrupts::default(),
joypads: [JoypadBtnState::empty(); 4],
four_player: FourPlayer::default(),
ports: [PortDevice::default(); 2],
expansion: ExpansionDevice::default(),
power_pad: PowerPad::new(),
zapper: Zapper::default(),
zapper_light: false,
}
}
}
impl CpuSnapshot {
/// Capture the requested snapshot.
pub fn capture(bus: &Bus, request: &DebugRequest) -> Self {
// Disassembled from memory as it is banked *now*, not as it was when these ran, so a line
// whose bank has since been swapped shows what currently lives at that address. The
// code map does not help here - it says which bytes are code, not which bank an address
// was mapped to at the time. Recording the bytes alongside the address would.
let history = bus.pc_history.as_ref().map_or_else(Vec::new, |history| {
let skip = history
.len()
.saturating_sub(usize::from(request.history_lines));
history
.iter()
.skip(skip)
.map(|addr| {
let mut pc = addr;
bus.disassemble(&mut pc)
})
.collect()
});
Self {
cpu: bus.cpu.clone(),
stack: if request.stack {
(0..0x0100u16)
.map(|offset| bus.peek(Cpu::SP_BASE + offset))
.collect()
} else {
Vec::new()
},
call_stack: match (request.call_stack, &bus.call_stack) {
(true, Some(call_stack)) => call_stack.frames().to_vec(),
_ => Vec::new(),
},
history,
memory: request.memory.map_or_else(Vec::new, |(start, len)| {
(0..len).map(|i| bus.peek(start.wrapping_add(i))).collect()
}),
memory_start: request.memory.map_or(0, |(start, _)| start),
// Filled by the caller, which owns the console the log is drained from.
access_log: Vec::new(),
// Filled by the caller, which owns the expressions the window asked for.
watches: Vec::new(),
prg_pages: *bus.memory.prg_pages(),
frame: bus.ppu.frame_number(),
interrupts: Interrupts::capture(bus),
joypads: bus.input.joypads.map(|joypad| joypad.buttons),
four_player: bus.input.four_player,
ports: bus.input.ports,
expansion: bus.input.expansion,
power_pad: bus.input.power_pad,
zapper: bus.input.zapper,
zapper_light: bus.input.zapper.aims_at_light(&bus.ppu),
}
}
}
/// The CPU address space as rows.
///
/// Rebuilt when the board's PRG mapping changes, since that is the only thing that can move an
/// instruction, and when the [`CodeMap`](tetanes_core::debug::CodeMap) marks something new, since
/// that determines whether an address is an instruction. The rows represent the currently mapped
/// banks, not where PC happens to be.
#[derive(Debug, Default, Clone)]
#[must_use]
pub struct AddressSpace {
pub rows: Vec<Row>,
}
impl AddressSpace {
/// Capture the current address space into rows.
///
/// Only mapped cart ROM is disassembled, and only where the
/// [`CodeMap`](tetanes_core::debug::CodeMap) marks instructions or where straight-line flow
/// from PC reaches. Everything else is a collapsed block.
pub fn capture(bus: &Bus, labels: &HashMap<LabelKey, AddrLabel>) -> Self {
let mut rows = Vec::new();
let mut disasm = Disasm::default();
let mut addr = 0u32;
let pc = bus.cpu.pc;
// Set while decoding forward from PC. The map contains only what has executed, so a
// debugger that has just attached knows nothing about the routine PC is sitting in.
let mut following = false;
while addr <= u32::from(u16::MAX) {
let start = addr as u16;
// Ahead of the row that owns the address, so the name reads as a heading over it the
// way an assembler listing writes one. A row with only a comment gets no line here,
// since the comment is drawn on the instruction itself.
//
// A board that mirrors one bank into two windows shows the name at both, which is
// what filing it by cart offset means: those addresses are the same bytes.
let key = LabelKey::new(start, prg_offset(bus.memory.prg_pages(), start));
if let Some(name) = labels.get(&key).map(|label| label.name.trim())
&& !name.is_empty()
{
rows.push(Row::Label {
addr: start,
name: name.to_string(),
});
}
let next = match Self::block_kind(bus, start) {
Some(kind) => {
following = false;
let mut end = start;
while end < u16::MAX && Self::block_kind(bus, end + 1) == Some(kind) {
end += 1;
}
rows.push(Row::Block { start, end, kind });
u32::from(end) + 1
}
None if following || Self::starts_instruction(bus, start, pc) => {
if start == pc {
following = true;
}
if following {
following = Cpu::INSTR_REF[usize::from(bus.peek(start))]
.instr
.falls_through();
}
let mut next = start;
bus.disassemble_into(&mut next, &mut disasm);
// Taken from the addressing mode rather than from where the decode landed,
// which wraps past $FFFF.
let len = disasm.len();
let end = start.wrapping_add(len - 1);
// PC is known to start an instruction, so a decode that overlaps it does not
// align with real instruction boundaries inside an instruction that has run
// (e.g. stepping into a jump computed at runtime). Skip decoding those bytes
// and resume there. Ensures the PC keeps a row of its own for the Debugger to
// highlight.
//
// Strictly after `start`, not from it: a decode that *begins* at PC is the
// aligned case. Including it would end the row where it started and resume at
// the same address, decoding forever.
if pc > start && pc <= end {
rows.push(Row::Block {
start,
end: pc - 1,
kind: BlockKind::Unknown,
});
u32::from(pc)
} else {
rows.push(Row::Instruction(disasm.clone()));
addr + u32::from(len)
}
}
// Mapped ROM that nothing has shown to be an instruction - the operands of the
// instruction above, a jump table, graphics, or code that has yet to run.
None => {
following = false;
let mut end = start;
while end < u16::MAX
&& Self::block_kind(bus, end + 1).is_none()
&& !Self::starts_instruction(bus, end + 1, pc)
{
end += 1;
}
rows.push(Row::Block {
start,
end,
kind: BlockKind::Unknown,
});
u32::from(end) + 1
}
};
// Every branch should progress by at least one address otherwise it'll spin forever.
debug_assert!(next > addr, "sweep made no progress at ${start:04X}");
addr = next.max(addr + 1);
}
Self { rows }
}
/// Whether `addr` collapses into a block. `None` means cart memory, which
/// [`AddressSpace::starts_instruction`] then decides how to render.
fn block_kind(bus: &Bus, addr: u16) -> Option<BlockKind> {
match addr {
0x0000..=0x1FFF => Some(BlockKind::Ram),
0x2000..=0x401F => Some(BlockKind::Registers),
_ => match bus.memory.prg_offset(addr) {
Some(_) if addr >= 0x8000 => None,
// Cart RAM, which some boards run code out of. It reads as save data until the
// code map has seen something execute there.
Some(offset) => {
let executed = bus
.code_map
.as_ref()
.is_some_and(|code_map| code_map.is_code(offset));
if executed {
None
} else {
Some(BlockKind::SaveRam)
}
}
None => Some(BlockKind::Unmapped),
},
}
}
/// Whether the capture sweep should start decoding at `addr`.
///
/// Execution is the only thing that says where an instruction begins, so this checks the
/// [`CodeMap`](tetanes_core::debug::CodeMap). PC counts as well - it is about to run, so it
/// starts an instruction whether or not it has yet, and it is the row the view highlights.
fn starts_instruction(bus: &Bus, addr: u16, pc: u16) -> bool {
addr == pc
|| match &bus.code_map {
// With nothing recorded there is no way to tell code from data, so everything
// mapped is decoded and the capture sweep drifts out of step wherever data
// resides.
None => true,
Some(code_map) => bus
.memory
.prg_offset(addr)
.is_some_and(|offset| code_map.is_code(offset)),
}
}
/// The row holding `addr`, or the one just before it when `addr` is mid-instruction.
pub fn row_at(&self, addr: u16) -> Option<usize> {
self.rows
.partition_point(|row| row.addr() <= addr)
.checked_sub(1)
}
}
/// A view in the debugger window.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[must_use]
pub enum Pane {
/// The address space as rows, which is the pane the window is built around.
Disassembly,
/// The CPU registers and status flags.
Registers,
/// The stack page, top of stack first.
Stack,
/// The calls execution is inside, innermost first.
CallStack,
/// The breakpoint list, and the box that adds one.
Breakpoints,
/// The instructions that ran most recently.
History,
/// Expressions and what they come to on the console as it stands.
Watches,
/// The CPU address space as hex bytes, where RAM can be typed over.
Memory,
/// The buttons held on each controller, which a click presses or releases.
Input,
}
impl Pane {
/// The id the window's panes and columns are keyed by, which keeps them apart from another
/// window's.
const WINDOW: &'static str = "debugger";
/// The panes a window opens with.
///
/// Everything but the history, the memory and the input. The history answers what has run,
/// where the call stack answers how execution got here, and it takes a ring buffer plus the
/// bottom of the window to do it. The memory pane takes the same bottom and a copy of the
/// console's bytes each frame. The input pane is for pressing buttons while stepping, which few
/// sessions do. All three wait for the View menu to ask.
pub const DEFAULT: [Self; 6] = [
Self::Disassembly,
Self::Registers,
Self::Stack,
Self::CallStack,
Self::Watches,
Self::Breakpoints,
];
}
impl panes::Pane for Pane {
const ALL: &'static [Self] = &[
Self::Disassembly,
Self::Registers,
Self::Stack,
Self::CallStack,
Self::Watches,
Self::Breakpoints,
Self::History,
Self::Memory,
Self::Input,
];
fn title(self) -> &'static str {
match self {
Self::Disassembly => "Disassembly",
Self::Registers => "Registers",
Self::Stack => "Stack",
Self::CallStack => "Call stack",
Self::Breakpoints => "Breakpoints",
Self::History => "Recently executed",
Self::Watches => "Watches",
Self::Memory => "Memory",
Self::Input => "Input",
}
}
fn column(self) -> Column {
match self {
Self::Disassembly => Column::Center,
Self::Registers
| Self::Stack
| Self::CallStack
| Self::Watches
| Self::Breakpoints
| Self::Input => Column::Right,
// A hex row is sixteen bytes plus their text, which is wider than the right column
// and about what the bottom one spans.
Self::History | Self::Memory => Column::Bottom,
}
}
fn default_size(self) -> f32 {
match self {
Self::Disassembly => 0.0,
Self::Registers => 116.0,
Self::Stack => 160.0,
Self::CallStack => 120.0,
Self::Breakpoints => 160.0,
Self::History => 140.0,
Self::Watches => 120.0,
Self::Memory => 180.0,
// Four controller rows with a four-player adapter, so the pane only scrolls when
// dragged shorter.
Self::Input => 132.0,
}
}
fn id(self) -> &'static str {
match self {
Self::Disassembly => "pane_disassembly",
Self::Registers => "pane_registers",
Self::Stack => "pane_stack",
Self::CallStack => "pane_call_stack",
Self::Breakpoints => "pane_breakpoints",
Self::History => "pane_history",
Self::Watches => "pane_watches",
Self::Memory => "pane_memory",
Self::Input => "pane_input",
}
}
}
/// What a click on a disassembly row asked for.
///
/// Reported rather than applied, since the row draws from state it borrows.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[must_use]
enum RowAction {
/// Add a breakpoint on this address in the bank at this arena offset, or remove the one
/// already on exactly it.
ToggleBreakpoint(u16, Option<u32>),
/// Remove the breakpoint this id names.
RemoveBreakpoint(u32),
/// Arm or disarm the breakpoint this id names, keeping it listed either way.
ArmBreakpoint(u32, bool),
/// Make this the row later commands act on.
Select(u16),
/// Open the label editor on this address, filed under this key.
EditLabel(LabelKey, u16),
/// Center the disassembly on this address and select it.
GoTo(u16),
/// Show this address in the memory pane, opening it if it is closed.
ViewInMemory(u16),
/// Watch the byte at this address, opening the watch pane if it is closed.
AddWatch(u16),
/// Start the console running from this address.
MovePc(u16),
/// Resume until execution reaches this address.
RunTo(u16),
}
#[derive(Debug)]
#[must_use]
struct State {
tx: NesEventProxy,
snapshot: CpuSnapshot,
address_space: AddressSpace,
/// Address to center in the disassembly, cleared once its row has been drawn and centered.
scroll_to: Option<u16>,
/// Rows the last draw put on screen. A center request for a row outside them needs a coarse
/// jump first.
visible_rows: Range<usize>,
goto: String,
/// The row later commands act on, by address rather than row index so it survives a capture
/// that moves the rows under it.
selected: Option<u16>,
/// What recording breakpoints have caught, oldest first, capped so a hot address cannot grow
/// it without limit.
access_log: Vec<AccessHit>,
breakpoints: Breakpoints,
/// What is typed in the breakpoint box, which is not a breakpoint until it is added.
breakpoint_goto: String,
/// What the addresses of this ROM have been named and annotated.
///
/// Kept beside the breakpoints because the ROM's session file holds the two together.
labels: HashMap<LabelKey, AddrLabel>,
/// The watched expressions as typed, in the order the pane lists them.
watches: Vec<String>,
/// What is typed in the watch box, which is not a watch until it is added.
watch_entry: String,
/// Which breakpoint the editor window is open on, by [`Breakpoint::id`].
///
/// An id rather than an index, so removing another breakpoint while the editor is open cannot
/// slide it onto a different one.
editing: Option<u32>,
/// What the editor's address box holds, which is not the breakpoint's range until it parses.
editing_range: String,
/// Which address the label editor is open on, and where the window is drawing it.
///
/// The address travels with the key so the editor can name what it is editing, which a cart
/// offset on its own does not say.
editing_label: Option<(LabelKey, u16)>,
/// The register whose cell is open as a box, and what has been typed into it.
///
/// One at a time, so clicking a second cell closes the first without writing it.
register_edit: Option<(Register, String)>,
/// What is typed in the memory pane's address box, which moves the view once it parses.
memory_goto: String,
/// The address to center the memory pane on, cleared once its row has been drawn.
memory_scroll_to: Option<u16>,
/// The `(start, len)` the console is asked to copy for the memory pane, as
/// [`memory_window()`] works it out.
memory_window: Option<(u16, u16)>,
/// The byte the memory pane has selected, and the hex digits typed onto it so far.
memory_edit: Option<(u16, String)>,
/// Rows the last draw of the memory pane put on screen. The window it asks the console for
/// covers these, and a selection has to leave them before the view follows it.
memory_rows: Range<usize>,
history_lines: u16,
/// The panes that are open, in [`Pane::ALL`] order.
panes: Vec<Pane>,
}
/// Width of the breakpoint column left of the disassembly. Wide enough to click at, where one
/// character of the monospace font is not.
const GUTTER_WIDTH: f32 = 16.0;
/// Parse an address as typed into one of the window's address boxes.
///
/// Bare hex, or prefixed with the assembler's `$` or the C-style `0x`, since both turn up in
/// documentation the address is likely to be copied out of.
fn parse_addr(text: &str) -> Option<u16> {
let text = text.trim();
let digits = text
.strip_prefix('$')
.or_else(|| text.strip_prefix("0x"))
.or_else(|| text.strip_prefix("0X"))
.unwrap_or(text);
u16::from_str_radix(digits, 16).ok()
}
/// Parse an address range as typed into the breakpoint box: one address, or `$lo-$hi`.
///
/// Reversed ends are put back in order rather than refused, since a range typed backwards says
/// plainly enough what was meant.
fn parse_range(text: &str) -> Option<(u16, u16)> {
match text.trim().split_once('-') {
Some((start, end)) => {
let (start, end) = (parse_addr(start)?, parse_addr(end)?);
Some((start.min(end), start.max(end)))
}
None => {
let addr = parse_addr(text)?;
Some((addr, addr))
}
}
}
/// The expression grammar, laid out in real columns.
///
/// A grid rather than one preformatted block, since the monospace font is a pixel font whose
/// advance widths round differently at scaled sizes, and columns padded with spaces drift.
fn syntax_help(ui: &mut Ui) {
Grid::new("expression_syntax")
.num_columns(2)
.spacing([12.0, 2.0])
.show(ui, |ui| {
for (name, detail) in Expr::SYNTAX {
ui.label(*name);
ui.monospace(*detail);
ui.end_row();
}
});
ui.label(Expr::SYNTAX_NOTE);
}
/// A watched expression's value.
///
/// A comparison reads as true or false. Anything else names a number, at the width the value
/// asks for: a byte reads as two digits and an address as four, so a column of bytes does not
/// pretend to be addresses.
fn watch_value(value: i32, boolean: bool) -> String {
if boolean {
return if value == 0 { "false" } else { "true" }.to_string();
}
match u16::try_from(value) {
Ok(value) if value <= 0xFF => format!("${value:02X} {value}"),
Ok(value) => format!("${value:04X} {value}"),
Err(_) => value.to_string(),
}
}
/// The three access letters a breakpoint watches, as the list and the hover write them.
fn access_text(access: Access) -> String {
[
(Access::EXEC, 'X'),
(Access::READ, 'R'),
(Access::WRITE, 'W'),
]
.into_iter()
.filter(|(flag, _)| access.contains(*flag))
.map(|(_, letter)| letter)
.collect()
}
/// What the gutter draws for the breakpoints covering a row.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum GutterMark {
/// One breakpoint, drawn in the color of the access it watches.
One { access: Access, enabled: bool },
/// Several, drawn as a cross so a single click is never a surprise.
Several { access: Access, enabled: bool },
}
impl GutterMark {
/// What to draw for `covering`, or `None` where nothing covers the row.
fn of(covering: &[&Breakpoint]) -> Option<Self> {
let (first, rest) = covering.split_first()?;
// The strongest access any of them watches, since one mark cannot show three. Execution
// is the strongest: it says the row itself runs, where a read or a write says only that
// something reaches the byte.
let access = covering.iter().fold(Access::empty(), |access, breakpoint| {
access | breakpoint.access
});
let enabled = covering.iter().any(|breakpoint| breakpoint.enabled);
Some(if rest.is_empty() {
Self::One {
access: first.access,
enabled,
}
} else {
Self::Several { access, enabled }
})
}
/// The color the strongest access is drawn in.
const fn color(access: Access, enabled: bool, palette: &Palette) -> Color32 {
if !enabled {
return palette.breakpoint_disabled;
}
if access.contains(Access::EXEC) {
palette.breakpoint_exec
} else if access.contains(Access::WRITE) {
palette.breakpoint_write
} else {
palette.breakpoint_read
}
}
/// Paint into `gutter`, filled for armed and hollow for listed.
fn paint(self, painter: &egui::Painter, gutter: Rect, palette: &Palette) {
let center = gutter.center();
let radius = GUTTER_WIDTH / 4.0;
match self {
Self::One { access, enabled } => {
let color = Self::color(access, enabled, palette);
if enabled {
painter.circle_filled(center, radius, color);
} else {
painter.circle_stroke(center, radius, egui::Stroke::new(1.5, color));
}
}
Self::Several { access, enabled } => {
let color = Self::color(access, enabled, palette);
let stroke = egui::Stroke::new(1.5, color);
painter.line_segment(
[
center - Vec2::new(radius, 0.0),
center + Vec2::new(radius, 0.0),
],
stroke,
);
painter.line_segment(
[
center - Vec2::new(0.0, radius),
center + Vec2::new(0.0, radius),
],
stroke,
);
}
}
}
}
/// What the mnemonic stands for, what it does, and how the console runs it.
fn instruction_tooltip(ui: &mut Ui, instr: &InstrRef) {
ui.strong(format!("{instr} - {}", instr.instr.name()));
ui.label(instr.instr.describe());
let affects = instr.instr.affects();
detail_rows(
ui,
"instruction",
&[
("Opcode", format!("${:02X}", instr.opcode)),
("Mode", instr.mode_name().to_string()),
("Cycles", instr.cycles.to_string()),
(
"Flags",
if affects.is_empty() {
"none".to_string()
} else {
FLAGS
.iter()
.filter(|(flag, _)| affects.contains(*flag))
.map(|(_, name)| *name)
.collect::<Vec<_>>()
.join(" ")
},
),
],
);
}
/// The status flags in the order the register prints them.
const FLAGS: [(Status, &str); 8] = [
(Status::N, "N"),
(Status::V, "V"),
(Status::U, "U"),
(Status::B, "B"),
(Status::D, "D"),
(Status::I, "I"),
(Status::Z, "Z"),
(Status::C, "C"),
];
/// A byte's value in the three bases worth reading it in.
fn byte_rows(value: u8) -> Vec<(&'static str, String)> {
vec![
("Hex", format!("${value:02X}")),
("Decimal", value.to_string()),
("Binary", format!("%{value:08b}")),
]
}
/// Lay a hover out as one label and value per line, so several readings of the same thing can be
/// compared down the column rather than picked out of a sentence.
fn detail_rows(ui: &mut Ui, id: &str, rows: &[(&str, String)]) {
Grid::new(("hover", id))
.num_columns(2)
.spacing([12.0, 2.0])
.show(ui, |ui| {
for (label, value) in rows {
ui.label(*label);
ui.monospace(value);
ui.end_row();
}
});
}
/// A register cell, where the name and the value both hover with `rows`.
/// How a register's value is written, in the box and out of it.
fn register_text(value: u16, digits: usize) -> String {
format!("{value:0digits$X}")
}
/// A CPU register the Registers pane draws, and writes when one is typed over.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[must_use]
enum Register {
/// The program counter.
Pc,
/// The accumulator.
Acc,
/// The X index register.
X,
/// The Y index register.
Y,
/// The stack pointer.
Sp,
}
impl Register {
/// The name the cell is labeled with.
const fn name(self) -> &'static str {
match self {
Self::Pc => "PC",
Self::Acc => "A",
Self::X => "X",
Self::Y => "Y",
Self::Sp => "SP",
}
}
/// What the cell's hover says the register is.
const fn heading(self) -> &'static str {
match self {
Self::Pc => "Program counter - the instruction about to run",
Self::Acc => "Accumulator",
Self::X => "Index register X",
Self::Y => "Index register Y",
Self::Sp => "Stack pointer",
}
}
/// How many hex digits the register is written in.
const fn digits(self) -> usize {
match self {
Self::Pc => 4,
Self::Acc | Self::X | Self::Y | Self::Sp => 2,
}
}
/// The write that sets the register to `val`. Only PC has a high byte to take.
const fn write(self, val: u16) -> DebugWrite {
match self {
Self::Pc => DebugWrite::Pc(val),
Self::Acc => DebugWrite::Acc(val as u8),
Self::X => DebugWrite::X(val as u8),
Self::Y => DebugWrite::Y(val as u8),
Self::Sp => DebugWrite::Sp(val as u8),
}
}
}
/// A register cell, where the name and the value both hover with `rows`.
///
/// Clicking the value opens a box with what the register reads now, so it can be edited in
/// place, and Enter writes what parses. `edit` names the one register being typed, so opening a
/// second cell closes the first without committing it.
fn register_cell(
ui: &mut Ui,
register: Register,
value: u16,
rows: &[(&str, String)],
edit: &mut Option<(Register, String)>,
) -> Option<DebugWrite> {
let name = register.name();
let digits = register.digits();
let hover = |ui: &mut Ui| {
ui.strong(register.heading());
detail_rows(ui, name, rows);
};
ui.strong(name).on_hover_ui(hover);
match edit {
Some((editing, text)) if *editing == register => {
let response = ui.add(
egui::TextEdit::singleline(text)
.font(egui::TextStyle::Monospace)
// Room for the digits plus the longest sigil `parse_addr` takes.
.char_limit(digits + 2)
// No taller than the label it stands in for. A row that grows on the click
// pushes the grid past the pane and scrolls the top of it off.
.margin(egui::Margin::symmetric(2, 0))
.desired_width(60.0),
);
// Focused on the frame the box opens, and never again, so clicking away can take it.
if !response.has_focus() && !response.lost_focus() {
response.request_focus();
}
if !submitted(ui, &response) {
// Focus lost to anything but Enter drops what was typed, the way Escape does.
if response.lost_focus() {
*edit = None;
}
return None;
}
let written = parse_addr(text).map(|val| register.write(val));
*edit = None;
written
}
_ => {
let text = format!("${}", register_text(value, digits));
if ui
.add(egui::Label::new(RichText::new(text).monospace()).sense(Sense::click()))
.on_hover_ui(hover)
.on_hover_text("Click to write it")
.clicked()
{
*edit = Some((register, register_text(value, digits)));
}
None
}
}
}
/// Where `addr` sits in the cart arena under `pages`, the mapping the window is drawing.
fn prg_offset(pages: &[Page; PRG_PAGES], addr: u16) -> Option<u32> {
Memory::offset_in(pages, addr).map(|offset| offset as u32)
}
/// The `(start, len)` the console is asked to copy to cover `rows` of the memory pane.
///
/// Widened by [`State::MEMORY_MARGIN`] and rounded out to whole pages, so a scroll of a row or two
/// reuses the bytes already in hand rather than asking again. Clamped to the address space at
/// both ends, since a length of 64K has no `u16` to say it in.
fn memory_window(rows: &Range<usize>) -> (u16, u16) {
let start = (rows.start * State::MEMORY_ROW_BYTES).saturating_sub(State::MEMORY_MARGIN) & !0xFF;
let end = (rows.end * State::MEMORY_ROW_BYTES + State::MEMORY_MARGIN)
.next_multiple_of(0x100)
.min(0x1_0000);
(start as u16, (end - start).min(0xFF00) as u16)
}
/// Whether a byte at `addr` can be typed over, under `pages`, the mapping the window is drawing.
///
/// The rule [`Bus::poke`] applies, resolved from the page table the window has rather than the one
/// the console has moved on to, so a cell greys out rather than taking a write that is refused.
const fn is_writable(pages: &[Page; PRG_PAGES], addr: u16) -> bool {
match addr {
0x0000..=0x1FFF => true,
0x4100..=0xFFFF => Memory::writable_in(pages, addr),
_ => false,
}
}
/// Whether the row starting at `base` covers `addr`.
///
/// Measured as a distance rather than as a range, since the last row starts at `$FFF0` and a range
/// to one past its end is empty.
const fn memory_row_holds(base: u16, addr: u16) -> bool {
(addr.wrapping_sub(base) as usize) < State::MEMORY_ROW_BYTES
}
/// The address a formatted operand names, and the span of text writing it.
///
/// Only a four digit address counts. A zero page operand is two digits, and taking those would
/// put a name over `$10` in every row that touches zero page.
fn operand_address(operand: &str) -> Option<(Range<usize>, u16)> {
let start = operand.find('$')?;
let digits = operand.get(start + 1..start + 5)?;
if !digits.chars().all(|digit| digit.is_ascii_hexdigit()) {
return None;
}
let addr = u16::from_str_radix(digits, 16).ok()?;
Some((start..start + 5, addr))
}
/// Whether the bytes `breakpoint` was set over are still mapped where it was set.
///
/// A breakpoint keyed by address alone is always in place, since no bank switch moves work RAM or
/// the registers.
fn is_mapped(pages: &[Page; PRG_PAGES], breakpoint: &Breakpoint) -> bool {
breakpoint.offset.is_none() || breakpoint.offset == prg_offset(pages, breakpoint.addr)
}
/// Whether the box that was just drawn was submitted with Enter.
fn submitted(ui: &Ui, response: &egui::Response) -> bool {
response.lost_focus() && ui.input(|input| input.key_pressed(egui::Key::Enter))
}
/// Whether the row covering `addr` falls inside `visible`, the rows the last draw put on screen.
///
/// False for an empty `visible`, so a window that has yet to draw centers on its first snapshot.
fn row_is_visible(address_space: &AddressSpace, visible: &Range<usize>, addr: u16) -> bool {
address_space
.row_at(addr)
.is_some_and(|row| visible.contains(&row))
}
/// What the console is asked to capture, folded over the panes in `open`.
///
/// A closed pane draws nothing, so what feeds it is not captured either.
fn request(open: &[Pane], history_lines: u16, memory: Option<(u16, u16)>) -> DebugRequest {
DebugRequest {
history_lines: if open.contains(&Pane::History) {
history_lines
} else {
0
},
stack: open.contains(&Pane::Stack),
call_stack: open.contains(&Pane::CallStack),
memory: open.contains(&Pane::Memory).then_some(memory).flatten(),
}
}
#[derive(Debug)]
#[must_use]
pub struct CpuDebugger {
pub id: ViewportId,
open: Arc<AtomicBool>,
state: Arc<Mutex<State>>,
}
impl CpuDebugger {
const TITLE: &'static str = "TetaNES - Debugger";
/// Enough context to see how the current instruction was reached without pushing it off-screen.
const HISTORY_LINES: u16 = 8;
/// Create a debugger with `panes` open, as saved in config by the last run.
pub fn new(tx: NesEventProxy, panes: &[Pane]) -> Self {
let panes = Pane::ALL
.iter()
.copied()
.filter(|pane| panes.contains(pane))
.collect::<Vec<_>>();
Self {
id: ViewportId::from_hash_of(Self::TITLE),
open: Arc::new(AtomicBool::new(false)),
state: Arc::new(Mutex::new(State {
tx,
snapshot: CpuSnapshot::default(),
address_space: AddressSpace::default(),
scroll_to: Some(0),
visible_rows: 0..0,
goto: String::new(),
selected: None,
access_log: Vec::new(),
breakpoints: Breakpoints::default(),
breakpoint_goto: String::new(),
labels: HashMap::new(),
watches: Vec::new(),
watch_entry: String::new(),
editing: None,
editing_range: String::new(),
editing_label: None,
register_edit: None,
memory_goto: String::new(),
memory_scroll_to: None,
memory_window: None,
memory_edit: None,
memory_rows: 0..0,
history_lines: Self::HISTORY_LINES,
panes,
})),
}
}
pub const fn id(&self) -> ViewportId {
self.id
}
pub fn open(&self) -> bool {
self.open.load(Ordering::Acquire)
}
pub fn set_open(&self, open: bool, ctx: &Context) {
self.open.store(open, Ordering::Release);
self.state.lock().subscribe(open);
if !open {
ctx.send_viewport_cmd_to(self.id, egui::ViewportCommand::Close);
}
}
pub fn toggle_open(&self, ctx: &Context) {
let Ok(was_open) = self
.open
.try_update(Ordering::Release, Ordering::Acquire, |open| Some(!open))
else {
return;
};
self.state.lock().subscribe(!was_open);
if was_open {
ctx.send_viewport_cmd_to(self.id, egui::ViewportCommand::Close);
}
}
/// Take a new CPU snapshot, centering the disassembly on PC once it leaves the view.
pub fn update_snapshot(&mut self, mut snapshot: CpuSnapshot) {
let mut state = self.state.lock();
// Each snapshot brings only what was caught since the last one, so the list accumulates
// them and drops the oldest at its cap.
state.access_log.append(&mut snapshot.access_log);
let over = state
.access_log
.len()
.saturating_sub(State::ACCESS_LOG_LINES);
state.access_log.drain(..over);
// Stepping through a routine walks the highlight down the rows already on screen. Only a
// jump that lands off screen moves the view, so the lines around PC stay where they were.
if state.snapshot.cpu.pc != snapshot.cpu.pc && !state.pc_is_visible(snapshot.cpu.pc) {
state.scroll_to = Some(snapshot.cpu.pc);
}
state.snapshot = snapshot;
}
/// Center the disassembly on PC, whatever the view was showing.
///
/// A stop is the one time the view has to move: the console jumped somewhere the user did not
/// scroll to, and the row indices it was following belong to an address space captured before
/// the jump.
pub fn center_on_pc(&mut self) {
let mut state = self.state.lock();
state.scroll_to = Some(state.snapshot.cpu.pc);
}
/// Forget the breakpoints that name the cart being unloaded.
///
/// An `offset` indexes the arena of the cart it was set against, so against the next one it
/// names an unrelated byte and would stop wherever that byte happens to be mapped. The ones
/// with no offset cover work RAM and the registers, which every cart shares, so those stay.
/// Take what the ROM that has just loaded left behind last session.
pub fn adopt_marks(&mut self, marks: Marks) {
self.state.lock().adopt_marks(marks);
}
pub fn drop_cart_breakpoints(&mut self) {
let mut state = self.state.lock();
state.breakpoints.retain_without_cart();
state.access_log.clear();
// Arming only: the console clears its own marks as the cart comes out and reads the next
// one's back in, so writing this list over them would undo that.
state.arm_breakpoints();
}
/// Take a new address space, keeping PC centered for a view that was following it.
pub fn update_address_space(&mut self, address_space: AddressSpace) {
let mut state = self.state.lock();
// A capture arrives whenever the code map marks something new, and rows added above PC
// move its row index. Re-center so PC stays on the same line, but only for a view that
// had it on screen, since one scrolled elsewhere is reading something else.
let following = state.pc_is_visible(state.snapshot.cpu.pc);
state.address_space = address_space;
if following {
state.scroll_to = Some(state.snapshot.cpu.pc);
}
}
/// Draw the debugger's viewport, as a window when viewports are embedded.
pub fn show(&mut self, ui: &mut Ui, opts: ViewportOptions, cfg: Config) {
if !self.open.load(Ordering::Relaxed) {
return;
}
let open = Arc::clone(&self.open);
let state = Arc::clone(&self.state);
let mut viewport_builder = egui::ViewportBuilder::default()
.with_title(Self::TITLE)
.with_inner_size(Vec2::new(940.0, 720.0));
if opts.always_on_top {
viewport_builder = viewport_builder.with_always_on_top();
}
// `show_viewport_deferred` wraps its callback in a window of its own when viewports embed,
// and that window carries the builder's title and size but no close button. Drawing the
// window here instead keeps the title bar, the ✖ and the size on the same window.
if ui.ctx().embed_viewports() {
let was_open = open.load(Ordering::Acquire);
let mut window_open = was_open;
egui::Window::new(Self::TITLE)
.open(&mut window_open)
.default_rect(ui.content_rect().shrink(16.0))
.show(ui, |ui| state.lock().ui(ui, opts.enabled, &cfg));
open.store(window_open, Ordering::Release);
// An embedded window raises no viewport close event, so this ✖ is the only word that
// the Debugger has gone. Unsubscribing disarms the breakpoints and stops the
// recording, and a console stopped with no window to say why just looks frozen.
if was_open && !window_open {
state.lock().subscribe(false);
}
} else {
ui.show_viewport_deferred(self.id, viewport_builder, move |ui, _| {
CentralPanel::default().show(ui, |ui| state.lock().ui(ui, opts.enabled, &cfg));
if ui.input(|i| i.viewport().close_requested()) {
open.store(false, Ordering::Release);
}
});
}
}
}
impl State {
/// Start or stop subscribing to debug events based on the window being open.
fn subscribe(&self, open: bool) {
self.tx
.event(EmulationEvent::DebugSubscribe(open.then(|| self.request())));
// Closing disarms them, since a console that stopped with nothing to show it would just
// look frozen. The list is kept here, so opening puts back what was armed.
if open {
self.arm_breakpoints();
}
self.send_watches();
}
/// Say that the list is full, which is the one reason adding a breakpoint does nothing.
fn warn_breakpoints_full(&self) {
self.tx.event(UiEvent::Message((
MessageType::Warn,
format!("Only {} breakpoints can be enabled.", DeckBreakpoints::MAX),
)));
}
/// Tell the console which addresses to stop at.
///
/// Arming only. The session file is not written from here, so a lifecycle event that re-arms
/// what is listed cannot overwrite the marks a ROM has just been loaded with.
fn arm_breakpoints(&self) {
self.tx
.event(EmulationEvent::DebugBreakpoints(self.breakpoints.armed()));
}
/// Tell the console which addresses to stop at, and what to keep for this ROM.
///
/// For a change the user made. The console is armed with what parses and is enabled, and the
/// session file takes the list as it stands, so a breakpoint left disarmed or half-written is
/// still there next session.
fn send_breakpoints(&self) {
self.arm_breakpoints();
self.send_marks();
}
/// Tell the console what this ROM's session file should keep.
fn send_marks(&self) {
self.tx.event(EmulationEvent::DebugMarks(Box::new(Marks {
breakpoints: self.breakpoints.iter().cloned().collect(),
labels: self.labels.clone(),
})));
}
/// Take what the session file kept for the ROM that has just loaded.
///
/// The ids are handed out again as the breakpoints are listed, since they name a breakpoint
/// for one run of the window and a file cannot know what this run has already used.
fn adopt_marks(&mut self, marks: Marks) {
self.breakpoints = Breakpoints::default();
for breakpoint in marks.breakpoints {
self.breakpoints.add(breakpoint);
}
self.labels = marks.labels;
// Armed straight away, so a breakpoint left enabled last session stops the console this
// one without being ticked again. Not sent back: these came from the console.
self.arm_breakpoints();
}
/// How many recorded accesses the breakpoint pane keeps, oldest dropped first.
const ACCESS_LOG_LINES: usize = 128;
/// Whether `pane` is drawn.
fn is_open(&self, pane: Pane) -> bool {
self.panes.contains(&pane)
}
/// Whether `pc`'s row was on screen in the last draw of the disassembly.
fn pc_is_visible(&self, pc: u16) -> bool {
row_is_visible(&self.address_space, &self.visible_rows, pc)
}
/// Where `addr` sits in the cart arena, as the last snapshot had it mapped.
///
/// `None` for work RAM, the registers and an unmapped page, none of which the arena addresses.
fn prg_offset(&self, addr: u16) -> Option<u32> {
prg_offset(&self.snapshot.prg_pages, addr)
}
/// Open or close `pane`, and tell config and the console what changed.
fn set_pane_open(&mut self, pane: Pane, open: bool) {
// Rebuilt in `Pane::ALL` order, so a reopened pane goes back where it was in its column.
self.panes = Pane::ALL
.iter()
.copied()
.filter(|other| {
if *other == pane {
open
} else {
self.panes.contains(other)
}
})
.collect();
self.tx
.event(ConfigEvent::DebuggerPanes(self.panes.clone()));
self.resubscribe();
self.send_watches();
}
/// What the console is asked to capture for the panes that are open.
fn request(&self) -> DebugRequest {
request(&self.panes, self.history_lines, self.memory_window)
}
/// Ask the console for what the panes now want.
///
/// A subscribe answers with a snapshot of its own, so a memory pane scrolled while the console
/// is stopped fills from that rather than waiting for a frame that never comes.
fn resubscribe(&self) {
self.tx
.event(EmulationEvent::DebugSubscribe(Some(self.request())));
}
fn ui(&mut self, ui: &mut Ui, enabled: bool, cfg: &Config) {
let mut closed = None;
ui.add_enabled_ui(enabled, |ui| {
Panel::top("debugger_toolbar").show(ui, |ui| self.toolbar(ui, cfg));
// Drawn through a closure rather than by the layout, since a body reads the window's
// own state. The pane the closure cannot reach is the one it reports closed.
let open = self.panes.clone();
closed = panes::columns(
ui,
Pane::WINDOW,
&open,
&Pane::default_size,
&mut |ui, pane| self.pane(ui, pane),
);
});
if let Some(pane) = closed {
self.set_pane_open(pane, false);
}
self.breakpoint_editor(ui.ctx());
self.label_editor(ui.ctx());
}
/// The window that edits one breakpoint, open while a row's ✏ names it.
///
/// A window rather than a modal, so the disassembly stays readable beside it while a
/// condition is written against what is on screen.
/// The window that names an address and writes a note about it.
///
/// Edits land as they are typed rather than behind an OK, the way the watch and condition
/// boxes do. An entry emptied back out is dropped, so clearing both fields removes it.
fn label_editor(&mut self, ctx: &Context) {
let Some((key, addr)) = self.editing_label else {
return;
};
let mut open = true;
let mut label = self.labels.get(&key).cloned().unwrap_or_default();
let before = label.clone();
egui::Window::new("Edit label")
.resizable(true)
.default_width(320.0)
.open(&mut open)
.show(ctx, |ui| {
Grid::new("label_editor")
.num_columns(2)
.spacing([12.0, 6.0])
.show(ui, |ui| {
ui.strong("Address");
ui.monospace(match key {
LabelKey::Cart(offset) => format!("${addr:04X} cart ${offset:06X}"),
LabelKey::Cpu(addr) => format!("${addr:04X}"),
})
.on_hover_text(match key {
LabelKey::Cart(_) => {
"Filed by cart offset, so the name follows these bytes when the \
board switches banks"
}
LabelKey::Cpu(_) => {
"Filed by address, which is what work RAM and the registers have"
}
});
ui.end_row();
ui.strong("Name");
ui.add(
egui::TextEdit::singleline(&mut label.name)
.hint_text("what to call it")
.desired_width(f32::INFINITY),
);
ui.end_row();
ui.strong("Comment");
ui.add(
egui::TextEdit::multiline(&mut label.comment)
.hint_text("what to remember about it")
.desired_rows(3)
.desired_width(f32::INFINITY),
);
ui.end_row();
});
ui.separator();
ui.weak(
"The name replaces the address wherever an operand reaches it, and heads the \
row it names. The comment follows the instruction.",
);
});
if label != before {
if label.is_empty() {
self.labels.remove(&key);
} else {
self.labels.insert(key, label);
}
self.send_marks();
}
if !open {
self.editing_label = None;
}
}
fn breakpoint_editor(&mut self, ctx: &Context) {
let Some(id) = self.editing else {
return;
};
// Whatever the editor named has been removed, so there is nothing left to edit.
if self.breakpoints.get(id).is_none() {
self.editing = None;
return;
}
let mut open = true;
let mut armed_changed = false;
let mut removed = false;
let mut range = std::mem::take(&mut self.editing_range);
let mut moved = false;
// Copied out because the closure borrows the breakpoint mutably and still has to resolve
// an address.
let pages = self.snapshot.prg_pages;
let response = egui::Window::new("Edit breakpoint")
// Resizable, and wide enough by default that the syntax below reads without
// wrapping, since a condition can run well past one line.
.resizable(true)
.default_width(400.0)
.open(&mut open)
.show(ctx, |ui| {
let Some(breakpoint) = self.breakpoints.get_mut(id) else {
return;
};
Grid::new("breakpoint_editor")
.num_columns(2)
.spacing([12.0, 6.0])
.show(ui, |ui| {
ui.strong("Address or range");
let response = ui.add(
egui::TextEdit::singleline(&mut range)
.hint_text("$addr or $lo-$hi")
.desired_width(160.0),
);
// Applied as it is typed, and left alone while it is not a range, so
// clearing the box to retype it does not move the breakpoint to $0000.
if response.changed()
&& let Some((addr, end)) = parse_range(&range)
{
breakpoint.addr = addr;
breakpoint.end = end;
// Resolved from the address just typed. Taking it from the one the
// box held when the frame began pins the breakpoint to the bank it
// has left, where nothing can ever match it.
breakpoint.offset = prg_offset(&pages, addr);
moved = true;
armed_changed = true;
}
ui.end_row();
ui.strong("Break on");
ui.horizontal(|ui| {
for (access, letter, hover) in [
(Access::EXEC, "X", "Execution"),
(Access::READ, "R", "Reads"),
(Access::WRITE, "W", "Writes"),
] {
let mut on = breakpoint.access.contains(access);
if ui
.toggle_value(&mut on, letter)
.on_hover_text(hover)
.changed()
{
breakpoint.access.set(access, on);
armed_changed = true;
}
}
});
ui.end_row();
ui.strong("Condition");
ui.vertical(|ui| {
let width = ui.available_width();
let response = ui.add(
egui::TextEdit::multiline(&mut breakpoint.condition)
.font(egui::TextStyle::Monospace)
.hint_text("a == 0xFF && mem[0x300] != 0")
.desired_width(width)
.desired_rows(3),
);
armed_changed |= response.changed();
// Reported under the box rather than on a hover: there is room here,
// and a condition that does not parse leaves the breakpoint unarmed.
if let Some(Err(error)) = breakpoint.condition() {
ui.label(
RichText::new(error.to_string()).small().color(Color32::RED),
);
}
});
ui.end_row();
ui.strong("Then");
ui.vertical(|ui| {
let mut logs = !breakpoint.breaks;
if ui
.checkbox(&mut logs, "Log and keep running")
.on_hover_text("Cleared, the console stops instead")
.changed()
{
breakpoint.breaks = !logs;
armed_changed = true;
}
armed_changed |=
ui.checkbox(&mut breakpoint.enabled, "Enabled").changed();
});
ui.end_row();
});
ui.collapsing("Expression syntax", syntax_help);
ui.separator();
ui.horizontal(|ui| {
removed = ui.button("Delete").clicked();
});
});
self.editing_range = range;
if moved {
// `add` inserts in address order and an edit moves one out from under that.
self.breakpoints.sort();
}
if let Some(response) = &response {
// Focused and on top the way the keybind window is, since it is opened by a click on
// the row behind it.
ctx.move_to_top(response.response.layer_id);
}
if removed {
self.breakpoints.remove(id);
armed_changed = true;
}
if removed || !open {
self.editing = None;
}
if armed_changed {
self.send_breakpoints();
}
}
/// The step buttons and the View menu.
fn toolbar(&mut self, ui: &mut Ui, cfg: &Config) {
ui.horizontal(|ui| {
for (step, label, hover) in [
(DebugStep::Into, "➡", "Step a single CPU instruction."),
(DebugStep::Out, "⬆", "Step out of the current CPU function."),
(DebugStep::Over, "⮫", "Step over the next CPU instruction."),
(DebugStep::Scanline, "➖", "Step an entire PPU scanline."),
(DebugStep::Frame, "🖼", "Step an entire PPU frame."),
] {
let shortcut = cfg.shortcut(Debug::Step(step));
let button = egui::Button::new(label);
if ui
.add(button)
.on_hover_text(format!("{hover} ({shortcut})"))
.clicked()
{
self.tx.event(EmulationEvent::DebugStep(step));
}
}
ui.separator();
for (interrupt, run_to, label, hover) in [
(
DebugInterrupt::Nmi,
RunTo::Nmi,
"NMI",
"Resume until the console takes the NMI vector.",
),
(
DebugInterrupt::Irq,
RunTo::Irq,
"IRQ",
"Resume until the console takes the IRQ vector. A `BRK` reaches it by \
executing, so break on one with an execute breakpoint.",
),
] {
let shortcut = cfg.shortcut(Debug::RunTo(interrupt));
if ui
.add(egui::Button::new(label))
.on_hover_text(format!("{hover} ({shortcut})"))
.clicked()
{
self.tx.event(EmulationEvent::DebugRunTo(Some(run_to)));
}
}
ui.separator();
if let Some((pane, open)) = panes::view_menu(ui, Pane::WINDOW, &self.panes) {
self.set_pane_open(pane, open);
}
});
}
/// Draw `pane`'s view. The layout draws the heading above it.
fn pane(&mut self, ui: &mut Ui, pane: Pane) {
match pane {
Pane::Disassembly => self.disassembly(ui),
Pane::Registers => self.registers(ui),
Pane::Stack => self.stack(ui),
Pane::CallStack => self.call_stack(ui),
Pane::Breakpoints => self.breakpoint_list(ui),
Pane::Watches => self.watch_list(ui),
// Its own pane rather than inline above PC: the disassembly is ordered by address and
// this is ordered by time, so the two only coincide in straight-line code.
Pane::History => self.history(ui),
Pane::Memory => self.memory(ui),
Pane::Input => self.input(ui),
}
}
fn registers(&mut self, ui: &mut Ui) {
// Every pane scrolls, so its panel keeps the height its splitter was dragged to.
ScrollArea::vertical()
.id_salt("registers")
.auto_shrink([false, false])
.show(ui, |ui| self.register_grid(ui));
}
/// The registers. Clicking one opens a box that writes it.
///
/// The console applies a write between instructions and answers with a fresh snapshot, so a
/// cell reads back what actually landed rather than what was typed.
fn register_grid(&mut self, ui: &mut Ui) {
// Copied out so the cells can borrow the edit box, which lives beside the snapshot.
let cpu = self.snapshot.cpu.clone();
let address_rows = self.address_rows(cpu.pc);
let stack_rows = self.stack_rows();
let cycle_rows = [
("Cycles", cpu.cycle.to_string()),
("Frame", self.snapshot.frame.to_string()),
];
let edit = &mut self.register_edit;
let mut written = None;
Grid::new("cpu_registers")
.num_columns(6)
.spacing([16.0, 4.0])
.show(ui, |ui| {
let mut cell = |ui: &mut Ui, register, value, rows: &[(&str, String)]| {
written = register_cell(ui, register, value, rows, edit).or(written);
};
cell(ui, Register::Pc, cpu.pc, &address_rows);
cell(ui, Register::Acc, cpu.acc.into(), &byte_rows(cpu.acc));
cell(ui, Register::Sp, cpu.sp.into(), &stack_rows);
ui.end_row();
cell(ui, Register::X, cpu.x.into(), &byte_rows(cpu.x));
cell(ui, Register::Y, cpu.y.into(), &byte_rows(cpu.y));
// The cycle count reports how far the console has run rather than naming a
// register, so nothing writes it and it draws as a plain pair.
let hover = |ui: &mut Ui| {
ui.strong("CPU cycles since power on");
detail_rows(ui, "Cycle", &cycle_rows);
};
ui.strong("Cycle").on_hover_ui(hover);
ui.monospace(cpu.cycle.to_string()).on_hover_ui(hover);
ui.end_row();
});
ui.horizontal(|ui| {
ui.strong("P").on_hover_text(
"Status register - the flags the last instruction to write one left behind.",
);
// Uppercase for set, lowercase and dimmed for clear, in NVUBDIZC order.
for (flag, name, meaning) in [
(Status::N, 'N', "Negative"),
(Status::V, 'V', "Overflow"),
(Status::U, 'U', "Unused - set whenever the status is pushed"),
(Status::B, 'B', "Break - set by the status PHP and BRK push"),
(
Status::D,
'D',
"Decimal - the NES CPU's ADC and SBC ignore it",
),
(Status::I, 'I', "Interrupt disable"),
(Status::Z, 'Z', "Zero"),
(Status::C, 'C', "Carry"),
] {
let set = cpu.status.contains(flag);
let text = if set {
RichText::new(name).monospace().strong()
} else {
RichText::new(name.to_ascii_lowercase())
.monospace()
.color(Color32::DARK_GRAY)
};
// A flag is one bit, so a click is the whole edit. The other seven come back
// unchanged, since the write names the register rather than the bit.
if ui
.add(egui::Label::new(text).sense(Sense::click()))
.on_hover_text(format!(
"{meaning}: {}. Click to {}.",
if set { "set" } else { "clear" },
if set { "clear" } else { "set" }
))
.clicked()
{
written = Some(DebugWrite::Status(cpu.status ^ flag));
}
}
});
written = self.interrupt_row(ui).or(written);
if let Some(write) = written {
self.tx.event(EmulationEvent::DebugWrite(write));
}
}
/// The pending interrupts as checkboxes, laid out the way Mesen's CPU status lays them out.
/// Ticking one raises it and clearing one drops it. Returns the write a click asked for.
fn interrupt_row(&self, ui: &mut Ui) -> Option<DebugWrite> {
let interrupts = self.snapshot.interrupts;
let blocked = self.snapshot.cpu.status.contains(Status::I);
let mut written = None;
ui.horizontal_wrapped(|ui| {
let line = interrupts.irq_line();
ui.strong("IRQs:").on_hover_text(if line && blocked {
"An IRQ source is asserted, but the I flag is holding it off."
} else if line {
"An IRQ source is asserted, and the IRQ is taken once the current instruction \
finishes."
} else {
"No interrupt is pending."
});
let mut nmi = interrupts.nmi_latched;
if ui
.checkbox(&mut nmi, "NMI")
.on_hover_text(format!(
"Taken after the current instruction. NMI on VBlank ($2000 bit 7) is {}.",
if interrupts.nmi_enabled { "on" } else { "off" }
))
.changed()
{
written = Some(DebugWrite::Nmi(nmi));
}
let mut cart = interrupts.mapper_irq;
if ui
.add_enabled(
interrupts.mapper_has_irq,
egui::Checkbox::new(&mut cart, "Cart"),
)
.on_hover_text(
"Cartridge board. The board's own acknowledge register clears it, as it \
would a real one.",
)
.on_disabled_hover_text("This cartridge board has no IRQ.")
.changed()
{
written = Some(DebugWrite::CartIrq(cart));
}
let mut frame = interrupts.frame_irq;
if ui
.checkbox(&mut frame, "Frame Counter")
.on_hover_text("APU frame counter. A read of $4015 acknowledges it.")
.changed()
{
written = Some(DebugWrite::FrameIrq(frame));
}
let mut dmc = interrupts.dmc_irq;
if ui
.checkbox(&mut dmc, "DMC")
.on_hover_text("APU DMC, at the end of a sample. A write to $4015 acknowledges it.")
.changed()
{
written = Some(DebugWrite::DmcIrq(dmc));
}
});
written
}
/// An address in both the terms it can be named in: where the CPU sees it, and where the byte
/// it reaches sits in the cart. Only cart memory has the second.
fn address_rows(&self, addr: u16) -> Vec<(&'static str, String)> {
let mut rows = vec![("CPU", format!("${addr:04X}"))];
if let Some(offset) = self.prg_offset(addr) {
rows.push(("Cart", format!("${offset:06X}")));
}
rows
}
/// What the stack pointer says about the stack, for its hover.
///
/// SP names the next free slot, so what a pull would take sits one above it. With the Stack
/// pane closed nothing has been captured to name, so only the push address is listed.
fn stack_rows(&self) -> Vec<(&'static str, String)> {
let cpu = &self.snapshot.cpu;
let pull = cpu.sp.wrapping_add(1);
let mut rows = vec![(
"Next push",
format!("${:04X}", Cpu::SP_BASE | u16::from(cpu.sp)),
)];
if let Some(value) = self.snapshot.stack.get(usize::from(pull)) {
rows.push((
"Next pull",
format!("${:04X} = ${value:02X}", Cpu::SP_BASE | u16::from(pull)),
));
}
rows
}
/// The instructions that ran most recently, oldest first, ending just before PC.
fn history(&mut self, ui: &mut Ui) {
// Newest last, so the view follows the end the way a log does. Scrolling up unsticks it
// until it is dragged back down.
ScrollArea::vertical()
.id_salt("history")
.auto_shrink([false, false])
.stick_to_bottom(true)
.show(ui, |ui| self.history_rows(ui));
}
fn history_rows(&mut self, ui: &mut Ui) {
if self.snapshot.history.is_empty() {
ui.weak("Nothing recorded - step or resume to start executing.");
return;
}
// A run of one address collapses to a count. A CPU waiting on NMI spins on a single
// instruction, and eight identical lines say far less than one line and a repeat count.
let mut history = self.snapshot.history.iter().peekable();
while let Some(line) = history.next() {
let mut repeats = 1;
while history.peek().is_some_and(|next| next.addr == line.addr) {
history.next();
repeats += 1;
}
let text = if repeats > 1 {
format!("{line} ×{repeats}")
} else {
line.to_string()
};
ui.label(RichText::new(text).monospace().color(Color32::DARK_GRAY));
}
}
/// How the console reached where it is, innermost call first.
///
/// The frames are recorded as the calls are made, so the pane fills in from wherever it was
/// opened rather than from the game's first `JSR`.
fn call_stack(&mut self, ui: &mut Ui) {
ScrollArea::vertical()
.id_salt("call_stack")
.auto_shrink([false, false])
.show(ui, |ui| self.call_stack_rows(ui));
}
fn call_stack_rows(&mut self, ui: &mut Ui) {
// PC first, so the column reads as one path from where execution is out to whoever
// started it.
let pc = self.snapshot.cpu.pc;
let mut scroll_to = None;
let executing = Label::new(
RichText::new(format!(" ${pc:04X}"))
.monospace()
.color(Color32::LIGHT_GRAY),
)
.sense(Sense::click());
if ui
.add(executing)
.on_hover_cursor(egui::CursorIcon::PointingHand)
.on_hover_text("Executing here - go to it")
.clicked()
{
scroll_to = Some(pc);
}
if self.snapshot.call_stack.is_empty() {
ui.weak("No call recorded - step or resume to enter one.");
}
for frame in self.snapshot.call_stack.iter().rev() {
let kind = match frame.kind {
FrameKind::Call => "JSR",
FrameKind::Nmi => "NMI",
FrameKind::Irq => "IRQ",
FrameKind::Brk => "BRK",
};
let label = Label::new(
RichText::new(format!(
"{kind} ${:04X} from ${:04X}",
frame.entry, frame.caller
))
.monospace()
.color(Color32::DARK_GRAY),
)
.sense(Sense::click());
if ui
.add(label)
.on_hover_cursor(egui::CursorIcon::PointingHand)
.on_hover_text("Go to the call")
.clicked()
{
scroll_to = Some(frame.caller);
}
}
if let Some(addr) = scroll_to {
self.scroll_to = scroll_to;
self.selected = Some(addr);
}
}
/// The watched expressions and what each comes to, with the box that adds one.
///
/// Values arrive on the snapshot, so they follow the console: they refresh every frame while
/// it runs and after every step.
fn watch_list(&mut self, ui: &mut Ui) {
ui.horizontal(|ui| {
let response = ui.add(
egui::TextEdit::singleline(&mut self.watch_entry)
.hint_text("expression")
.desired_width(140.0),
);
let add = submitted(ui, &response) | ui.button("Add").clicked();
if add && !self.watch_entry.trim().is_empty() {
self.watches.push(std::mem::take(&mut self.watch_entry));
self.send_watches();
}
ui.menu_button("?", syntax_help)
.response
.on_hover_text("Expression syntax");
});
if self.watches.is_empty() {
ui.weak("None. Add an expression above, like `a` or `mem16[0xFFFC]`.");
return;
}
let mut changed = false;
let mut removed = None;
let values = &self.snapshot.watches;
let watches = &mut self.watches;
ScrollArea::vertical()
.id_salt("watches")
.auto_shrink([false, false])
.show(ui, |ui| {
for (index, watch) in watches.iter_mut().enumerate() {
ui.horizontal(|ui| {
// The value leads the row, so a column of them reads down the pane rather
// than being hunted for past expressions of every length.
match Expr::parse(watch.trim()) {
Ok(expr) => {
// A value arrives a frame after the expression it answers, so a
// row that has just been typed has none yet.
let text = values.get(index).copied().flatten().map_or_else(
|| "…".to_string(),
|value| watch_value(value, expr.is_boolean()),
);
ui.monospace(text);
}
Err(error) => {
ui.label(RichText::new("error").monospace().color(Color32::RED))
.on_hover_text(error.to_string());
}
}
// Laid right to left so ✖ ends the row the way it ends a breakpoint's,
// with the box taking what is left rather than pushing it off.
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.small_button("✖").clicked() {
removed = Some(index);
}
// Sized from what the button left, rather than asked to fill, so a
// long expression cannot push it back off the row.
let width = ui.available_width();
changed |= ui
.add(
egui::TextEdit::singleline(watch)
.font(egui::TextStyle::Monospace)
.desired_width(width),
)
.changed();
});
});
}
});
if let Some(index) = removed {
self.watches.remove(index);
changed = true;
}
if changed {
self.send_watches();
}
}
/// Tell the console which expressions to evaluate each snapshot.
///
/// Nothing while the pane is closed, which leaves the console evaluating nothing, the way a
/// closed pane captures nothing.
fn send_watches(&self) {
if !self.is_open(Pane::Watches) {
self.tx.event(EmulationEvent::DebugWatches(Vec::new()));
return;
}
self.tx.event(EmulationEvent::DebugWatches(
self.watches
.iter()
.map(|watch| Expr::parse(watch.trim()).ok())
.collect(),
));
}
/// The breakpoints, and the box that adds one.
fn breakpoint_list(&mut self, ui: &mut Ui) {
ui.horizontal(|ui| {
let response = ui.add(
egui::TextEdit::singleline(&mut self.breakpoint_goto)
.hint_text("$addr or $lo-$hi")
.desired_width(140.0),
);
let add = submitted(ui, &response) | ui.button("Add").clicked();
if let Some((addr, end)) = parse_range(&self.breakpoint_goto)
&& add
{
if self.breakpoints.is_full() {
self.warn_breakpoints_full();
} else {
self.breakpoint_goto.clear();
let offset = self.prg_offset(addr);
self.breakpoints.add(Breakpoint::range(addr, end, offset));
self.send_breakpoints();
}
}
});
self.access_log_rows(ui);
if self.breakpoints.is_empty() {
ui.weak("None. Add one above, or click the gutter beside an instruction.");
return;
}
// The list borrows itself for the walk, so what each row asks for is applied after it.
let mut armed_changed = false;
let mut removed = None;
let mut scroll_to = None;
let pages = &self.snapshot.prg_pages;
let mut editing = None;
let breakpoints = &mut self.breakpoints;
ScrollArea::vertical()
.id_salt("breakpoints")
.auto_shrink([false, false])
.show(ui, |ui| {
for breakpoint in breakpoints.iter_mut() {
ui.horizontal(|ui| {
let enabled = breakpoint.enabled;
armed_changed |= ui
.checkbox(&mut breakpoint.enabled, "")
.on_hover_text(if enabled {
"Disable breakpoint"
} else {
"Enable breakpoint"
})
.changed();
// One letter each, since three of them plus the range have to fit a
// column narrower than the disassembly.
for (access, letter, hover) in [
(Access::EXEC, "X", "Break on execution"),
(Access::READ, "R", "Break on read"),
(Access::WRITE, "W", "Break on write"),
] {
let mut on = breakpoint.access.contains(access);
if ui
.toggle_value(&mut on, letter)
.on_hover_text(hover)
.changed()
{
breakpoint.access.set(access, on);
armed_changed = true;
}
}
// A breakpoint whose bank has been switched out cannot fire, and nothing
// else on screen would say why, so the range says it here.
let mapped = is_mapped(pages, breakpoint);
let label =
Label::new(RichText::new(breakpoint.range_text()).monospace().color(
if mapped {
Color32::LIGHT_RED
} else {
Color32::DARK_GRAY
},
))
.sense(Sense::click());
if ui
.add(label)
.on_hover_cursor(egui::CursorIcon::PointingHand)
.on_hover_text(if mapped {
"Go to location"
} else {
"Go to location - its bank is not mapped there now"
})
.clicked()
{
scroll_to = Some(breakpoint.addr);
}
// What only the editor sets still shows here, so the collapsed list
// says which breakpoints are narrowed and which only log.
if !breakpoint.breaks {
ui.label(RichText::new("log").small().color(Color32::DARK_GRAY))
.on_hover_text("Records the access and keeps running");
}
match breakpoint.condition() {
Some(Ok(expr)) => {
ui.label(RichText::new("if").small())
.on_hover_text(expr.source().to_string());
}
Some(Err(error)) => {
ui.label(RichText::new("if").small().color(Color32::LIGHT_RED))
.on_hover_text(error.to_string());
}
None => (),
}
if ui
.small_button("✏")
.on_hover_text("Edit breakpoint")
.clicked()
{
editing = Some(breakpoint.id);
}
if ui.small_button("✖").clicked() {
removed = Some(breakpoint.id);
}
});
}
});
if let Some(id) = editing {
// The box starts from the breakpoint's own range, so opening the editor and closing
// it again changes nothing.
self.editing_range = self
.breakpoints
.get(id)
.map(Breakpoint::range_text)
.unwrap_or_default();
self.editing = Some(id);
}
if let Some(id) = removed {
self.breakpoints.remove(id);
armed_changed = true;
}
if let Some(addr) = scroll_to {
self.scroll_to = scroll_to;
// Selected as well as scrolled to, so the row it lands on is marked when it arrives.
// A block takes the mark by covering the address, which is how an address in a range
// nothing has decoded still shows where it went.
self.selected = Some(addr);
}
if armed_changed {
self.send_breakpoints();
}
}
/// What the breakpoints that keep running have caught, newest last.
fn access_log_rows(&mut self, ui: &mut Ui) {
if self.access_log.is_empty() {
return;
}
let mut cleared = false;
let log = &self.access_log;
// Claims its strip before the list, whose scroll area takes whatever is left.
Panel::bottom("breakpoint_log")
.resizable(true)
.default_size(ui.text_style_height(&egui::TextStyle::Monospace) * 7.0)
.show(ui, |ui| {
ui.horizontal(|ui| {
ui.strong("Caught");
cleared = ui.small_button("Clear").clicked();
});
ScrollArea::vertical()
.id_salt("access_log")
.auto_shrink([false, false])
.stick_to_bottom(true)
.show(ui, |ui| {
for hit in log {
// The instruction first, since "what touches this address" is the
// question a recording breakpoint is set to answer.
let text = if hit.access.contains(Access::EXEC) {
// An execution names one address, and the disassembly already
// says what sits there.
format!("${:04X} ran", hit.pc)
} else {
let verb = if hit.access.contains(Access::WRITE) {
"wrote"
} else {
"read"
};
format!(
"${:04X} {verb} ${:04X} = ${:02X}",
hit.pc, hit.addr, hit.value
)
};
ui.label(RichText::new(text).monospace());
}
});
});
if cleared {
self.access_log.clear();
}
}
fn disassembly(&mut self, ui: &mut Ui) {
ui.horizontal(|ui| {
let response = ui.add(
egui::TextEdit::singleline(&mut self.goto)
.hint_text("$addr")
.desired_width(90.0),
);
let go = submitted(ui, &response) | ui.button("Go").clicked();
if let Some(addr) = parse_addr(&self.goto)
&& go
{
self.scroll_to = Some(addr);
self.selected = Some(addr);
}
});
if self.address_space.rows.is_empty() {
ui.weak("No ROM is loaded.");
return;
}
let pc = self.snapshot.cpu.pc;
let row_height = ui.text_style_height(&egui::TextStyle::Monospace);
// Rows have to stay exactly one line tall: `show_rows` maps scroll offset to row index by
// multiplying, so a row that wraps desynchronizes both the virtual window and the jump.
ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend);
let pitch = row_height + ui.spacing().item_spacing.y;
let viewport_height = ui.available_height();
// Scrolls sideways as well: a row runs to about 44 columns at its longest, and the
// window is resizable down past that.
let mut scroll_area = ScrollArea::both()
.id_salt("disassembly")
.auto_shrink([false, false]);
// A row per instruction rather than per address, so the only way to scroll to an address
// is to look up which row covers it.
let target = self
.scroll_to
.and_then(|addr| self.address_space.row_at(addr));
// `show_rows` only builds widgets for the rows it believes are visible, so a row that was
// not drawn cannot center itself. This brings it into the window, and the exact centering
// happens below.
if let Some(row) = target.filter(|row| !self.visible_rows.contains(row)) {
let approx = (row as f32).mul_add(pitch, -(viewport_height - row_height) / 2.0);
scroll_area = scroll_area.vertical_scroll_offset(approx.max(0.0));
}
let palette = Palette::new(ui.visuals());
let font = egui::TextStyle::Monospace.resolve(ui.style());
let mut drawn = 0..0;
let mut centered = false;
let mut act = None;
scroll_area.show_rows(
ui,
row_height,
self.address_space.rows.len(),
|ui, range| {
drawn = range.clone();
for (offset, row) in self.address_space.rows[range.clone()].iter().enumerate() {
let (response, clicked) = self.row(ui, row, pc, &palette, &font, row_height);
if clicked.is_some() {
act = clicked;
}
if target == Some(range.start + offset) {
// egui measures the drawn row, where the offset arithmetic above can only
// estimate it, so this lands the row on the center line.
// Unanimated, to match the rest of the window updating in one step.
response.scroll_to_me_animation(
Some(egui::Align::Center),
egui::style::ScrollAnimation::none(),
);
centered = true;
}
}
},
);
self.visible_rows = drawn;
if centered {
self.scroll_to = None;
}
match act {
Some(RowAction::ToggleBreakpoint(addr, offset)) => {
// A full list refuses the add, so say so. Clicking a gutter and having nothing
// appear reads as a broken window.
if self.breakpoints.is_full() && self.breakpoints.single_at(addr, offset).is_none()
{
self.warn_breakpoints_full();
} else {
self.breakpoints.toggle(addr, offset);
self.send_breakpoints();
}
}
Some(RowAction::RemoveBreakpoint(id)) => {
self.breakpoints.remove(id);
self.send_breakpoints();
}
Some(RowAction::ArmBreakpoint(id, enabled)) => {
if let Some(breakpoint) = self.breakpoints.get_mut(id) {
breakpoint.enabled = enabled;
}
self.send_breakpoints();
}
Some(RowAction::Select(addr)) => self.selected = Some(addr),
Some(RowAction::EditLabel(key, addr)) => self.editing_label = Some((key, addr)),
Some(RowAction::GoTo(addr)) => {
self.scroll_to = Some(addr);
self.selected = Some(addr);
}
Some(RowAction::ViewInMemory(addr)) => {
if !self.is_open(Pane::Memory) {
self.set_pane_open(Pane::Memory, true);
}
self.memory_scroll_to = Some(addr);
self.memory_edit = Some((addr, String::new()));
}
Some(RowAction::AddWatch(addr)) => {
if !self.is_open(Pane::Watches) {
self.set_pane_open(Pane::Watches, true);
}
self.watches.push(format!("mem[${addr:04X}]"));
self.send_watches();
}
Some(RowAction::MovePc(addr)) => {
self.tx
.event(EmulationEvent::DebugWrite(DebugWrite::Pc(addr)));
}
Some(RowAction::RunTo(addr)) => {
self.tx
.event(EmulationEvent::DebugRunTo(Some(RunTo::Address(addr))));
}
None => (),
}
}
/// Draw one row, reporting it and what a click on it asked for.
///
/// The row is split by hand rather than laid out with [`Ui::horizontal`], which sizes to its
/// contents. `show_rows` maps scroll offset to row index by multiplying, so a row a pixel
/// taller desynchronizes both the virtual window and the jump to an address.
fn row(
&self,
ui: &mut Ui,
row: &Row,
pc: u16,
palette: &Palette,
font: &egui::FontId,
row_height: f32,
) -> (egui::Response, Option<RowAction>) {
let (galley, mnemonic_span) = self.row_galley(ui, row, pc, palette, font);
// At least the viewport's width, so the gutter and the row highlights span it, and at
// least the text's, so the scroll area learns how far right the disassembly reaches.
let width = (GUTTER_WIDTH + galley.size().x).max(ui.available_width());
let (rect, response) = ui.allocate_exact_size(Vec2::new(width, row_height), Sense::hover());
let (gutter, text) = rect.split_left_right_at_x(rect.left() + GUTTER_WIDTH);
// Only an instruction has one address to arm. A block spans a range, so its gutter is
// inert and the address box stays the way to break inside it.
let instruction = match row {
Row::Instruction(disasm) => Some(disasm),
Row::Block { .. } | Row::Label { .. } => None,
};
let addr = instruction.map(|disasm| disasm.addr);
// A block holds PC and the selection by covering their address, so a console stopped
// inside a collapsed range still shows where it is.
let holds_pc = row.covers(pc);
let holds_selection = self.selected.is_some_and(|selected| row.covers(selected));
// Interacted with before it is painted, so hovering the gutter can light it up. A row
// whose gutter has no breakpoint would otherwise give no sign of being clickable.
let gutter_response =
addr.map(|addr| ui.interact(gutter, ui.id().with(("gutter", addr)), Sense::click()));
let painter = ui.painter();
painter.rect_filled(
gutter,
0.0,
match &gutter_response {
Some(response) if response.hovered() => palette.gutter_hovered,
_ => palette.gutter,
},
);
if holds_pc {
painter.rect_filled(text, 0.0, palette.pc_background);
}
if holds_selection {
// An outline rather than a fill, so a selected row that PC is also on keeps both
// marks.
painter.rect_stroke(text, 0.0, palette.selection, egui::StrokeKind::Inside);
}
// Where the mnemonic was laid, measured before the galley is handed to the painter, so
// its span can be hovered over. The row is painted from `text.left()`.
let mnemonic = Rect::from_x_y_ranges(
text.left()
+ galley
.pos_from_cursor(CCursor::new(mnemonic_span.start))
.left()
..=text.left()
+ galley
.pos_from_cursor(CCursor::new(mnemonic_span.end))
.left(),
text.y_range(),
);
// Centered on the galley's own height rather than the font's, which is shorter than the
// row and leaves the line sitting low in it, off center inside the selection outline.
painter.galley(
egui::Pos2::new(text.left(), text.center().y - galley.size().y / 2.0),
galley,
palette.operand,
);
// A name is a heading over the row below it, not a row to act on, so it interacts with
// nothing. Interacting would also collide with that row: both are keyed by the address.
if matches!(row, Row::Label { .. }) {
return (response, None);
}
let (Some(addr), Some(disasm)) = (addr, instruction) else {
let row_response =
ui.interact(text, ui.id().with(("block", row.addr())), Sense::click());
let selected = row_response
.on_hover_cursor(egui::CursorIcon::PointingHand)
.clicked()
.then(|| RowAction::Select(row.addr()));
return (response, selected);
};
// Every breakpoint covering this row, so a range marks the whole of itself rather than
// the row it starts on. One set on the same address in another bank belongs to code that
// is not on screen, which `covering` leaves out.
let offset = self.prg_offset(addr);
let covering = self
.breakpoints
.covering(addr, &self.snapshot.prg_pages)
.collect::<Vec<_>>();
if let Some(mark) = GutterMark::of(&covering) {
mark.paint(painter, gutter, palette);
}
let gutter_response = gutter_response.expect("an instruction row interacts");
let mut action = gutter_response
.clicked()
.then_some(RowAction::ToggleBreakpoint(addr, offset));
// The click owns the breakpoint on exactly this address. Anything else covering the row
// is reachable from the menu, so one click never means two things.
let single = self.breakpoints.single_at(addr, offset);
let gutter_response = if covering.is_empty() {
gutter_response.on_hover_text("Add breakpoint")
} else {
gutter_response.on_hover_ui(|ui| {
ui.label(if single.is_some() {
"Click to remove the breakpoint on this address"
} else {
"Click to add a breakpoint on this address"
});
for breakpoint in &covering {
ui.monospace(format!(
"{} {}",
breakpoint.range_text(),
access_text(breakpoint.access)
));
}
})
};
gutter_response.context_menu(|ui| {
for breakpoint in &covering {
let enabled = breakpoint.enabled;
ui.menu_button(breakpoint.range_text(), |ui| {
if ui
.button(if enabled { "Disable" } else { "Enable" })
.clicked()
{
action = Some(RowAction::ArmBreakpoint(breakpoint.id, !enabled));
ui.close();
}
if ui.button("Remove").clicked() {
action = Some(RowAction::RemoveBreakpoint(breakpoint.id));
ui.close();
}
});
}
if single.is_none() && ui.button("Add breakpoint here").clicked() {
action = Some(RowAction::ToggleBreakpoint(addr, offset));
ui.close();
}
});
let row_response = ui.interact(text, ui.id().with(("row", addr)), Sense::click());
if row_response.clicked() {
action = Some(RowAction::Select(addr));
}
// Hung off the row rather than given a widget of its own, so nothing overlays the row and
// takes the click that selects it.
let row_response = if row_response
.hover_pos()
.is_some_and(|pos| mnemonic.contains(pos))
{
row_response.on_hover_ui(|ui| instruction_tooltip(ui, &disasm.instr))
} else {
row_response
};
// Every address the row names is worth copying, not only the one it starts at: the
// effective address is where an indexed operand actually landed.
row_response.context_menu(|ui| {
let copy = |ui: &mut Ui, label: &str, text: String| {
if ui.button(label).clicked() {
ui.ctx().copy_text(text);
ui.close();
}
};
let mut act = |ui: &mut Ui, label: &str, row_action: RowAction| {
if ui.button(label).clicked() {
action = Some(row_action);
ui.close();
}
};
act(
ui,
"Toggle breakpoint",
RowAction::ToggleBreakpoint(addr, offset),
);
act(ui, "Add to watch", RowAction::AddWatch(addr));
act(
ui,
"Edit label",
RowAction::EditLabel(LabelKey::new(addr, offset), addr),
);
act(ui, "View in memory", RowAction::ViewInMemory(addr));
ui.separator();
act(ui, "Run to location", RowAction::RunTo(addr));
act(ui, "Move program counter here", RowAction::MovePc(addr));
act(ui, "Go to location", RowAction::GoTo(addr));
ui.separator();
copy(ui, "Copy address", format!("${addr:04X}"));
if let Some(effective) = disasm.effective_text() {
copy(ui, "Copy effective address", effective);
}
if let Some(value) = disasm.value {
copy(ui, "Copy value", value.to_string());
}
});
(response, action)
}
/// Lay a row out as one galley, each part in its own color.
///
/// One galley rather than a painted string per part, so the row is measured once and the
/// columns stay where the monospace padding puts them.
fn row_galley(
&self,
ui: &Ui,
row: &Row,
pc: u16,
palette: &Palette,
font: &egui::FontId,
) -> (Arc<egui::Galley>, Range<usize>) {
let mut job = egui::text::LayoutJob::default();
let disasm = match row {
Row::Instruction(disasm) => disasm,
Row::Block { start, end, kind } => {
job.append(
&format!("${start:04X}-${end:04X} {}", kind.label()),
0.0,
egui::TextFormat {
font_id: font.clone(),
color: palette.block,
..Default::default()
},
);
return (ui.painter().layout_job(job), 0..0);
}
// Inset a little from the address column and closed with a colon, which is how an
// assembler listing writes one, so it reads as a heading over the rows below it
// without lining up with any of their columns.
Row::Label { name, .. } => {
job.append(
&format!(" {name}:"),
0.0,
egui::TextFormat {
font_id: font.clone(),
color: palette.label,
..Default::default()
},
);
return (ui.painter().layout_job(job), 0..0);
}
};
// The console is about to run the row at PC, so it reads as one line rather than as a
// handful of tinted parts.
let at_pc = disasm.addr == pc;
// Each part reports the characters it laid down, so the mnemonic's own span can be found
// again to hover over.
let mut laid = 0;
let mut part = |text: String, color: Color32| {
let start = laid;
laid += text.chars().count();
job.append(
&text,
0.0,
egui::TextFormat {
font_id: font.clone(),
color: if at_pc { palette.pc_text } else { color },
..Default::default()
},
);
start..laid
};
let _ = part(format!("${:04X} ", disasm.addr), palette.address);
let mut bytes = format!("${:02X} ", disasm.instr.opcode);
let mut columns = 0;
for byte in disasm.operands() {
bytes.push_str(&format!("${byte:02X} "));
columns += 4;
}
for _ in columns..Disasm::BYTE_COLUMNS {
bytes.push(' ');
}
let _ = part(bytes, palette.bytes);
let mnemonic = disasm.instr.to_string();
let unofficial = mnemonic.starts_with('*');
let mnemonic_span = part(
mnemonic,
if unofficial {
palette.mnemonic_unofficial
} else {
palette.mnemonic
},
);
if !disasm.operand.is_empty() {
let _ = part(
format!(" {}", self.named_operand(&disasm.operand)),
palette.operand,
);
}
// Bracketed and tinted apart from the operand that computed it, since it names a second
// address the row did not write down.
if let Some(effective) = disasm.effective_text() {
let _ = part(format!(" [{effective}]"), palette.effective);
}
if let Some(value) = disasm.value {
let _ = part(format!(" = {value}"), palette.resolved);
}
// Last on the line, the way an assembler listing writes one, so the columns before it
// stay where they are whatever was written.
if let Some(comment) = self
.label_at(disasm.addr)
.map(|label| label.comment.trim())
.filter(|comment| !comment.is_empty())
{
let _ = part(format!(" ;{comment}"), palette.comment);
}
(ui.painter().layout_job(job), mnemonic_span)
}
/// What was written about `addr`, under the mapping the window is drawing.
fn label_at(&self, addr: u16) -> Option<&AddrLabel> {
self.labels.get(&LabelKey::new(addr, self.prg_offset(addr)))
}
/// `operand` with the address it names replaced by that address's name.
///
/// Rewritten as text because the operand is already formatted, so `$D094,X` becomes
/// `handler,X` and the addressing mode's punctuation stays where the disassembler put it.
fn named_operand(&self, operand: &str) -> String {
let Some((span, addr)) = operand_address(operand) else {
return operand.to_string();
};
match self.label_at(addr).map(|label| label.name.trim()) {
Some(name) if !name.is_empty() => {
format!("{}{name}{}", &operand[..span.start], &operand[span.end..])
}
_ => operand.to_string(),
}
}
/// Bytes on one row of the memory pane.
const MEMORY_ROW_BYTES: usize = 16;
/// Rows the memory pane covers, which is the whole CPU address space.
const MEMORY_ROWS: usize = 0x1_0000 / Self::MEMORY_ROW_BYTES;
/// How far either side of the rows on screen the console is asked to copy.
const MEMORY_MARGIN: usize = 0x200;
/// The CPU address space as hex bytes, sixteen to a row.
///
/// The console copies a window around the rows on screen rather than the whole 64K, so a byte
/// scrolled to draws as `--` until the snapshot answering the new window arrives.
fn memory(&mut self, ui: &mut Ui) {
ui.horizontal(|ui| {
let response = ui.add(
egui::TextEdit::singleline(&mut self.memory_goto)
.hint_text("$addr")
.desired_width(90.0),
);
let go = submitted(ui, &response) | ui.button("Go").clicked();
if let Some(addr) = parse_addr(&self.memory_goto)
&& go
{
self.memory_scroll_to = Some(addr);
self.memory_edit = Some((addr, String::new()));
}
if ui
.button("PC")
.on_hover_text("Go to the instruction about to run")
.clicked()
{
let pc = self.snapshot.cpu.pc;
self.memory_scroll_to = Some(pc);
self.memory_edit = Some((pc, String::new()));
}
ui.weak(match self.memory_edit {
Some((addr, _)) => {
format!("${addr:04X} selected - type two hex digits to write it.")
}
None => "Click a byte to select it.".to_string(),
});
});
// Typed straight onto the selected byte rather than into a box of its own, which would
// make one row taller than the rest and desynchronize the virtual window below. Skipped
// while a text box has focus, since the same keys are meant to land there.
if ui.memory(|memory| memory.focused().is_none()) {
self.type_memory(ui);
}
let row_height = ui.text_style_height(&egui::TextStyle::Monospace);
ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Extend);
let pitch = row_height + ui.spacing().item_spacing.y;
let viewport_height = ui.available_height();
// Scrolls sideways too, since a row runs to about 74 columns and the pane is resizable
// down past that.
let mut scroll_area = ScrollArea::both()
.id_salt("memory")
.auto_shrink([false, false]);
// Every row is the same height and covers the same count of bytes, so the offset a row
// sits at is exact and one step lands it on the center line.
if let Some(addr) = self.memory_scroll_to.take() {
let row = usize::from(addr) / Self::MEMORY_ROW_BYTES;
let offset = (row as f32).mul_add(pitch, -(viewport_height - row_height) / 2.0);
scroll_area = scroll_area.vertical_scroll_offset(offset.max(0.0));
}
let palette = Palette::new(ui.visuals());
let font = egui::TextStyle::Monospace.resolve(ui.style());
let mut drawn = 0..0;
let mut clicked = None;
scroll_area.show_rows(ui, row_height, Self::MEMORY_ROWS, |ui, range| {
drawn = range.clone();
for row in range {
let base = (row * Self::MEMORY_ROW_BYTES) as u16;
let galley = self.memory_galley(ui, base, &palette, &font);
let width = galley.size().x.max(ui.available_width());
let (rect, _) =
ui.allocate_exact_size(Vec2::new(width, row_height), Sense::hover());
// Centered on the galley's own height rather than the font's, which is shorter
// than the row and would leave the bytes sitting low inside the selection box.
let origin = egui::Pos2::new(rect.left(), rect.center().y - galley.size().y / 2.0);
// Outlined rather than filled, so the digits already typed into it stay readable.
// Measured off the galley rather than off a character width, so the box sits on
// the two digits whatever the font does with them.
if let Some((addr, _)) = self.memory_edit
&& memory_row_holds(base, addr)
{
let column = Self::memory_column(usize::from(addr) % Self::MEMORY_ROW_BYTES);
let left = galley.pos_from_cursor(CCursor::new(column)).left();
let right = galley.pos_from_cursor(CCursor::new(column + 2)).left();
let cell =
Rect::from_x_y_ranges(origin.x + left..=origin.x + right, rect.y_range());
ui.painter().rect_stroke(
cell.expand(1.0),
2.0,
palette.selection,
egui::StrokeKind::Inside,
);
}
let response = ui.interact(rect, ui.id().with(("memory", base)), Sense::click());
if let Some(pos) = response
.interact_pointer_pos()
.filter(|_| response.clicked())
{
let column = galley.cursor_from_pos(pos - origin).index.into();
clicked = Self::memory_index(column).map(|index| base + index as u16);
}
ui.painter().galley(origin, galley, palette.memory_writable);
}
});
self.memory_rows = drawn;
if let Some(addr) = clicked {
self.memory_edit = Some((addr, String::new()));
}
self.follow_memory_rows();
}
/// Where the hex digits of the `index`th byte of a row start, in characters across it.
///
/// Past the address and its two spaces, then two digits and a space each, with the gap after
/// the eighth widened so a byte can be counted off in eights.
const fn memory_column(index: usize) -> usize {
7 + index * 3 + if index >= 8 { 1 } else { 0 }
}
/// Which byte of a row the `column`th character falls on, or `None` between two of them.
fn memory_index(column: usize) -> Option<usize> {
(0..Self::MEMORY_ROW_BYTES).find(|index| {
(Self::memory_column(*index)..Self::memory_column(*index) + 2).contains(&column)
})
}
/// Ask the console for a window covering the rows the last draw put on screen.
fn follow_memory_rows(&mut self) {
let window = memory_window(&self.memory_rows);
if self.memory_window != Some(window) {
self.memory_window = Some(window);
self.resubscribe();
}
}
/// Take what was typed onto the selected byte.
///
/// Two hex digits write it and step on to the next, the arrows move the selection, and Escape
/// drops it. The view follows the selection only on the frame it moves, and only off screen,
/// the way the disassembly follows PC. Following it every frame pulls the pane back as soon
/// as a scroll carries the selection off screen.
fn type_memory(&mut self, ui: &Ui) {
if self.memory_edit.is_none() {
return;
}
let (typed, escape, step) = ui.input(|input| {
let typed = input
.events
.iter()
.filter_map(|event| match event {
egui::Event::Text(text) => Some(text.as_str()),
_ => None,
})
.collect::<String>();
let row = Self::MEMORY_ROW_BYTES as i16;
let step = i16::from(input.key_pressed(egui::Key::ArrowRight))
- i16::from(input.key_pressed(egui::Key::ArrowLeft))
+ row * i16::from(input.key_pressed(egui::Key::ArrowDown))
- row * i16::from(input.key_pressed(egui::Key::ArrowUp));
(typed, input.key_pressed(egui::Key::Escape), step)
});
if escape {
self.memory_edit = None;
return;
}
let mut written = Vec::new();
let Some((addr, digits)) = self.memory_edit.as_mut() else {
return;
};
let mut moved = step != 0;
if step != 0 {
*addr = addr.wrapping_add_signed(step);
digits.clear();
}
for digit in typed.chars().filter(char::is_ascii_hexdigit) {
digits.push(digit);
if digits.len() < 2 {
continue;
}
let val = u8::from_str_radix(digits, 16).expect("two hex digits");
written.push(DebugWrite::Memory { addr: *addr, val });
*addr = addr.wrapping_add(1);
digits.clear();
moved = true;
}
let addr = *addr;
for write in written {
self.tx.event(EmulationEvent::DebugWrite(write));
}
if moved
&& !self
.memory_rows
.contains(&(usize::from(addr) / Self::MEMORY_ROW_BYTES))
{
self.memory_scroll_to = Some(addr);
}
}
/// One row of the memory pane laid out: the address, sixteen bytes, then the same as text.
///
/// A byte the console has not copied draws as `--`, and one nothing can write greys.
fn memory_galley(
&self,
ui: &Ui,
base: u16,
palette: &Palette,
font: &egui::FontId,
) -> Arc<egui::Galley> {
let mut job = egui::text::LayoutJob::default();
let mut part = |text: &str, color: Color32| {
job.append(
text,
0.0,
egui::TextFormat {
font_id: font.clone(),
color,
..Default::default()
},
);
};
part(&format!("${base:04X} "), palette.address);
let mut text = String::with_capacity(Self::MEMORY_ROW_BYTES);
for index in 0..Self::MEMORY_ROW_BYTES {
let addr = base.wrapping_add(index as u16);
let byte = self.memory_byte(addr);
part(
&byte.map_or_else(|| "--".to_string(), |byte| format!("{byte:02X}")),
match byte {
None => palette.bytes,
Some(_) if is_writable(&self.snapshot.prg_pages, addr) => {
palette.memory_writable
}
Some(_) => palette.memory_readonly,
},
);
part(if index == 7 { " " } else { " " }, palette.address);
text.push(match byte {
Some(byte) if byte.is_ascii_graphic() || byte == b' ' => byte as char,
_ => '.',
});
}
part(&format!(" {text}"), palette.resolved);
ui.painter().layout_job(job)
}
/// What the last snapshot had at `addr`, or `None` where the window it answered did not reach.
fn memory_byte(&self, addr: u16) -> Option<u8> {
let offset = addr.wrapping_sub(self.snapshot.memory_start);
self.snapshot.memory.get(usize::from(offset)).copied()
}
fn stack(&mut self, ui: &mut Ui) {
ScrollArea::vertical()
.id_salt("stack")
.auto_shrink([false, false])
.show(ui, |ui| {
if self.snapshot.stack.is_empty() {
ui.weak("No ROM is loaded.");
return;
}
// Top of stack first: SP points at the next free slot, so the most recently pushed
// byte is at SP + 1 and the walk runs upward from there.
let sp = self.snapshot.cpu.sp;
for offset in (u16::from(sp) + 1)..0x0100 {
let Some(value) = self.snapshot.stack.get(usize::from(offset)) else {
break;
};
ui.label(RichText::new(format!("$01{offset:02X} ${value:02X}")).monospace());
}
});
}
/// What is plugged into each port, with its buttons. Clicking one presses or releases it.
///
/// A click sends the same [`EmulationEvent::Joypad`] or [`EmulationEvent::PowerPad`] a key
/// does, so a replay records it, and the button stays as set until a click or a key changes
/// it, so a frame can be stepped with Right held. Ports 3 and 4 are listed only with a
/// four-player adapter. The Zapper row shows the aim, the light sense and the trigger, and
/// Fire pulls the trigger. Aiming stays with the mouse.
fn input(&mut self, ui: &mut Ui) {
// Each button's label for a narrow button, then for one wide enough to spell it out.
const BUTTONS: [(JoypadBtn, &str, &str); 8] = [
(JoypadBtn::Up, "U", "Up"),
(JoypadBtn::Down, "D", "Down"),
(JoypadBtn::Left, "L", "Left"),
(JoypadBtn::Right, "R", "Right"),
(JoypadBtn::Select, "SEL", "Select"),
(JoypadBtn::Start, "STA", "Start"),
(JoypadBtn::B, "B", "B"),
(JoypadBtn::A, "A", "A"),
];
// Wide enough for six monospace characters plus the button's padding.
const WIDE: f32 = 56.0;
const ROW_HEIGHT: f32 = 20.0;
let snapshot = &self.snapshot;
let ports: &[Player] = if snapshot.four_player == FourPlayer::Disabled {
&[Player::One, Player::Two]
} else {
&[Player::One, Player::Two, Player::Three, Player::Four]
};
let device = |player: Player| match player {
Player::One => snapshot.ports[0],
Player::Two => snapshot.ports[1],
Player::Three | Player::Four => PortDevice::Joypad,
};
// The Family Trainer reads the same mat state a port's Power Pad does, so it gets a row of
// its own only when no port already draws the mat.
let trainer_mat = snapshot.expansion == ExpansionDevice::FamilyTrainer
&& !snapshot.ports.contains(&PortDevice::PowerPad);
const LABEL_WIDTH: f32 = 32.0;
let gap = ui.spacing().item_spacing.x;
// Buttons share the width left of the label evenly, so a wide pane gets wide buttons
// rather than a cluster at the left edge.
let button_size = |ui: &Ui, count: f32| {
let width = (ui.available_width() - LABEL_WIDTH - gap * count) / count;
Vec2::new(width.clamp(24.0, 72.0), ROW_HEIGHT)
};
let label = |ui: &mut Ui, text: &str| {
ui.add_sized(
[LABEL_WIDTH, ROW_HEIGHT],
Label::new(RichText::new(text).strong()),
);
};
let mut event = None;
let mat = |ui: &mut Ui, row: &str, event: &mut Option<EmulationEvent>| {
let size = button_size(ui, 4.0);
// Three rows of four, numbered the way the mat prints them.
for first in [1, 5, 9] {
ui.horizontal(|ui| {
label(ui, if first == 1 { row } else { "" });
for button in first..first + 4 {
let on = snapshot.power_pad.button(button);
let name = format!("Mat {button}");
if toggle_button(ui, &button.to_string(), &name, on, size) {
*event = Some(EmulationEvent::PowerPad((button, press_state(!on))));
}
}
});
}
};
ScrollArea::vertical()
.id_salt("input")
.auto_shrink([false, false])
.show(ui, |ui| {
for &player in ports {
let row = format!("P{}", player as usize + 1);
match device(player) {
PortDevice::Joypad => {
let held = snapshot.joypads[player as usize];
let size = button_size(ui, BUTTONS.len() as f32);
ui.horizontal(|ui| {
label(ui, &row);
for (button, short, long) in BUTTONS {
let on = held.contains(button.into());
let text = if size.x >= WIDE { long } else { short };
if toggle_button(ui, text, button.as_ref(), on, size) {
event = Some(EmulationEvent::Joypad((
player,
button,
press_state(!on),
)));
}
}
});
}
PortDevice::Zapper => {
ui.horizontal(|ui| {
label(ui, &row);
if zapper_row(ui, &snapshot.zapper, snapshot.zapper_light) {
event = Some(EmulationEvent::ZapperTrigger);
}
});
}
PortDevice::PowerPad => mat(ui, &row, &mut event),
// A device this panel has no controls for yet still gets its row.
other => {
ui.horizontal(|ui| {
label(ui, &row);
ui.label(other.to_string());
});
}
}
}
if trainer_mat {
mat(ui, "Mat", &mut event);
}
});
if let Some(event) = event {
self.tx.event(event);
}
}
}
/// The Zapper's aim, light sense and trigger, plus a Fire button. Returns whether Fire was
/// clicked.
fn zapper_row(ui: &mut Ui, zapper: &Zapper, light: bool) -> bool {
let mark = |ui: &mut Ui, name: &str, on: bool, hover: &str| {
let text = if on {
RichText::new(name).monospace().strong()
} else {
RichText::new(name).monospace().color(Color32::DARK_GRAY)
};
ui.label(text).on_hover_text(hover);
};
ui.monospace(format!("X {:3} Y {:3}", zapper.x, zapper.y))
.on_hover_text("Where the Zapper is aimed, in screen pixels.");
mark(
ui,
"LIGHT",
light,
if light {
"Aimed at a bright pixel. The game senses it in the scanlines just after the PPU \
draws it."
} else {
"Aimed at a dark pixel, or off the screen."
},
);
let pulled = zapper.is_triggered();
mark(
ui,
"TRIGGER",
pulled,
if pulled {
"Trigger: pulled. It releases itself after about 100ms of emulated time."
} else {
"Trigger: released."
},
);
ui.button("Fire")
.on_hover_text("Pull the trigger, as a click on the game screen does.")
.clicked()
}
/// A button the Input pane toggles, filled while held. Returns whether it was clicked.
fn toggle_button(ui: &mut Ui, label: &str, name: &str, on: bool, size: Vec2) -> bool {
let text = if on {
RichText::new(label).monospace().strong()
} else {
RichText::new(label).monospace()
};
ui.add(egui::Button::new(text).selected(on).min_size(size))
.on_hover_text(format!(
"{name}: {}. Click to {}.",
if on { "held" } else { "released" },
if on { "release" } else { "press" },
))
.clicked()
}
/// The key state a click that presses (`true`) or releases (`false`) a button stands for.
const fn press_state(press: bool) -> ElementState {
if press {
ElementState::Pressed
} else {
ElementState::Released
}
}
#[cfg(test)]
mod tests {
use super::{
AddrLabel, AddressSpace, BlockKind, Breakpoint, Breakpoints, Column, CpuSnapshot, HashMap,
LabelKey, PRG_PAGES, Page, Pane, Row, State, is_mapped, memory_row_holds, memory_window,
operand_address, parse_addr, parse_range, prg_offset, request, row_is_visible, watch_value,
};
use crate::nes::renderer::gui::panes::Pane as _;
/// The addresses of what the console was told to arm, which is all these tests look at.
fn armed_at(breakpoints: &Breakpoints) -> Vec<u16> {
breakpoints
.armed()
.into_iter()
.map(|breakpoint| breakpoint.start)
.collect()
}
use tetanes_core::{control_deck::ControlDeck, cpu::Cpu, debug::Access};
const HISTORY_LINES: u16 = 8;
/// The column stacks all but one pane at a fixed height and gives the last what is left, so
/// closing a pane redistributes space inside the column rather than resizing the window.
#[test]
fn the_last_open_pane_in_a_column_takes_what_is_left() {
let (sized, filling) = Column::Right
.tiling(Pane::ALL)
.expect("the right column has panes");
// Read off `Pane::ALL` rather than written out, so this pins the rule and adding a pane
// does not rewrite it.
let (last, rest) = Pane::ALL
.iter()
.copied()
.filter(|pane| pane.column() == Column::Right)
.collect::<Vec<_>>()
.split_last()
.map(|(last, rest)| (*last, rest.to_vec()))
.expect("the right column has panes");
assert_eq!(sized, rest);
assert_eq!(filling, last);
}
/// A column that reports nothing is not drawn, so it takes no width or height from the rest.
#[test]
fn a_column_with_nothing_open_is_not_drawn() {
assert_eq!(Column::Bottom.tiling(&[Pane::Disassembly]), None);
assert_eq!(Column::Right.tiling(&[Pane::Disassembly]), None);
}
/// [`Column::ALL`] reaches every column, and every column places its panes, so no open pane
/// goes undrawn.
#[test]
fn every_pane_is_laid_out_in_exactly_one_column() {
let mut placed = Vec::new();
for column in Column::ALL {
if let Some((sized, filling)) = column.tiling(Pane::ALL) {
placed.extend(sized);
placed.push(filling);
}
}
for pane in Pane::ALL.iter().copied() {
let times = placed.iter().filter(|other| **other == pane).count();
assert_eq!(times, 1, "{pane:?} was laid out {times} times");
}
assert_eq!(placed.len(), Pane::ALL.len());
}
/// Some boards run code out of cart RAM, and a range that only ever reads as `save ram` gives
/// a console stopped in there no row to sit on. The code map has seen it execute, so the
/// sweep asks rather than taking everything below `$8000` for data.
#[test]
fn cart_ram_that_has_executed_is_disassembled() {
let mut deck = ControlDeck::new();
deck.load_rom_path("../tetanes-core/test_roms/spritecans.nes")
.expect("load rom");
deck.attach_code_map(None);
// `LDA #$00` in cart RAM, run from there the way a board that copies a routine into RAM
// reaches it.
deck.bus_mut().write(0x6000, 0xA9);
deck.bus_mut().write(0x6001, 0x00);
deck.bus_mut().cpu.pc = 0x6000;
deck.bus_mut().clock_instr();
let space = AddressSpace::capture(deck.bus(), &HashMap::new());
let row = space.row_at(0x6000).expect("covered");
assert!(
matches!(space.rows[row], Row::Instruction(_)),
"$6000 executed but reads as {:?}",
space.rows[row]
);
// A neighbor nothing has run stays collapsed, so the whole range does not decode blind.
let untouched = space.row_at(0x7F00).expect("covered");
assert!(matches!(
space.rows[untouched],
Row::Block {
kind: BlockKind::SaveRam,
..
}
));
}
/// Stepping walks the highlight down rows already on screen, so only a PC that lands outside
/// them moves the view. Centering on every step jogs the disassembly once per instruction.
#[test]
fn only_a_pc_off_screen_moves_the_disassembly() {
let deck = ControlDeck::new();
let address_space = AddressSpace::capture(deck.bus(), &HashMap::new());
let row = address_space.row_at(0x1234).expect("covered");
assert!(row_is_visible(&address_space, &(row..row + 4), 0x1234));
assert!(!row_is_visible(&address_space, &(row + 1..row + 4), 0x1234));
assert!(
!row_is_visible(&address_space, &(0..0), 0x1234),
"a window that has yet to draw has to center on its first snapshot"
);
}
/// A closed pane draws nothing, so the console is asked for nothing on its behalf.
#[test]
fn closing_a_pane_drops_what_only_it_draws() {
let window = Some((0x0200, 0x0400));
let all = request(Pane::ALL, HISTORY_LINES, window);
assert_eq!(all.history_lines, HISTORY_LINES);
assert!(all.stack);
assert!(all.call_stack);
assert_eq!(all.memory, window);
let closed = Pane::ALL
.iter()
.copied()
.filter(|pane| {
!matches!(
pane,
Pane::History | Pane::Stack | Pane::CallStack | Pane::Memory
)
})
.collect::<Vec<_>>();
let request = request(&closed, HISTORY_LINES, window);
assert_eq!(request.history_lines, 0);
assert!(!request.stack);
assert!(!request.call_stack);
assert_eq!(request.memory, None);
}
/// A click lands on the byte it points at. This is the arithmetic tying the hit test to the
/// row `memory_galley` lays out, and one column out of step puts a neighbor into edit.
#[test]
fn every_hex_cell_hit_tests_back_to_its_own_byte() {
assert_eq!(
State::memory_column(0),
7,
"past the address and the two spaces after it"
);
assert_eq!(
State::memory_column(8),
32,
"past the wider gap down the middle"
);
for index in 0..State::MEMORY_ROW_BYTES {
let column = State::memory_column(index);
assert_eq!(State::memory_index(column), Some(index), "byte {index}");
assert_eq!(
State::memory_index(column + 1),
Some(index),
"byte {index}, second digit"
);
assert_eq!(
State::memory_index(column + 2),
None,
"the gap after byte {index}"
);
}
assert_eq!(State::memory_index(0), None, "the address column");
}
/// The window has to cover the rows on screen, or they draw as `--` however long it is looked
/// at, and it has to stay inside the address space, since a `u16` length cannot say 64K.
#[test]
fn the_memory_window_covers_the_rows_on_screen() {
for rows in [0..12usize, 0..1, 100..140, 4084..4096, 0..4096] {
let (start, len) = memory_window(&rows);
let first = rows.start * State::MEMORY_ROW_BYTES;
let last = rows.end * State::MEMORY_ROW_BYTES;
assert!(
usize::from(start) <= first,
"{rows:?} starts at ${start:04X}"
);
assert!(
usize::from(start) + usize::from(len) >= last || len == 0xFF00,
"{rows:?} runs to ${:04X}",
usize::from(start) + usize::from(len)
);
assert!(
usize::from(start) + usize::from(len) <= 0x1_0000,
"{rows:?} runs past the address space"
);
}
}
/// A name heads the row it belongs to rather than replacing it, and `row_at` still lands on
/// the row that owns the address, so a go-to selects the instruction and not the name over it.
#[test]
fn a_named_address_gains_a_row_above_the_one_it_names() {
let mut deck = ControlDeck::new();
deck.load_rom_path("../tetanes-core/test_roms/spritecans.nes")
.expect("load rom");
let plain = AddressSpace::capture(deck.bus(), &HashMap::new());
let pc = deck.bus().cpu.pc;
let key = LabelKey::new(pc, prg_offset(deck.bus().memory.prg_pages(), pc));
let labels = HashMap::from([(
key,
AddrLabel {
name: "entry".to_string(),
comment: String::new(),
},
)]);
let named = AddressSpace::capture(deck.bus(), &labels);
// At least one: a board that mirrors a bank into two windows puts the same cart bytes at
// two addresses, and a name filed by offset belongs to both of them.
assert!(named.rows.len() > plain.rows.len(), "rows were added");
let row = named.row_at(pc).expect("covered");
assert!(
named.rows[row].covers(pc),
"a go-to lands on the row the name is over, not the name"
);
assert!(
matches!(&named.rows[row - 1], Row::Label { name, .. } if name == "entry"),
"the name sits directly above it"
);
}
/// A name is put into an operand by rewriting the address it names, so what counts as an
/// address decides which rows get one. Two digits do not: a name over those would rewrite
/// `$10` in every row that touches zero page.
/// The last row starts at `$FFF0`, where one past its end wraps to `$0000`. A range there is
/// empty, so the byte a click selects would be written with nothing on screen to say so.
#[test]
fn the_memory_row_at_the_top_of_the_address_space_still_holds_its_bytes() {
assert!(
memory_row_holds(0xFFF0, 0xFFF0),
"the first of the last row"
);
assert!(memory_row_holds(0xFFF0, 0xFFFF), "and the last of it");
assert!(!memory_row_holds(0xFFF0, 0x0000), "which does not wrap on");
assert!(!memory_row_holds(0xFFF0, 0xFFEF), "or reach back");
assert!(memory_row_holds(0x0000, 0x000F));
assert!(!memory_row_holds(0x0000, 0x0010));
}
#[test]
fn only_a_full_address_in_an_operand_takes_a_name() {
let found = |operand: &str| {
operand_address(operand).map(|(span, addr)| (span.start, span.end, addr))
};
assert_eq!(found("$D094"), Some((0, 5, 0xD094)));
assert_eq!(
found("$D094,X"),
Some((0, 5, 0xD094)),
"the index stays outside the span"
);
assert_eq!(
found("($D094),Y"),
Some((1, 6, 0xD094)),
"and so do the brackets"
);
assert_eq!(found("$94"), None, "a zero page operand");
assert_eq!(found("#$42"), None, "an immediate");
assert_eq!(found(""), None, "no operand at all");
}
#[test]
fn an_address_parses_with_or_without_its_sigil() {
assert_eq!(parse_addr("$C04F"), Some(0xC04F));
assert_eq!(parse_addr(" c04f "), Some(0xC04F));
assert_eq!(parse_addr(""), None);
assert_eq!(parse_addr("$1C04F"), None, "wider than the address bus");
assert_eq!(parse_addr("$C04G"), None);
}
/// Clicking a row in the disassembly is both how a breakpoint is set and how it is cleared.
#[test]
fn toggling_an_address_adds_a_breakpoint_and_toggling_it_again_removes_it() {
let mut breakpoints = Breakpoints::default();
breakpoints.toggle(0xC000, None);
assert_eq!(armed_at(&breakpoints), [0xC000]);
breakpoints.toggle(0xC000, None);
assert!(breakpoints.is_empty());
}
/// The list is drawn in the order it is kept, which is the order the disassembly reads in.
#[test]
fn breakpoints_are_held_in_address_order_however_they_are_added() {
let mut breakpoints = Breakpoints::default();
for addr in [0xE000, 0x8000, 0xC000] {
breakpoints.add(Breakpoint::execute(addr, None));
}
assert_eq!(armed_at(&breakpoints), [0x8000, 0xC000, 0xE000]);
}
/// The box takes one address or a range, and a range typed backwards says plainly enough
/// what was meant.
#[test]
fn a_breakpoint_range_parses_either_way_round() {
assert_eq!(parse_range("$C000"), Some((0xC000, 0xC000)));
assert_eq!(parse_range("$C000-$C0FF"), Some((0xC000, 0xC0FF)));
assert_eq!(parse_range("0xC0FF-0xC000"), Some((0xC000, 0xC0FF)));
assert_eq!(parse_range("$C000-"), None);
}
/// An `offset` indexes one cart's arena, so a breakpoint carrying one means nothing against
/// the next cart. A breakpoint on work RAM or the registers is as true for one cart as the
/// next.
#[test]
fn a_cart_change_drops_the_breakpoints_that_named_it() {
let mut breakpoints = Breakpoints::default();
breakpoints.add(Breakpoint::execute(0x8000, Some(0x4000)));
breakpoints.add(Breakpoint::execute(0x0300, None));
breakpoints.retain_without_cart();
assert_eq!(armed_at(&breakpoints), [0x0300]);
}
/// A condition still being typed does not parse, and arming the breakpoint without it would
/// stop on every access the range covers rather than the few that were asked for.
#[test]
fn a_breakpoint_whose_condition_does_not_parse_is_not_armed() {
let mut breakpoints = Breakpoints::default();
breakpoints.add(Breakpoint::execute(0xC000, None));
for breakpoint in breakpoints.iter_mut() {
breakpoint.condition = "a ==".to_string();
}
assert!(breakpoints.armed().is_empty());
assert!(
!breakpoints.is_empty(),
"it stays listed so the rest can be typed"
);
for breakpoint in breakpoints.iter_mut() {
breakpoint.condition = "a == 0x42".to_string();
}
assert_eq!(armed_at(&breakpoints), [0xC000]);
}
/// A breakpoint with no access ticked stops nothing, so the console is not told about it.
#[test]
fn a_breakpoint_with_no_access_selected_is_not_armed() {
let mut breakpoints = Breakpoints::default();
breakpoints.add(Breakpoint::execute(0xC000, None));
for breakpoint in breakpoints.iter_mut() {
breakpoint.access = Access::empty();
}
assert!(breakpoints.armed().is_empty());
assert!(
!breakpoints.is_empty(),
"it stays listed so its ticks can be put back"
);
}
/// The same address in two banks is two instructions, so each keeps a breakpoint of its own
/// and removing one leaves the other.
#[test]
fn an_address_holds_a_breakpoint_for_each_bank() {
let mut breakpoints = Breakpoints::default();
let first = breakpoints
.add(Breakpoint::execute(0x8000, Some(0x4000)))
.expect("added");
let second = breakpoints
.add(Breakpoint::execute(0x8000, Some(0x8000)))
.expect("added");
assert_eq!(armed_at(&breakpoints), [0x8000, 0x8000]);
assert!(breakpoints.remove(first));
assert_eq!(
breakpoints.get(second).map(|bp| bp.offset),
Some(Some(0x8000)),
"removing one bank's breakpoint took the other bank's with it"
);
}
/// One address holds as many breakpoints as are set on it. A range and a single address are
/// different questions, and so are two accesses of one byte under different conditions.
#[test]
fn one_address_holds_as_many_breakpoints_as_are_set_on_it() {
let mut breakpoints = Breakpoints::default();
breakpoints.add(Breakpoint::execute(0x6000, None));
breakpoints.add(Breakpoint::range(0x6000, 0x7FFF, None));
assert_eq!(armed_at(&breakpoints), [0x6000, 0x6000]);
let unmapped = [Page::UNMAPPED; PRG_PAGES];
assert_eq!(breakpoints.covering(0x6000, &unmapped).count(), 2);
assert_eq!(
breakpoints.covering(0x6500, &unmapped).count(),
1,
"a range marks every row it covers, not only the one it starts on"
);
assert_eq!(breakpoints.covering(0x8000, &unmapped).count(), 0);
}
/// A gutter click owns the breakpoint on exactly its address, and a range covering the row
/// is not it.
#[test]
fn a_gutter_toggle_leaves_a_range_covering_the_row_alone() {
let mut breakpoints = Breakpoints::default();
breakpoints.add(Breakpoint::range(0x6000, 0x7FFF, None));
breakpoints.toggle(0x6000, None);
assert_eq!(armed_at(&breakpoints), [0x6000, 0x6000], "added its own");
breakpoints.toggle(0x6000, None);
assert_eq!(armed_at(&breakpoints), [0x6000], "took its own back");
assert!(
breakpoints.single_at(0x6000, None).is_none(),
"the range answered for a single address"
);
}
/// The window keys a breakpoint by the offset it resolves from its own copy of the page
/// table, and the console checks it against the arena. A copy that disagreed would arm
/// breakpoints on bytes the console never maps there.
#[test]
fn the_window_resolves_the_same_offsets_the_console_does() {
let mut deck = ControlDeck::new();
deck.load_rom_path("../tetanes-core/test_roms/spritecans.nes")
.expect("load rom");
let snapshot = CpuSnapshot::capture(deck.bus(), &request(Pane::ALL, 8, None));
for addr in [0x0300u16, 0x2000, 0x6000, 0x8000, 0xC000, 0xFFFF] {
assert_eq!(
prg_offset(&snapshot.prg_pages, addr),
deck.bus()
.memory
.prg_offset(addr)
.map(|offset| u32::try_from(offset).expect("fits the arena")),
"${addr:04X}"
);
}
}
/// A bank that is no longer mapped resolves to no offset, so the list greys the breakpoint
/// rather than leaving it looking armed.
#[test]
fn a_breakpoint_whose_bank_is_gone_reads_as_unmapped() {
let unmapped = [Page::UNMAPPED; PRG_PAGES];
assert!(is_mapped(&unmapped, &Breakpoint::execute(0x0300, None)));
assert!(!is_mapped(
&unmapped,
&Breakpoint::execute(0x8000, Some(0x4000))
));
}
/// Adding is not toggling: typing an address that is already listed adds a second breakpoint
/// on it rather than clearing the first.
#[test]
fn adding_an_address_twice_leaves_both_breakpoints() {
let mut breakpoints = Breakpoints::default();
let first = breakpoints
.add(Breakpoint::execute(0xC000, None))
.expect("added");
let second = breakpoints
.add(Breakpoint::execute(0xC000, None))
.expect("added");
assert_eq!(armed_at(&breakpoints), [0xC000, 0xC000]);
assert_ne!(first, second, "the second took the first one's name");
}
/// A watch's width follows its value, so a column of bytes does not read as addresses. Only a
/// comparison or a subtraction goes negative, where hex says nothing.
#[test]
fn a_watch_is_written_at_the_width_of_its_value() {
assert_eq!(watch_value(0x42, false), "$42 66");
assert_eq!(watch_value(0xFF, false), "$FF 255");
assert_eq!(watch_value(0x0100, false), "$0100 256");
assert_eq!(watch_value(0xFFFF, false), "$FFFF 65535");
assert_eq!(watch_value(-1, false), "-1");
assert_eq!(watch_value(0, true), "false");
assert_eq!(watch_value(1, true), "true");
}
/// The editor's address box round-trips a breakpoint's own range, so opening the editor and
/// closing it again leaves the breakpoint where it was.
#[test]
fn the_editor_reads_back_the_range_it_writes() {
for (addr, end) in [(0xC000, 0xC000), (0x6000, 0x7FFF)] {
let breakpoint = Breakpoint::range(addr, end, None);
assert_eq!(
parse_range(&breakpoint.range_text()),
Some((addr, end)),
"${addr:04X}-${end:04X}"
);
}
}
/// An id names one breakpoint for as long as it is listed. Handing a removed one out again
/// would let the open editor, or a click already in flight, land on whatever took its place.
#[test]
fn an_id_is_never_handed_out_twice() {
let mut breakpoints = Breakpoints::default();
let first = breakpoints
.add(Breakpoint::execute(0xC000, None))
.expect("added");
breakpoints.remove(first);
let second = breakpoints
.add(Breakpoint::execute(0xC000, None))
.expect("added");
assert_ne!(first, second);
assert!(breakpoints.get(first).is_none());
}
/// Disabling keeps a breakpoint in the list and out of what the console is told to stop at.
#[test]
fn a_disabled_breakpoint_stays_listed_but_is_not_armed() {
let mut breakpoints = Breakpoints::default();
breakpoints.add(Breakpoint::execute(0xC000, None));
breakpoints.add(Breakpoint::execute(0xD000, None));
let disabled = breakpoints.single_at(0xC000, None).expect("listed");
breakpoints.get_mut(disabled).expect("listed").enabled = false;
assert_eq!(armed_at(&breakpoints), [0xD000]);
assert!(
breakpoints.get(disabled).is_some_and(|bp| !bp.enabled),
"a disabled breakpoint was dropped rather than kept"
);
}
/// With no cart loaded nothing is disassembled, which makes this a test of the sweep itself:
/// that it covers every address exactly once and terminates at `$FFFF` rather than wrapping.
#[test]
fn the_sweep_covers_the_whole_address_space_in_order() {
let deck = ControlDeck::new();
let address_space = AddressSpace::capture(deck.bus(), &HashMap::new());
let mut next = 0u32;
for row in &address_space.rows {
assert_eq!(u32::from(row.addr()), next, "gap or overlap at ${next:04X}");
next = match row {
Row::Block { end, .. } => u32::from(*end) + 1,
Row::Instruction(_) | Row::Label { .. } => u32::from(row.addr()) + 1,
};
}
assert_eq!(next, 0x1_0000, "sweep stopped short of the end");
}
#[test]
fn ram_and_registers_are_blocks_rather_than_disassembly() {
let deck = ControlDeck::new();
let address_space = AddressSpace::capture(deck.bus(), &HashMap::new());
let kind_at = |addr: u16| {
let row = address_space.row_at(addr).expect("covered");
match address_space.rows[row] {
Row::Block { kind, .. } => Some(kind),
Row::Instruction(_) | Row::Label { .. } => None,
}
};
assert_eq!(kind_at(0x0000), Some(BlockKind::Ram));
assert_eq!(kind_at(0x1FFF), Some(BlockKind::Ram));
assert_eq!(kind_at(0x2000), Some(BlockKind::Registers));
// Nothing is banked in without a cart.
assert_eq!(kind_at(0x8000), Some(BlockKind::Unmapped));
}
/// A decoded range cannot tell where instructions begin, so it decodes straight through data
/// and stays misaligned. Landing mid-row leaves PC with no row of its own and nothing for the
/// view to highlight.
#[test]
fn pc_always_starts_a_row_however_misaligned_the_sweep_is() {
let mut deck = ControlDeck::new();
deck.load_rom_path("../tetanes-core/test_roms/spritecans.nes")
.expect("load rom");
for _ in 0..10 {
let _ = deck.clock_frame().expect("clock frame");
}
// An address strictly inside a multi-byte instruction: the sweep decoded across it, so
// without a pc anchor there is no row that starts there and nothing for the view to mark.
let swept = AddressSpace::capture(deck.bus(), &HashMap::new());
let interior = swept
.rows
.windows(2)
.find_map(|pair| match &pair[0] {
Row::Instruction(line) if pair[1].addr() > line.addr + 1 => Some(line.addr + 1),
_ => None,
})
.expect("a multi-byte instruction somewhere in the sweep");
assert_ne!(
swept.rows[swept.row_at(interior).expect("covered")].addr(),
interior,
"the chosen address was already a row start, so this proves nothing"
);
// Landing there is what stepping into a call does when the sweep is out of step with the
// real instruction boundaries.
deck.bus_mut().cpu.pc = interior;
let anchored = AddressSpace::capture(deck.bus(), &HashMap::new());
let row = anchored.row_at(interior).expect("covered");
assert_eq!(
anchored.rows[row].addr(),
interior,
"PC ${interior:04X} fell inside a row instead of starting one"
);
}
/// The aligned case, which is the common one: anchoring on it rather than strictly after it
/// ends a row where it began and resumes at the same address, sweeping forever.
#[test]
fn pc_already_starting_a_row_still_terminates() {
let mut deck = ControlDeck::new();
deck.load_rom_path("../tetanes-core/test_roms/spritecans.nes")
.expect("load rom");
for _ in 0..10 {
let _ = deck.clock_frame().expect("clock frame");
}
let swept = AddressSpace::capture(deck.bus(), &HashMap::new());
let aligned = swept
.rows
.iter()
.find_map(|row| match row {
Row::Instruction(line) => Some(line.addr),
Row::Block { .. } | Row::Label { .. } => None,
})
.expect("a disassembled row");
deck.bus_mut().cpu.pc = aligned;
let anchored = AddressSpace::capture(deck.bus(), &HashMap::new());
let row = anchored.row_at(aligned).expect("covered");
assert_eq!(anchored.rows[row].addr(), aligned);
// One row per address at worst, so anything beyond that means rows were emitted without
// advancing.
assert!(anchored.rows.len() <= 0x1_0000, "sweep emitted extra rows");
}
/// Without a code map the sweep decodes every mapped byte, which is how data ends up rendered
/// as instructions and the decode stays out of step with the real boundaries. With one, only
/// bytes that have run are decoded and the rest collapses into `unknown`.
#[test]
fn only_bytes_that_have_executed_are_disassembled() {
let mut deck = ControlDeck::new();
deck.load_rom_path("../tetanes-core/test_roms/spritecans.nes")
.expect("load rom");
deck.attach_code_map(None);
for _ in 0..10 {
let _ = deck.clock_frame().expect("clock frame");
}
let mapped = AddressSpace::capture(deck.bus(), &HashMap::new());
let pc = deck.bus().cpu.pc;
let code_map = deck.code_map().expect("recording");
for row in &mapped.rows {
if let Row::Instruction(line) = row
&& line.addr != pc
{
let offset = deck.bus().memory.prg_offset(line.addr).expect("mapped");
assert!(
code_map.is_code(offset),
"${:04X} was disassembled without having run",
line.addr
);
}
}
assert!(
mapped.rows.iter().any(|row| matches!(
row,
Row::Block {
kind: BlockKind::Unknown,
..
}
)),
"ten frames cannot have executed the whole ROM"
);
// The same console with the map taken away, which leaves the sweep decoding all of it.
deck.detach_code_map();
let blind = AddressSpace::capture(deck.bus(), &HashMap::new());
let instructions = |space: &AddressSpace| {
space
.rows
.iter()
.filter(|row| matches!(row, Row::Instruction(_)))
.count()
};
assert!(
instructions(&mapped) < instructions(&blind),
"the map disassembled as much as decoding blind did, so it changed nothing"
);
}
/// A debugger that has just attached has an empty map, so PC would otherwise be the only
/// decoded row on screen. Straight-line flow from PC is decodable without having run.
#[test]
fn the_routine_at_pc_is_decoded_before_anything_has_run() {
let mut deck = ControlDeck::new();
deck.load_rom_path("../tetanes-core/test_roms/spritecans.nes")
.expect("load rom");
deck.attach_code_map(None);
let rows = AddressSpace::capture(deck.bus(), &HashMap::new()).rows;
let pc = deck.bus().cpu.pc;
let from_pc = rows
.iter()
.skip_while(|row| row.addr() != pc)
.take_while(|row| matches!(row, Row::Instruction(_)))
.count();
assert!(
from_pc > 1,
"only {from_pc} row(s) decoded at PC ${pc:04X} with an empty code map"
);
// The run ends at the first instruction that does not reach the next address, and the
// bytes after it are unknown until something executes them.
let end = rows
.iter()
.skip_while(|row| row.addr() != pc)
.take(from_pc)
.last()
.expect("a decoded run");
let Row::Instruction(line) = end else {
unreachable!("take_while kept only instructions")
};
let instr = Cpu::INSTR_REF[usize::from(deck.bus().peek(line.addr))].instr;
assert!(
!instr.falls_through(),
"the run stopped at {instr:?} at ${:04X}, which reaches the next address",
line.addr
);
}
/// PC is about to run whether or not it has run before, so it starts an instruction even where
/// the map says nothing. Without that it would fall inside an `unknown` block with no row of
/// its own for the view to highlight.
#[test]
fn pc_starts_a_row_even_where_nothing_has_executed() {
let mut deck = ControlDeck::new();
deck.load_rom_path("../tetanes-core/test_roms/spritecans.nes")
.expect("load rom");
deck.attach_code_map(None);
for _ in 0..10 {
let _ = deck.clock_frame().expect("clock frame");
}
// Strictly inside an unknown block, so nothing but PC itself can start a row there.
let unexecuted = AddressSpace::capture(deck.bus(), &HashMap::new())
.rows
.iter()
.find_map(|row| match row {
Row::Block {
start,
end,
kind: BlockKind::Unknown,
} if *start >= 0x8000 && end > start => Some(start + 1),
_ => None,
})
.expect("some of the ROM has not run");
deck.bus_mut().cpu.pc = unexecuted;
let anchored = AddressSpace::capture(deck.bus(), &HashMap::new());
let row = anchored.row_at(unexecuted).expect("covered");
assert_eq!(
anchored.rows[row].addr(),
unexecuted,
"PC ${unexecuted:04X} fell inside an unknown block instead of starting a row"
);
}
#[test]
fn an_address_inside_a_block_finds_that_block() {
let deck = ControlDeck::new();
let address_space = AddressSpace::capture(deck.bus(), &HashMap::new());
let row = address_space.row_at(0x1234).expect("covered");
match address_space.rows[row] {
Row::Block { start, end, .. } => assert!(start <= 0x1234 && 0x1234 <= end),
Row::Instruction(_) | Row::Label { .. } => panic!("work ram should be a block"),
}
}
}