systemless 0.1.76

High-Level Emulation for classic Macintosh applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
//! Fixture Runner - Loading and execution infrastructure

use crate::cpu::{M68kCpu, Register, StepResult};
use crate::loader::{
    ApplicationSizeResource, Code0Header, CodeSegmentHeader, JumpTableEntry, LoadedApp,
};
use crate::managers::resource::ResourceFork;
use crate::memory::{MacMemoryBus, MemoryBus};
use crate::trap::TrapDispatcher;
use crate::ui_theme::{ThemeMetricsMode, UiTheme, UiThemeId};
use crate::{Error, Result};
use std::collections::HashMap;
use std::time::{Instant, SystemTime, UNIX_EPOCH};

// Cache env-var lookups (per-call syscall otherwise).
use std::sync::OnceLock;
static TRACE_DIALOG_FILTER: OnceLock<bool> = OnceLock::new();
static TRACE_TIMER: OnceLock<bool> = OnceLock::new();
static TRACE_VBL: OnceLock<bool> = OnceLock::new();
static TRACE_SOUND_RUNNER: OnceLock<bool> = OnceLock::new();
static TRACE_DIALOG_PROCS: OnceLock<bool> = OnceLock::new();

const APP_ZONE_HEADER_SIZE: u32 = 64;
const APP_STACK_SAFETY_MARGIN: u32 = 0x2000;

fn trace_dialog_filter_enabled() -> bool {
    *TRACE_DIALOG_FILTER
        .get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_DIALOG_FILTER").is_some())
}

fn trace_timer_enabled() -> bool {
    *TRACE_TIMER.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_TIMER").is_some())
}

fn trace_vbl_enabled() -> bool {
    *TRACE_VBL.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_VBL").is_some())
}

fn trace_sound_runner_enabled() -> bool {
    *TRACE_SOUND_RUNNER.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_SOUND").is_some())
}

fn trace_dialog_procs_enabled() -> bool {
    *TRACE_DIALOG_PROCS.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_DIALOG_PROCS").is_some())
}

// Gate the per-instruction trace_buffer behind an env var. The buffer
// is populated on EVERY instruction fetch and only used from
// `dump_trace()` on halt/crash. Default-disabled saves per-instruction
// `VecDeque` pop_front + push_back + an extra `bus.read_word` + 6
// register reads. Enable with `SYSTEMLESS_TRACE_BUFFER=1` when diagnosing
// a crash.
#[cfg(not(target_arch = "wasm32"))]
static TRACE_BUFFER_ENABLED: OnceLock<bool> = OnceLock::new();
fn trace_buffer_enabled() -> bool {
    #[cfg(target_arch = "wasm32")]
    {
        return false;
    }
    #[cfg(not(target_arch = "wasm32"))]
    *TRACE_BUFFER_ENABLED.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_BUFFER").is_some())
}

#[cfg(not(target_arch = "wasm32"))]
static TRACE_PC_RANGE: OnceLock<Option<(u32, u32)>> = OnceLock::new();
#[cfg(not(target_arch = "wasm32"))]
static TRACE_PC_RANGE_TICKS: OnceLock<Option<(Option<u32>, Option<u32>)>> = OnceLock::new();
#[cfg(not(target_arch = "wasm32"))]
fn trace_pc_range() -> Option<(u32, u32)> {
    *TRACE_PC_RANGE.get_or_init(|| {
        let value = std::env::var("SYSTEMLESS_TRACE_PC_RANGE").ok()?;
        let mut parts = value.split(':');
        let start = parts.next()?.trim();
        let end = parts.next()?.trim();
        let parse = |s: &str| u32::from_str_radix(s.trim_start_matches("0x"), 16).ok();
        Some((parse(start)?, parse(end)?))
    })
}

#[cfg(not(target_arch = "wasm32"))]
fn trace_pc_range_ticks() -> Option<(Option<u32>, Option<u32>)> {
    *TRACE_PC_RANGE_TICKS.get_or_init(|| {
        let min = std::env::var("SYSTEMLESS_TRACE_PC_RANGE_TICK_MIN")
            .ok()
            .and_then(|v| v.parse::<u32>().ok());
        let max = std::env::var("SYSTEMLESS_TRACE_PC_RANGE_TICK_MAX")
            .ok()
            .and_then(|v| v.parse::<u32>().ok());
        (min.is_some() || max.is_some()).then_some((min, max))
    })
}

fn trace_pc_range_contains(pc: u32, tick: u32) -> bool {
    #[cfg(target_arch = "wasm32")]
    {
        let _ = (pc, tick);
        return false;
    }
    #[cfg(not(target_arch = "wasm32"))]
    {
        let in_range = trace_pc_range()
            .map(|(start, end)| pc >= start && pc <= end)
            .unwrap_or(false);
        if !in_range {
            return false;
        }
        trace_pc_range_ticks()
            .map(|(min, max)| {
                min.map(|min| tick >= min).unwrap_or(true)
                    && max.map(|max| tick <= max).unwrap_or(true)
            })
            .unwrap_or(true)
    }
}

// Gate the most-prominent startup/load chatter behind an env var.
// Library consumers shouldn't see arbitrary debug stderr output by
// default — these prints are useful when bring-up debugging a new game
// but pure noise once the loader works. Enable with
// `SYSTEMLESS_TRACE_LOAD=1` when diagnosing a load/halt.
static TRACE_LOAD_ENABLED: OnceLock<bool> = OnceLock::new();
pub(crate) fn trace_load_enabled() -> bool {
    *TRACE_LOAD_ENABLED.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_LOAD").is_some())
}

/// If `pc` matches a `GetTrapAddress` fake-pointer pattern, return a
/// human-readable hint identifying the trap that the game most
/// likely tried to JMP/JSR through. Else `None`.
///
/// Background: `GetTrapAddress` (and friends) on Systemless return a
/// unique-per-trap fake address so apps can compare against
/// `_Unimplemented` without hitting cache aliasing. Apps that ONLY
/// compare the address (the documented use) are fine. Apps that
/// actually `JMP (A0)` / `JSR (A0)` through the fake pointer land in
/// unmapped or garbage-filled memory and trip an IllegalInstruction
/// 30-100 instructions later. Surfacing the trap word at halt time
/// lets future investigators identify the missing trampoline at a
/// glance instead of having to disassemble around the halted PC.
///
/// Fake-pointer ranges (matching trap/memory.rs ranges):
///   OS-style:    `$00F00000 | (trap_word as u32)` — range
///                `$00F00000-$00F0FFFF`.
///   Tool-style:  `$CAFE0000 + (trap_word & 0x3FF)` — range
///                `$CAFE0000-$CAFE03FF`.
pub fn decode_fakeptr_pc(pc: u32) -> Option<String> {
    if (0x00F00000..=0x00F0FFFF).contains(&pc) {
        let trap_word = (pc & 0xFFFF) as u16;
        Some(format!(
            "PC matches GetTrapAddress fake-ptr ($A046/$A346/$A746) for trap ${:04X}\
             game likely JMP/JSR'd through the unique-address placeholder. Implementing \
             a re-trap trampoline at the fake-ptr address would unblock this path.",
            trap_word
        ))
    } else if (0xCAFE0000..=0xCAFE03FF).contains(&pc) {
        let trap_num = (pc - 0xCAFE0000) as u16;
        let trap_word = 0xA800 | trap_num;
        Some(format!(
            "PC matches GetToolTrapAddress fake-ptr for trap ${:04X} (tool num=${:03X}) — \
             same trampoline gap as the OS-style fake-ptr range.",
            trap_word, trap_num
        ))
    } else {
        None
    }
}

// Per-opcode M68K histogram, opt-in via
// `SYSTEMLESS_TRACE_OPCODE_COUNTS=1`. Complements the trap histogram
// (which only sees A-line traps). Populated in `run_steps_internal`
// after each step succeeds. Use to prioritize decode-table / super-
// instruction-fusion work — the instruction mix is the input to that
// kind of optimization.
#[cfg(not(target_arch = "wasm32"))]
static TRACE_OPCODE_COUNTS: OnceLock<bool> = OnceLock::new();
fn trace_opcode_counts_enabled() -> bool {
    #[cfg(target_arch = "wasm32")]
    {
        return false;
    }
    #[cfg(not(target_arch = "wasm32"))]
    *TRACE_OPCODE_COUNTS
        .get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_OPCODE_COUNTS").is_some())
}

// Sampled PC histogram, opt-in via `SYSTEMLESS_TRACE_HOT_PC=1`. Every
// 1000th step's PC increments a `HashMap` entry. Use to locate the
// code address of a hot game loop. 1/1000 sampling keeps `HashMap`
// overhead negligible while still giving high-confidence attribution
// for any loop that takes more than ~0.1% of runtime.
const PC_SAMPLE_INTERVAL: u64 = 1000;
#[cfg(not(target_arch = "wasm32"))]
static TRACE_HOT_PC: OnceLock<bool> = OnceLock::new();
fn trace_hot_pc_enabled() -> bool {
    #[cfg(target_arch = "wasm32")]
    {
        return false;
    }
    #[cfg(not(target_arch = "wasm32"))]
    *TRACE_HOT_PC.get_or_init(|| std::env::var_os("SYSTEMLESS_TRACE_HOT_PC").is_some())
}

// Generic TickCount spin-wait fast-forward. Tri-state default:
// headless callers (scripted harnesses, no real-time pacing) get the fast-
// forward by default — they gain the spin-elimination win. GUI
// callers (`yield_for_ui = true`) get the fast-forward OFF by default
// because tick-driven animations look wrong when ticks advance in
// batches. Two env vars override:
//   SYSTEMLESS_SPIN_WAIT_FASTFWD=1     force on (any mode)
//   SYSTEMLESS_DISABLE_SPIN_FASTFWD=1  force off (any mode)
static SPIN_WAIT_FASTFWD_FORCE_ON: OnceLock<bool> = OnceLock::new();
static SPIN_WAIT_FASTFWD_FORCE_OFF: OnceLock<bool> = OnceLock::new();

fn spin_wait_fastfwd_force_on() -> bool {
    *SPIN_WAIT_FASTFWD_FORCE_ON
        .get_or_init(|| std::env::var_os("SYSTEMLESS_SPIN_WAIT_FASTFWD").is_some())
}
fn spin_wait_fastfwd_force_off() -> bool {
    *SPIN_WAIT_FASTFWD_FORCE_OFF
        .get_or_init(|| std::env::var_os("SYSTEMLESS_DISABLE_SPIN_FASTFWD").is_some())
}

/// Resolve the fast-forward gate for the current run-loop call.
/// Tri-state precedence:
///   1. force-off env wins.
///   2. force-on env wins next.
///   3. default = headless (yield_for_ui = false) gets it on,
///      GUI (yield_for_ui = true) gets it off.
fn spin_wait_fastfwd_enabled_for(yield_for_ui: bool) -> bool {
    spin_wait_fastfwd_gate(
        spin_wait_fastfwd_force_on(),
        spin_wait_fastfwd_force_off(),
        yield_for_ui,
    )
}

/// Pure decision function for the tri-state gate. Split out from
/// `spin_wait_fastfwd_enabled_for` so the env-var reads can be mocked
/// in unit tests (the `OnceLock`-based env caches initialise once per
/// process and would prevent testing all three modes in one test
/// run).
fn spin_wait_fastfwd_gate(force_on: bool, force_off: bool, yield_for_ui: bool) -> bool {
    if force_off {
        return false;
    }
    if force_on {
        return true;
    }
    !yield_for_ui
}

/// Pure decision function for the ModalDialog noop-refire skip. ALL
/// of these must be true for the skip to fire:
///   - mode is headless (`yield_for_ui = false`)
///   - dialog tracking is active (`has_tracking = true`)
///   - no filter proc callback is due (`filter_allows_noop`)
///   - no button flash animating (`flash_remaining_zero`)
///   - initial draw procs all completed (`draw_procs_done`)
///   - dialog pixels already captured (`rendered_pixels_final`)
///   - event queue is empty (no input pending)
fn modaldialog_refire_is_noop(
    yield_for_ui: bool,
    has_tracking: bool,
    filter_allows_noop: bool,
    flash_remaining_zero: bool,
    draw_procs_done: bool,
    rendered_pixels_final: bool,
    event_queue_empty: bool,
) -> bool {
    !yield_for_ui
        && has_tracking
        && filter_allows_noop
        && flash_remaining_zero
        && draw_procs_done
        && rendered_pixels_final
        && event_queue_empty
}

/// Some tracking traps should block the application's foreground event
/// loop without advancing the app-visible tick clock in GUI mode. ModalDialog
/// is different: the dialog manager is itself the active event loop, and
/// Sound/VBL/Time Manager work must keep advancing while it tracks input.
fn tracking_refire_should_freeze_ticks(opcode: u16) -> bool {
    let trap_no_autopop = opcode & !0x0400;
    trap_no_autopop == 0xA93D // MenuSelect
        || trap_no_autopop == 0xA80B // PopUpMenuSelect / MenuKey tracking
        || trap_no_autopop == 0xA968 // TrackControl
}

fn canonical_trap_number(opcode: u16) -> (bool, u16) {
    let is_tool = (opcode & 0x0800) != 0;
    let trap_num = if is_tool {
        opcode & 0x03FF
    } else {
        opcode & 0x00FF
    };
    (is_tool, trap_num)
}

fn hle_trap_extra_tick_cost(opcode: u16) -> i32 {
    let (is_tool, trap_num) = canonical_trap_number(opcode);
    match (is_tool, trap_num) {
        // Event/time polling rates vary with host speed; charging these
        // creates false game-time drift instead of modelling ROM work.
        (true, 0x0170) // GetNextEvent
        | (true, 0x0060) // WaitNextEvent
        | (true, 0x0171) // EventAvail
        | (true, 0x0175) // TickCount
        | (true, 0x0062) // Button
        | (false, 0x0031) // GetOSEvent
        | (_, 0x003B) => 0, // Delay already advances requested ticks explicitly

        // SANE Pack4/Pack5 calls can be hot inner-loop arithmetic in games.
        // Treat them as guest computation, not manager work that should yield.
        (true, 0x006C) | (true, 0x006E) | (true, 0x01EB) | (true, 0x01EC) => 0,

        // QuickDraw blits and PICT draws do substantial HLE-side pixel work.
        (true, 0x00EC) | (true, 0x00F6) => 96,

        // Resource loads move and parse data that real ROM/file-system code
        // would not complete in one 68k instruction.
        (true, 0x01A0) | (true, 0x01A1) | (true, 0x01A2) | (true, 0x01BC) => 96,

        // Resource metadata/release calls are cheaper than loads but still
        // non-trivial manager work.
        (true, 0x019D..=0x01CF) => 24,

        // Other Toolbox/OS HLE traps should cost more than a single guest
        // opcode without making simple math/geometry helpers dominate timing.
        (true, _) => 4,
        (false, _) => 2,
    }
}
// Cap how many ticks the fast-forward will advance in one shot,
// to protect against pathological target values (e.g. overflowed
// unsigned register values being misinterpreted as huge-future
// ticks). If the cap trips, we fall back to normal spin — still
// correct, just not fast.
const SPIN_FASTFWD_MAX_TICKS: u32 = 1_000_000;

/// Outcome of `advance_until_tick`. Used to distinguish the "we
/// advanced, please synthesise the exit state" happy path from
/// the abort paths: tick_cap reached (caller must break the
/// outer run loop), pathological target difference (caller must
/// NOT synthesise — let the guest spin normally), and interrupt
/// callback injection (caller must leave the CPU at the callback
/// trampoline).
enum AdvanceResult {
    Advanced,
    CapHit,
    Interrupted,
    TooFar,
}

// Layout for dialog callback scratch region.
const DIALOG_DRAW_TRAMPOLINE_OFFSET: u32 = 0x00;
const DIALOG_FILTER_TRAMPOLINE_OFFSET: u32 = 0x40;
const DIALOG_FILTER_EVENT_OFFSET: u32 = 0x80;
// 2-byte scratch where the filter trampoline writes its Boolean return value.
const DIALOG_FILTER_RESULT_OFFSET: u32 = 0x96;
const MENU_HOOK_TRAMPOLINE_OFFSET: u32 = 0xA0;
const DIALOG_CALLBACK_SCRATCH_FALLBACK: u32 = 0x0000_1200;
/// Compact Mac video hardware refreshes at approximately 60.15 Hz.
pub const DEFAULT_VBL_HZ: f64 = 60.15;
/// Default emulated CPU speed for realtime frontends (Mac IIci-class 68030).
pub const DEFAULT_REALTIME_CPU_MHZ: f64 =
    crate::machine_profile::ORACLE_MACHINE_PROFILE.realtime_cpu_mhz;
/// Shared default realtime CPU budget used by the GUI runner and scripted
/// realtime mode so both frontends expose the same machine profile.
pub const DEFAULT_REALTIME_INSTRUCTIONS_PER_SECOND: f64 = DEFAULT_REALTIME_CPU_MHZ * 1_000_000.0;
// Default instructions per VBL tick for non-realtime execution (scripted harnesses, tests).
// Realtime frontends override this via set_instructions_per_tick() to match the
// shared default machine profile defined above.
// This lower value lets scripted harnesses run quickly without being wall-clock-paced.
const INSTRUCTIONS_PER_TICK: u32 = 12_000;
const MAC_EPOCH_OFFSET_FROM_UNIX: u64 = 2_082_844_800;
const CURSOR_TASK_NOOP_ADDR: u32 = 0x0000_0060;

fn current_mac_epoch_seconds() -> u32 {
    let unix_now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    unix_now
        .saturating_add(MAC_EPOCH_OFFSET_FROM_UNIX)
        .min(u32::MAX as u64) as u32
}

#[derive(Clone, Copy, Debug)]
enum ActiveInterruptCallbackSource {
    Timer,
    Vbl,
    CursorTask,
    SoundCallback,
    SoundFileCompletion,
    SoundDoubleBack,
    DialogDrawProc,
    DialogFilterProc,
    MenuHook,
}

#[derive(Clone, Copy, Debug)]
struct ActiveInterruptCallback {
    source: ActiveInterruptCallbackSource,
    resume_pc: u32,
    resume_sp: u32,
    d_regs: [u32; 8],
    a_regs: [u32; 8],
    ccr: u8,
    restore_port: Option<(u32, u32)>,
}

fn is_sound_interrupt_source(source: ActiveInterruptCallbackSource) -> bool {
    matches!(
        source,
        ActiveInterruptCallbackSource::SoundCallback
            | ActiveInterruptCallbackSource::SoundFileCompletion
            | ActiveInterruptCallbackSource::SoundDoubleBack
    )
}

/// Configuration knobs for [`FixtureRunner`]. Use
/// [`FixtureRunnerConfig::default`] for the canonical defaults
/// (10M-instruction budget, 0x10000 load base, arrow-keys NOT
/// remapped to numpad) — only override fields you actually need.
pub struct FixtureRunnerConfig {
    /// Hard cap on instructions executed by the simpler unbounded
    /// [`FixtureRunner::run`] entry point. Not consulted by
    /// [`FixtureRunner::run_steps`], which uses its own per-call
    /// `max_steps` argument. Default: 10,000,000.
    pub max_instructions: usize,
    /// Base address where 68k CODE segments are loaded into guest
    /// RAM. Default: 0x10000 (64 KiB above the low-mem globals).
    /// Most games tolerate the default; a few with hardcoded
    /// expectations about A5 placement may need a higher value.
    pub load_address: u32,
    /// When true, arrow key virtual key codes are remapped to their numpad equivalents.
    /// Useful on keyboards without a numeric keypad, since many classic Mac games use
    /// the numpad for movement. Inside Macintosh Volume V, V-191.
    pub arrows_as_numpad: bool,
    /// Selected UI rendering provider. The default `classic-system7` provider
    /// represents the existing renderer; non-classic themes are explicit and
    /// must not alter guest-visible Toolbox behavior in classic metrics mode.
    pub ui_theme: UiThemeId,
    /// Declares whether theme rendering preserves classic guest metrics or opts
    /// into future themed hit/measurement behavior.
    pub theme_metrics_mode: ThemeMetricsMode,
}

impl Default for FixtureRunnerConfig {
    fn default() -> Self {
        Self {
            max_instructions: 10_000_000,
            load_address: 0x10000,
            arrows_as_numpad: false,
            ui_theme: UiThemeId::ClassicSystem7,
            theme_metrics_mode: ThemeMetricsMode::ClassicGuestMetrics,
        }
    }
}

/// Canonical entry point of the systemless library.
///
/// `FixtureRunner` owns the three pieces of guest state — the [`M68kCpu`]
/// interpreter, the [`MacMemoryBus`], and the [`TrapDispatcher`] (Toolbox
/// + OS trap handlers) — and exposes the load / step / halt-inspect
/// surface that drives them.
///
/// **Lifecycle:**
/// 1. [`FixtureRunner::new`] — allocate guest RAM + dispatcher.
/// 2. [`crate::game::load_game`] — auto-detect StuffIt / MacBinary,
///    populate guest memory, seed CPU state.
/// 3. [`run_steps`](Self::run_steps) (preferred) or [`run`](Self::run)
///    — drive the CPU. `run_steps` returns `(steps_executed,
///    still_running)`; `run` runs until halt or
///    [`FixtureRunnerConfig::max_instructions`].
/// 4. After halt: [`halted_pc`](Self::halted_pc) /
///    [`halted_trap`](Self::halted_trap) /
///    [`halted_sp`](Self::halted_sp) / [`halted_d0`](Self::halted_d0)
///    expose per-halt detail, and
///    [`halted_by_exit_to_shell`](Self::halted_by_exit_to_shell) classifies
///    the common clean application-exit path.
///
/// **Defaults:** kiosk mode (Mac menu bar suppressed regardless of the
/// guest's `MBarHeight`); arrow keys NOT remapped to numpad. Override
/// each via [`set_menu_bar_visible`](Self::set_menu_bar_visible) /
/// [`set_arrows_as_numpad`](Self::set_arrows_as_numpad) or the
/// `SYSTEMLESS_SHOW_MENU_BAR` env var.
///
/// See `examples/run_headless.rs` for a runnable end-to-end example.
pub struct FixtureRunner {
    cpu: M68kCpu,
    bus: MacMemoryBus,
    dispatcher: TrapDispatcher,
    config: FixtureRunnerConfig,
    trace_buffer: std::collections::VecDeque<(u32, u16, u32, u32, u32, u32)>, // (PC, Op, A0, SP, A6, A5)
    /// Set to true when the application calls ExitToShell
    halted: bool,
    /// Trap opcode that caused the halt, if known.
    halted_trap: Option<u16>,
    /// Program counter at the point of halt.
    halted_pc: Option<u32>,
    /// Stack pointer at the point of halt.
    halted_sp: Option<u32>,
    /// D0 register at the point of halt.
    halted_d0: Option<u32>,
    /// Total guest instructions retired by the interpreter.
    total_instructions: u64,
    /// Number of interpreted guest instructions per `Ticks` increment.
    instructions_per_tick: u32,
    /// Optional cap on per-WaitNextEvent-call sleep tick advance in headless
    /// mode (when `run_steps` is called without a `tick_override`). `None`
    /// keeps the legacy drain-all behavior. `Some(n)` advances at most `n`
    /// ticks per WNE call, mirroring GUI mode's 1-tick cap. Used for
    /// scripted tick alignment with Basilisk.
    wait_sleep_cap_in_headless: Option<u32>,
    /// Remaining instruction budget for the current tick. Both 68k instructions
    /// and HLE trap costs are deducted. When this reaches zero or below, the
    /// tick advances and the budget is refilled from `instructions_per_tick`.
    tick_budget: i32,
    /// Tick value saved when menu tracking starts.  While set, run_steps caps
    /// its tick_override to this value so the game clock is frozen — matching
    /// the real Mac where MenuSelect blocks the application event loop.
    frozen_ticks: Option<u32>,
    /// Guest-memory address of the Time Manager interrupt trampoline code.
    /// Allocated once on first use and reused for all subsequent timer fires.
    timer_trampoline: u32,
    /// Guest-memory address of the Vertical Retrace Manager trampoline code.
    /// Allocated once on first use and reused for all VBL callbacks.
    vbl_trampoline: u32,
    /// Guest-memory address of the low-memory `JCrsrTask` callback trampoline.
    /// Allocated once on first use and reused for cursor task callbacks.
    cursor_task_trampoline: u32,
    /// Currently executing Time Manager callback, if any.
    ///
    /// Real timer delivery happens from interrupt context, so the same timer source
    /// must not be re-entered by our synthetic tick advancement while the callback
    /// is still unwinding back to interrupted guest code.
    active_interrupt_callback: Option<ActiveInterruptCallback>,
    /// Audio output backend (None = no audio output).
    audio: Option<Box<dyn crate::audio::AudioBackend>>,
    /// Accumulated audio samples for external consumers (e.g. WASM).
    /// Unsigned 8-bit mono PCM at OUTPUT_RATE Hz (silence = 0x80).
    audio_buffer: Vec<u8>,
    /// Guest-memory address of the SndPlayDoubleBuffer doubleback trampoline.
    /// Allocated once on first use and reused for all double-buffer callbacks.
    sound_doubleback_trampoline: u32,
    /// Guest-memory address of the SndNewChannel callback trampoline.
    /// Allocated once on first use and reused for all callback procedures.
    sound_callback_trampoline: u32,
    /// Guest-memory address of the SndStartFilePlay completion trampoline.
    /// Allocated once on first use and reused for all file completion routines.
    sound_file_completion_trampoline: u32,
    /// Guest-memory address of the dialog userItem draw proc trampoline (26 bytes).
    /// Allocated once on first use and reused for all subsequent draw proc calls.
    dialog_draw_trampoline: u32,
    /// Guest-memory address of the ModalDialog filter proc trampoline.
    /// Allocated once on first use and reused for all callback invocations.
    dialog_filter_trampoline: u32,
    /// Guest-memory address of the MenuSelect MenuHook trampoline.
    /// Allocated once on first use and reused for all callback invocations.
    menu_hook_trampoline: u32,
    /// Guest-memory address of a scratch EventRecord passed to ModalDialog filters.
    dialog_filter_event: u32,
    /// Last dialog/tick pair that received a synthetic ModalDialog null event.
    /// Real queued events bypass this; it only paces the no-input idle callback.
    dialog_filter_last_null_event_tick: Option<(u32, u32)>,
    /// Override for the application's startup time in Mac-epoch seconds.
    /// Used by scripted frontends to keep guest-visible time deterministic.
    app_start_time: Option<u32>,
    /// Optional Finder-style application partition size override in bytes.
    /// Scripted frontends use this to model a user raising the preferred
    /// memory size before launch without mutating the application's resources.
    application_partition_size: Option<u32>,
    /// Per-opcode histogram for M68K instructions. Indexed by the
    /// full 16-bit opcode word (`cpu.core.ir` after step). Always
    /// allocated (512 KB); populated only when
    /// `SYSTEMLESS_TRACE_OPCODE_COUNTS=1` is set at startup. Zero cost
    /// on the hot path when disabled (cached bool compare, branch
    /// short-circuited). Complements the trap histogram, which only
    /// sees A-line opcodes; this captures MOVE/ADD/Bcc/etc. too,
    /// which is what decode-table or super-instruction-fusion work
    /// needs to prioritize.
    opcode_histogram: Box<[u64; 65536]>,
    /// Sampled PC histogram. When `SYSTEMLESS_TRACE_HOT_PC=1` is set,
    /// every 1000th step's PC increments a `HashMap` bucket. Answers
    /// "which CODE ADDRESS is hot", useful for locating game-side
    /// hot loops by routine. Sampling (1/1000) keeps `HashMap`
    /// overhead low; a million hot samples still fits in tens of
    /// unique addresses.
    pc_histogram: HashMap<u32, u64>,
}

impl FixtureRunner {
    /// Construct a fresh runner with `ram_size` bytes of guest RAM and
    /// the given [`FixtureRunnerConfig`]. The CPU starts halted at
    /// PC = 0; the framebuffer is whatever bytes the host allocator
    /// hands us. Call [`load_app`](Self::load_app) (or the higher-level
    /// `systemless::game::load_game`) to populate guest memory and seed the
    /// run state, then drive the guest with [`run_steps`](Self::run_steps).
    ///
    /// `ram_size` is typically 4 MiB to 16 MiB — most games never push
    /// past 8 MiB. The runner allocates a single contiguous host
    /// region of this size; bumping it costs only the upfront alloc.
    ///
    /// The dispatcher defaults to **kiosk mode** (Mac menu bar
    /// suppressed, regardless of the guest's `MBarHeight`). Call
    /// [`set_menu_bar_visible`](Self::set_menu_bar_visible) to opt back
    /// in to the original Mac menu-bar behaviour.
    pub fn new(ram_size: usize, config: FixtureRunnerConfig) -> Self {
        let mut dispatcher = TrapDispatcher::new();
        dispatcher.set_ui_theme_id(config.ui_theme);
        Self {
            cpu: M68kCpu::new(),
            bus: MacMemoryBus::new(ram_size),
            dispatcher,
            config,
            trace_buffer: std::collections::VecDeque::with_capacity(2000),
            halted: false,
            halted_trap: None,
            halted_pc: None,
            halted_sp: None,
            halted_d0: None,
            total_instructions: 0,
            instructions_per_tick: INSTRUCTIONS_PER_TICK,
            wait_sleep_cap_in_headless: None,
            tick_budget: INSTRUCTIONS_PER_TICK as i32,
            frozen_ticks: None,
            timer_trampoline: 0,
            vbl_trampoline: 0,
            cursor_task_trampoline: 0,
            active_interrupt_callback: None,
            audio: None,
            audio_buffer: Vec::new(),
            sound_doubleback_trampoline: 0,
            sound_callback_trampoline: 0,
            sound_file_completion_trampoline: 0,
            dialog_draw_trampoline: 0,
            dialog_filter_trampoline: 0,
            menu_hook_trampoline: 0,
            dialog_filter_event: 0,
            dialog_filter_last_null_event_tick: None,
            app_start_time: None,
            application_partition_size: None,
            opcode_histogram: Box::new([0u64; 65536]),
            pc_histogram: HashMap::new(),
        }
    }

    /// Returns true once guest execution has stopped.
    pub fn is_halted(&self) -> bool {
        self.halted
    }

    /// Returns true when the halt was the documented clean application
    /// termination path, `_ExitToShell` (`$A9F4`).
    ///
    /// This lets runners and tests distinguish apps that intentionally quit
    /// from halts caused by faults, invalid PCs, or other fatal errors.
    pub fn halted_by_exit_to_shell(&self) -> bool {
        self.halted && self.halted_trap == Some(0xA9F4)
    }

    pub fn guest_tick(&self) -> u32 {
        self.bus.read_long(0x016A)
    }

    pub fn host_now(&self) -> Instant {
        Instant::now()
    }

    pub fn halted_trap(&self) -> Option<u16> {
        self.halted_trap
    }

    pub fn halted_pc(&self) -> Option<u32> {
        self.halted_pc
    }

    pub fn halted_sp(&self) -> Option<u32> {
        self.halted_sp
    }

    pub fn halted_stack_word0(&self) -> Option<u16> {
        self.halted_sp.map(|sp| self.bus.read_word(sp))
    }

    pub fn halted_stack_word(&self, word_index: u32) -> Option<u16> {
        self.halted_sp
            .map(|sp| self.bus.read_word(sp + word_index.saturating_mul(2)))
    }

    pub fn halted_d0(&self) -> Option<u32> {
        self.halted_d0
    }

    pub fn total_instructions(&self) -> u64 {
        self.total_instructions
    }

    pub fn cpu(&self) -> &M68kCpu {
        &self.cpu
    }

    pub fn cpu_mut(&mut self) -> &mut M68kCpu {
        &mut self.cpu
    }

    pub fn bus(&self) -> &MacMemoryBus {
        &self.bus
    }

    pub fn bus_mut(&mut self) -> &mut MacMemoryBus {
        &mut self.bus
    }

    pub fn dispatcher(&self) -> &crate::trap::dispatch::TrapDispatcher {
        &self.dispatcher
    }

    pub fn dispatcher_mut(&mut self) -> &mut crate::trap::dispatch::TrapDispatcher {
        &mut self.dispatcher
    }

    /// Returns the selected UI theme provider. `classic-system7` is the
    /// default and maps to the existing renderer path; non-classic providers
    /// are explicit Systemless-owned rendering contracts.
    pub fn ui_theme(&self) -> &'static dyn UiTheme {
        self.config.ui_theme.provider()
    }

    pub fn ui_theme_id(&self) -> UiThemeId {
        self.config.ui_theme
    }

    pub fn theme_metrics_mode(&self) -> ThemeMetricsMode {
        self.config.theme_metrics_mode
    }

    pub fn uses_classic_guest_metrics(&self) -> bool {
        self.config
            .theme_metrics_mode
            .preserves_classic_guest_metrics()
    }

    /// Show or hide the Mac menu bar.
    ///
    /// systemless runs in **kiosk mode** by default — the Mac menu bar is
    /// suppressed regardless of the guest's `MBarHeight` ($0BAA) value
    /// and `DrawMenuBar` is a no-op. This matches the typical embedding
    /// case (running a single classic Mac game inside a fullscreen
    /// host window) where the host owns the chrome and the guest's
    /// menu bar would just diverge from the original-machine
    /// appearance whenever the cursor entered `y < 20`.
    ///
    /// Pass `true` to opt back in to original Mac behavior — for
    /// example, when running a Mac *application* that relies on the
    /// menu bar as its primary user surface.
    ///
    /// The same toggle is also accessible via the `SYSTEMLESS_SHOW_MENU_BAR`
    /// environment variable (set to any value to show) and via
    /// `systemless --show-menu-bar`. This library method is the
    /// preferred entry point for library embedders that don't want
    /// to depend on environment-variable plumbing.
    ///
    /// Inside Macintosh Volume I, I-354 (DrawMenuBar);
    /// Inside Macintosh Volume V, V-245 (MBarHeight global).
    pub fn set_menu_bar_visible(&mut self, visible: bool) {
        self.dispatcher.menu_bar_hidden = !visible;
    }

    /// Returns true when the Mac menu bar is currently being rendered.
    /// In the default kiosk configuration this returns `false`.
    pub fn menu_bar_visible(&self) -> bool {
        !self.dispatcher.menu_bar_hidden
    }

    /// Disassemble M68K instructions starting at `pc` for `count`
    /// instruction words. Returns one entry per word: `(pc, mnemonic,
    /// size_in_bytes)`. The size includes any operand words consumed
    /// by the instruction; advance `pc` by `size` to reach the next.
    ///
    /// Unknown opcodes (including A-line traps and other reserved
    /// patterns) come back as `DC.W $XXXX` with size 2 — the same
    /// convention the underlying [`m68k::dasm::disassemble`] uses.
    /// Reads past the end of guest RAM yield `(addr, "<unmapped>", 2)`
    /// rather than panicking.
    ///
    /// Diagnostic helper for pixel-divergence and trap-misroute
    /// investigations: pair with the framebuffer-write tracer
    /// (`SYSTEMLESS_TRACE_FB_WRITE_RANGE`) to see what the guest is
    /// actually executing at a suspect PC.
    pub fn disassemble_at(&self, pc: u32, count: usize) -> Vec<(u32, String, u32)> {
        use crate::memory::MemoryBus;
        let mut out = Vec::with_capacity(count);
        let mut cur = pc;
        for _ in 0..count {
            // bus.read_word returns 0 for OOB rather than panicking,
            // so wrap-around safety is a property of the underlying
            // bus impl. Tag explicitly when the read landed at an
            // address we know is past the framebuffer.
            let opcode = self.bus.read_word(cur);
            let unmapped = (cur as u64) >= (8 * 1024 * 1024);
            let (mnemonic, size) = if unmapped {
                ("<unmapped>".to_string(), 2)
            } else {
                m68k::dasm::disassemble(cur, opcode, m68k::CpuType::M68000)
            };
            // m68k's disassemble returns the instruction's TOTAL size
            // including operand words; cap at a reasonable max so a
            // malformed opcode doesn't run away.
            let size = size.clamp(2, 10);
            out.push((cur, mnemonic, size));
            cur = cur.wrapping_add(size);
        }
        out
    }

    /// Dump the top-N M68K opcodes by execution count. No-op when
    /// `SYSTEMLESS_TRACE_OPCODE_COUNTS` wasn't set at startup. Format:
    ///   [OPCODE-HIST]   43210123  $3F3C  MOVE.W #imm,-(SP)
    /// Unknown opcodes fall back to showing just the hex word.
    pub fn print_opcode_histogram(&self, top_n: usize) {
        if !trace_opcode_counts_enabled() {
            return;
        }
        let mut entries: Vec<(u16, u64)> = self
            .opcode_histogram
            .iter()
            .enumerate()
            .filter_map(|(i, &c)| if c > 0 { Some((i as u16, c)) } else { None })
            .collect();
        entries.sort_by_key(|e| std::cmp::Reverse(e.1));
        let total: u64 = entries.iter().map(|(_, c)| c).sum();
        eprintln!(
            "[OPCODE-HIST] top {} of {} distinct opcodes ({} total non-Aline instructions)",
            top_n.min(entries.len()),
            entries.len(),
            total
        );
        for (opcode, count) in entries.iter().take(top_n) {
            let group = (opcode >> 12) & 0xF;
            let group_name = match group {
                0x0 => "bit-op/MOVEP/immediate",
                0x1 => "MOVE.B",
                0x2 => "MOVE.L",
                0x3 => "MOVE.W",
                0x4 => "misc (LEA/JSR/etc.)",
                0x5 => "ADDQ/SUBQ/Scc/DBcc",
                0x6 => "Bcc/BSR",
                0x7 => "MOVEQ",
                0x8 => "OR/DIV/SBCD",
                0x9 => "SUB/SUBX",
                0xA => "A-line (should be in trap-hist)",
                0xB => "CMP/EOR",
                0xC => "AND/MUL/ABCD/EXG",
                0xD => "ADD/ADDX",
                0xE => "shift/rotate",
                0xF => "F-line (FPU/coproc)",
                _ => "?",
            };
            eprintln!(
                "[OPCODE-HIST]   {:>10}  ${:04X}  group {:X}: {}",
                count, opcode, group, group_name
            );
        }
    }

    /// Dump the top-N hottest PCs by sampled hit count. No-op when
    /// `SYSTEMLESS_TRACE_HOT_PC` is unset. Each count represents one
    /// `PC_SAMPLE_INTERVAL` (=1000) M68K instructions; multiply by
    /// 1000 for an approximate instruction count attributed to that
    /// PC.
    pub fn print_pc_histogram(&self, top_n: usize) {
        if !trace_hot_pc_enabled() {
            return;
        }
        let mut entries: Vec<(u32, u64)> =
            self.pc_histogram.iter().map(|(&a, &c)| (a, c)).collect();
        entries.sort_by_key(|e| std::cmp::Reverse(e.1));
        let total: u64 = entries.iter().map(|(_, c)| c).sum();
        eprintln!(
            "[PC-HIST] top {} of {} distinct PCs ({} samples × {} = ~{} instructions)",
            top_n.min(entries.len()),
            entries.len(),
            total,
            PC_SAMPLE_INTERVAL,
            total * PC_SAMPLE_INTERVAL
        );
        for (pc, count) in entries.iter().take(top_n) {
            // Classify by address region: the common Mac-app
            // convention for loaded segments is roughly $00010000-
            // $00600000 (game code) and $01000000+ (ROM).
            let region = match *pc {
                0x0000_0000..=0x0000_FFFF => "low-mem",
                0x0001_0000..=0x005F_FFFF => "app code",
                0x0060_0000..=0x00FF_FFFF => "heap/data",
                0x0100_0000..=0x01FF_FFFF => "ROM",
                _ => "other",
            };
            eprintln!("[PC-HIST]   {:>8}  PC=${:08X}  ({})", count, pc, region);
        }
    }

    pub fn install_application_clut(&mut self, clut: [[u16; 3]; 256]) {
        self.dispatcher
            .install_application_clut(&mut self.bus, clut);
    }

    pub fn set_app_start_time(&mut self, secs: u32) {
        self.app_start_time = Some(secs);
    }

    pub fn set_application_partition_size(&mut self, bytes: Option<u32>) {
        self.application_partition_size = bytes.filter(|&bytes| bytes >= 128 * 1024);
    }

    /// Getter for the pinned Mac epoch seconds. Returns `None` when no
    /// pin has been applied — without a pin, `init_app` falls back to
    /// `current_mac_epoch_seconds()` (host wall-clock), which leaks
    /// into the guest's `Time` global (`$020C`) and breaks
    /// reproducibility.
    pub fn app_start_time(&self) -> Option<u32> {
        self.app_start_time
    }

    pub fn application_partition_size(&self) -> Option<u32> {
        self.application_partition_size
    }

    pub fn enable_oracle_recording(
        &mut self,
        output_dir: impl AsRef<std::path::Path>,
        source: crate::oracle::OracleSource,
    ) -> Result<()> {
        self.dispatcher.enable_oracle_recording(output_dir, source)
    }

    /// Composite chrome/dialog overlays onto the framebuffer.
    /// Call before reading raw pixels for screenshots.
    pub fn composite_frame(&mut self) {
        self.dispatcher.redraw_chrome(&mut self.bus);
    }

    /// Enable or disable arrow-key-to-numpad remapping.
    pub fn set_arrows_as_numpad(&mut self, enabled: bool) {
        self.config.arrows_as_numpad = enabled;
    }

    /// Returns true when arrow keys are remapped to numpad key codes.
    pub fn arrows_as_numpad(&self) -> bool {
        self.config.arrows_as_numpad
    }

    /// Move the mouse without changing the button state. Updates the
    /// dispatcher's tracked position and the six mouse-position
    /// low-memory globals (MTemp / RawMouse / Mouse) so guest code that
    /// reads them directly sees the new coordinates immediately. Leaves
    /// MBState ($0172) untouched. Inside Macintosh Volume II, II-371.
    pub fn set_mouse_position(&mut self, v: i16, h: i16) {
        self.dispatcher.set_mouse_position(v, h);
        self.sync_mouse_position_lowmem();
    }

    /// Inject a mouse-down event and sync low-memory globals.
    ///
    /// On real hardware the VBL interrupt handler updates MBState ($0172)
    /// and the mouse-position globals whenever the button state changes.
    /// Since our HLE has no interrupt-driven mouse driver, we sync these
    /// globals here so that code polling the low-memory locations directly
    /// (instead of calling Button or GetNextEvent) sees the correct state.
    pub fn push_mouse_down(&mut self, v: i16, h: i16) {
        self.dispatcher.push_mouse_down(v, h);
        self.sync_mouse_lowmem();
    }

    /// Inject a mouse-up event.
    ///
    /// Sync MBState ($0172) immediately so code that polls the low-memory
    /// byte directly (rather than calling Button or GetNextEvent) sees the
    /// release without waiting for the next tick advance.
    ///
    /// On real hardware the ADB manager polls the mouse at ~200 Hz, updating
    /// MBState within a few milliseconds of the physical release. Deferring
    /// the update to the next advance_guest_tick left MBState stale for an
    /// entire tick (~16 ms), which is longer than real hardware and caused
    /// frame-rate-dependent games to read the wrong button state for too
    /// many loop iterations after a click-up.
    /// Inside Macintosh Volume II, II-371
    pub fn push_mouse_up(&mut self, v: i16, h: i16) {
        self.dispatcher.push_mouse_up(v, h);
        self.sync_mouse_lowmem();
    }

    /// Write the three mouse-position low-memory globals (MTemp $0828,
    /// RawMouse $082C, Mouse $0830) from `self.dispatcher.mouse_pos`.
    /// Inside Macintosh Volume I, I-258.
    fn sync_mouse_position_lowmem(&mut self) {
        let (v, h) = self.dispatcher.mouse_pos;
        self.bus.write_word(0x0828, v as u16);
        self.bus.write_word(0x082A, h as u16);
        self.bus.write_word(0x082C, v as u16);
        self.bus.write_word(0x082E, h as u16);
        self.bus.write_word(0x0830, v as u16);
        self.bus.write_word(0x0832, h as u16);
    }

    /// Sync mouse button + position low-memory globals from internal state.
    ///
    /// MBState ($0172): 0x00 = button down, 0x80 = button up
    /// MTemp ($0828), RawMouse ($082C), Mouse ($0830): current position
    /// Inside Macintosh Volume I, I-258; Inside Macintosh Volume II, II-371
    fn sync_mouse_lowmem(&mut self) {
        let mb_state: u8 = if self.dispatcher.mouse_button {
            0x00
        } else {
            0x80
        };
        self.bus.write_byte(0x0172, mb_state);
        self.sync_mouse_position_lowmem();
    }

    /// Sync the 16-byte KeyMapLM low-memory bitmap from the dispatcher's
    /// current key state. Inside Macintosh Volume I, I-260 documents the
    /// KeyMap returned by GetKeys; MPW SysEqu.h exposes the ROM-maintained
    /// low-memory mirror at $0174 for code that polls it directly.
    fn sync_key_map_lowmem(&mut self) {
        use crate::memory::globals::addr;

        self.bus
            .write_bytes(addr::KEY_MAP_LM, self.dispatcher.key_map_bytes());
    }

    /// Inject a key-down event, applying arrow→numpad remapping if configured.
    pub fn push_key_down(&mut self, mac_key: u8, char_code: u8) {
        let (key, char_code) = self.remap_key(mac_key, char_code);
        self.dispatcher.push_key_down(key, char_code);
        self.sync_key_map_lowmem();
    }

    /// Inject a key-up event, applying arrow→numpad remapping if configured.
    pub fn push_key_up(&mut self, mac_key: u8, char_code: u8) {
        let (key, char_code) = self.remap_key(mac_key, char_code);
        self.dispatcher.push_key_up(key, char_code);
        self.sync_key_map_lowmem();
    }

    /// Remap arrow key virtual key codes to numpad equivalents when enabled.
    /// Arrow keys: Left=0x7B, Right=0x7C, Down=0x7D, Up=0x7E
    /// Numpad dirs: 4(left)=0x56, 6(right)=0x58, 5(down)=0x57, 8(up)=0x5B
    /// Inside Macintosh Volume V, V-191
    fn remap_key(&self, mac_key: u8, char_code: u8) -> (u8, u8) {
        if self.config.arrows_as_numpad {
            match mac_key {
                0x7B => (0x56, b'4'), // Left  -> Numpad4
                0x7C => (0x58, b'6'), // Right -> Numpad6
                0x7D => (0x57, b'5'), // Down  -> Numpad5
                0x7E => (0x5B, b'8'), // Up    -> Numpad8
                _ => (mac_key, char_code),
            }
        } else {
            (mac_key, char_code)
        }
    }

    /// Set the audio output backend. If not set, no audio is produced.
    pub fn set_audio(&mut self, audio: Box<dyn crate::audio::AudioBackend>) {
        self.audio = Some(audio);
    }

    pub fn set_instructions_per_tick(&mut self, instructions_per_tick: u32) {
        let old = self.instructions_per_tick.max(1);
        let new = instructions_per_tick.max(1);
        // Scale the remaining budget proportionally so a mid-run change
        // doesn't cause an immediate tick advance or an artificially long tick.
        self.tick_budget = ((self.tick_budget as i64 * new as i64) / old as i64) as i32;
        self.instructions_per_tick = new;
    }

    pub fn instructions_per_tick(&self) -> u32 {
        self.instructions_per_tick
    }

    /// Cap the per-WaitNextEvent-call sleep tick advance in headless mode.
    /// None (default) preserves the legacy drain-all behavior. Some(n) caps
    /// each WNE sleep to at most n tick advances, mirroring GUI mode.
    pub fn set_wait_sleep_cap_in_headless(&mut self, cap: Option<u32>) {
        self.wait_sleep_cap_in_headless = cap;
    }

    pub fn wait_sleep_cap_in_headless(&self) -> Option<u32> {
        self.wait_sleep_cap_in_headless
    }

    /// Drain accumulated audio samples for external consumers (e.g. WASM).
    /// Returns unsigned 8-bit mono PCM at 22050 Hz (silence = 0x80).
    pub fn drain_audio(&mut self) -> Vec<u8> {
        std::mem::take(&mut self.audio_buffer)
    }

    /// Drain accumulated audio samples into a caller-owned buffer.
    ///
    /// This avoids transferring the runner's `Vec` allocation out on every
    /// browser frame, so the next audio mix can reuse its existing capacity.
    pub fn drain_audio_into(&mut self, out: &mut Vec<u8>) {
        out.clear();
        out.extend_from_slice(&self.audio_buffer);
        self.audio_buffer.clear();
    }

    /// Current number of buffered audio samples (for diagnostics).
    pub fn audio_buffer_len(&self) -> usize {
        self.audio_buffer.len()
    }

    pub fn has_pending_sound_work(&self) -> bool {
        self.active_interrupt_callback
            .map(|callback| {
                matches!(
                    callback.source,
                    ActiveInterruptCallbackSource::SoundCallback
                        | ActiveInterruptCallbackSource::SoundFileCompletion
                        | ActiveInterruptCallbackSource::SoundDoubleBack
                )
            })
            .unwrap_or(false)
            || !self
                .dispatcher
                .sound_manager
                .pending_sound_callbacks
                .is_empty()
            || !self.dispatcher.sound_manager.pending_callbacks.is_empty()
    }

    pub fn is_ui_tracking_active(&self) -> bool {
        self.frozen_ticks.is_some()
            || self.dispatcher.is_menu_tracking()
            || self.dispatcher.is_dialog_tracking()
            || self.dispatcher.is_control_tracking()
    }

    /// Advance the guest tick counter by one, firing VBL and timer tasks.
    /// Used by the GUI runner to force-advance ticks when the CPU can't
    /// keep up with wall-clock time (e.g. during expensive PICT draws).
    pub fn force_advance_guest_tick(&mut self) {
        self.advance_guest_tick();
    }

    pub fn set_output_path(&mut self, path: std::path::PathBuf) {
        // The path points to a specific file (e.g. temp/foo/fixture_dump.bin).
        // Use its parent directory as the VFS output directory.
        if let Some(dir) = path.parent() {
            self.dispatcher.output_dir = Some(dir.to_path_buf());
        }
    }

    /// Get the contents of a file from the virtual filesystem.
    pub fn vfs_read(&self, filename: &str) -> Option<&[u8]> {
        self.dispatcher.vfs.get(filename).map(|v| v.as_slice())
    }

    /// Execute exactly one 68k instruction. Returns the per-step result
    /// (continue / halted / unimplemented opcode). Most embedders
    /// should call [`run_steps`](Self::run_steps) instead — it amortises
    /// the per-step bookkeeping (tick advancement, halt detection,
    /// trace ring filling) across the whole budget.
    pub fn step(&mut self) -> StepResult {
        self.cpu.step(&mut self.bus)
    }

    /// Load a parsed Mac resource fork into guest memory: registers
    /// every resource with the Resource Manager, links the application
    /// CODE segments through the trap dispatcher's segment table, and
    /// returns a [`LoadedApp`] describing the entry-point base address
    /// and per-segment offsets.
    ///
    /// Lower-level than [`systemless::game::load_game`](crate::game::load_game) —
    /// that helper auto-detects StuffIt / MacBinary / raw-resource-fork
    /// containers and calls this method internally. Use `load_app`
    /// directly only when you've already parsed the resource fork
    /// yourself (e.g. building a custom test fixture).
    pub fn load_app(&mut self, fork: &ResourceFork) -> Option<LoadedApp> {
        // Resource data is allocated before `init_app` writes the
        // application heap zone header. Reserve the header range first so
        // early app resources cannot land at the zone base and later be
        // overwritten by `bkLim`, `hFstFree`, or `zcbFree`.
        // Inside Macintosh Volume II, II-22.
        self.bus.reserve_heap(APP_ZONE_HEADER_SIZE);
        // Load resources into dispatcher for GetResource trap
        self.dispatcher.load_resources(fork, &mut self.bus);

        let app = load_app_generic(fork, &mut self.bus, self.config.load_address);

        if let Some(ref loaded_app) = app {
            let segments: HashMap<i16, u32> = loaded_app
                .segment_bases
                .iter()
                .map(|(&k, &v)| (k, v))
                .collect();
            self.dispatcher.register_segments(segments);
        }

        app
    }

    pub(crate) fn merge_resources_into_application(&mut self, fork: &ResourceFork) -> usize {
        self.dispatcher
            .merge_resources_into_existing_file(fork, &mut self.bus, 0)
    }

    fn alloc_handle_with_bytes(&mut self, bytes: &[u8]) -> u32 {
        let data_ptr = if bytes.is_empty() {
            0
        } else {
            let data_ptr = self.bus.alloc(bytes.len() as u32);
            if data_ptr == 0 {
                return 0;
            }
            self.bus.write_bytes(data_ptr, bytes);
            data_ptr
        };

        let handle = self.bus.alloc(4);
        if handle == 0 {
            if data_ptr != 0 {
                self.bus.free(data_ptr);
            }
            return 0;
        }

        self.bus.write_long(handle, data_ptr);
        if data_ptr != 0 {
            self.dispatcher.ptr_to_handle.insert(data_ptr, handle);
        }
        handle
    }

    /// Seed the Mac-canonical low-memory globals (`MemTop`,
    /// `CurStackBase`, `ApplLimit`, `Lo3Bytes`, `Ticks`, etc.) and
    /// the A5 World start so `run_steps` lands the guest in a
    /// runnable state. Must be called after [`load_app`](Self::load_app)
    /// and before the first call to [`run_steps`](Self::run_steps);
    /// the higher-level `systemless::game::load_game` helper invokes it
    /// automatically.
    ///
    /// Without `init_app`, A5-relative startup code (CodeWarrior /
    /// Think C runtimes, e.g. Koji / Munchies) sees `CurStackBase` =
    /// 0 and spins forever in the globals-decompression loop.
    pub fn init_app(&mut self, app: &LoadedApp) {
        use crate::memory::globals::addr;
        let ram_size = self.bus.ram_size();

        // Initialize low-memory globals
        self.bus.write_long(addr::MEM_TOP, ram_size);
        // CurStackBase ($0908): "Address of base of stack; start of
        // application global variables." Per Inside Macintosh: Memory
        // 1992, p. 2-104, this points at the boundary where the
        // application's stack region meets the A5 World — equivalently,
        // the address of the *first* below-A5 global. CodeWarrior /
        // Think C runtime startup code (e.g. Koji the Frog, Munchies)
        // reads $0908 as a destination pointer when decompressing
        // initial values into the A5 globals area; pointing it at the
        // stack top instead leaves that decompression loop spinning
        // forever because its termination condition compares the
        // walked-forward A1 against (A5)+. Use `a5_base - below_a5`
        // here — that's the Mac-canonical "start of application
        // globals" regardless of where the stack lives in our
        // (inverted) host memory map.
        let app_globals_start = app.a5_base.saturating_sub(app.code0_header.below_a5);
        self.bus.write_long(addr::CUR_STACK_BASE, app_globals_start);
        self.bus.write_long(addr::CURRENT_A5, app.a5_base);
        self.bus.write_word(addr::ROM85, 0x0000);
        // MMU32Bit ($0CB2): TRUE when 32-bit addressing mode is in effect.
        // Inside Macintosh: Memory 1992, p. 4-25 says applications can test
        // this low-memory byte directly; Systemless's TrapDispatcher already
        // defaults SwapMMUMode to true32b and Gestalt('addr') bit 0 to set.
        self.bus.write_byte(addr::MMU32_BIT, 1);
        // Initialize Ticks ($016A) to a realistic post-boot value.
        // On a real Mac, hundreds of ticks elapse during the boot ROM,
        // system extensions, and Finder startup before the application
        // launches. Games that read Ticks early (e.g. to seed a PRNG)
        // expect a non-zero value; starting at 0 produces degenerate
        // random sequences (e.g., ship heading always zero in EV).
        // 600 ticks ≈ 10 seconds of post-boot time, a conservative
        // estimate for a minimal System 7 configuration.
        self.bus.write_long(addr::TICKS, 0);
        let time = self
            .app_start_time
            .unwrap_or_else(current_mac_epoch_seconds);
        self.bus.write_long(addr::TIME, time);
        // RndSeed ($0156): system random seed initialized during boot.
        // On a real Mac, the boot code seeds this from the real-time clock
        // so that programs that read it directly (without calling Random)
        // get non-deterministic entropy. Use the startup time so play
        // scripts produce repeatable but non-trivial random sequences.
        // Inside Macintosh Volume II, II-387
        self.bus.write_long(addr::RND_SEED, time);
        // MBState: $80 = button UP (Mac convention: 0 = down, $80 = up).
        // RAM is zero-initialized which would mean "button down" — must set explicitly.
        self.bus.write_byte(addr::MB_STATE, 0x80);
        // KeyMapLM ($0174): ROM-maintained current-key bitmap mirrored by
        // GetKeys. Keep it explicitly clear at launch for direct pollers.
        // Inside Macintosh Volume I, I-260; MPW SysEqu.h `KeyMapLM`.
        self.sync_key_map_lowmem();
        // JCrsrTask ($08EE): address of the cursor VBL task routine.
        // MPW Interfaces/AIncludes/LowMemEqu.a lists `JCrsrTask EQU $8EE`.
        // Classic applications can wrap this low-memory vector and then wait
        // for their wrapper to run at interrupt time, so the default must be
        // both non-NIL and callable. `$0060` is one of Systemless's low-memory
        // RTS stubs for direct-call compatibility.
        self.bus.write_word(CURSOR_TASK_NOOP_ADDR, 0x4E75);
        self.bus
            .write_long(addr::J_CRSR_TASK, CURSOR_TASK_NOOP_ADDR);
        // MBarHeight: 20 pixels (standard Roman system script value).
        // Games may set this to 0 to hide the menu bar for full-screen mode.
        // Inside Macintosh Volume V, V-245
        self.bus.write_word(addr::MBAR_HEIGHT, 20);
        // SdVolume ($0260): current speaker volume, low three bits only.
        // Inside Macintosh Volume III, III-425. Some classic apps also read
        // this byte directly as a "Sound Driver present" sentinel — most
        // notably Marathon 1, whose sound module (CODE 5 +$0003F2:
        // `MOVE.B (mem $260).W, (A0)`) short-circuits its audio submission
        // path when this byte is zero. Initialize it to the minimum nonzero
        // compatibility value; higher legacy volume values can change old
        // Sound Driver clients' control flow.
        self.bus.write_byte(addr::SD_VOLUME, 1);

        // Memory Manager zone globals
        // Inside Macintosh Volume II, II-19 and II-29..II-30.
        // The heap starts at 0x200000 (set in bus.rs). HeapEnd begins at
        // the initial application-zone extent; ApplLimit is the ceiling the
        // Memory Manager can grow toward, and BufPtr sits above that limit
        // for sound/disk buffers.
        let heap_start: u32 = 0x200000;
        let zone_header_size: u32 = APP_ZONE_HEADER_SIZE;
        let initial_heap_end = heap_start + zone_header_size;
        let stack_base = app.initial_sp;
        let default_appl_limit = stack_base - APP_STACK_SAFETY_MARGIN;
        let requested_partition_size = self.application_partition_size.or_else(|| {
            app.size_resource
                .and_then(|size| size.preferred_partition_size())
        });
        let appl_limit = requested_partition_size
            .and_then(|partition_size| {
                // Processes 1994, pp. 1-3 and 2-18: the Process Manager
                // allocates the application partition from the app's 'SIZE'
                // resource preferred size when available. A scripted override
                // represents the same Finder-style preferred-memory setting
                // applied to a temporary launch. Systemless keeps the physical
                // stack at the top of guest RAM, but narrows the observable
                // heap limit so FreeMem/MaxMem/process info see the same
                // partition pressure.
                partition_size
                    .checked_sub(APP_STACK_SAFETY_MARGIN)
                    .and_then(|heap_span| heap_start.checked_add(heap_span))
            })
            .filter(|&limit| limit > initial_heap_end && limit < default_appl_limit)
            .unwrap_or(default_appl_limit);
        let buf_ptr = appl_limit; // Buffer area at the limit
        self.bus.write_long(addr::SYS_ZONE, heap_start);
        self.bus.write_long(addr::APP_L_ZONE, heap_start);
        self.bus.write_long(addr::HEAP_END, initial_heap_end);
        self.bus.write_long(addr::APPL_LIMIT, appl_limit);
        self.bus.write_long(addr::BUF_PTR, buf_ptr);
        self.bus.write_long(addr::THE_ZONE, heap_start);

        // CurApRefNum: resource file reference number of the application (word).
        // CurApName: application name as Pascal string (Str31).
        // AppParmHandle is allocated below, after the zone header is reserved.
        // Inside Macintosh Volume II, II-57 to II-58
        self.bus.write_word(addr::CUR_APREF_NUM, 0); // app resources use refnum 0
        if let Some(app_path) = &self.dispatcher.launched_app_path {
            let app_name = crate::trap::dispatch::TrapDispatcher::vfs_basename(app_path);
            let name_bytes = app_name.as_bytes();
            let len = name_bytes.len().min(31);
            self.bus.write_byte(addr::CUR_APNAME, len as u8);
            for (i, &b) in name_bytes.iter().take(len).enumerate() {
                self.bus.write_byte(addr::CUR_APNAME + 1 + i as u32, b);
            }
        }

        // Set the current directory to the application's parent folder so that
        // file-relative lookups (e.g. Marathon opening "Music") resolve correctly.
        // CurDirStore: directory ID of directory last opened (long)
        // SFSaveDisk: negative of volume reference number (word)
        // Inside Macintosh Volume IV, IV-72
        let app_dir_id = self.dispatcher.default_dir_id;
        self.bus.write_long(addr::CUR_DIR_STORE, app_dir_id);
        self.bus.write_word(
            addr::SF_SAVE_DISK,
            (-crate::trap::dispatch::BOOT_VOLUME_REF_NUM) as u16,
        );
        eprintln!(
            "[INIT] CurDirStore={} SFSaveDisk={}",
            app_dir_id,
            (-crate::trap::dispatch::BOOT_VOLUME_REF_NUM) as u16
        );

        // The application stack is ordinary RAM used for stack frames and
        // local variables; classic Mac code does not get it pre-cleared.
        // Memory 1992, 1-9 and 1-39 describe the stack as the region where
        // stack frames live and grow downward from high memory. Seed the
        // unused top-of-stack window with a deterministic nonzero pattern so
        // partially initialized stack records behave like real hardware
        // instead of inheriting zeroed RAM.
        let stack_seed_start = stack_base.saturating_sub(0x8000);
        self.bus
            .fill_bytes(stack_seed_start, stack_base - stack_seed_start, 0xA5);

        // Zone header at heap_start (Inside Macintosh Volume II, II-22)
        // Apps and the Memory Manager read the zone header to determine
        // available memory. zcbFree (offset +12) must reflect free bytes.
        // Reserve heap space so alloc() doesn't overwrite the zone header.
        self.bus.reserve_heap(zone_header_size);
        let zone_size = appl_limit - heap_start;
        let free_bytes = zone_size - zone_header_size;
        self.bus.write_long(heap_start, appl_limit); // bkLim: end of zone
        self.bus
            .write_long(heap_start + 8, heap_start + zone_header_size); // hFstFree
        self.bus.write_long(heap_start + 12, free_bytes); // zcbFree: total free
        self.bus
            .write_long(heap_start + 56, heap_start + zone_header_size); // allocPtr
        eprintln!(
            "[INIT] Zone header: start=${:08X} bkLim=${:08X} zcbFree={} ({:.1}MB)",
            heap_start,
            appl_limit,
            free_bytes,
            free_bytes as f64 / (1024.0 * 1024.0)
        );

        // AppParmHandle: handle to Finder information about files selected
        // when launching the application. A normal Finder application launch
        // with no documents still provides the message/count header:
        // appOpen (0), count 0. Assembly code may read this global directly.
        // Inside Macintosh Volume II, II-57; Files 1992, 1-58.
        let app_param_handle = self.alloc_handle_with_bytes(&[0, 0, 0, 0]);
        self.bus.write_long(addr::APP_PARM_HANDLE, app_param_handle);

        // Write an ExitToShell trap at a known low-memory address so that when
        // main() returns via RTS, the CPU executes ExitToShell and halts cleanly.
        // We use address 0x100 (safe, unused low memory) to hold the A-line instruction.
        let exit_trampoline = 0x100u32;
        self.bus.write_word(exit_trampoline, 0xA9F4); // ExitToShell

        // Pre-allocate the main GDevice with 800x600 8bpp settings
        // and set the low-memory globals that games read directly.
        // screenBits is already initialized to 800x600 8bpp by the bus.
        let gdh = self.dispatcher.ensure_main_gdevice(&mut self.bus);
        let gd_ptr = self.bus.read_long(gdh);
        self.bus.write_long(0x8A4, gdh); // MainDevice
        self.bus.write_long(0xCC8, gdh); // TheGDevice
        self.bus.write_long(0x8A8, gdh); // DeviceList
        eprintln!(
            "[INIT] Set MainDevice=${:08X}, TheGDevice=${:08X} (ptr=${:08X})",
            gdh, gdh, gd_ptr
        );

        // Initialize screen_mode from the main GDevice PixMap.
        let pmap_h = self.bus.read_long(gd_ptr + 22);
        let pmap = self.bus.read_long(pmap_h);
        let scrn_base = self.bus.read_long(pmap);
        let rb = (self.bus.read_word(pmap + 4) & 0x3FFF) as u32;
        let top = self.bus.read_word(pmap + 6) as i16;
        let left = self.bus.read_word(pmap + 8) as i16;
        let bottom = self.bus.read_word(pmap + 10) as i16;
        let right = self.bus.read_word(pmap + 12) as i16;
        let pixel_size = self.bus.read_word(pmap + 32);
        let width = (right - left).max(1) as u16;
        let height = (bottom - top).max(1) as u16;
        self.dispatcher.screen_mode = (scrn_base, rb, width, height, pixel_size);

        // Debug: dump the GDevice chain to verify correctness
        {
            let main_dev = self.bus.read_long(0x8A4);
            let gd = self.bus.read_long(main_dev);
            let pmap_h = self.bus.read_long(gd + 22);
            let pmap = self.bus.read_long(pmap_h);
            let rb = self.bus.read_word(pmap + 4);
            let top = self.bus.read_word(pmap + 6) as i16;
            let left = self.bus.read_word(pmap + 8) as i16;
            let bottom = self.bus.read_word(pmap + 10) as i16;
            let right = self.bus.read_word(pmap + 12) as i16;
            let ps = self.bus.read_word(pmap + 32);
            let gd_top = self.bus.read_word(gd + 34) as i16;
            let gd_left = self.bus.read_word(gd + 36) as i16;
            let gd_bottom = self.bus.read_word(gd + 38) as i16;
            let gd_right = self.bus.read_word(gd + 40) as i16;
            let gd_flags = self.bus.read_word(gd + 20);
            eprintln!(
                "[INIT] GDevice chain: $8A4→${:08X}→${:08X} gdPMap→${:08X}→${:08X}",
                main_dev, gd, pmap_h, pmap
            );
            eprintln!(
                "[INIT]   PixMap: rowBytes=${:04X} bounds=({},{},{},{}) pixelSize={}",
                rb, top, left, bottom, right, ps
            );
            eprintln!(
                "[INIT]   GDevice: gdRect=({},{},{},{}) gdFlags=${:04X}",
                gd_top, gd_left, gd_bottom, gd_right, gd_flags
            );
        }

        // Set CPU state
        self.cpu.write_reg(Register::A5, app.a5_base);
        // Push the exit trampoline as the return address on the stack
        let sp = app.initial_sp.wrapping_sub(4);
        self.bus.write_long(sp, exit_trampoline);
        self.cpu.write_reg(Register::A7, sp);
        // Initialize A6 (frame pointer) to the stack pointer.
        // On a real Mac, the Process Manager sets up A6 before launching
        // the application. The CRT startup code (e.g. Think C's __start)
        // expects A6 to be a valid stack address for its initial LINK frame.
        self.cpu.write_reg(Register::A6, sp);
        self.cpu
            .write_reg(Register::PC, app.entry_point(app.a5_base));
    }

    /// Mix and queue audio samples without full frame finalization.
    /// Used to keep the audio buffer fed during long CPU frames.
    pub fn mix_audio(&mut self, num_samples: usize) {
        self.mix_host_audio(num_samples);
    }

    fn queue_mixed_audio(&mut self, stereo_samples: &[u8]) {
        if stereo_samples.is_empty() {
            return;
        }
        if let Some(ref mut audio) = self.audio {
            audio.queue_stereo_samples(stereo_samples);
        }
        for frame in stereo_samples.chunks_exact(2) {
            let left = frame[0] as i32 - 0x80;
            let right = frame[1] as i32 - 0x80;
            self.audio_buffer
                .push(((left + right) / 2 + 0x80).clamp(0, 255) as u8);
        }
    }

    fn queue_host_silence_audio(&mut self, num_samples: usize) {
        if num_samples == 0 {
            return;
        }
        if let Some(ref mut audio) = self.audio {
            audio.queue_stereo_samples(&vec![0x80; num_samples * 2]);
        }
    }

    fn mix_host_audio(&mut self, mut remaining_samples: usize) {
        while remaining_samples > 0 {
            self.try_load_pending_double_buffers();
            self.dispatcher.service_guest_sound_queues(&mut self.bus);

            let chunk = self
                .dispatcher
                .sound_manager
                .samples_until_next_exhaustion()
                .map(|samples| samples.max(1).min(remaining_samples))
                .unwrap_or(remaining_samples);

            let samples = self.dispatcher.sound_manager.mix_frame_stereo(chunk);
            if samples.is_empty() {
                self.queue_host_silence_audio(remaining_samples);
                self.dispatcher
                    .release_finished_internal_sound_channels(&mut self.bus);
                break;
            }
            self.queue_mixed_audio(&samples);
            self.dispatcher
                .release_finished_internal_sound_channels(&mut self.bus);
            remaining_samples -= chunk;
        }
    }

    fn finish_host_frame(&mut self, audio_samples: usize, sound_interrupt_dispatched: bool) {
        // Redraw menu bar and window chrome after each frame.
        // On a real Mac the Window Manager maintains these as
        // separate layers; here they are raw framebuffer pixels
        // that game drawing (explosions, etc.) can overwrite.
        self.dispatcher.redraw_chrome(&mut self.bus);
        self.finish_audio_frame(audio_samples, sound_interrupt_dispatched);
    }

    fn finish_audio_frame(&mut self, audio_samples: usize, sound_interrupt_dispatched: bool) {
        // Try to load any double-buffer data that callbacks have refilled.
        self.try_load_pending_double_buffers();

        // Sound channels expose an in-memory queue that some games update
        // directly instead of routing every command through SndDoCommand.
        self.dispatcher.service_guest_sound_queues(&mut self.bus);

        // Mix and output audio for this frame.
        if audio_samples > 0 {
            self.mix_host_audio(audio_samples);
        }

        self.dispatcher
            .sync_guest_sound_channel_state(&mut self.bus);

        if !sound_interrupt_dispatched {
            let fired_sound_callback = self.fire_sound_callbacks();
            if !fired_sound_callback {
                // Fire pending double-buffer callbacks (SndPlayDoubleBuffer).
                self.fire_sound_doubleback_callbacks();
            }
        }
    }

    /// Mix a GUI-only audio slice without running foreground guest code or
    /// redrawing the frame. Used by realtime frontends to let Sound Manager
    /// doubleback callbacks run between small audio chunks when TickCount is
    /// already caught up to the wall clock.
    pub fn mix_gui_audio_slice(&mut self, audio_samples: usize) {
        self.finish_audio_frame(audio_samples, false);
    }

    /// Try to fast-forward past a TickCount spin-wait loop. Returns
    /// true iff the `tick_cap` was hit during advancement (caller
    /// should break the outer run loop); returns false if no match,
    /// if the advance succeeded, or if the max-cap
    /// (`SPIN_FASTFWD_MAX_TICKS`) protected us from a runaway target.
    /// All bytes are read from guest memory — the function never runs
    /// game code.
    fn try_tickcount_spin_fastfwd(
        &mut self,
        pc_after_trap: u32,
        tick_cap: Option<u32>,
        count: &mut usize,
    ) -> bool {
        // Step 1: MOVE.L (A7)+, Dn (shared by all templates).
        let w0 = self.bus.read_word(pc_after_trap);
        if (w0 & 0xF1FF) != 0x201F {
            return false;
        }
        let dn = ((w0 >> 9) & 7) as usize;

        let w1 = self.bus.read_word(pc_after_trap.wrapping_add(2));

        // Template A: SUBQ.L #imm, Dn; CMP.L Dn, Dm; BHI.S <back-to-SUBQ-#4,A7>
        if (w1 & 0xF1F8) == 0x5180 && (w1 & 0x0007) as usize == dn {
            return self.try_spin_template_a(pc_after_trap, dn, w1, tick_cap, count);
        }

        // Template B: CMP.L (d16, An), Dn; BLS.S <back>
        if (w1 & 0xF1F8) == 0xB0A8 && ((w1 >> 9) & 7) as usize == dn {
            return self.try_spin_template_b(pc_after_trap, dn, w1, tick_cap, count);
        }

        // Template C: CMP.L (xxx).L, Dn; BCS.S <back>
        if (w1 & 0xF1FF) == 0xB0B9 && ((w1 >> 9) & 7) as usize == dn {
            return self.try_spin_template_c(pc_after_trap, dn, tick_cap, count);
        }

        false
    }

    /// Template A: classic pre-System-7 SUBQ-compare spin.
    ///   MOVE.L (A7)+, Dn
    ///   SUBQ.L #imm, Dn
    ///   CMP.L  Dn, Dm
    ///   BHI.S  <SUBQ.W #4, A7 before the _TickCount>
    fn try_spin_template_a(
        &mut self,
        pc_after_trap: u32,
        dn: usize,
        w1: u16,
        tick_cap: Option<u32>,
        count: &mut usize,
    ) -> bool {
        let imm_bits = ((w1 >> 9) & 7) as u32;
        let imm = if imm_bits == 0 { 8 } else { imm_bits };

        let w2 = self.bus.read_word(pc_after_trap.wrapping_add(4));
        let w3 = self.bus.read_word(pc_after_trap.wrapping_add(6));

        // CMP.L Dn, Dm (0xB_80 family, src-mode 000 = data reg direct).
        if (w2 & 0xF1F8) != 0xB080 || (w2 & 0x0007) as usize != dn {
            return false;
        }
        let dm = ((w2 >> 9) & 7) as usize;

        // BHI.S
        if (w3 & 0xFF00) != 0x6200 {
            return false;
        }
        let disp8 = (w3 & 0xFF) as i8 as i32;
        if disp8 == 0 {
            return false;
        }
        let branch_src = pc_after_trap.wrapping_add(6);
        let target = (branch_src.wrapping_add(2) as i32).wrapping_add(disp8) as u32;
        if target != pc_after_trap.wrapping_sub(4) {
            return false;
        }

        let dm_val = self.cpu.core.d(dm);
        let target_tick = dm_val.wrapping_add(imm);
        match self.advance_until_tick(target_tick, tick_cap) {
            AdvanceResult::CapHit => return true,
            AdvanceResult::Interrupted | AdvanceResult::TooFar => return false,
            AdvanceResult::Advanced => {}
        }

        // Synthesise exit: Dn = final_tick - imm = Dm (by definition of
        // the fall-through condition), A7 += 4, PC past BHI.S.
        let final_tick = self.dispatcher.tick_count;
        let sp = self.cpu.core.a(7);
        self.cpu.core.set_a(7, sp.wrapping_add(4));
        self.cpu.core.set_d(dn, final_tick.wrapping_sub(imm));
        self.cpu.core.pc = pc_after_trap.wrapping_add(8);

        *count += 4;
        self.total_instructions = self.total_instructions.wrapping_add(4);
        false
    }

    /// Template B: memory-target variant.
    ///   MOVE.L (A7)+, Dn
    ///   CMP.L  (d16, An), Dn    ; 4 bytes (opcode word + d16)
    ///   BLS.S  <backward, into body that rewrites (An+d16)>
    ///
    /// Exit when `TickCount() > *(An+d16)`, i.e. `target_tick =
    /// *(An+d16) + 1`.
    fn try_spin_template_b(
        &mut self,
        pc_after_trap: u32,
        dn: usize,
        w1: u16,
        tick_cap: Option<u32>,
        count: &mut usize,
    ) -> bool {
        let an = (w1 & 7) as usize;
        let d16 = self.bus.read_word(pc_after_trap.wrapping_add(4)) as i16 as i32;
        let w_brk = self.bus.read_word(pc_after_trap.wrapping_add(6));

        // BLS.S disp8
        if (w_brk & 0xFF00) != 0x6300 {
            return false;
        }
        let disp8 = (w_brk & 0xFF) as i8 as i32;
        if disp8 == 0 {
            return false;
        }
        // Branch target must be a short backward branch. We don't
        // insist on an exact target since template B's body runs
        // BEFORE the _TickCount trap (not just the SUBQ #4, A7).
        let branch_src = pc_after_trap.wrapping_add(6);
        let target = (branch_src.wrapping_add(2) as i32).wrapping_add(disp8) as u32;
        if target >= pc_after_trap || pc_after_trap.wrapping_sub(target) > 128 {
            return false;
        }

        let an_val = self.cpu.core.a(an);
        let mem_addr = (an_val as i32).wrapping_add(d16) as u32;
        let mem_target = self.bus.read_long(mem_addr);
        let target_tick = mem_target.wrapping_add(1);

        match self.advance_until_tick(target_tick, tick_cap) {
            AdvanceResult::CapHit => return true,
            AdvanceResult::Interrupted | AdvanceResult::TooFar => return false,
            AdvanceResult::Advanced => {}
        }

        // Synthesise exit: Dn = final_tick, A7 += 4, PC past BLS.S.
        // body_size: MOVE.L (2) + CMP.L w/d16 (4) + BLS.S (2) = 8 bytes.
        let final_tick = self.dispatcher.tick_count;
        let sp = self.cpu.core.a(7);
        self.cpu.core.set_a(7, sp.wrapping_add(4));
        self.cpu.core.set_d(dn, final_tick);
        self.cpu.core.pc = pc_after_trap.wrapping_add(8);

        *count += 3;
        self.total_instructions = self.total_instructions.wrapping_add(3);
        false
    }

    /// Template C: absolute-long target variant.
    ///   MOVE.L (A7)+, Dn
    ///   CMP.L  (xxx).L, Dn
    ///   BCS.S  <back-to-SUBQ.W #4,A7 before the _TickCount>
    ///
    /// Exit when `TickCount() >= *(xxx).L`.
    fn try_spin_template_c(
        &mut self,
        pc_after_trap: u32,
        dn: usize,
        tick_cap: Option<u32>,
        count: &mut usize,
    ) -> bool {
        let target_addr = self.bus.read_long(pc_after_trap.wrapping_add(4));
        let w_brk = self.bus.read_word(pc_after_trap.wrapping_add(8));

        // BCS.S/BLO.S disp8. The loop repeats while Dn < *(xxx).L.
        if (w_brk & 0xFF00) != 0x6500 {
            return false;
        }
        let disp8 = (w_brk & 0xFF) as i8 as i32;
        if disp8 == 0 {
            return false;
        }
        let branch_src = pc_after_trap.wrapping_add(8);
        let target = (branch_src.wrapping_add(2) as i32).wrapping_add(disp8) as u32;
        if target != pc_after_trap.wrapping_sub(4) {
            return false;
        }

        let target_tick = self.bus.read_long(target_addr);
        match self.advance_until_tick(target_tick, tick_cap) {
            AdvanceResult::CapHit => return true,
            AdvanceResult::Interrupted | AdvanceResult::TooFar => return false,
            AdvanceResult::Advanced => {}
        }

        let final_tick = self.dispatcher.tick_count;
        let sp = self.cpu.core.a(7);
        self.cpu.core.set_a(7, sp.wrapping_add(4));
        self.cpu.core.set_d(dn, final_tick);
        self.cpu.core.pc = pc_after_trap.wrapping_add(10);

        *count += 3;
        self.total_instructions = self.total_instructions.wrapping_add(3);
        false
    }

    /// Shared helper: advance guest ticks until `target_tick` is
    /// reached.
    fn advance_until_tick(&mut self, target_tick: u32, tick_cap: Option<u32>) -> AdvanceResult {
        let current_tick = self.dispatcher.tick_count;
        let ticks_to_advance = target_tick.wrapping_sub(current_tick);
        if ticks_to_advance > SPIN_FASTFWD_MAX_TICKS {
            return AdvanceResult::TooFar;
        }
        for _ in 0..ticks_to_advance {
            if let Some(cap) = tick_cap {
                if self.bus.read_long(0x016A) >= cap {
                    return AdvanceResult::CapHit;
                }
            }
            self.advance_guest_tick();
            if self.active_interrupt_callback.is_some() {
                return AdvanceResult::Interrupted;
            }
        }
        AdvanceResult::Advanced
    }

    fn run_steps_internal(
        &mut self,
        max_steps: usize,
        tick_cap: Option<u32>,
        audio_samples: usize,
        yield_for_ui: bool,
        sound_work_only: bool,
    ) -> (usize, bool) {
        // Freeze ticks while menu/control tracking is active. ModalDialog
        // refires still return to the GUI for intermediate rendering, but
        // they must not freeze ticks: EV's pilot dialogs keep Sound/VBL/Time
        // Manager work alive through the dialog manager's event loop.
        // On entry, cap tick_cap to the frozen value; when tracking ends
        // mid-frame, snap $016A to wall-clock time so there's no gap to catch
        // up on.
        let real_tick_cap = tick_cap;
        let tick_cap = match self.frozen_ticks {
            Some(frozen) => tick_cap.map(|_| frozen),
            None => tick_cap,
        };

        self.dispatcher.instruction_count = self.total_instructions;
        let mut count = 0;
        let mut tick_cap_reached = false;
        let mut sound_interrupt_dispatched = self
            .active_interrupt_callback
            .map(|callback| is_sound_interrupt_source(callback.source))
            .unwrap_or(false);

        while count < max_steps && !self.halted && !tick_cap_reached {
            if sound_work_only
                && self.active_interrupt_callback.is_none()
                && (sound_interrupt_dispatched || !self.has_pending_sound_work())
            {
                break;
            }

            // Sound callbacks are interrupt work. If a previous slice queued
            // one, dispatch it before running more foreground guest code. Do
            // not drain the whole queue in one CPU slice: double-buffer
            // callbacks are paced by audio-buffer completion, and firing
            // several back-to-back at the same guest PC/tick makes games that
            // run their own mixer refill with click-sized fragments.
            if self.active_interrupt_callback.is_none() && !sound_interrupt_dispatched {
                sound_interrupt_dispatched = self.fire_sound_callbacks();
                if !sound_interrupt_dispatched {
                    sound_interrupt_dispatched = self.fire_sound_doubleback_callbacks();
                }
                if sound_work_only && !sound_interrupt_dispatched {
                    continue;
                }
            }

            if sound_work_only && self.active_interrupt_callback.is_none() {
                break;
            }

            // Service blocking traps (Delay, WaitNextEvent sleep).
            if !sound_work_only {
                if self.service_wait_sleep_ticks(tick_cap) {
                    break;
                }
                if self.service_delay_ticks(tick_cap) {
                    break;
                }
            }
            if self.cpu.is_stopped() {
                self.halted = true;
                self.halted_pc = Some(self.cpu.read_reg(Register::PC));
                self.halted_sp = Some(self.cpu.read_reg(Register::A7));
                self.halted_d0 = Some(self.cpu.read_reg(Register::D0));
                self.dump_trace();
                return (count, false);
            }

            let pc = self.cpu.read_reg(Register::PC);
            // Defer reading SP until needed. sp is only used by the
            // interrupt-callback match (rare), the env-gated
            // trace_buffer path, and the PC-bounds error branch.
            //
            // Opcode + trace_buffer reads are gated behind
            // `SYSTEMLESS_TRACE_BUFFER`. Without the gate the `read_word`
            // and `VecDeque` pop/push run on every instruction fetch
            // just so `dump_trace()` can show recent instructions on a
            // halt. Default off; enable for crash diagnostics.
            if trace_buffer_enabled() {
                let opcode = self.bus.read_word(pc);
                let a0 = self.cpu.read_reg(Register::A0);
                let a6 = self.cpu.read_reg(Register::A6);
                let a5 = self.cpu.read_reg(Register::A5);
                let sp = self.cpu.read_reg(Register::A7);
                if self.trace_buffer.len() >= 200 {
                    self.trace_buffer.pop_front();
                }
                self.trace_buffer.push_back((pc, opcode, a0, sp, a6, a5));
            }

            if let Some(active_interrupt_callback) = self.active_interrupt_callback {
                let sp = self.cpu.read_reg(Register::A7);
                if pc == active_interrupt_callback.resume_pc
                    && sp == active_interrupt_callback.resume_sp
                {
                    if trace_timer_enabled() {
                        eprintln!(
                            "[TIMER] resume {:?} pc=${:08X} sp=${:08X} restore_ccr=${:02X}",
                            active_interrupt_callback.source, pc, sp, active_interrupt_callback.ccr
                        );
                    }
                    if trace_sound_runner_enabled()
                        && is_sound_interrupt_source(active_interrupt_callback.source)
                    {
                        eprintln!(
                            "[SOUND-CB] resume {:?} pc=${:08X} sp=${:08X} restore_ccr=${:02X}",
                            active_interrupt_callback.source, pc, sp, active_interrupt_callback.ccr
                        );
                    }
                    for (index, value) in
                        active_interrupt_callback.d_regs.iter().copied().enumerate()
                    {
                        self.cpu.write_reg(
                            match index {
                                0 => Register::D0,
                                1 => Register::D1,
                                2 => Register::D2,
                                3 => Register::D3,
                                4 => Register::D4,
                                5 => Register::D5,
                                6 => Register::D6,
                                _ => Register::D7,
                            },
                            value,
                        );
                    }
                    for (index, value) in
                        active_interrupt_callback.a_regs.iter().copied().enumerate()
                    {
                        self.cpu.write_reg(
                            match index {
                                0 => Register::A0,
                                1 => Register::A1,
                                2 => Register::A2,
                                3 => Register::A3,
                                4 => Register::A4,
                                5 => Register::A5,
                                6 => Register::A6,
                                _ => Register::A7,
                            },
                            value,
                        );
                    }
                    self.cpu.core.set_ccr(active_interrupt_callback.ccr);
                    if let Some((port, gdevice)) = active_interrupt_callback.restore_port {
                        self.dispatcher.set_current_port_state(
                            &mut self.bus,
                            &mut self.cpu,
                            port,
                            Some(gdevice),
                        );
                    }
                    let completed_dialog_draw_proc = matches!(
                        active_interrupt_callback.source,
                        ActiveInterruptCallbackSource::DialogDrawProc
                    );
                    let completed_modeless_dialog_draw_proc = completed_dialog_draw_proc
                        && self.dispatcher.active_modeless_dialog_draw_proc.is_some();
                    if completed_dialog_draw_proc {
                        self.dispatcher
                            .finalize_dialog_draw_procs_if_idle(&mut self.bus);
                    }
                    self.active_interrupt_callback = None;
                    if completed_modeless_dialog_draw_proc && self.fire_modeless_dialog_draw_proc()
                    {
                        continue;
                    }
                    if sound_work_only {
                        break;
                    }
                } else if trace_timer_enabled() {
                    eprintln!(
                        "[TIMER] pending {:?} pc=${:08X} sp=${:08X} waiting_for pc=${:08X} sp=${:08X}",
                        active_interrupt_callback.source,
                        pc,
                        sp,
                        active_interrupt_callback.resume_pc,
                        active_interrupt_callback.resume_sp
                    );
                }
            }

            if pc == 0 {
                // App's RTS chain reached PC=0 — treat as clean exit.
                // Some apps (e.g. Centaurian 1.2.1) zero out our
                // exit-trampoline at \$100 during their CRT init then
                // pop past the saved A6 chain and JMP through a
                // popped-from-out-of-RAM zero. Real Mac OS would have
                // a launcher-provided return-to-Finder address; on
                // the HLE we just halt gracefully.
                if trace_load_enabled() {
                    eprintln!(
                        "[RUN_STEPS] App reached PC=0 (clean exit via deep RTS chain) at count={}",
                        count
                    );
                }
                self.dump_trace();
                self.halted = true;
                self.halted_pc = Some(0);
                self.halted_sp = Some(self.cpu.read_reg(Register::A7));
                self.halted_d0 = Some(self.cpu.read_reg(Register::D0));
                return (count, false);
            }

            if pc >= self.bus.ram_size() || pc < 0x60 {
                // Read opcode + sp on-demand in the error branch.
                let opcode = self.bus.read_word(pc);
                let sp = self.cpu.read_reg(Register::A7);
                eprintln!(
                    "[RUN_STEPS] Invalid PC ${:08X} at count={} sp=${:08X} op=${:04X}",
                    pc, count, sp, opcode
                );
                self.dump_invalid_pc_state();
                if let Some(hint) = decode_fakeptr_pc(pc) {
                    eprintln!("[RUN_STEPS]   {}", hint);
                } else if let Some((entry_pc, hint)) = self.trace_find_fakeptr_entry() {
                    eprintln!(
                        "[RUN_STEPS]   PC drifted ${:X} bytes from a fake-ptr entry at \
                         ${:08X}. {}",
                        pc.wrapping_sub(entry_pc),
                        entry_pc,
                        hint
                    );
                }
                self.halted = true;
                self.halted_pc = Some(pc);
                self.halted_sp = Some(sp);
                self.halted_d0 = Some(self.cpu.read_reg(Register::D0));
                self.dump_trace();
                return (count, false);
            }

            // Tick advancement: deduct 1 instruction; when the budget hits
            // zero, advance $016A and refill from instructions_per_tick.
            if !sound_work_only {
                tick_cap_reached = self.charge_tick_budget(1, tick_cap);
                if tick_cap_reached {
                    break;
                }
            }

            // Update debug counters for watchpoint tracking (debug builds only)
            #[cfg(debug_assertions)]
            if crate::memory::bus::watchpoint_armed() {
                crate::memory::bus::increment_step();
                crate::memory::bus::set_current_pc(pc);
                crate::memory::bus::set_watch_registers(
                    self.cpu.read_reg(Register::A0),
                    self.cpu.read_reg(Register::A1),
                    self.cpu.read_reg(Register::A6),
                    self.cpu.read_reg(Register::A7),
                );
            }

            // Mirror PC for release-mode memory/framebuffer traces;
            // watchpoint context above is debug-only.
            if crate::memory::bus::fb_write_trace_active()
                || crate::memory::bus::mem_read_trace_active()
            {
                crate::memory::bus::set_current_pc(pc);
            }

            let trace_pc_range_hit = trace_pc_range_contains(pc, self.dispatcher.tick_count);
            if trace_pc_range_hit {
                let sp = self.cpu.read_reg(Register::A7);
                let a6 = self.cpu.read_reg(Register::A6);
                let stack0 = self.bus.read_long(sp);
                let stack4 = self.bus.read_long(sp.wrapping_add(4));
                let stack8 = self.bus.read_word(sp.wrapping_add(8));
                let frame_ret = self.bus.read_long(a6.wrapping_add(4));
                let frame_arg = self.bus.read_word(a6.wrapping_add(8));
                eprintln!(
                    "[TRACE-PC-RANGE] pc=${:08X} op=${:04X} ccr=${:02X} d0=${:08X} d1=${:08X} d2=${:08X} d3=${:08X} d4=${:08X} d5=${:08X} d6=${:08X} d7=${:08X} a0=${:08X} a1=${:08X} a2=${:08X} a3=${:08X} a4=${:08X} a5=${:08X} a6=${:08X} sp=${:08X} stack0=${:08X} stack4=${:08X} stack8=${:04X} frame_ret=${:08X} frame_arg=${:04X}",
                    pc,
                    self.bus.read_word(pc),
                    self.cpu.core.get_ccr(),
                    self.cpu.read_reg(Register::D0),
                    self.cpu.read_reg(Register::D1),
                    self.cpu.read_reg(Register::D2),
                    self.cpu.read_reg(Register::D3),
                    self.cpu.read_reg(Register::D4),
                    self.cpu.read_reg(Register::D5),
                    self.cpu.read_reg(Register::D6),
                    self.cpu.read_reg(Register::D7),
                    self.cpu.read_reg(Register::A0),
                    self.cpu.read_reg(Register::A1),
                    self.cpu.read_reg(Register::A2),
                    self.cpu.read_reg(Register::A3),
                    self.cpu.read_reg(Register::A4),
                    self.cpu.read_reg(Register::A5),
                    a6,
                    sp,
                    stack0,
                    stack4,
                    stack8,
                    frame_ret,
                    frame_arg,
                );
            }
            // Execute one instruction.
            match self.cpu.step(&mut self.bus) {
                StepResult::Ok => {
                    count += 1;
                    self.total_instructions = self.total_instructions.wrapping_add(1);
                    // Populate opcode histogram if enabled. cpu.core.ir
                    // holds the last-fetched opcode (set by step's
                    // read_imm_16). Only counts successful non-trap
                    // steps here; A-line opcodes go through the trap
                    // histogram instead. Zero cost when disabled
                    // (cached bool).
                    if trace_opcode_counts_enabled() {
                        let opcode = self.cpu.core.ir as u16 as usize;
                        self.opcode_histogram[opcode] =
                            self.opcode_histogram[opcode].saturating_add(1);
                    }
                    // Sampled PC histogram. 1/1000 sampling keeps the
                    // HashMap cost bounded.
                    if trace_hot_pc_enabled()
                        && self.total_instructions.is_multiple_of(PC_SAMPLE_INTERVAL)
                    {
                        *self.pc_histogram.entry(pc).or_insert(0) += 1;
                    }
                }
                StepResult::Stopped => {
                    let halted_pc = self.cpu.read_reg(Register::PC);
                    eprintln!(
                        "[RUN_STEPS] CPU stopped at count={} pc=${:08X} op=${:04X}",
                        count,
                        halted_pc,
                        self.bus.read_word(halted_pc)
                    );
                    if let Some(hint) = decode_fakeptr_pc(halted_pc) {
                        eprintln!("[RUN_STEPS]   {}", hint);
                    } else if let Some((entry_pc, hint)) = self.trace_find_fakeptr_entry() {
                        eprintln!(
                            "[RUN_STEPS]   PC drifted ${:X} bytes from a fake-ptr entry at \
                             ${:08X}. {}",
                            halted_pc.wrapping_sub(entry_pc),
                            entry_pc,
                            hint
                        );
                    }
                    self.halted = true;
                    self.halted_pc = Some(halted_pc);
                    self.halted_sp = Some(self.cpu.read_reg(Register::A7));
                    self.halted_d0 = Some(self.cpu.read_reg(Register::D0));
                    self.dump_trace();
                    return (count, false);
                }
                StepResult::Aline(opcode) => {
                    count += 1;
                    self.total_instructions = self.total_instructions.wrapping_add(1);

                    // --- Runner-inline fast paths for hot traps ---
                    //
                    // Rule of thumb: only inline a trap's body here if
                    // BOTH hold:
                    //   (a) per-call saving > ~100ns (handler does
                    //       non-trivial work relative to dispatch
                    //       overhead), AND
                    //   (b) call count > ~5M per reference workload.
                    // Below either threshold, the dispatch-cost
                    // saving is swamped by I-cache pressure from
                    // adding more code to this hot loop.
                    //
                    // Current inlines:
                    //   $A975 TickCount
                    //   $A991 ModalDialog no-op
                    // plus:
                    //   $A975 spin-wait fast-fwd — detects TickCount
                    //       compare-and-branch templates and advances
                    //       guest ticks.
                    // --- end guidance ---

                    // Pre-dispatch fast path for TickCount ($A975).
                    // Handler body is `read self.tick_count` (cached)
                    // + write to SP. Skip the full dispatch →
                    // `dispatch_toolbox` → match chain; inline the
                    // 3-line body directly. Counters still update so
                    // logs and the trap histogram reflect real
                    // dispatch count.
                    if opcode == 0xA975 {
                        let sp = self.cpu.core.a(7);
                        let tick = self.dispatcher.tick_count;
                        self.bus.write_long(sp, tick);
                        self.dispatcher.trap_count += 1;
                        self.dispatcher.current_trap_word = opcode;
                        let idx = (opcode & 0xFFF) as usize;
                        self.dispatcher.trap_histogram[idx] =
                            self.dispatcher.trap_histogram[idx].saturating_add(1);
                        // Count this entry as inline-skipped — the
                        // fast path bypassed dispatch().
                        self.dispatcher.inline_skipped[idx] =
                            self.dispatcher.inline_skipped[idx].saturating_add(1);

                        // Generic TickCount spin-wait fast-forward (opt-in).
                        // Check post-trap bytes against the spin-wait
                        // template; if matched, skip straight past the
                        // loop. m68k's step() advances PC past the A-trap
                        // (read_imm_16 does pc += 2), so the post-trap
                        // PC is already at pc + 2.
                        if spin_wait_fastfwd_enabled_for(yield_for_ui) {
                            let post_trap_pc = pc.wrapping_add(2);
                            let hit_cap =
                                self.try_tickcount_spin_fastfwd(post_trap_pc, tick_cap, &mut count);
                            if hit_cap {
                                break;
                            }
                        }
                        continue;
                    }

                    // Pre-dispatch fast skip for no-op ModalDialog
                    // refires. When dialog tracking is active and no
                    // state change is possible this step (draw procs
                    // done, pixels already captured, no filter, no
                    // flash animation, no queued events), skip the
                    // full dispatch → handler → post-dispatch rewind
                    // loop entirely. Rewind PC directly and continue.
                    // Counters still update so logs and the trap
                    // histogram reflect real dispatch count.
                    if opcode == 0xA991 {
                        // Extracted into `modaldialog_refire_is_noop` so
                        // the gate logic is unit-tested. See its
                        // doc-comment for the full list of conditions.
                        let (
                            has_tracking,
                            filter_allows_noop,
                            flash_remaining_zero,
                            draw_procs_done,
                            rendered_pixels_final,
                        ) = self
                            .dispatcher
                            .dialog_tracking
                            .as_ref()
                            .map(|t| {
                                let idle_dialog_mouse =
                                    self.dispatcher.mouse_down_over_dialog_button()
                                        || self.dispatcher.mouse_down_over_dialog_plain_user_item()
                                        || (self.dispatcher.event_queue.is_empty()
                                            && self
                                                .dispatcher
                                                .pending_dialog_plain_user_item_mouse_down());
                                let paced_filter_idle = t.filter_proc != 0
                                    && t.last_filter_event.is_none()
                                    && !idle_dialog_mouse
                                    && self.dialog_filter_null_event_already_sent_this_tick(
                                        t.dialog_ptr,
                                    )
                                    && !self.dialog_filter_has_real_event_pending(t.dialog_ptr);
                                (
                                    true,
                                    t.filter_proc == 0 || paced_filter_idle,
                                    t.flash_remaining == 0,
                                    t.draw_procs_done,
                                    t.rendered_pixels_final,
                                )
                            })
                            .unwrap_or((false, false, false, false, false));
                        let noop_refire = modaldialog_refire_is_noop(
                            yield_for_ui,
                            has_tracking,
                            filter_allows_noop,
                            flash_remaining_zero,
                            draw_procs_done,
                            rendered_pixels_final,
                            self.dispatcher.event_queue.is_empty(),
                        );
                        if noop_refire {
                            // Batch additional virtual no-op refires
                            // without re-entering `cpu.step`. Each saved
                            // step avoids the PC save + register snapshot
                            // + opcode fetch + `dispatch_group_a` branch
                            // path.
                            let idx = (opcode & 0xFFF) as usize;
                            self.dispatcher.trap_count += 1;
                            self.dispatcher.current_trap_word = opcode;
                            self.dispatcher.trap_histogram[idx] =
                                self.dispatcher.trap_histogram[idx].saturating_add(1);
                            // Count inline-skipped entries separately
                            // from real dispatches so the trap-timing
                            // histogram can show per-real-dispatch ns.
                            self.dispatcher.inline_skipped[idx] =
                                self.dispatcher.inline_skipped[idx].saturating_add(1);
                            const BATCH: u32 = 64;
                            let mut budget = BATCH - 1;
                            while budget > 0 && count < max_steps && !tick_cap_reached {
                                tick_cap_reached = self.charge_tick_budget(1, tick_cap);
                                if tick_cap_reached {
                                    break;
                                }
                                count += 1;
                                self.total_instructions = self.total_instructions.wrapping_add(1);
                                self.dispatcher.trap_count += 1;
                                self.dispatcher.trap_histogram[idx] =
                                    self.dispatcher.trap_histogram[idx].saturating_add(1);
                                self.dispatcher.inline_skipped[idx] =
                                    self.dispatcher.inline_skipped[idx].saturating_add(1);
                                budget -= 1;
                            }
                            self.cpu.write_reg(Register::PC, pc);
                            continue;
                        }
                    }

                    // Pre-dispatch fast path for PtInRect ($A8AD).
                    // EV calls this millions of times while walking dialog
                    // controls. The handler is pure stack/Rect arithmetic, so
                    // inline the exact Pascal ABI and keep accounting aligned
                    // with TrapDispatcher::dispatch.
                    if opcode == 0xA8AD {
                        let sp = self.cpu.core.a(7);
                        let rect_ptr = self.bus.read_long(sp);
                        let pt_v = self.bus.read_word(sp + 4) as i16;
                        let pt_h = self.bus.read_word(sp + 6) as i16;
                        let top = self.bus.read_word(rect_ptr) as i16;
                        let left = self.bus.read_word(rect_ptr + 2) as i16;
                        let bottom = self.bus.read_word(rect_ptr + 4) as i16;
                        let right = self.bus.read_word(rect_ptr + 6) as i16;
                        let in_rect = pt_v >= top && pt_v < bottom && pt_h >= left && pt_h < right;
                        self.bus
                            .write_word(sp + 8, if in_rect { 0x0100 } else { 0 });
                        self.cpu.write_reg(Register::A7, sp + 8);

                        self.dispatcher.trap_count += 1;
                        self.dispatcher.current_trap_word = opcode;
                        if pc < 0x0080_0000
                            && !self.dispatcher.is_menu_tracking()
                            && !self.dispatcher.is_dialog_tracking()
                            && !self.dispatcher.is_control_tracking()
                        {
                            self.dispatcher.game_trap_count += 1;
                        }
                        let idx = (opcode & 0xFFF) as usize;
                        self.dispatcher.trap_histogram[idx] =
                            self.dispatcher.trap_histogram[idx].saturating_add(1);
                        self.dispatcher.inline_skipped[idx] =
                            self.dispatcher.inline_skipped[idx].saturating_add(1);
                        continue;
                    }

                    // Pre-dispatch fast path for EventAvail ($A971).
                    // Marathon polls this heavily while waiting at terminal
                    // panels. Reuse the dispatcher helpers so event filtering
                    // and EventRecord layout stay centralized.
                    if opcode == 0xA971 {
                        let sp = self.cpu.core.a(7);
                        let event_ptr = self.bus.read_long(sp);
                        let event_mask = self.bus.read_word(sp + 4);

                        if let Some(ev) = self.dispatcher.peek_toolbox_event(&self.bus, event_mask)
                        {
                            self.dispatcher.write_event_record(
                                &mut self.bus,
                                event_ptr,
                                ev.what,
                                ev.message,
                                ev.where_v,
                                ev.where_h,
                                ev.modifiers,
                            );
                            self.bus.write_word(sp + 6, 0xFFFF);
                        } else {
                            self.dispatcher.write_event_record(
                                &mut self.bus,
                                event_ptr,
                                0,
                                0,
                                self.dispatcher.mouse_pos.0,
                                self.dispatcher.mouse_pos.1,
                                self.dispatcher.current_event_modifiers(),
                            );
                            self.bus.write_word(sp + 6, 0);
                        }
                        self.cpu.write_reg(Register::A7, sp + 6);

                        self.dispatcher.trap_count += 1;
                        self.dispatcher.current_trap_word = opcode;
                        let idx = (opcode & 0xFFF) as usize;
                        self.dispatcher.trap_histogram[idx] =
                            self.dispatcher.trap_histogram[idx].saturating_add(1);
                        self.dispatcher.inline_skipped[idx] =
                            self.dispatcher.inline_skipped[idx].saturating_add(1);
                        continue;
                    }

                    match self
                        .dispatcher
                        .dispatch(opcode, &mut self.cpu, &mut self.bus)
                    {
                        Ok(()) => {
                            let extra_tick_cost = hle_trap_extra_tick_cost(opcode);
                            if extra_tick_cost > 0
                                && self.charge_tick_budget(extra_tick_cost, tick_cap)
                            {
                                tick_cap_reached = true;
                            }
                            // The m68k CPU already advanced PC past the A-line
                            // instruction during fetch (read_imm_16 does pc += 2).
                            //
                            // When menu or dialog tracking is active, REWIND PC
                            // back to the A-line instruction so it re-fires on
                            // the next frame.
                            //
                            // Shared check with `dispatch.rs`'s auto-pop
                            // push-back logic — both call
                            // `TrapDispatcher::is_tracking_refire` so
                            // they can never diverge. Strips auto-pop
                            // bit so `$AD3D` / `$AC0B` / `$AD91`
                            // match too.
                            let is_tracking_refire = self.dispatcher.is_tracking_refire(opcode);
                            if is_tracking_refire {
                                // In GUI mode, freeze ticks so the game clock doesn't
                                // advance while the host renders intermediate frames.
                                // In headless mode (scripted harnesses), let the budget
                                // advance ticks naturally — frozen_ticks would snap
                                // $016A on each re-fire, which consumes ticks at a
                                // different rate than real hardware where ModalDialog's
                                // WNE loop paces against the VBL.
                                if yield_for_ui
                                    && self.frozen_ticks.is_none()
                                    && tracking_refire_should_freeze_ticks(opcode)
                                {
                                    self.frozen_ticks = Some(self.bus.read_long(0x016A));
                                }
                                if yield_for_ui
                                    && self.frozen_ticks.is_some()
                                    && !tracking_refire_should_freeze_ticks(opcode)
                                {
                                    self.unfreeze_ticks_to(real_tick_cap);
                                }
                                self.cpu.write_reg(Register::PC, pc);

                                // Fire MenuSelect's documented MenuHook while
                                // the dropdown is still live on screen. The
                                // hook is guest code, so inject it before the
                                // next A93D re-fire instead of approximating it
                                // inside the HLE trap body.
                                let fired_menu_hook = self.fire_menu_hook_proc(opcode);

                                // Fire pending dialog userItem draw procs.
                                // The trampoline redirects PC to execute the
                                // 68K draw proc; when it RTS's, PC returns to
                                // the ModalDialog A-line for the next re-fire.
                                let fired_draw_proc = if fired_menu_hook {
                                    false
                                } else {
                                    self.fire_dialog_draw_procs()
                                };
                                let mut fired_filter_proc = false;
                                if !fired_menu_hook && !fired_draw_proc {
                                    // Fire the filter proc for any dialog that has one,
                                    // once draw procs are complete. On a real Mac,
                                    // ModalDialog calls the filter for every event
                                    // (including null events) regardless of item types.
                                    // Inside Macintosh Volume I, I-415
                                    if self.should_fire_dialog_filter_proc() {
                                        self.fire_dialog_filter_proc();
                                        fired_filter_proc = true;
                                    }
                                }

                                // In realtime frontends, yield only once the
                                // tracking trap is idle. A just-scheduled
                                // dialog draw/filter proc has not run yet, so
                                // presenting here shows half-painted screens.
                                // Headless mode keeps executing as before.
                                if yield_for_ui
                                    && !fired_menu_hook
                                    && !fired_draw_proc
                                    && !fired_filter_proc
                                {
                                    if (opcode & !0x0400) == 0xA991
                                        && !self.service_gui_modal_dialog_idle_tick(tick_cap)
                                    {
                                        continue;
                                    }
                                    self.finish_host_frame(
                                        audio_samples,
                                        sound_interrupt_dispatched,
                                    );
                                    return (count, true);
                                }
                            }
                            // If tracking just ended this trap (MenuSelect or
                            // ModalDialog completed), unfreeze ticks and snap
                            // $016A to wall-clock time so the game doesn't
                            // fast-forward through the pause gap.
                            if self.frozen_ticks.is_some() {
                                self.unfreeze_ticks_to(real_tick_cap);
                            }

                            if !is_tracking_refire && self.fire_modeless_dialog_draw_proc() {
                                continue;
                            }

                            // Service any pending Delay ticks immediately after
                            // the trap dispatch, before the next instruction.
                            self.service_delay_ticks(tick_cap);
                        }
                        Err(Error::Halted) => {
                            // Surface the auto-pop caller PC if the
                            // halted trap was called via JSR through a
                            // trampoline. Without this, the halt log
                            // only shows the trampoline PC; the actual
                            // game-side caller is what investigators
                            // want to disassemble.
                            let caller_str = self
                                .dispatcher
                                .current_trap_caller
                                .map(|c| format!(" caller=${:08X}", c))
                                .unwrap_or_default();
                            eprintln!(
                                "[RUN_STEPS] Application halted at count={} pc=${:08X} trap=${:04X}{}",
                                count,
                                pc,
                                opcode,
                                caller_str,
                            );
                            self.halted = true;
                            self.halted_pc = Some(pc);
                            self.halted_trap = Some(opcode);
                            self.halted_sp = Some(self.cpu.read_reg(Register::A7));
                            self.halted_d0 = Some(self.cpu.read_reg(Register::D0));
                            self.dump_trace();
                            return (count, false);
                        }
                        Err(Error::UnimplementedTrap(t)) => {
                            eprintln!("[RUN_STEPS] Unimplemented trap ${:04X} — skipping", t);
                            self.cpu.write_reg(Register::PC, pc + 2);
                        }
                        Err(e) => {
                            eprintln!(
                                "[RUN_STEPS] Error {:?} at PC=${:08X} trap=${:04X} count={}",
                                e, pc, opcode, count
                            );
                            self.halted = true;
                            self.halted_pc = Some(pc);
                            self.halted_sp = Some(self.cpu.read_reg(Register::A7));
                            self.halted_d0 = Some(self.cpu.read_reg(Register::D0));
                            self.dump_trace();
                            return (count, false);
                        }
                    }
                }
            }

            self.dispatcher.instruction_count = self.total_instructions;
        }

        self.finish_host_frame(audio_samples, sound_interrupt_dispatched || sound_work_only);

        (count, !self.halted)
    }

    /// Run for a specific number of steps and mix the supplied amount of host audio.
    /// Returns the number of instructions executed and whether the CPU is still running.
    ///
    /// `tick_override`: If `Some(ticks)`, `Ticks` is capped to the supplied external
    /// wall-clock target. If `None`, `Ticks` advances from the runner's configured
    /// instruction cadence.
    pub fn run_steps_with_audio(
        &mut self,
        max_steps: usize,
        tick_override: Option<u32>,
        audio_samples: usize,
    ) -> (usize, bool) {
        self.run_steps_internal(
            max_steps,
            tick_override,
            audio_samples,
            tick_override.is_some(),
            false,
        )
    }

    /// Run a realtime GUI/WASM slice using the runner's internal tick cadence.
    /// The caller is responsible for converting wall-clock time into `max_steps`
    /// and `audio_samples`.
    pub fn run_realtime_steps_with_audio(
        &mut self,
        max_steps: usize,
        audio_samples: usize,
    ) -> (usize, bool) {
        self.run_steps_internal(max_steps, None, audio_samples, true, false)
    }

    /// Run a GUI frame slice paced by wall-clock time.
    ///
    /// Wall-clock GUI pacing works differently from the reference-runtime oracle:
    /// in the oracle, ticks are driven purely by the instruction budget
    /// (deterministic, host-speed-independent). In the GUI, the user expects
    /// the game to run at real time regardless of how fast the emulator can
    /// execute instructions, so the caller computes a `deadline_tick` from
    /// host wall-clock time and we cap `$016A` advancement there. The CPU
    /// runs flat out (up to `max_steps`) until either the tick cap is hit
    /// or the instruction budget is exhausted, at which point the caller
    /// yields to the UI thread for rendering.
    pub fn run_gui_slice_with_audio(
        &mut self,
        max_steps: usize,
        deadline_tick: u32,
        audio_samples: usize,
    ) -> (usize, bool) {
        self.run_steps_internal(max_steps, Some(deadline_tick), audio_samples, true, false)
    }

    /// Run pending Sound Manager interrupt work without advancing TickCount
    /// or continuing into foreground guest code after the callback returns.
    pub fn run_pending_sound_work(&mut self, max_steps: usize) -> (usize, bool) {
        self.run_steps_internal(max_steps, None, 0, true, true)
    }

    /// Run for a specific number of steps (for GUI/headless callers that don't
    /// provide a real wall-clock audio budget).
    ///
    /// Returns `(steps_executed, still_running)` — note that the bool is
    /// **`still_running`**, not `halted`. `false` means the CPU halted
    /// (via `ExitToShell`, an unimplemented opcode, or a memory fault).
    /// The per-halt detail (trap word, PC, SP, D0) is exposed via the
    /// [`halted_trap`](Self::halted_trap), [`halted_pc`](Self::halted_pc),
    /// [`halted_sp`](Self::halted_sp), [`halted_d0`](Self::halted_d0)
    /// accessors after this call returns.
    pub fn run_steps(&mut self, max_steps: usize, tick_override: Option<u32>) -> (usize, bool) {
        self.run_steps_internal(max_steps, tick_override, 0, false, false)
    }

    fn charge_tick_budget(&mut self, units: i32, tick_cap: Option<u32>) -> bool {
        if units <= 0 {
            return false;
        }

        self.tick_budget -= units;
        while self.tick_budget <= 0 && self.frozen_ticks.is_none() {
            if let Some(cap) = tick_cap {
                if self.bus.read_long(0x016A) >= cap {
                    return true;
                }
            }
            self.advance_guest_tick();
            self.tick_budget += self.instructions_per_tick as i32;
            if let Some(cap) = tick_cap {
                if self.bus.read_long(0x016A) >= cap {
                    return true;
                }
            }
        }
        false
    }

    fn advance_guest_tick(&mut self) -> u32 {
        let new_tick = self.bus.read_long(0x016A).wrapping_add(1);
        self.bus.write_long(0x016A, new_tick);
        self.dispatcher.tick_count = new_tick;

        // Sync MBState ($0172) from the internal button state.
        // On real hardware the VBL interrupt handler reads the ADB mouse
        // state and writes $0172 at each retrace. In our HLE, the button
        // state and the event queue are updated together by push_mouse_down;
        // keep $0172 at "pressed" while either the button is physically
        // held OR an unconsumed mouseDown is still pending in the queue
        // WITHOUT a later mouseUp pairing it off. This ensures code that
        // polls $0172 directly (rather than calling GetNextEvent) can
        // detect clicks injected before polling started, while a
        // mouse_up queued behind the mouse_down still flips MBState back
        // to 0x80 even when no GetNextEvent ever drains the queue —
        // critical for polling-only games (Bonkheads-Deluxe class titles)
        // that would otherwise see the button as "held forever".
        let mut unmatched_mousedowns: i32 = 0;
        for e in self.dispatcher.event_queue.iter() {
            match e.what {
                1 => unmatched_mousedowns += 1, // mouseDown
                2 => unmatched_mousedowns -= 1, // mouseUp pairs off the previous mouseDown
                _ => {}
            }
        }
        let has_pending_unmatched_down = unmatched_mousedowns > 0;
        let pressed = self.dispatcher.mouse_button || has_pending_unmatched_down;
        let mb_state: u8 = if pressed { 0x00 } else { 0x80 };
        self.bus.write_byte(0x0172, mb_state);

        // Advance the real-time clock ($020C) once per second.
        // On a real Mac the IOP or VIA increments Time every second;
        // we approximate this by incrementing every 60 ticks (~1 s at
        // 60.15 Hz VBL). Games that read $020C directly (e.g. for
        // PRNG seeding or save-file timestamps) need a changing value.
        // Inside Macintosh Volume II, II-378
        if new_tick.is_multiple_of(60) {
            let time = self.bus.read_long(0x020C);
            self.bus.write_long(0x020C, time.wrapping_add(1));
        }

        // Fire the cursor task and vertical-retrace tasks before Time Manager
        // tasks. Games commonly drive screen/audio housekeeping from VBL, so
        // letting those callbacks run first avoids starving them behind
        // unrelated timer traffic.
        self.fire_cursor_task();
        self.fire_vbl_tasks();
        self.fire_timer_tasks(new_tick);
        new_tick
    }

    fn service_wait_sleep_ticks(&mut self, tick_cap: Option<u32>) -> bool {
        if self.dispatcher.pending_wait_sleep_ticks == 0 || self.active_interrupt_callback.is_some()
        {
            return false;
        }

        if self.frozen_ticks.is_some() {
            self.dispatcher.pending_wait_sleep_ticks = 0;
            return false;
        }

        // On a real Mac, WaitNextEvent returns immediately when an event
        // is available, regardless of the requested sleep duration.
        // Macintosh Toolbox Essentials 1992, 2-22
        if !self.dispatcher.event_queue.is_empty() {
            self.dispatcher.pending_wait_sleep_ticks = 0;
            return false;
        }

        // If a modal dialog is visibly retained between ModalDialog calls,
        // treat WaitNextEvent sleep as an app-yield hint rather than a
        // wall-clock delay. Apps can return from ModalDialog, do modal control
        // work from their filter proc, then re-enter the modal loop while the
        // dialog remains frontmost.
        if tick_cap.is_some()
            && (self.dispatcher.is_dialog_tracking()
                || !self.dispatcher.dialog_visible_snapshots.is_empty())
        {
            self.dispatcher.pending_wait_sleep_ticks = 0;
            return false;
        }

        // In GUI mode (tick_cap present), cap the effective sleep to 1 tick.
        // The sleep parameter in WaitNextEvent is a hint to the OS about how
        // long the app is willing to wait; on a real Mac the Process Manager
        // may return sooner. Sleeping for the full duration (often 60 ticks =
        // 1 second) starves the game loop of CPU time. Advancing 1 tick per
        // WaitNextEvent call matches the behavior of a 60 Hz VBL-paced game.
        if let Some(cap) = tick_cap {
            self.dispatcher.pending_wait_sleep_ticks = 0;
            if self.bus.read_long(0x016A) < cap {
                self.advance_guest_tick();
                self.tick_budget = self.instructions_per_tick as i32;
            }
            // Yield to the host if we've reached the tick cap for this frame,
            // otherwise let the game continue processing.
            if self.bus.read_long(0x016A) >= cap {
                return true;
            }
            return false;
        }

        // Headless mode (no tick_cap from caller).
        //
        // Default: drain all pending sleep ticks at once (faster wall-clock).
        // Opt-in cap (set via `FixtureRunner::set_wait_sleep_cap_in_headless`):
        // honor the cap as a per-WNE-call ceiling, mirroring GUI mode's
        // 1-tick cap. Used by scripted harnesses to prevent Systemless's tick rate
        // from rocketing ahead of Basilisk's during event-loop-heavy
        // gameplay.
        if let Some(cap) = self.wait_sleep_cap_in_headless {
            let advance = self.dispatcher.pending_wait_sleep_ticks.min(cap);
            self.dispatcher.pending_wait_sleep_ticks = 0;
            for _ in 0..advance {
                self.advance_guest_tick();
                self.tick_budget = self.instructions_per_tick as i32;
                if self.active_interrupt_callback.is_some() {
                    break;
                }
            }
            return false;
        }

        while self.dispatcher.pending_wait_sleep_ticks > 0 {
            self.dispatcher.pending_wait_sleep_ticks -= 1;
            self.advance_guest_tick();
            self.tick_budget = self.instructions_per_tick as i32;

            if self.active_interrupt_callback.is_some() {
                break;
            }
        }
        false
    }

    fn service_delay_ticks(&mut self, tick_cap: Option<u32>) -> bool {
        if self.dispatcher.pending_delay_ticks == 0 || self.active_interrupt_callback.is_some() {
            return false;
        }

        if self.frozen_ticks.is_some() {
            self.dispatcher.pending_delay_ticks = 0;
            return false;
        }

        // Drain delay ticks one at a time, firing VBL/timer callbacks each tick.
        // In GUI mode with a tick_cap, yield if we reach the cap.
        while self.dispatcher.pending_delay_ticks > 0 {
            if let Some(cap) = tick_cap {
                if self.bus.read_long(0x016A) >= cap {
                    return true;
                }
            }
            self.dispatcher.pending_delay_ticks -= 1;
            self.advance_guest_tick();
            self.tick_budget = self.instructions_per_tick as i32;
            if self.active_interrupt_callback.is_some() {
                break;
            }
        }

        if self.dispatcher.pending_delay_ticks == 0 {
            let final_ticks = self.bus.read_long(0x016A);
            self.cpu.write_reg(Register::D0, final_ticks);
        }

        false
    }

    fn service_gui_modal_dialog_idle_tick(&mut self, tick_cap: Option<u32>) -> bool {
        if self.active_interrupt_callback.is_some() || self.frozen_ticks.is_some() {
            return true;
        }

        if let Some(cap) = tick_cap {
            if self.bus.read_long(0x016A) >= cap {
                return true;
            }
        }

        self.advance_guest_tick();
        self.tick_budget = self.instructions_per_tick as i32;

        tick_cap
            .map(|cap| self.bus.read_long(0x016A) >= cap)
            .unwrap_or(true)
    }

    fn unfreeze_ticks_to(&mut self, target_tick: Option<u32>) {
        self.frozen_ticks = None;
        if let Some(target_tick) = target_tick {
            self.bus.write_long(0x016A, target_tick);
            // Keep `dispatcher.tick_count` in sync with $016A.
            // `advance_guest_tick` does this during ordinary advancement.
            self.dispatcher.tick_count = target_tick;
        }
    }

    /// Fire the low-memory cursor task vector, if an app has installed one.
    ///
    /// JCrsrTask runs from interrupt-time cursor/VBL maintenance. MPW
    /// Interfaces/AIncludes/LowMemEqu.a names the ProcPtr at $08EE.
    fn fire_cursor_task(&mut self) {
        if self.active_interrupt_callback.is_some() {
            return;
        }

        let callback_addr = self
            .bus
            .read_long(crate::memory::globals::addr::J_CRSR_TASK);
        if callback_addr == 0 || callback_addr == CURSOR_TASK_NOOP_ADDR {
            return;
        }

        if self.cursor_task_trampoline == 0 {
            // JCrsrTask is a no-argument ProcPtr. Invoke it from interrupt
            // context and preserve the same volatile register set as VBL and
            // Time Manager callbacks. MPW Interfaces/AIncludes/LowMemEqu.a:
            // `JCrsrTask EQU $8EE`.
            let tramp = self.bus.alloc(16);
            self.bus.write_word(tramp, 0x48E7); // MOVEM.L D0-D3/A0-A3,-(SP)
            self.bus.write_word(tramp + 2, 0xF0F0);
            self.bus.write_word(tramp + 4, 0x4EB9); // JSR abs.L
                                                    // +6..+9: callback_addr (patched per-fire)
            self.bus.write_word(tramp + 10, 0x4CDF); // MOVEM.L (SP)+,D0-D3/A0-A3
            self.bus.write_word(tramp + 12, 0x0F0F);
            self.bus.write_word(tramp + 14, 0x4E75); // RTS
            self.cursor_task_trampoline = tramp;
        }

        let tramp = self.cursor_task_trampoline;
        self.bus.write_long(tramp + 6, callback_addr);
        if trace_vbl_enabled() {
            eprintln!(
                "[VBL] fire JCrsrTask addr=${:08X} interrupted_pc=${:08X} interrupted_sp=${:08X}",
                callback_addr,
                self.cpu.read_reg(Register::PC),
                self.cpu.read_reg(Register::A7)
            );
        }
        self.inject_interrupt_callback(ActiveInterruptCallbackSource::CursorTask, tramp);
    }

    /// Fire the next due Vertical Retrace Manager task.
    ///
    /// VBL tasks run at interrupt time with A0 pointing at the task record.
    /// Processes 1994, 4-6 to 4-7; executor src/time/vbl.cpp
    fn fire_vbl_tasks(&mut self) {
        if self.active_interrupt_callback.is_some() {
            return;
        }

        let mut due_task = None;
        for task in &self.dispatcher.vbl_tasks {
            let count = self.bus.read_word(task.task_ptr + 10) as i16;
            if count <= 0 {
                continue;
            }
            let new_count = count - 1;
            self.bus.write_word(task.task_ptr + 10, new_count as u16);
            if new_count == 0 {
                due_task = Some(task.task_ptr);
                break;
            }
        }

        let Some(task_ptr) = due_task else {
            return;
        };

        let callback_addr = self.bus.read_long(task_ptr + 6);
        if callback_addr == 0 {
            return;
        }

        if self.vbl_trampoline == 0 {
            let tramp = self.bus.alloc(22);
            self.bus.write_word(tramp, 0x48E7); // MOVEM.L D0-D3/A0-A3,-(SP)
            self.bus.write_word(tramp + 2, 0xF0F0);
            self.bus.write_word(tramp + 4, 0x207C); // MOVEA.L #imm,A0
            self.bus.write_word(tramp + 10, 0x4EB9); // JSR abs.L
            self.bus.write_word(tramp + 16, 0x4CDF); // MOVEM.L (SP)+,D0-D3/A0-A3
            self.bus.write_word(tramp + 18, 0x0F0F);
            self.bus.write_word(tramp + 20, 0x4E75); // RTS
            self.vbl_trampoline = tramp;
        }

        let tramp = self.vbl_trampoline;
        self.bus.write_long(tramp + 6, task_ptr);
        self.bus.write_long(tramp + 12, callback_addr);

        let current_pc = self.cpu.read_reg(Register::PC);
        let sp = self.cpu.read_reg(Register::A7);
        let d_regs = [
            self.cpu.read_reg(Register::D0),
            self.cpu.read_reg(Register::D1),
            self.cpu.read_reg(Register::D2),
            self.cpu.read_reg(Register::D3),
            self.cpu.read_reg(Register::D4),
            self.cpu.read_reg(Register::D5),
            self.cpu.read_reg(Register::D6),
            self.cpu.read_reg(Register::D7),
        ];
        let a_regs = [
            self.cpu.read_reg(Register::A0),
            self.cpu.read_reg(Register::A1),
            self.cpu.read_reg(Register::A2),
            self.cpu.read_reg(Register::A3),
            self.cpu.read_reg(Register::A4),
            self.cpu.read_reg(Register::A5),
            self.cpu.read_reg(Register::A6),
            sp,
        ];
        let ccr = self.cpu.core.get_ccr();
        let new_sp = sp.wrapping_sub(4);
        self.bus.write_long(new_sp, current_pc);
        self.cpu.write_reg(Register::A7, new_sp);
        self.active_interrupt_callback = Some(ActiveInterruptCallback {
            source: ActiveInterruptCallbackSource::Vbl,
            resume_pc: current_pc,
            resume_sp: sp,
            d_regs,
            a_regs,
            ccr,
            restore_port: None,
        });
        self.cpu.write_reg(Register::PC, tramp);

        if trace_vbl_enabled() {
            eprintln!(
                "[VBL] fire task=${:08X} addr=${:08X} interrupted_pc=${:08X} interrupted_sp=${:08X} count={}",
                task_ptr,
                callback_addr,
                current_pc,
                sp,
                self.bus.read_word(task_ptr + 10) as i16
            );
        }
    }

    /// Fire any expired Time Manager tasks by injecting a call to their callback.
    ///
    /// On a real Mac, timer callbacks execute at interrupt time — the 68K hardware
    /// saves the entire CPU state (SR + PC + all registers via the exception frame)
    /// before dispatching the interrupt handler. The callback may freely clobber
    /// A0-A3 and D0-D3 (Processes 1994, 3-22).
    ///
    /// We simulate this by writing a small native 68K trampoline at a fixed
    /// low-memory address ($0110) that:
    ///   1. Saves D0-D3/A0-A3 via MOVEM.L to the stack
    ///   2. Loads A1 with the task record pointer (from inline data)
    ///   3. JSR's to the callback address (from inline data)
    ///   4. Restores D0-D3/A0-A3 via MOVEM.L from the stack
    ///   5. RTS back to the interrupted code
    fn fire_timer_tasks(&mut self, current_tick: u32) {
        if self.active_interrupt_callback.is_some() {
            return;
        }

        // Collect tasks that need to fire (avoid borrow issues)
        let mut to_fire: Vec<(u32, u32)> = Vec::new(); // (task_ptr, tm_addr)
        for task in &mut self.dispatcher.timer_tasks {
            if task.active && current_tick >= task.fire_at_tick {
                to_fire.push((task.task_ptr, task.tm_addr));
                task.active = false; // Mark as fired; callback may re-prime
            }
        }

        // Fire at most one task per tick to avoid deep nesting
        if let Some((task_ptr, tm_addr)) = to_fire.into_iter().next() {
            if tm_addr == 0 {
                return;
            }

            // Allocate trampoline code in guest heap on first use.
            // Layout (22 bytes):
            //   +0:  MOVEM.L D0-D3/A0-A3,-(SP)  ; 48E7 F0F0
            //   +4:  MOVEA.L #task_ptr,A1         ; 227C xxxx xxxx
            //   +10: JSR     tm_addr              ; 4EB9 xxxx xxxx
            //   +16: MOVEM.L (SP)+,D0-D3/A0-A3   ; 4CDF 0F0F
            //   +20: RTS                          ; 4E75
            if self.timer_trampoline == 0 {
                let tramp = self.bus.alloc(24); // 22 bytes + 2 padding
                self.bus.write_word(tramp, 0x48E7); // MOVEM.L regs,-(SP)
                self.bus.write_word(tramp + 2, 0xF0F0); // D0-D3/A0-A3
                self.bus.write_word(tramp + 4, 0x227C); // MOVEA.L #imm32,A1
                                                        // +6..+9: task_ptr (patched per-fire)
                self.bus.write_word(tramp + 10, 0x4EB9); // JSR abs.L
                                                         // +12..+15: tm_addr (patched per-fire)
                self.bus.write_word(tramp + 16, 0x4CDF); // MOVEM.L (SP)+,regs
                self.bus.write_word(tramp + 18, 0x0F0F); // D0-D3/A0-A3
                self.bus.write_word(tramp + 20, 0x4E75); // RTS
                self.timer_trampoline = tramp;
            }

            // Patch the inline data for this specific fire
            let tramp = self.timer_trampoline;
            self.bus.write_long(tramp + 6, task_ptr);
            self.bus.write_long(tramp + 12, tm_addr);

            // Snapshot the interrupted CPU state before mutating A7 for the
            // synthetic return address. The Time Manager callback should resume
            // with the guest stack exactly as it was when interrupted.
            let current_pc = self.cpu.read_reg(Register::PC);
            let sp = self.cpu.read_reg(Register::A7);
            let d_regs = [
                self.cpu.read_reg(Register::D0),
                self.cpu.read_reg(Register::D1),
                self.cpu.read_reg(Register::D2),
                self.cpu.read_reg(Register::D3),
                self.cpu.read_reg(Register::D4),
                self.cpu.read_reg(Register::D5),
                self.cpu.read_reg(Register::D6),
                self.cpu.read_reg(Register::D7),
            ];
            let a_regs = [
                self.cpu.read_reg(Register::A0),
                self.cpu.read_reg(Register::A1),
                self.cpu.read_reg(Register::A2),
                self.cpu.read_reg(Register::A3),
                self.cpu.read_reg(Register::A4),
                self.cpu.read_reg(Register::A5),
                self.cpu.read_reg(Register::A6),
                sp,
            ];
            let ccr = self.cpu.core.get_ccr();

            // Inject: push current PC, jump to trampoline
            let new_sp = sp.wrapping_sub(4);
            self.bus.write_long(new_sp, current_pc);
            self.cpu.write_reg(Register::A7, new_sp);
            self.active_interrupt_callback = Some(ActiveInterruptCallback {
                source: ActiveInterruptCallbackSource::Timer,
                resume_pc: current_pc,
                resume_sp: sp,
                d_regs,
                a_regs,
                ccr,
                restore_port: None,
            });
            if trace_timer_enabled() {
                eprintln!(
                    "[TIMER] fire task=${:08X} tm_addr=${:08X} interrupted_pc=${:08X} interrupted_sp=${:08X} ccr=${:02X}",
                    task_ptr, tm_addr, current_pc, sp, ccr
                );
            }
            self.cpu.write_reg(Register::PC, tramp);
        }
    }

    /// Check all channels with active double-buffers: if a channel is not
    /// currently playing but its current_buffer is ready in guest memory,
    /// load the samples so mix_frame() can produce audio.
    fn try_load_pending_double_buffers(&mut self) {
        if self.active_interrupt_callback.is_some() {
            return;
        }

        let queued_doublebacks = self
            .dispatcher
            .sound_manager
            .pending_callbacks
            .iter()
            .map(|cb| (cb.chan_ptr, cb.exhausted_buffer_index))
            .collect::<Vec<_>>();

        for chan in &mut self.dispatcher.sound_manager.channels {
            if chan.is_playing() {
                continue; // already has data
            }
            let (header_ptr, buf_idx, sample_rate, num_channels, sample_size) =
                match chan.double_buffer {
                    Some(ref db) if !db.last_buffer_seen => (
                        db.header_ptr,
                        db.current_buffer,
                        db.sample_rate,
                        db.num_channels,
                        db.sample_size,
                    ),
                    _ => continue,
                };
            let mut load_idx = buf_idx;
            let mut buf_ptr = self.bus.read_long(header_ptr + 12 + (buf_idx as u32) * 4);
            let mut can_load = buf_ptr != 0
                && self.bus.read_long(buf_ptr + 4) & 0x01 != 0
                && !queued_doublebacks
                    .iter()
                    .any(|&(pending_chan, pending_idx)| {
                        pending_chan == chan.guest_ptr && pending_idx == buf_idx
                    });
            let original_idx = load_idx;
            if !can_load {
                let other_idx = buf_idx ^ 1;
                let other_ptr = self.bus.read_long(header_ptr + 12 + (other_idx as u32) * 4);
                if other_ptr == 0 {
                    continue;
                }
                let other_flags = self.bus.read_long(other_ptr + 4);
                let other_pending =
                    queued_doublebacks
                        .iter()
                        .any(|&(pending_chan, pending_idx)| {
                            pending_chan == chan.guest_ptr && pending_idx == other_idx
                        });
                if other_flags & 0x01 == 0 || other_pending {
                    continue; // neither available buffer is ready yet
                }
                load_idx = other_idx;
                buf_ptr = other_ptr;
                can_load = true;
                if let Some(ref mut db) = chan.double_buffer {
                    db.current_buffer = other_idx;
                }
            }
            if !can_load {
                continue;
            }
            let flags = self.bus.read_long(buf_ptr + 4);
            if trace_sound_runner_enabled() {
                let preview = self
                    .bus
                    .read_bytes(buf_ptr + 16, 16)
                    .iter()
                    .map(|byte| format!("{:02X}", byte))
                    .collect::<Vec<_>>()
                    .join(" ");
                eprintln!(
                    "[SOUND-DB] load-ready chan=${:08X} header=${:08X} requested_idx={} load_idx={} buf=${:08X} frames={} flags=${:08X} pending={:?} first={}",
                    chan.guest_ptr,
                    header_ptr,
                    original_idx,
                    load_idx,
                    buf_ptr,
                    self.bus.read_long(buf_ptr),
                    flags,
                    chan.double_buffer
                        .as_ref()
                        .map(|db| db.pending_callback_buffers)
                        .unwrap_or([false; 2]),
                    preview
                );
            }
            crate::trap::TrapDispatcher::load_double_buffer_samples(
                &mut self.bus,
                chan,
                buf_ptr,
                sample_rate,
                num_channels,
                sample_size,
            );
            if flags & 0x01 != 0 {
                if let Some(ref mut db) = chan.double_buffer {
                    db.current_buffer = load_idx;
                    db.complete_callback_for(load_idx);
                }
            }
        }
    }

    fn dump_invalid_pc_state(&self) {
        let d_regs = [
            self.cpu.read_reg(Register::D0),
            self.cpu.read_reg(Register::D1),
            self.cpu.read_reg(Register::D2),
            self.cpu.read_reg(Register::D3),
            self.cpu.read_reg(Register::D4),
            self.cpu.read_reg(Register::D5),
            self.cpu.read_reg(Register::D6),
            self.cpu.read_reg(Register::D7),
        ];
        let a_regs = [
            self.cpu.read_reg(Register::A0),
            self.cpu.read_reg(Register::A1),
            self.cpu.read_reg(Register::A2),
            self.cpu.read_reg(Register::A3),
            self.cpu.read_reg(Register::A4),
            self.cpu.read_reg(Register::A5),
            self.cpu.read_reg(Register::A6),
            self.cpu.read_reg(Register::A7),
        ];
        eprintln!(
            "[RUN_STEPS]   D0-D7: {:08X} {:08X} {:08X} {:08X} {:08X} {:08X} {:08X} {:08X}",
            d_regs[0], d_regs[1], d_regs[2], d_regs[3], d_regs[4], d_regs[5], d_regs[6], d_regs[7]
        );
        eprintln!(
            "[RUN_STEPS]   A0-A7: {:08X} {:08X} {:08X} {:08X} {:08X} {:08X} {:08X} {:08X}",
            a_regs[0], a_regs[1], a_regs[2], a_regs[3], a_regs[4], a_regs[5], a_regs[6], a_regs[7]
        );
        eprintln!("[RUN_STEPS]   CCR=${:02X}", self.cpu.core.get_ccr());
        if let Some(active) = self.active_interrupt_callback {
            eprintln!(
                "[RUN_STEPS]   active_callback={:?} resume_pc=${:08X} resume_sp=${:08X}",
                active.source, active.resume_pc, active.resume_sp
            );
        }
        self.bus.dump_stack(a_regs[7], "invalid PC");
    }

    fn inject_interrupt_callback(
        &mut self,
        source: ActiveInterruptCallbackSource,
        trampoline: u32,
    ) {
        let current_pc = self.cpu.read_reg(Register::PC);
        let sp = self.cpu.read_reg(Register::A7);
        let d_regs = [
            self.cpu.read_reg(Register::D0),
            self.cpu.read_reg(Register::D1),
            self.cpu.read_reg(Register::D2),
            self.cpu.read_reg(Register::D3),
            self.cpu.read_reg(Register::D4),
            self.cpu.read_reg(Register::D5),
            self.cpu.read_reg(Register::D6),
            self.cpu.read_reg(Register::D7),
        ];
        let a_regs = [
            self.cpu.read_reg(Register::A0),
            self.cpu.read_reg(Register::A1),
            self.cpu.read_reg(Register::A2),
            self.cpu.read_reg(Register::A3),
            self.cpu.read_reg(Register::A4),
            self.cpu.read_reg(Register::A5),
            self.cpu.read_reg(Register::A6),
            sp,
        ];
        let ccr = self.cpu.core.get_ccr();
        let new_sp = sp.wrapping_sub(4);
        self.bus.write_long(new_sp, current_pc);
        self.cpu.write_reg(Register::A7, new_sp);
        self.active_interrupt_callback = Some(ActiveInterruptCallback {
            source,
            resume_pc: current_pc,
            resume_sp: sp,
            d_regs,
            a_regs,
            ccr,
            restore_port: None,
        });
        self.cpu.write_reg(Register::PC, trampoline);
    }

    /// Fire pending Sound Manager callback procedures and file completion routines.
    fn fire_sound_callbacks(&mut self) -> bool {
        if self.active_interrupt_callback.is_some() {
            return false;
        }

        if self
            .dispatcher
            .sound_manager
            .pending_sound_callbacks
            .is_empty()
        {
            return false;
        }

        let cb = self
            .dispatcher
            .sound_manager
            .pending_sound_callbacks
            .remove(0);
        match cb {
            crate::sound::PendingSoundCallback::Command {
                callback_addr,
                chan_ptr,
                cmd,
            } => {
                if callback_addr == 0 {
                    return false;
                }

                // Sound 1994, 2-152
                if self.sound_callback_trampoline == 0 {
                    // Sound callback:
                    //   PROCEDURE MyCallBack(chan: SndChannelPtr; cmd: SndCommand);
                    //
                    // In practice shipped apps commonly receive `cmd` as a
                    // pointer-sized argument and differ on how much stack they
                    // pop on return. Push cmdPtr nearest SP and chan beneath it,
                    // then reset SP to the saved-register frame after JSR so
                    // one-arg, two-arg, and C-style cleanup all resume safely.
                    let tramp = self.bus.alloc(42);
                    self.bus.write_word(tramp, 0x48E7); // MOVEM.L regs,-(SP)
                    self.bus.write_word(tramp + 2, 0xF0F0); // D0-D3/A0-A3
                    self.bus.write_word(tramp + 4, 0x2F3C); // MOVE.L #chan,-(SP)
                    self.bus.write_word(tramp + 10, 0x2F3C); // MOVE.L #cmdPtr,-(SP)
                    self.bus.write_word(tramp + 16, 0x4EB9); // JSR abs.L
                    self.bus.write_word(tramp + 22, 0x2E7C); // MOVEA.L #savedSP,A7
                    self.bus.write_word(tramp + 28, 0x4CDF); // MOVEM.L (SP)+,regs
                    self.bus.write_word(tramp + 30, 0x0F0F); // D0-D3/A0-A3
                    self.bus.write_word(tramp + 32, 0x4E75); // RTS
                    self.sound_callback_trampoline = tramp;
                }

                let tramp = self.sound_callback_trampoline;
                let cmd_ptr = tramp + 34;
                let interrupted_sp = self.cpu.read_reg(Register::A7);
                let saved_regs_sp = interrupted_sp.wrapping_sub(4 + 32);
                self.bus.write_long(tramp + 6, chan_ptr);
                self.bus.write_long(tramp + 12, cmd_ptr);
                self.bus.write_long(tramp + 18, callback_addr);
                self.bus.write_long(tramp + 24, saved_regs_sp);
                self.bus.write_word(cmd_ptr, cmd.cmd);
                self.bus.write_word(cmd_ptr + 2, cmd.param1 as u16);
                self.bus.write_long(cmd_ptr + 4, cmd.param2);
                self.inject_interrupt_callback(ActiveInterruptCallbackSource::SoundCallback, tramp);
                true
            }
            crate::sound::PendingSoundCallback::FileCompletion {
                callback_addr,
                chan_ptr,
            } => {
                if callback_addr == 0 {
                    return false;
                }

                // Sound 1994, 2-151
                if self.sound_file_completion_trampoline == 0 {
                    let tramp = self.bus.alloc(28);
                    self.bus.write_word(tramp, 0x48E7); // MOVEM.L regs,-(SP)
                    self.bus.write_word(tramp + 2, 0xF0F0); // D0-D3/A0-A3
                    self.bus.write_word(tramp + 4, 0x2F3C); // MOVE.L #chan,-(SP)
                    self.bus.write_word(tramp + 10, 0x4EB9); // JSR abs.L
                    self.bus.write_word(tramp + 16, 0x2E7C); // MOVEA.L #savedSP,A7
                    self.bus.write_word(tramp + 22, 0x4CDF); // MOVEM.L (SP)+,regs
                    self.bus.write_word(tramp + 24, 0x0F0F); // D0-D3/A0-A3
                    self.bus.write_word(tramp + 26, 0x4E75); // RTS
                    self.sound_file_completion_trampoline = tramp;
                }

                let tramp = self.sound_file_completion_trampoline;
                let interrupted_sp = self.cpu.read_reg(Register::A7);
                let saved_regs_sp = interrupted_sp.wrapping_sub(4 + 32);
                self.bus.write_long(tramp + 6, chan_ptr);
                self.bus.write_long(tramp + 12, callback_addr);
                self.bus.write_long(tramp + 18, saved_regs_sp);
                self.inject_interrupt_callback(
                    ActiveInterruptCallbackSource::SoundFileCompletion,
                    tramp,
                );
                true
            }
        }
    }

    /// Fire pending SndPlayDoubleBuffer doubleback callbacks.
    ///
    /// When mix_frame() exhausts a double buffer, it queues a callback request.
    /// Here we clear dbBufferReady on the exhausted buffer and inject a
    /// trampoline to call the game's doubleback proc to refill it.
    ///
    /// The doubleback procedure signature (Sound 1994, 2-146):
    ///   PROCEDURE MyDoubleBackProc(chan: SndChannelPtr;
    ///                              exhaustedBuffer: SndDoubleBufferPtr);
    fn fire_sound_doubleback_callbacks(&mut self) -> bool {
        if self.active_interrupt_callback.is_some() {
            return false;
        }

        if self.dispatcher.sound_manager.pending_callbacks.is_empty() {
            return false;
        }

        // Take one callback at a time (like timer tasks).
        let cb = self.dispatcher.sound_manager.pending_callbacks.remove(0);

        // Read the exhausted buffer pointer from the header.
        // dbhBufferPtr[0] at header+12, dbhBufferPtr[1] at header+16
        let exhausted_buf_ptr = self
            .bus
            .read_long(cb.header_ptr + 12 + (cb.exhausted_buffer_index as u32) * 4);

        // Clear dbBufferReady on the exhausted buffer.
        if exhausted_buf_ptr != 0 {
            let flags = self.bus.read_long(exhausted_buf_ptr + 4);
            if trace_sound_runner_enabled() {
                let preview = self
                    .bus
                    .read_bytes(exhausted_buf_ptr + 16, 16)
                    .iter()
                    .map(|byte| format!("{:02X}", byte))
                    .collect::<Vec<_>>()
                    .join(" ");
                eprintln!(
                    "[SOUND-DB] fire-doubleback tick={} chan=${:08X} header=${:08X} idx={} buf=${:08X} frames={} flags_before=${:08X} callback=${:08X} sr=${:04X} first={}",
                    self.bus.read_long(0x016A),
                    cb.chan_ptr,
                    cb.header_ptr,
                    cb.exhausted_buffer_index,
                    exhausted_buf_ptr,
                    self.bus.read_long(exhausted_buf_ptr),
                    flags,
                    cb.callback_addr,
                    self.cpu.core.get_sr(),
                    preview
                );
            }
            self.bus.write_long(exhausted_buf_ptr + 4, flags & !0x01);
        }

        if cb.callback_addr == 0 {
            return false;
        }

        // Allocate trampoline on first use.
        // The doubleback proc is a Pascal procedure (callee pops params):
        //   PROCEDURE MyDoubleBackProc(chan: SndChannelPtr;
        //                              exhaustedBuffer: SndDoubleBufferPtr);
        //
        // Trampoline layout (34 bytes):
        //   +0:  MOVEM.L D0-D3/A0-A3,-(SP)  ; 48E7 F0F0 (save regs)
        //   +4:  MOVE.L  #chanPtr,-(SP)       ; 2F3C xxxx xxxx (Pascal param1 = deeper)
        //   +10: MOVE.L  #exhaustedBuf,-(SP) ; 2F3C xxxx xxxx (Pascal param2 = top)
        //   +16: JSR     callback             ; 4EB9 xxxx xxxx
        //   +22: MOVEA.L #savedRegsSP,A7      ; ignore guest callback cleanup convention
        //   +28: MOVEM.L (SP)+,D0-D3/A0-A3   ; 4CDF 0F0F (restore regs)
        //   +32: RTS                          ; 4E75
        if self.sound_doubleback_trampoline == 0 {
            let tramp = self.bus.alloc(34);
            self.bus.write_word(tramp, 0x48E7); // MOVEM.L regs,-(SP)
            self.bus.write_word(tramp + 2, 0xF0F0); // D0-D3/A0-A3
            self.bus.write_word(tramp + 4, 0x2F3C); // MOVE.L #imm,-(SP)
                                                    // +6..+9: chan ptr (patched)
            self.bus.write_word(tramp + 10, 0x2F3C); // MOVE.L #imm,-(SP)
                                                     // +12..+15: exhausted buf ptr (patched)
            self.bus.write_word(tramp + 16, 0x4EB9); // JSR abs.L
                                                     // +18..+21: callback addr (patched)
            self.bus.write_word(tramp + 22, 0x2E7C); // MOVEA.L #savedSP,A7
                                                     // +24..+27: saved regs SP (patched)
            self.bus.write_word(tramp + 28, 0x4CDF); // MOVEM.L (SP)+,regs
            self.bus.write_word(tramp + 30, 0x0F0F); // D0-D3/A0-A3
            self.bus.write_word(tramp + 32, 0x4E75); // RTS
            self.sound_doubleback_trampoline = tramp;
        }

        let tramp = self.sound_doubleback_trampoline;
        let interrupted_sp = self.cpu.read_reg(Register::A7);
        let saved_regs_sp = interrupted_sp.wrapping_sub(4 + 32);
        self.bus.write_long(tramp + 6, cb.chan_ptr);
        self.bus.write_long(tramp + 12, exhausted_buf_ptr);
        self.bus.write_long(tramp + 18, cb.callback_addr);
        self.bus.write_long(tramp + 24, saved_regs_sp);

        // Doubleback procedures execute at interrupt time, so the interrupted
        // guest CPU state must be restored after the callback unwinds.
        // Sound 1994, 2-72
        self.inject_interrupt_callback(ActiveInterruptCallbackSource::SoundDoubleBack, tramp);
        true
    }

    fn dialog_callback_scratch_base(&self) -> u32 {
        DIALOG_CALLBACK_SCRATCH_FALLBACK
    }

    fn looks_like_dialog_proc_entry(&self, addr: u32) -> bool {
        if addr == 0 {
            return false;
        }
        let entry = self.bus.read_word(addr);
        entry == 0x4E56 || entry == 0x48E7 || entry == 0x4EF9 || entry == 0x4EFA
    }

    fn resolve_dialog_draw_proc_addr(&self, proc_addr: u32) -> Option<u32> {
        if self.looks_like_dialog_proc_entry(proc_addr) {
            return Some(proc_addr);
        }
        let a5_relative = self.cpu.read_reg(Register::A5).wrapping_add(proc_addr);
        if self.looks_like_dialog_proc_entry(a5_relative) {
            Some(a5_relative)
        } else {
            None
        }
    }

    fn inject_dialog_draw_proc(
        &mut self,
        proc_addr: u32,
        item_no: i16,
        dialog_ptr: u32,
        modeless: bool,
    ) -> bool {
        if self.active_interrupt_callback.is_some() {
            return false;
        }

        if proc_addr == 0 {
            return false;
        }

        // Many dialogs stuff non-code placeholders into userItem proc fields.
        // Only fire callbacks that look like real 68K entry points.
        let Some(call_addr) = self.resolve_dialog_draw_proc_addr(proc_addr) else {
            if trace_dialog_procs_enabled() {
                let a5_relative = self.cpu.read_reg(Register::A5).wrapping_add(proc_addr);
                eprintln!(
                    "[DIALOG-PROC] skip dialog=${:08X} item={} proc=${:08X} a5rel=${:08X} entry=${:04X} a5entry=${:04X}",
                    dialog_ptr,
                    item_no,
                    proc_addr,
                    a5_relative,
                    self.bus.read_word(proc_addr),
                    self.bus.read_word(a5_relative),
                );
            }
            return false;
        };

        // Allocate trampoline on first use (32 bytes):
        //   +0:  MOVEM.L D0-D3/A0-A3,-(SP)   ; 48E7 F0F0
        //   +4:  MOVE.L  #dialogPtr,-(SP)      ; 2F3C xxxx xxxx
        //   +10: MOVE.W  #itemNo,-(SP)         ; 3F3C xxxx
        //   +14: JSR     proc_addr              ; 4EB9 xxxx xxxx
        //   +20: MOVEA.L #savedRegsSP,A7       ; 4FF9 xxxx xxxx
        //   +26: MOVEM.L (SP)+,D0-D3/A0-A3    ; 4CDF 0F0F
        //   +30: RTS                            ; 4E75
        if self.dialog_draw_trampoline == 0 {
            let tramp = self.dialog_callback_scratch_base() + DIALOG_DRAW_TRAMPOLINE_OFFSET;
            self.bus.write_word(tramp, 0x48E7); // MOVEM.L regs,-(SP)
            self.bus.write_word(tramp + 2, 0xF0F0); // D0-D3/A0-A3
            self.bus.write_word(tramp + 4, 0x2F3C); // MOVE.L #imm,-(SP)
                                                    // +6..+9: dialogPtr (patched per-fire)
            self.bus.write_word(tramp + 10, 0x3F3C); // MOVE.W #imm,-(SP)
                                                     // +12..+13: itemNo (patched per-fire)
            self.bus.write_word(tramp + 14, 0x4EB9); // JSR abs.L
                                                     // +16..+19: proc_addr (patched per-fire)
            self.bus.write_word(tramp + 20, 0x4FF9); // MOVEA.L #imm,A7
                                                     // +22..+25: savedRegsSP (patched per-fire)
            self.bus.write_word(tramp + 26, 0x4CDF); // MOVEM.L (SP)+,regs
            self.bus.write_word(tramp + 28, 0x0F0F); // D0-D3/A0-A3
            self.bus.write_word(tramp + 30, 0x4E75); // RTS
            self.dialog_draw_trampoline = tramp;
        }

        let tramp = self.dialog_draw_trampoline;
        self.bus.write_long(tramp + 6, dialog_ptr);
        self.bus.write_word(tramp + 12, item_no as u16);
        self.bus.write_long(tramp + 16, call_addr);

        // The Dialog Manager sets the current port to the dialog before
        // calling a userItem draw proc. It does not restore an older
        // application port over the callback's final QuickDraw state.
        self.dispatcher
            .set_current_port_state(&mut self.bus, &mut self.cpu, dialog_ptr, None);

        // Inject: push current PC, jump to trampoline
        let current_pc = self.cpu.read_reg(Register::PC);
        let sp = self.cpu.read_reg(Register::A7);
        let d_regs = [
            self.cpu.read_reg(Register::D0),
            self.cpu.read_reg(Register::D1),
            self.cpu.read_reg(Register::D2),
            self.cpu.read_reg(Register::D3),
            self.cpu.read_reg(Register::D4),
            self.cpu.read_reg(Register::D5),
            self.cpu.read_reg(Register::D6),
            self.cpu.read_reg(Register::D7),
        ];
        let a_regs = [
            self.cpu.read_reg(Register::A0),
            self.cpu.read_reg(Register::A1),
            self.cpu.read_reg(Register::A2),
            self.cpu.read_reg(Register::A3),
            self.cpu.read_reg(Register::A4),
            self.cpu.read_reg(Register::A5),
            self.cpu.read_reg(Register::A6),
            sp,
        ];
        let ccr = self.cpu.core.get_ccr();
        let new_sp = sp.wrapping_sub(4);
        let saved_regs_sp = new_sp.wrapping_sub(32);
        self.bus.write_long(tramp + 22, saved_regs_sp);
        self.bus.write_long(new_sp, current_pc);
        self.cpu.write_reg(Register::A7, new_sp);
        self.active_interrupt_callback = Some(ActiveInterruptCallback {
            source: ActiveInterruptCallbackSource::DialogDrawProc,
            resume_pc: current_pc,
            resume_sp: sp,
            d_regs,
            a_regs,
            ccr,
            restore_port: None,
        });
        if modeless {
            self.dispatcher.active_modeless_dialog_draw_proc = Some(dialog_ptr);
        }
        if trace_dialog_procs_enabled() {
            eprintln!(
                "[DIALOG-PROC] fire {} dialog=${:08X} item={} proc=${:08X} call=${:08X} return_pc=${:08X}",
                if modeless { "modeless" } else { "modal" },
                dialog_ptr,
                item_no,
                proc_addr,
                call_addr,
                current_pc,
            );
        }
        self.cpu.write_reg(Register::PC, tramp);
        true
    }

    fn fire_modeless_dialog_draw_proc(&mut self) -> bool {
        if self.active_interrupt_callback.is_some() {
            return false;
        }

        while let Some((dialog_ptr, proc_addr, item_no)) =
            self.dispatcher.modeless_dialog_draw_proc_queue.pop_front()
        {
            if self.inject_dialog_draw_proc(proc_addr, item_no, dialog_ptr, true) {
                return true;
            }
        }
        false
    }

    /// Fire the next pending dialog userItem draw proc by injecting a trampoline.
    ///
    /// On a real Mac, ModalDialog calls each userItem's draw proc during
    /// the update pass. The draw proc is a Pascal callback:
    ///   PROCEDURE MyItem (theWindow: WindowPtr; itemNo: INTEGER);
    /// Inside Macintosh Volume I, I-405
    ///
    /// We simulate this by writing a small 68K trampoline that:
    ///   1. Saves D0-D3/A0-A3 via MOVEM.L to the stack
    ///   2. Pushes params so MPW-style Pascal prologues see itemNo at
    ///      8(A6) and theWindow at 10(A6), matching Pascal's stack layout
    ///   3. JSR to draw proc address
    ///   4. Resets A7 to the saved-register frame, tolerating callbacks
    ///      that return with either `RTD #6` or plain `RTS`
    ///   5. Restores D0-D3/A0-A3
    ///   6. RTS back to interrupted code (the ModalDialog A-line)
    fn fire_dialog_draw_procs(&mut self) -> bool {
        if self.active_interrupt_callback.is_some() {
            return false;
        }

        if let Some(tracking) = self
            .dispatcher
            .dialog_tracking
            .as_mut()
            .filter(|tracking| !tracking.draw_procs_done)
        {
            let Some((proc_addr, item_no)) = tracking.draw_proc_queue.pop_front() else {
                // All draw procs fired and returned
                tracking.draw_procs_done = true;
                return false;
            };
            let dialog_ptr = tracking.dialog_ptr;
            return self.inject_dialog_draw_proc(proc_addr, item_no, dialog_ptr, false);
        }

        self.fire_modeless_dialog_draw_proc()
    }

    fn fire_menu_hook_proc(&mut self, opcode: u16) -> bool {
        if self.active_interrupt_callback.is_some() || (opcode & !0x0400) != 0xA93D {
            return false;
        }
        if self.dispatcher.menu_tracking.is_none() || self.bus.read_byte(0x0172) != 0x00 {
            return false;
        }

        // MenuHook ($0A30)
        // Address of a no-argument routine that MenuSelect calls repeatedly
        // while the mouse button is down.
        // PROCEDURE MyMenuHook;
        // Inside Macintosh Volume I, I-356; Inside Macintosh Volume III, III-446
        let hook_addr = self.bus.read_long(0x0A30);
        let Some(call_addr) = self.resolve_dialog_draw_proc_addr(hook_addr) else {
            return false;
        };

        // Trampoline (22 bytes):
        //   +0:  MOVEM.L D0-D3/A0-A3,-(SP)   ; 48E7 F0F0
        //   +4:  JSR     hook_addr            ; 4EB9 xxxx xxxx
        //   +10: MOVEA.L #savedRegsSP,A7      ; 4FF9 xxxx xxxx
        //   +16: MOVEM.L (SP)+,D0-D3/A0-A3   ; 4CDF 0F0F
        //   +20: RTS                          ; 4E75
        if self.menu_hook_trampoline == 0 {
            let tramp = self.dialog_callback_scratch_base() + MENU_HOOK_TRAMPOLINE_OFFSET;
            self.bus.write_word(tramp, 0x48E7); // MOVEM.L regs,-(SP)
            self.bus.write_word(tramp + 2, 0xF0F0); // D0-D3/A0-A3
            self.bus.write_word(tramp + 4, 0x4EB9); // JSR abs.L
                                                    // +6..+9: hook_addr
            self.bus.write_word(tramp + 10, 0x4FF9); // MOVEA.L #imm,A7
                                                     // +12..+15: savedRegsSP
            self.bus.write_word(tramp + 16, 0x4CDF); // MOVEM.L (SP)+,regs
            self.bus.write_word(tramp + 18, 0x0F0F); // D0-D3/A0-A3
            self.bus.write_word(tramp + 20, 0x4E75); // RTS
            self.menu_hook_trampoline = tramp;
        }

        let tramp = self.menu_hook_trampoline;
        self.bus.write_long(tramp + 6, call_addr);

        let current_pc = self.cpu.read_reg(Register::PC);
        let sp = self.cpu.read_reg(Register::A7);
        let d_regs = [
            self.cpu.read_reg(Register::D0),
            self.cpu.read_reg(Register::D1),
            self.cpu.read_reg(Register::D2),
            self.cpu.read_reg(Register::D3),
            self.cpu.read_reg(Register::D4),
            self.cpu.read_reg(Register::D5),
            self.cpu.read_reg(Register::D6),
            self.cpu.read_reg(Register::D7),
        ];
        let a_regs = [
            self.cpu.read_reg(Register::A0),
            self.cpu.read_reg(Register::A1),
            self.cpu.read_reg(Register::A2),
            self.cpu.read_reg(Register::A3),
            self.cpu.read_reg(Register::A4),
            self.cpu.read_reg(Register::A5),
            self.cpu.read_reg(Register::A6),
            sp,
        ];
        let ccr = self.cpu.core.get_ccr();
        let new_sp = sp.wrapping_sub(4);
        let saved_regs_sp = new_sp.wrapping_sub(32);
        self.bus.write_long(tramp + 12, saved_regs_sp);
        self.bus.write_long(new_sp, current_pc);
        self.cpu.write_reg(Register::A7, new_sp);
        self.active_interrupt_callback = Some(ActiveInterruptCallback {
            source: ActiveInterruptCallbackSource::MenuHook,
            resume_pc: current_pc,
            resume_sp: sp,
            d_regs,
            a_regs,
            ccr,
            restore_port: None,
        });
        self.cpu.write_reg(Register::PC, tramp);
        true
    }

    fn dialog_filter_has_real_event_pending(&self, dialog_ptr: u32) -> bool {
        self.dispatcher
            .event_queue
            .iter()
            .any(|event| matches!(event.what, 1 | 2 | 3 | 4 | 6))
            || self
                .dispatcher
                .pending_update_event(&self.bus, 1u16 << 6)
                .is_some_and(|event| event.message == dialog_ptr)
    }

    fn dialog_filter_null_event_already_sent_this_tick(&self, dialog_ptr: u32) -> bool {
        self.dialog_filter_last_null_event_tick
            .is_some_and(|(sent_dialog, sent_tick)| {
                sent_dialog == dialog_ptr && sent_tick == self.dispatcher.tick_count
            })
    }

    fn should_fire_dialog_filter_proc(&self) -> bool {
        let Some(tracking) = self.dispatcher.dialog_tracking.as_ref() else {
            return false;
        };

        if tracking.filter_proc == 0
            || !tracking.draw_procs_done
            || tracking.last_filter_event.is_some()
        {
            return false;
        }

        let dialog_ptr = tracking.dialog_ptr;
        let has_real_event = self.dialog_filter_has_real_event_pending(dialog_ptr);

        // A queued mouseDown on a standard dialog item is still a real event:
        // ModalDialog passes it to the filter first, then handles it itself if
        // the filter returns FALSE. Only suppress idle/null callbacks while
        // the mouse is physically held over a dialog item. IM:I 1985 I-415.
        if !has_real_event
            && (self.dispatcher.mouse_down_over_dialog_button()
                || self.dispatcher.mouse_down_over_dialog_plain_user_item()
                || self.dispatcher.pending_dialog_plain_user_item_mouse_down())
        {
            return false;
        }

        // ModalDialog gets events through GetNextEvent and passes them to the
        // filter proc. A null event means there was no real event to dequeue;
        // pace those synthetic idle callbacks to one per guest tick so the HLE
        // refire loop does not manufacture hundreds of thousands of no-input
        // filter calls between VBLs. Mouse/key/update events still bypass this
        // gate and are delivered immediately. IM:I 1985 I-415; MTE 1992 6-136.
        if !has_real_event && self.dialog_filter_null_event_already_sent_this_tick(dialog_ptr) {
            return false;
        }

        true
    }

    /// Fire the ModalDialog filter proc for game-managed dialogs.
    ///
    /// On a real Mac, ModalDialog's internal loop calls GetNextEvent (consuming
    /// the event) and then passes it to the filter proc. If the filter returns
    /// TRUE, ModalDialog returns immediately with the itemHit value the filter
    /// wrote. If FALSE, ModalDialog processes the event itself.
    /// Inside Macintosh Volume I, I-415
    ///
    /// We simulate this by:
    /// 1. Consuming the next actionable event from our queue (like GetNextEvent)
    /// 2. Writing it to a scratch EventRecord in guest memory
    /// 3. Injecting a 68K trampoline that calls the filter proc with correct
    ///    Pascal calling convention (Boolean result space + 3 params)
    /// 4. The trampoline saves the Boolean return value to a scratch location
    ///    so the ModalDialog re-fire path can read it
    fn fire_dialog_filter_proc(&mut self) -> bool {
        let (filter_proc, dialog_ptr, item_hit_ptr) = {
            let tracking = match self.dispatcher.dialog_tracking.as_ref() {
                Some(t) => t,
                None => return false,
            };
            (
                tracking.filter_proc,
                tracking.dialog_ptr,
                tracking.item_hit_ptr,
            )
        };

        if filter_proc == 0 {
            return false;
        }

        // Only fire the filter if the proc address contains recognisable 68K
        // function entry code. Some games pass a non-nil but invalid filterProc
        // (e.g. Marathon passes a stack address reused as a Rect buffer by
        // GetDItem, leaving it full of coordinate data, not instructions).
        // Executing garbage code would halt the CPU; skip the call instead.
        // Standard 68K function preambles: LINK A6 (0x4E56),
        //   MOVEM.L regs,-(SP) (0x48E7), JMP abs (0x4EF9), JMP PC+n (0x4EFA).
        // Inside Macintosh Volume I, I-415
        let entry = self.bus.read_word(filter_proc);
        if entry != 0x4E56 && entry != 0x48E7 && entry != 0x4EF9 && entry != 0x4EFA {
            if trace_dialog_filter_enabled() {
                eprintln!(
                    "[DIALOG-FILTER] skip invalid-entry dialog=${:08X} proc=${:08X} entry=${:04X}",
                    dialog_ptr, filter_proc, entry
                );
            }
            return false;
        }
        // Allocate EventRecord scratch space on first use.
        // EventRecord = what(2), message(4), when(4), where(4), modifiers(2)
        if self.dialog_filter_event == 0 {
            self.dialog_filter_event =
                self.dialog_callback_scratch_base() + DIALOG_FILTER_EVENT_OFFSET;
        }
        let evt = self.dialog_filter_event;

        // Allocate the 2-byte Boolean result scratch on first use.
        if self.dispatcher.dialog_filter_result_addr == 0 {
            self.dispatcher.dialog_filter_result_addr =
                self.dialog_callback_scratch_base() + DIALOG_FILTER_RESULT_OFFSET;
        }
        let result_addr = self.dispatcher.dialog_filter_result_addr;

        // Clear the filter result before each invocation.
        self.bus.write_word(result_addr, 0);

        let ticks = self.bus.read_long(0x016A);

        // Consume the next actionable event from the queue, mirroring the real
        // Mac ModalDialog which calls GetNextEvent before invoking the filter.
        // Inside Macintosh Volume I, I-415
        let idx = self
            .dispatcher
            .event_queue
            .iter()
            .position(|e| matches!(e.what, 1 | 2 | 3 | 4 | 6));
        let next_event = idx.map(|i| self.dispatcher.event_queue.remove(i).unwrap());

        let filter_event = if let Some(e) = next_event {
            e
        } else if let Some(update_event) = self
            .dispatcher
            .pending_update_event(&self.bus, 1u16 << 6)
            .filter(|event| event.message == dialog_ptr)
        {
            // `GetNextEvent` normally obtains updateEvt records from the
            // Window Manager's invalid region state. The queued-event path is
            // a one-shot approximation, but apps can flush that queued event
            // before entering a nested ModalDialog filter. If the active dialog
            // itself is still invalid, deliver that real pending update to the
            // filter rather than falling through to a null event. Restrict this
            // to the current dialog so unrelated behind-window invalid regions
            // cannot flood modal filters.
            update_event
        } else {
            // Modal filters are called on null events too; many apps render
            // their dialog content from this path (e.g., idle redraw).
            let (v, h) = self.dispatcher.mouse_position();
            crate::trap::dispatch::QueuedEvent {
                what: 0,
                message: 0,
                where_v: v,
                where_h: h,
                modifiers: self.dispatcher.current_event_modifiers(),
            }
        };
        if let Some(tracking) = self.dispatcher.dialog_tracking.as_mut() {
            tracking.last_filter_event = Some(filter_event.clone());
        }
        let what = filter_event.what;
        let message = filter_event.message;
        let where_v = filter_event.where_v;
        let where_h = filter_event.where_h;
        let modifiers = filter_event.modifiers;
        if what == 0 {
            self.dialog_filter_last_null_event_tick = Some((dialog_ptr, ticks));
        } else {
            self.dialog_filter_last_null_event_tick = None;
        }
        self.dispatcher.tick_count = ticks;
        self.dispatcher.write_event_record(
            &mut self.bus,
            evt,
            what,
            message,
            where_v,
            where_h,
            modifiers,
        );
        if trace_dialog_filter_enabled() {
            eprintln!(
                "[DIALOG-FILTER] call dialog=${:08X} proc=${:08X} event=what:{} message=${:08X} where=({}, {}) mods=${:04X}",
                dialog_ptr, filter_proc, what, message, where_v, where_h, modifiers
            );
        }

        // Trampoline (48 bytes) with correct Pascal calling convention:
        //
        // FUNCTION MyFilter(theDialog: DialogPtr; VAR theEvent: EventRecord;
        //                   VAR itemHit: INTEGER): BOOLEAN;
        // Inside Macintosh Volume I, I-415
        //
        // Pascal convention: caller pushes 2-byte result space, then params
        // left-to-right. Callee pops params; result is left on stack.
        //
        //   +0:  MOVEM.L D0-D3/A0-A3,-(SP)     ; 48E7 F0F0
        //   +4:  CLR.W   -(SP)                   ; 4267 — Boolean result space
        //   +6:  MOVE.L  #dialogPtr,-(SP)         ; 2F3C xxxx xxxx
        //   +12: MOVE.L  #eventPtr,-(SP)          ; 2F3C xxxx xxxx
        //   +18: MOVE.L  #itemHitPtr,-(SP)        ; 2F3C xxxx xxxx
        //   +24: JSR     filter_proc              ; 4EB9 xxxx xxxx
        //        ; callee popped 12 bytes of params; SP → 2-byte Boolean result
        //   +30: MOVE.W  (SP),(result_addr).L     ; 33D7 xxxx xxxx
        //   +36: MOVEA.L #savedSP,A7              ; 2E7C xxxx xxxx
        //   +42: MOVEM.L (SP)+,D0-D3/A0-A3       ; 4CDF 0F0F
        //   +46: RTS                              ; 4E75
        if self.dialog_filter_trampoline == 0 {
            let tramp = self.dialog_callback_scratch_base() + DIALOG_FILTER_TRAMPOLINE_OFFSET;
            self.bus.write_word(tramp, 0x48E7); // MOVEM.L regs,-(SP)
            self.bus.write_word(tramp + 2, 0xF0F0); // D0-D3/A0-A3
            self.bus.write_word(tramp + 4, 0x4267); // CLR.W -(SP) — result space
            self.bus.write_word(tramp + 6, 0x2F3C); // MOVE.L #imm,-(SP)
                                                    // +8..+11: dialogPtr
            self.bus.write_word(tramp + 12, 0x2F3C); // MOVE.L #imm,-(SP)
                                                     // +14..+17: eventPtr
            self.bus.write_word(tramp + 18, 0x2F3C); // MOVE.L #imm,-(SP)
                                                     // +20..+23: itemHitPtr
            self.bus.write_word(tramp + 24, 0x4EB9); // JSR abs.L
                                                     // +26..+29: filter_proc
            self.bus.write_word(tramp + 30, 0x33D7); // MOVE.W (SP),(abs).L
                                                     // +32..+35: result_addr
            self.bus.write_word(tramp + 36, 0x2E7C); // MOVEA.L #imm,A7
                                                     // +38..+41: savedSP
            self.bus.write_word(tramp + 42, 0x4CDF); // MOVEM.L (SP)+,regs
            self.bus.write_word(tramp + 44, 0x0F0F); // D0-D3/A0-A3
            self.bus.write_word(tramp + 46, 0x4E75); // RTS
            self.dialog_filter_trampoline = tramp;
        }

        let tramp = self.dialog_filter_trampoline;
        self.bus.write_long(tramp + 8, dialog_ptr);
        self.bus.write_long(tramp + 14, evt);
        self.bus.write_long(tramp + 20, item_hit_ptr);
        self.bus.write_long(tramp + 26, filter_proc);
        self.bus.write_long(tramp + 32, result_addr);

        // ModalDialog handles events through DialogSelect, which selects the
        // dialog port before event handling. Leave that port current when the
        // filter returns so application follow-up drawing/invalidations target
        // the active dialog.
        self.dispatcher
            .set_current_port_state(&mut self.bus, &mut self.cpu, dialog_ptr, None);

        // Inject callback execution.
        let current_pc = self.cpu.read_reg(Register::PC);
        let sp = self.cpu.read_reg(Register::A7);
        let d_regs = [
            self.cpu.read_reg(Register::D0),
            self.cpu.read_reg(Register::D1),
            self.cpu.read_reg(Register::D2),
            self.cpu.read_reg(Register::D3),
            self.cpu.read_reg(Register::D4),
            self.cpu.read_reg(Register::D5),
            self.cpu.read_reg(Register::D6),
            self.cpu.read_reg(Register::D7),
        ];
        let a_regs = [
            self.cpu.read_reg(Register::A0),
            self.cpu.read_reg(Register::A1),
            self.cpu.read_reg(Register::A2),
            self.cpu.read_reg(Register::A3),
            self.cpu.read_reg(Register::A4),
            self.cpu.read_reg(Register::A5),
            self.cpu.read_reg(Register::A6),
            sp,
        ];
        let ccr = self.cpu.core.get_ccr();
        let new_sp = sp.wrapping_sub(4);
        let saved_sp = new_sp.wrapping_sub(32); // SP after MOVEM save at trampoline entry

        // Zero the stack region the filter proc will use as local variables.
        //
        // On a real Mac, ModalDialog's internal event loop calls GetNextEvent
        // and DialogSelect between filter proc invocations, which naturally
        // overwrites the stack area with fresh data. In our HLE, the filter
        // proc is called directly without these intermediate calls, so stale
        // local variables from the previous invocation persist. This causes
        // bugs when the filter proc's code reads uninitialized locals that
        // happen to contain residual data (e.g., a stale Pascal string length
        // byte interpreted as a large count, overflowing a buffer).
        //
        // Clear 2KB below the filter proc's entry SP to simulate the stack
        // hygiene that ModalDialog's real event loop provides.
        let filter_entry_sp = saved_sp.wrapping_sub(50); // after MOVEM+params+JSR
        let clear_size: u32 = 2048;
        let clear_start = filter_entry_sp.wrapping_sub(clear_size);
        self.bus.fill_zeros(clear_start, clear_size);

        self.bus.write_long(tramp + 38, saved_sp);
        self.bus.write_long(new_sp, current_pc);
        self.cpu.write_reg(Register::A7, new_sp);
        self.active_interrupt_callback = Some(ActiveInterruptCallback {
            source: ActiveInterruptCallbackSource::DialogFilterProc,
            resume_pc: current_pc,
            resume_sp: sp,
            d_regs,
            a_regs,
            ccr,
            restore_port: None,
        });
        self.cpu.write_reg(Register::PC, tramp);

        // Mark rendered_pixels stale while the filter proc is executing so
        // redraw_chrome skips restoration (which would erase the filter's
        // framebuffer output). After the filter returns and ModalDialog refires,
        // the re-snapshot path captures the filter's drawing into rendered_pixels.
        if let Some(tracking) = self.dispatcher.dialog_tracking.as_mut() {
            tracking.rendered_pixels_final = false;
        }
        true
    }

    /// Run the 68k guest until it halts or [`FixtureRunnerConfig::max_instructions`]
    /// is reached. Returns:
    /// - `Ok(())` on a clean halt (`Stopped`, ExitToShell, or invalid PC).
    /// - `Err(Error::Halted)` is *not* returned here — halt-via-trap maps
    ///   to `Ok(())`. Trap dispatch errors (other than `Halted`) propagate.
    /// - [`Error::Timeout`] when the instruction count cap is reached
    ///   before any halt condition fires.
    ///
    /// Most embedders should prefer [`FixtureRunner::run_steps`], which
    /// gives you per-call budget control, returns whether the CPU is
    /// still running, and exposes per-halt detail via the
    /// [`halted_pc`](Self::halted_pc) / [`halted_trap`](Self::halted_trap)
    /// accessors.
    pub fn run(&mut self) -> Result<()> {
        let mut count = 0;

        if trace_load_enabled() {
            eprintln!("========================================");
            eprintln!("        FIXTURE RUNNER STARTING         ");
            eprintln!("========================================");

            eprintln!(
                "[RUN] Starting at PC=${:08X}, A5=${:08X}, A7=${:08X}",
                self.cpu.read_reg(Register::PC),
                self.cpu.read_reg(Register::A5),
                self.cpu.read_reg(Register::A7)
            );
        }

        while count < self.config.max_instructions {
            if self.cpu.is_stopped() {
                if trace_load_enabled() {
                    eprintln!(
                        "[RUN] Stopped after {} instructions, PC=${:08X}",
                        count,
                        self.cpu.read_reg(Register::PC)
                    );
                }
                return Ok(());
            }

            let pc = self.cpu.read_reg(Register::PC);

            // Safety Trigger: If PC jumps outside RAM or to Low Mem, stop immediately
            // Allow $60+ since CRT relocation installs trampolines in low memory
            if pc >= self.bus.ram_size() || (pc < 0x60 && pc > 0) {
                eprintln!(
                    "[RUN] CRITICAL: PC jumped to invalid address ${:08X}! Halting trace.",
                    pc
                );
                self.dump_trace();
                return Ok(());
            }

            // Trace: Push current PC/Opcode/Regs (gated on env var).
            if trace_buffer_enabled() {
                let opcode = self.bus.read_word(pc);
                let a0 = self.cpu.read_reg(Register::A0);
                let sp = self.cpu.read_reg(Register::A7);
                let a6 = self.cpu.read_reg(Register::A6);
                let a5 = self.cpu.read_reg(Register::A5);
                if self.trace_buffer.len() >= 200 {
                    self.trace_buffer.pop_front();
                }
                self.trace_buffer.push_back((pc, opcode, a0, sp, a6, a5));
            }

            match self.cpu.step(&mut self.bus) {
                StepResult::Ok => {}
                StepResult::Stopped => {
                    if trace_load_enabled() {
                        let stopped_pc = self.cpu.read_reg(Register::PC);
                        let opcode = self.bus.read_word(stopped_pc);
                        eprintln!(
                            "[RUN] Step returned Stopped after {} instructions, PC=${:08X}, Opcode=${:04X}",
                            count, stopped_pc, opcode
                        );
                    }
                    self.dump_trace();
                    return Ok(());
                }
                StepResult::Aline(opcode) => {
                    match self
                        .dispatcher
                        .dispatch(opcode, &mut self.cpu, &mut self.bus)
                    {
                        Ok(()) => {
                            // Smart PC Advance:
                            // Only advance PC if the trap didn't change it
                            // (auto-pop traps set PC to return address)
                            let pc_after = self.cpu.read_reg(Register::PC);
                            if pc_after == pc {
                                self.cpu.write_reg(Register::PC, pc + 2);
                            }

                            // Log traps to stderr, but don't dump trace unless it's suspicious
                            // eprintln!("[RUN] Trap ${:04X} handled...", opcode);
                        }
                        Err(Error::Halted) => {
                            if trace_load_enabled() {
                                eprintln!("[RUN] Halted via trap after {} instructions", count);
                            }
                            self.dump_trace();
                            return Ok(());
                        }
                        Err(e) => {
                            self.dump_trace();
                            return Err(e);
                        }
                    }
                }
            }
            count += 1;
        }
        if trace_load_enabled() {
            eprintln!("[RUN] Timeout after {} instructions", count);
        }
        self.dump_trace();
        Err(Error::Timeout(count))
    }

    /// Walk the trace_buffer (most-recent first) and return the first
    /// PC that decode_fakeptr_pc recognises, plus its hint. Used by
    /// the halt log to surface drifted PCs that landed in unmapped
    /// memory after a JSR through a GetTrapAddress fakeptr — the
    /// halted PC itself can be 0x1000+ bytes past the original entry,
    /// well outside the documented fakeptr range, so a direct decode
    /// of the halted PC misses it. The trace_buffer is opt-in via
    /// SYSTEMLESS_TRACE_BUFFER=1; without it this scan returns None.
    fn trace_find_fakeptr_entry(&self) -> Option<(u32, String)> {
        for (pc, _op, _a0, _sp, _a6, _a5) in self.trace_buffer.iter().rev() {
            if let Some(hint) = decode_fakeptr_pc(*pc) {
                return Some((*pc, hint));
            }
        }
        None
    }

    /// Print the last N executed instructions to stderr in PC/Op/Reg
    /// form. Used by halt paths in `run` / `run_steps_internal` to
    /// surface the run-up to a crash. Early-exits when the trace
    /// buffer is empty (the default — `SYSTEMLESS_TRACE_BUFFER=1`
    /// must be set to populate the buffer in the first place).
    pub fn dump_trace(&self) {
        if self.trace_buffer.is_empty() {
            return;
        }
        eprintln!(
            "[TRACE] Last {} executed instructions:",
            self.trace_buffer.len()
        );
        eprintln!("  PC        Op    A0       SP       A6       D0");
        for (pc, opcode, a0, sp, a6, d0) in &self.trace_buffer {
            eprintln!(
                "  {:08X}  {:04X}  {:08X} {:08X} {:08X} {:08X}",
                pc, opcode, a0, sp, a6, d0
            );
        }
    }
}

/// Dump the diagnostic histograms when the runner is dropped. Each
/// `print_*_histogram` already early-returns when its env-var gate
/// isn't set, so this is a no-op for normal runs (including tests).
/// Investigate interactive-mode behavior with
/// `SYSTEMLESS_TRACE_TRAP_COUNTS=1`, `SYSTEMLESS_TRACE_OPCODE_COUNTS=1`,
/// `SYSTEMLESS_TRACE_HOT_PC=1`, or `SYSTEMLESS_TRACE_TRAP_TIMING=1`.
impl Drop for FixtureRunner {
    fn drop(&mut self) {
        self.dispatcher.print_trap_histogram(40);
        self.print_opcode_histogram(40);
        self.print_pc_histogram(40);
        self.dispatcher.print_trap_timing_histogram(40);
    }
}

// =============================================================================
// Loader Implementation
// =============================================================================

fn load_app_generic<M: MemoryBus>(
    fork: &ResourceFork,
    bus: &mut M,
    load_address: u32,
) -> Option<LoadedApp> {
    // 1. Load CODE 0 Header
    let code0 = fork.get_code(0)?;
    let header = Code0Header::parse(&code0.data)?;
    if trace_load_enabled() {
        eprintln!(
            "[LOAD] CODE 0 header: above_a5={}, below_a5={}, jt_size={}, jt_offset={}",
            header.above_a5, header.below_a5, header.jump_table_size, header.jump_table_offset
        );
    }

    let a5_base = load_address + header.below_a5;
    // For classic Mac apps, above_a5 defines the space needed above A5.
    // However, some apps place QuickDraw globals at higher offsets (e.g., A5+39KB).
    // Add 48KB reserve to accommodate most classic apps.
    let qd_globals_reserve = 48 * 1024; // 48KB reserve for QD globals
    let globals_end = a5_base + header.above_a5 + qd_globals_reserve;

    // Clear A5 world
    let globals_zero_end = globals_end + 0x40000;
    for addr in load_address..globals_zero_end {
        bus.write_byte(addr, 0);
    }
    bus.write_long(0x0904, a5_base); // CurrentA5
    bus.write_word(0x0934, header.jump_table_offset as u16); // CurJTOffset - Inside Macintosh Volume II, II-62
    bus.write_word(0x028E, 0x0000); // ROM85

    // Write RTS stubs at low-memory jump vectors that some runtimes
    // (Think C, CodeWarrior) call directly instead of via A-line traps.
    // On a real Mac, these contain ROM routine addresses. In our HLE,
    // we place RTS instructions so JSRs to these addresses return safely.
    // Only cover $0060-$00FF to avoid corrupting system globals in $0100+
    // (e.g., $012D is a debugger presence flag that must remain 0).
    // The CRT's relocation pass will populate the real runtime trampolines.
    for addr in (0x0060..0x0100).step_by(2) {
        bus.write_word(addr, 0x4E75); // RTS
    }

    // Install default RTE stubs for the "post-instruction" exception
    // vectors that real Mac OS would route to SysError. Because these
    // exceptions all stack the PC of the *next* instruction (per
    // M68000PRM, "Group 2 — internal" — vectors 5/6/7 advance PC past
    // the offending op before taking the trap), an RTE simply resumes
    // execution at the next instruction without re-entering the fault.
    // Inside Macintosh Volume I, I-103 (Exception Vector Table).
    //
    //   vector 5 ($14): Zero Divide  — DIVU/DIVS with src == 0
    //   vector 6 ($18): CHK          — bounds-check trap
    //   vector 7 ($1C): TRAPV        — programmed overflow trap
    //
    // Bus error (vector 2) and address error (vector 3) are deliberately
    // NOT installed: they stack PPC (the start of the faulting
    // instruction), so RTE-ing would re-execute it and loop forever.
    // Properly handling those requires a skip-the-instruction stub
    // which is a separate undertaking.
    bus.write_word(0x00FE, 0x4E73); // RTE
    bus.write_long(0x0014, 0x0000_00FE); // ZeroDivide vector
    bus.write_long(0x0018, 0x0000_00FE); // CHK vector
    bus.write_long(0x001C, 0x0000_00FE); // TRAPV vector

    // Load DATA 0 into A5 world (initialized globals)
    // DATA goes below A5 at address (A5 - below_a5) = load_address
    if let Some(data) = fork.get(*b"DATA", 0) {
        // DATA resource starts at offset 0 from load_address and fills up to A5
        let data_dest = load_address;
        if trace_load_enabled() {
            eprintln!(
                "[LOAD] Writing DATA 0 ({} bytes) to ${:08X}",
                data.data.len(),
                data_dest
            );
        }
        bus.write_bytes(data_dest, &data.data);
    }

    // 2. Parse Jump Table from CODE 0
    let mut jump_table = Vec::new();
    let jt_data = &code0.data[16..];

    for i in 0..header.num_entries() {
        let entry_offset = i * 8;
        if entry_offset + 8 > jt_data.len() {
            break;
        }

        let word_2_3 = u16::from_be_bytes([jt_data[entry_offset + 2], jt_data[entry_offset + 3]]);
        let (offset, segment) = if word_2_3 == 0xA9F0 {
            // FAR Format
            let seg = i16::from_be_bytes([jt_data[entry_offset], jt_data[entry_offset + 1]]);
            let off = u16::from_be_bytes([jt_data[entry_offset + 6], jt_data[entry_offset + 7]]);
            (off, seg)
        } else if word_2_3 == 0xFFFF {
            // NULL
            (0u16, 0i16)
        } else {
            // NEAR Format
            let off = u16::from_be_bytes([jt_data[entry_offset], jt_data[entry_offset + 1]]);
            let seg = i16::from_be_bytes([jt_data[entry_offset + 4], jt_data[entry_offset + 5]]);
            (off, seg)
        };

        jump_table.push(JumpTableEntry {
            offset,
            segment,
            loaded: false,
            address: 0,
        });
        if trace_load_enabled() {
            eprintln!(
                "[LOAD] Parsed JT[{}]: segment={}, offset=0x{:04X}, raw=[{:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X} {:02X}]",
                i, segment, offset,
                jt_data[entry_offset], jt_data[entry_offset+1],
                jt_data[entry_offset+2], jt_data[entry_offset+3],
                jt_data[entry_offset+4], jt_data[entry_offset+5],
                jt_data[entry_offset+6], jt_data[entry_offset+7]
            );
        }
    }

    // 3. Setup Layout
    let code0_base = globals_end;
    let code0_size = code0.data.len() as u32;
    let code0_user = code0_base + 4;
    let jt_base = a5_base + header.jump_table_offset;
    if trace_load_enabled() {
        eprintln!("[LOAD] Memory layout: a5_base=${:08X}, globals_end=${:08X}, code0_user=${:08X}, code0_size={}, jt_base=${:08X} (jt_offset={})",
                  a5_base, globals_end, code0_user, code0_size, jt_base, header.jump_table_offset);
    }

    // 4. Load CODE 0 (Resident)
    bus.write_long(code0_base, code0_size);
    bus.write_bytes(code0_user, &code0.data);

    // Copy the JT data from CODE 0 to the actual JT area at A5+jt_offset.
    // On a real Mac, the system writes CODE 0's JT content (bytes after the
    // 16-byte header) to A5+CurJTOffset. This populates the initial JT
    // entries with unloaded-format stubs (offset, MOVE.W #seg, _LoadSeg).
    // Inside Macintosh Volume II, II-60
    let jt_content = &code0.data[16..];
    if !jt_content.is_empty() {
        bus.write_bytes(jt_base, jt_content);
    }

    // 5. Load all other CODE resources
    let mut segment_bases = HashMap::new();
    segment_bases.insert(0, code0_user);
    crate::trap::dispatch::record_segment_base(0, code0_user);

    // Load CODE segments into memory but do NOT pre-patch jump table entries.
    // Think C / CodeWarrior apps populate the JT at runtime via their startup
    // code (crt0). Our LoadSeg trap handler patches entries on demand when
    // segments are first called, matching real Mac Segment Loader behavior.
    // Inside Macintosh Volume II, II-60; Executor segment.cpp
    //
    // Reserve space: scan CODE headers to find max JT extent so CODE segments
    // are placed above the JT area.
    let mut max_jt_end: u32 = jt_base + (jump_table.len() as u32 * 8);
    let mut all_codes = fork.get_all_code();
    all_codes.sort_by_key(|c| c.id);

    for code_res in &all_codes {
        if code_res.id == 0 || code_res.data.len() < 4 {
            continue;
        }
        let Some(segment_header) = CodeSegmentHeader::parse(&code_res.data) else {
            continue;
        };
        let Some(tab_off) = segment_header.jump_table_start_offset() else {
            continue;
        };
        let Some(n_entries) = segment_header.jump_table_entry_count() else {
            continue;
        };
        let end = jt_base + tab_off + n_entries * 8;
        if end > max_jt_end {
            max_jt_end = end;
        }

        // Pre-populate unloaded-JT-entry stubs for entries this segment
        // owns that are still ALL ZERO (i.e. not yet populated by CODE 0's
        // jt_content write). Per Inside Macintosh Volume II, II-60, an
        // unloaded entry is `offset(2) + \$3F3C(2) + seg(2) + \$A9F0(2)`
        // — JSR-ing to entry+2 fires LoadSeg via the trap. Real System 7
        // writes these stubs at app-launch time; without them, segments
        // not represented in CODE 0's jt_content stay zeroed, so a
        // guest JSR-through-JT walks zeros (or falls into the next
        // patched entry) and faults (Centaurian 1.2.1 hits this).
        //
        // Skip entries with non-zero content — they've already been
        // initialised by CODE 0's load (as stubs) or pre-patched as
        // loaded JMP.L. Stomping either of those would break MPW-style
        // fixtures where CODE 0 carries the canonical layout.
        for i in 0..n_entries {
            let entry = jt_base + tab_off + i * 8;
            let is_empty = bus.read_long(entry) == 0 && bus.read_long(entry + 4) == 0;
            let is_null_placeholder = bus.read_word(entry + 2) == 0xFFFF;
            if !is_empty && !is_null_placeholder {
                continue;
            }
            if is_null_placeholder {
                // Some near-model apps leave segment-owned CODE 0 entries as
                // `offset, FFFF, FFFF, FFFF` placeholders and call the slot at
                // entry+0. Materialize a Think-style unload stub so that first
                // call enters LoadSeg instead of executing the placeholder.
                let routine_offset = bus.read_word(entry);
                bus.write_word(entry, 0xA9F0);
                bus.write_word(entry + 2, 0);
                bus.write_word(entry + 4, routine_offset);
                bus.write_word(entry + 6, code_res.id as u16);
            } else {
                bus.write_word(entry, 0);
                bus.write_word(entry + 2, 0x3F3C);
                bus.write_word(entry + 4, code_res.id as u16);
                bus.write_word(entry + 6, 0xA9F0);
            }
        }
    }

    let reserved_boundary = std::cmp::max(code0_user + code0_size, max_jt_end);
    let mut current_load_ptr = (reserved_boundary + 4) & !3;

    for code_res in all_codes {
        if code_res.id == 0 {
            continue;
        }

        let size = code_res.data.len() as u32;
        let phys_addr = current_load_ptr;
        let user_addr = current_load_ptr + 4;

        // Dump segment header info
        let segment_header = CodeSegmentHeader::parse(&code_res.data);
        let hdr_info = match segment_header {
            Some(CodeSegmentHeader::MpwFar) => "mpw-far-model".to_string(),
            Some(CodeSegmentHeader::Near {
                table_offset,
                entry_count,
            }) => format!("near-model taboff={} n={}", table_offset, entry_count),
            Some(CodeSegmentHeader::ThinkFar {
                has_relocations,
                first_entry_index,
                entry_count,
            }) => format!(
                "think-far-model first_jt={} n={} relocs={}",
                first_entry_index, entry_count, has_relocations
            ),
            None => "unknown".to_string(),
        };
        if trace_load_enabled() {
            eprintln!(
                "[LOAD] Loading CODE {} ({} bytes) to ${:08X} [{}]",
                code_res.id, size, user_addr, hdr_info
            );
        }

        bus.write_long(phys_addr, size);
        bus.write_bytes(user_addr, &code_res.data);

        segment_bases.insert(code_res.id, user_addr);
        crate::trap::dispatch::record_segment_base(code_res.id, user_addr);

        // Only patch JT for CODE 0's entries (far-model segments from the
        // original CODE 0 parse). Near-model segments get their JT entries
        // populated by the app's startup code and patched by LoadSeg.
        if matches!(segment_header, Some(CodeSegmentHeader::MpwFar)) {
            // Far-model CODE segment (40-byte header)
            let header_size = 40u32;
            for (i, entry) in jump_table.iter_mut().enumerate() {
                if entry.segment == code_res.id {
                    entry.loaded = true;
                    let effective_offset = entry.offset as u32;
                    entry.address = user_addr + header_size + effective_offset;

                    let jt_addr = jt_base + (i as u32 * 8);
                    bus.write_word(jt_addr, code_res.id as u16);
                    bus.write_word(jt_addr + 2, 0x4EF9); // JMP
                    bus.write_long(jt_addr + 4, entry.address);
                    if trace_load_enabled() {
                        eprintln!(
                            "[LOAD] JT[{}] -> CODE {} @ ${:08X} (far-model, off=${:04X})",
                            i, code_res.id, entry.address, effective_offset
                        );
                    }
                }
            }
        }

        current_load_ptr = (user_addr + size + 4 + 3) & !3;
    }

    let size_resource = fork
        .get(*b"SIZE", -1)
        .and_then(|res| ApplicationSizeResource::parse(&res.data));

    // Stack at top of RAM
    let stack_top = bus.ram_size() - 16;

    Some(LoadedApp {
        code0_header: header,
        a5_base,
        jump_table,
        segment_bases,
        initial_sp: stack_top,
        size_resource,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::audio::AudioBackend;
    use crate::loader::{ApplicationSizeResource, Code0Header, LoadedApp};
    use crate::sound::{
        DoubleBufferState, PendingDoubleBackCallback, PendingSoundCallback, PlaybackKind,
        SndChannel, SndCommand, OUTPUT_RATE,
    };
    use crate::trap::dispatch::{DialogItem, DialogTrackingState, QueuedEvent, TimerTask, VblTask};
    use std::cell::RefCell;
    use std::collections::{HashMap, VecDeque};
    use std::rc::Rc;

    #[derive(Clone, Default)]
    struct CapturingAudioBackend {
        stereo_samples: Rc<RefCell<Vec<u8>>>,
    }

    impl CapturingAudioBackend {
        fn new() -> (Self, Rc<RefCell<Vec<u8>>>) {
            let stereo_samples = Rc::new(RefCell::new(Vec::new()));
            (
                Self {
                    stereo_samples: stereo_samples.clone(),
                },
                stereo_samples,
            )
        }
    }

    impl AudioBackend for CapturingAudioBackend {
        fn queue_samples(&mut self, samples: &[u8]) {
            self.stereo_samples.borrow_mut().extend(samples);
        }

        fn queue_stereo_samples(&mut self, samples: &[u8]) {
            self.stereo_samples.borrow_mut().extend(samples);
        }

        fn stop(&mut self) {}
    }

    fn make_resource_fork_bytes(resources: &[([u8; 4], i16, &[u8])]) -> Vec<u8> {
        let mut type_groups: Vec<([u8; 4], Vec<(i16, &[u8], u32)>)> = Vec::new();
        for (res_type, res_id, data) in resources {
            let group_idx = type_groups
                .iter()
                .position(|(existing_type, _)| existing_type == res_type)
                .unwrap_or_else(|| {
                    type_groups.push((*res_type, Vec::new()));
                    type_groups.len() - 1
                });
            type_groups[group_idx].1.push((*res_id, *data, 0));
        }
        type_groups.sort_by_key(|(res_type, _)| *res_type);
        for (_, entries) in &mut type_groups {
            entries.sort_by_key(|(res_id, _, _)| *res_id);
        }

        let data_offset = 16u32;
        let mut data_section = Vec::new();
        for (_, entries) in &mut type_groups {
            for (_, data, data_pos) in entries {
                *data_pos = data_section.len() as u32;
                data_section.extend_from_slice(&(data.len() as u32).to_be_bytes());
                data_section.extend_from_slice(data);
            }
        }

        let map_offset = data_offset + data_section.len() as u32;
        let type_list_offset = 30u16;
        let type_count = type_groups.len();
        let resource_count: usize = type_groups.iter().map(|(_, entries)| entries.len()).sum();
        let ref_lists_offset = 2 + type_count * 8;
        let name_list_offset = type_list_offset as usize + ref_lists_offset + resource_count * 12;
        let map_length = name_list_offset as u32;

        let mut bytes = vec![0u8; (map_offset + map_length) as usize];
        let mut header = [0u8; 16];
        header[0..4].copy_from_slice(&data_offset.to_be_bytes());
        header[4..8].copy_from_slice(&map_offset.to_be_bytes());
        header[8..12].copy_from_slice(&(data_section.len() as u32).to_be_bytes());
        header[12..16].copy_from_slice(&map_length.to_be_bytes());
        bytes[0..16].copy_from_slice(&header);
        bytes[data_offset as usize..data_offset as usize + data_section.len()]
            .copy_from_slice(&data_section);

        let map_start = map_offset as usize;
        bytes[map_start..map_start + 16].copy_from_slice(&header);
        bytes[map_start + 24..map_start + 26].copy_from_slice(&type_list_offset.to_be_bytes());
        bytes[map_start + 26..map_start + 28]
            .copy_from_slice(&(name_list_offset as u16).to_be_bytes());
        bytes[map_start + 28..map_start + 30]
            .copy_from_slice(&((type_count as u16) - 1).to_be_bytes());

        let type_list_start = map_start + type_list_offset as usize;
        bytes[type_list_start..type_list_start + 2]
            .copy_from_slice(&((type_count as u16) - 1).to_be_bytes());
        let mut next_ref_list_offset = ref_lists_offset;
        for (i, (res_type, entries)) in type_groups.iter().enumerate() {
            let type_entry = type_list_start + 2 + i * 8;
            bytes[type_entry..type_entry + 4].copy_from_slice(res_type);
            bytes[type_entry + 4..type_entry + 6]
                .copy_from_slice(&((entries.len() as u16) - 1).to_be_bytes());
            bytes[type_entry + 6..type_entry + 8]
                .copy_from_slice(&(next_ref_list_offset as u16).to_be_bytes());

            let ref_list_start = type_list_start + next_ref_list_offset;
            for (j, (res_id, _, data_pos)) in entries.iter().enumerate() {
                let ref_entry = ref_list_start + j * 12;
                bytes[ref_entry..ref_entry + 2].copy_from_slice(&(*res_id as u16).to_be_bytes());
                bytes[ref_entry + 2..ref_entry + 4].copy_from_slice(&0xFFFFu16.to_be_bytes());
                bytes[ref_entry + 4] = 0;
                let data_offset_bytes = data_pos.to_be_bytes();
                bytes[ref_entry + 5..ref_entry + 8].copy_from_slice(&data_offset_bytes[1..4]);
            }

            next_ref_list_offset += entries.len() * 12;
        }

        bytes
    }

    fn minimal_code0(above_a5: u32, below_a5: u32, jt_size: u32, jt_offset: u32) -> Vec<u8> {
        let mut code0 = Vec::with_capacity(16 + jt_size as usize);
        code0.extend_from_slice(&above_a5.to_be_bytes());
        code0.extend_from_slice(&below_a5.to_be_bytes());
        code0.extend_from_slice(&jt_size.to_be_bytes());
        code0.extend_from_slice(&jt_offset.to_be_bytes());
        code0.resize(16 + jt_size as usize, 0);
        code0
    }

    #[test]
    fn init_app_preserves_resources_allocated_before_zone_header() {
        let code0 = minimal_code0(0, 0x2000, 0, 0);
        let bgas = [0x4E, 0x56, 0xFF, 0xA6, 0x2D, 0x7A, 0x1C, 0x72];
        let fork_bytes = make_resource_fork_bytes(&[(*b"BGAS", 128, &bgas), (*b"CODE", 0, &code0)]);
        let fork = ResourceFork::parse(&fork_bytes).expect("parse synthetic app fork");
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());

        let app = runner.load_app(&fork).expect("load app");
        let (_, bgas_ptr) = runner
            .dispatcher
            .find_resource_any(*b"BGAS", 128)
            .expect("BGAS resource loaded");
        assert_eq!(runner.bus.read_bytes(bgas_ptr, bgas.len()), bgas);

        runner.init_app(&app);

        assert_eq!(
            runner.bus.read_bytes(bgas_ptr, bgas.len()),
            bgas,
            "init_app must not overwrite resources loaded before zone setup"
        );
    }

    #[test]
    fn load_app_records_application_size_resource_id_minus_one() {
        let code0 = minimal_code0(0, 0x2000, 0, 0);
        let size = [
            0x00, 0x80, // mode32BitCompatible
            0x00, 0x30, 0x00, 0x00, // preferred partition
            0x00, 0x20, 0x00, 0x00, // minimum partition
        ];
        let fork_bytes = make_resource_fork_bytes(&[(*b"CODE", 0, &code0), (*b"SIZE", -1, &size)]);
        let fork = ResourceFork::parse(&fork_bytes).expect("parse synthetic app fork");
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());

        let app = runner.load_app(&fork).expect("load app");

        assert_eq!(
            app.size_resource,
            Some(ApplicationSizeResource {
                flags: 0x0080,
                preferred_size: 0x0030_0000,
                minimum_size: 0x0020_0000,
            })
        );
    }

    #[test]
    fn fixture_runner_defaults_to_classic_system7_theme() {
        let runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());

        assert_eq!(runner.ui_theme_id(), UiThemeId::ClassicSystem7);
        assert_eq!(runner.dispatcher().ui_theme_id(), UiThemeId::ClassicSystem7);
        assert_eq!(runner.ui_theme().id(), UiThemeId::ClassicSystem7);
        assert_eq!(
            runner.theme_metrics_mode(),
            ThemeMetricsMode::ClassicGuestMetrics
        );
        assert!(runner.uses_classic_guest_metrics());
    }

    #[test]
    fn fixture_runner_accepts_explicit_systemless_theme_without_themed_metrics() {
        let runner = FixtureRunner::new(
            8 * 1024 * 1024,
            FixtureRunnerConfig {
                ui_theme: UiThemeId::SystemlessDefault,
                theme_metrics_mode: ThemeMetricsMode::ClassicGuestMetrics,
                ..FixtureRunnerConfig::default()
            },
        );
        let classic = UiThemeId::ClassicSystem7.provider();

        assert_eq!(runner.ui_theme_id(), UiThemeId::SystemlessDefault);
        assert_eq!(
            runner.dispatcher().ui_theme_id(),
            UiThemeId::SystemlessDefault
        );
        assert_eq!(runner.ui_theme().id(), UiThemeId::SystemlessDefault);
        assert!(runner.uses_classic_guest_metrics());
        assert_eq!(runner.ui_theme().menu_metrics(), classic.menu_metrics());
        assert_eq!(
            runner.ui_theme().control_metrics(),
            classic.control_metrics()
        );
        assert_ne!(runner.ui_theme().palette(), classic.palette());
    }

    fn write_double_buffer(bus: &mut MacMemoryBus, ptr: u32, samples: &[u8]) {
        bus.write_long(ptr, samples.len() as u32);
        bus.write_long(ptr + 4, 0x0000_0001);
        for (offset, sample) in samples.iter().copied().enumerate() {
            bus.write_byte(ptr + 16 + offset as u32, sample);
        }
    }

    #[test]
    fn headless_run_steps_does_not_implicitly_mix_audio() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let program_start = 0x0001_0000;
        for offset in (0..16).step_by(2) {
            runner.bus.write_word(program_start + offset, 0x4E71); // NOP
        }
        runner.cpu.write_reg(Register::PC, program_start);
        runner.cpu.write_reg(Register::A7, 0x007F_FFC0);

        let mut chan = SndChannel::new(0x0039_38C8, false);
        chan.play_buffer(
            vec![0x90, 0x91, 0x92],
            OUTPUT_RATE << 16,
            PlaybackKind::Buffer,
            0,
        );
        runner.dispatcher.sound_manager.channels.push(chan);

        let (steps, running) = runner.run_steps(2, None);

        assert!(running);
        assert_eq!(steps, 2);
        assert_eq!(
            runner.audio_buffer_len(),
            0,
            "plain headless stepping must not consume sound buffers"
        );
        assert_eq!(runner.dispatcher.sound_manager.debug_samples_mixed, 0);

        runner.mix_audio(2);
        assert_eq!(runner.drain_audio(), vec![0x90, 0x91]);
        assert_eq!(runner.dispatcher.sound_manager.debug_samples_mixed, 2);
    }

    #[test]
    fn host_audio_backend_receives_silence_while_sound_manager_idle() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let (audio_backend, stereo_samples) = CapturingAudioBackend::new();
        runner.set_audio(Box::new(audio_backend));

        runner.mix_audio(4);

        assert_eq!(
            stereo_samples.borrow().as_slice(),
            &[0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80]
        );
        assert_eq!(
            runner.audio_buffer_len(),
            0,
            "host silence must not become captured guest audio"
        );
        assert_eq!(runner.dispatcher.sound_manager.debug_samples_mixed, 0);
    }

    #[test]
    fn host_audio_backend_receives_low_rate_sample_hold_output() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let (audio_backend, stereo_samples) = CapturingAudioBackend::new();
        runner.set_audio(Box::new(audio_backend));

        let mut chan = SndChannel::new(0x0039_38C8, false);
        chan.play_buffer(
            vec![0x90, 0xA0],
            (OUTPUT_RATE / 2) << 16,
            PlaybackKind::Buffer,
            0,
        );
        runner.dispatcher.sound_manager.channels.push(chan);

        runner.mix_audio(4);

        assert_eq!(
            stereo_samples.borrow().as_slice(),
            &[
                0x90, 0x90, // source[0] at position 0.0
                0x90, 0x90, // source[0] held at position 0.5
                0xA0, 0xA0, // source[1] at position 1.0
                0xA0, 0xA0, // source[1] held at position 1.5
            ],
            "GUI/host audio path must receive the sample-hold low-rate output, not the old linear midpoint"
        );
        assert_eq!(runner.dispatcher.sound_manager.debug_samples_mixed, 4);
    }

    fn dialog_tracking_for_test(filter_proc: u32, item_hit_ptr: u32) -> DialogTrackingState {
        DialogTrackingState {
            dialog_ptr: 0x0020_0000,
            bounds: (0, 0, 32, 32),
            title: String::new(),
            proc_id: 1,
            items: Vec::new(),
            default_item: 0,
            cancel_item: 0,
            edit_text: String::new(),
            edit_item: 0,
            saved_pixels: Vec::new(),
            stack_ptr: 0,
            item_hit_ptr,
            rendered_pixels: Vec::new(),
            flash_remaining: 0,
            flash_delay: 0,
            flash_item: 0,
            edit_text_modified: false,
            draw_proc_queue: VecDeque::new(),
            draw_procs_done: true,
            rendered_pixels_final: true,
            filter_proc,
            game_managed: false,
            last_filter_event: None,
            popup_draws: Vec::new(),
            active_popup: None,
            active_button: None,
            active_user_item: None,
        }
    }

    #[test]
    fn arrows_as_numpad_remaps_key_and_char_together() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        runner.set_arrows_as_numpad(true);

        assert_eq!(runner.remap_key(0x7B, 28), (0x56, b'4'));
        assert_eq!(runner.remap_key(0x7C, 29), (0x58, b'6'));
        assert_eq!(runner.remap_key(0x7D, 31), (0x57, b'5'));
        assert_eq!(runner.remap_key(0x7E, 30), (0x5B, b'8'));
        assert_eq!(runner.remap_key(0x2E, b'm'), (0x2E, b'm'));
    }

    #[test]
    fn arrows_not_remapped_by_default() {
        let runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());

        assert!(!runner.arrows_as_numpad());
        assert_eq!(runner.remap_key(0x7B, 28), (0x7B, 28));
        assert_eq!(runner.remap_key(0x7C, 29), (0x7C, 29));
        assert_eq!(runner.remap_key(0x2E, b'm'), (0x2E, b'm'));
    }

    #[test]
    fn key_events_sync_low_memory_keymap() {
        use crate::memory::globals::addr;

        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());

        assert_eq!(runner.bus.read_byte(addr::KEY_MAP_LM + 4), 0);
        assert_eq!(runner.bus.read_byte(addr::KEY_MAP_LM + 15), 0);

        runner.push_key_down(0x26, b'j');
        runner.push_key_down(0x7E, 30);

        assert_eq!(
            runner.bus.read_byte(addr::KEY_MAP_LM + 4),
            0x40,
            "J key should be visible to byte/bit KeyMap readers"
        );
        assert_eq!(
            runner.bus.read_byte(addr::KEY_MAP_LM + 5),
            0,
            "J key should not alias M at KeyMapLM byte 5 bit 6"
        );
        assert_eq!(
            runner.bus.read_byte(addr::KEY_MAP_LM + 15),
            0x40,
            "up arrow should be visible to byte/bit KeyMap readers"
        );
        assert_eq!(
            runner.bus.read_byte(addr::KEY_MAP_LM + 14),
            0,
            "up arrow should not be mirrored into the unused raw byte"
        );

        runner.push_key_up(0x26, b'j');

        assert_eq!(
            runner.bus.read_byte(addr::KEY_MAP_LM + 4),
            0,
            "J key release should clear the low-memory mirror"
        );
        assert_eq!(
            runner.bus.read_byte(addr::KEY_MAP_LM + 5),
            0,
            "J key release should leave the M-key byte clear"
        );
        assert_eq!(
            runner.bus.read_byte(addr::KEY_MAP_LM + 15),
            0x40,
            "unrelated byte/bit down keys should remain mirrored"
        );
        assert_eq!(
            runner.bus.read_byte(addr::KEY_MAP_LM + 14),
            0,
            "unused raw byte should stay clear"
        );
    }

    #[test]
    fn init_app_seeds_top_of_stack_with_nonzero_bytes() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let app = LoadedApp {
            code0_header: Code0Header {
                above_a5: 0,
                below_a5: 0x2000,
                jump_table_size: 0,
                jump_table_offset: 0,
            },
            a5_base: 0x0040_0000,
            jump_table: Vec::new(),
            segment_bases: HashMap::new(),
            initial_sp: 0x007F_FFC0,
            size_resource: None,
        };

        runner.init_app(&app);

        let stack_seed_start = app.initial_sp.saturating_sub(0x8000);
        assert_eq!(
            runner.bus.read_long(stack_seed_start),
            0xA5A5_A5A5,
            "top-of-stack window must not be zeroed"
        );
    }

    #[test]
    fn init_app_leaves_application_heap_room_below_appllimit() {
        use crate::memory::globals::addr;

        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let app = LoadedApp {
            code0_header: Code0Header {
                above_a5: 0,
                below_a5: 0x2000,
                jump_table_size: 0,
                jump_table_offset: 0,
            },
            a5_base: 0x0040_0000,
            jump_table: Vec::new(),
            segment_bases: HashMap::new(),
            initial_sp: 0x007F_FFC0,
            size_resource: None,
        };

        runner.init_app(&app);

        let heap_end = runner.bus.read_long(addr::HEAP_END);
        let appl_limit = runner.bus.read_long(addr::APPL_LIMIT);
        assert_eq!(
            heap_end,
            0x0020_0000 + APP_ZONE_HEADER_SIZE,
            "HeapEnd should expose the initial application-zone extent"
        );
        assert!(
            appl_limit.saturating_sub(heap_end) >= 2300 * 1024,
            "direct low-memory startup checks should see growable heap room below ApplLimit"
        );
    }

    #[test]
    fn init_app_honors_size_resource_preferred_partition_for_heap_reporting() {
        use crate::memory::globals::addr;

        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let preferred_partition = 3 * 1024 * 1024;
        let app = LoadedApp {
            code0_header: Code0Header {
                above_a5: 0,
                below_a5: 0x2000,
                jump_table_size: 0,
                jump_table_offset: 0,
            },
            a5_base: 0x0040_0000,
            jump_table: Vec::new(),
            segment_bases: HashMap::new(),
            initial_sp: 0x007F_FFC0,
            size_resource: Some(ApplicationSizeResource {
                flags: 0x0080,
                preferred_size: preferred_partition,
                minimum_size: 2 * 1024 * 1024,
            }),
        };

        runner.init_app(&app);

        let expected_limit = 0x0020_0000 + preferred_partition - APP_STACK_SAFETY_MARGIN;
        let expected_free = expected_limit - (0x0020_0000 + APP_ZONE_HEADER_SIZE);
        assert_eq!(runner.bus.read_long(addr::APPL_LIMIT), expected_limit);
        assert_eq!(runner.bus.read_long(addr::BUF_PTR), expected_limit);
        assert_eq!(runner.bus.read_long(0x0020_0000), expected_limit);
        assert_eq!(runner.bus.read_long(0x0020_0000 + 12), expected_free);
        assert_eq!(
            crate::memory::app_heap_free_bytes(runner.bus()),
            expected_free
        );
        assert!(
            expected_free < crate::memory::APP_HEAP_COMPAT_FREE_FLOOR,
            "explicit SIZE partitions must bypass the compatibility floor"
        );
    }

    #[test]
    fn init_app_application_partition_override_takes_precedence_over_size_resource() {
        use crate::memory::globals::addr;

        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let size_partition = 3 * 1024 * 1024;
        let override_partition = 4 * 1024 * 1024;
        runner.set_application_partition_size(Some(override_partition));
        let app = LoadedApp {
            code0_header: Code0Header {
                above_a5: 0,
                below_a5: 0x2000,
                jump_table_size: 0,
                jump_table_offset: 0,
            },
            a5_base: 0x0040_0000,
            jump_table: Vec::new(),
            segment_bases: HashMap::new(),
            initial_sp: 0x007F_FFC0,
            size_resource: Some(ApplicationSizeResource {
                flags: 0x0080,
                preferred_size: size_partition,
                minimum_size: 2 * 1024 * 1024,
            }),
        };

        runner.init_app(&app);

        let expected_limit = 0x0020_0000 + override_partition - APP_STACK_SAFETY_MARGIN;
        assert_eq!(runner.bus.read_long(addr::APPL_LIMIT), expected_limit);
        assert_eq!(
            crate::memory::app_heap_free_bytes(runner.bus()),
            expected_limit - (0x0020_0000 + APP_ZONE_HEADER_SIZE)
        );
    }

    #[test]
    fn init_app_ignores_too_small_application_partition_override() {
        use crate::memory::globals::addr;

        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        runner.set_application_partition_size(Some(64 * 1024));
        assert_eq!(runner.application_partition_size(), None);
        let app = LoadedApp {
            code0_header: Code0Header {
                above_a5: 0,
                below_a5: 0x2000,
                jump_table_size: 0,
                jump_table_offset: 0,
            },
            a5_base: 0x0040_0000,
            jump_table: Vec::new(),
            segment_bases: HashMap::new(),
            initial_sp: 0x007F_FFC0,
            size_resource: None,
        };

        runner.init_app(&app);

        assert_eq!(
            runner.bus.read_long(addr::APPL_LIMIT),
            app.initial_sp - APP_STACK_SAFETY_MARGIN,
            "invalid tiny overrides must fall back to the default launch limit"
        );
    }

    #[test]
    fn init_app_seeds_appparmhandle_with_empty_finder_information() {
        use crate::memory::globals::addr;

        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        runner
            .dispatcher_mut()
            .set_launched_app_path("Games/Armor Alley");
        let app = LoadedApp {
            code0_header: Code0Header {
                above_a5: 0,
                below_a5: 0x2000,
                jump_table_size: 0,
                jump_table_offset: 0,
            },
            a5_base: 0x0040_0000,
            jump_table: Vec::new(),
            segment_bases: HashMap::new(),
            initial_sp: 0x007F_FFC0,
            size_resource: None,
        };

        runner.init_app(&app);

        let handle = runner.bus.read_long(addr::APP_PARM_HANDLE);
        assert_ne!(
            handle, 0,
            "AppParmHandle should point at Finder launch information"
        );
        let data_ptr = runner.bus.read_long(handle);
        assert_ne!(
            data_ptr, 0,
            "Finder launch information handle should be loaded"
        );
        assert_eq!(
            runner.bus.get_alloc_size(data_ptr),
            Some(4),
            "empty Finder launch information is message/count only"
        );
        assert_eq!(
            runner.bus.read_word(data_ptr),
            0,
            "message should be appOpen for a normal application launch"
        );
        assert_eq!(
            runner.bus.read_word(data_ptr + 2),
            0,
            "normal application launch has no selected documents"
        );
    }

    #[test]
    fn init_app_sets_legacy_sound_driver_low_memory_defaults() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let app = LoadedApp {
            code0_header: Code0Header {
                above_a5: 0,
                below_a5: 0x2000,
                jump_table_size: 0,
                jump_table_offset: 0,
            },
            a5_base: 0x0040_0000,
            jump_table: Vec::new(),
            segment_bases: HashMap::new(),
            initial_sp: 0x007F_FFC0,
            size_resource: None,
        };

        runner.init_app(&app);

        assert_eq!(
            runner
                .bus
                .read_byte(crate::memory::globals::addr::SD_VOLUME),
            1,
            "SdVolume ($0260) should boot to the nonzero legacy compatibility value"
        );
        assert_eq!(
            runner
                .bus
                .read_byte(crate::memory::globals::addr::SOUND_LEVEL),
            0,
            "SoundLevel ($027F) is a distinct Sound Driver amplitude byte"
        );
        let sound_base = runner
            .bus
            .read_long(crate::memory::globals::addr::SOUND_BASE);
        assert_eq!(
            sound_base, 0x007F_5300,
            "SoundBase ($0266) should point at the 370-word legacy sound buffer in reserved display memory"
        );
        assert_eq!(
            runner.bus.read_byte(sound_base),
            0x80,
            "legacy SoundBase buffer starts at neutral amplitude"
        );
    }

    #[test]
    fn init_app_seeds_mmu32bit_low_memory_flag() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let app = LoadedApp {
            code0_header: Code0Header {
                above_a5: 0,
                below_a5: 0x2000,
                jump_table_size: 0,
                jump_table_offset: 0,
            },
            a5_base: 0x0040_0000,
            jump_table: Vec::new(),
            segment_bases: HashMap::new(),
            initial_sp: 0x007F_FFC0,
            size_resource: None,
        };

        runner.init_app(&app);

        assert_eq!(
            runner
                .bus
                .read_byte(crate::memory::globals::addr::MMU32_BIT),
            1,
            "MMU32Bit ($0CB2) should mirror Systemless's default 32-bit addressing mode"
        );
    }

    #[test]
    fn init_app_seeds_cursor_task_low_memory_vector() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let app = LoadedApp {
            code0_header: Code0Header {
                above_a5: 0,
                below_a5: 0x2000,
                jump_table_size: 0,
                jump_table_offset: 0,
            },
            a5_base: 0x0040_0000,
            jump_table: Vec::new(),
            segment_bases: HashMap::new(),
            initial_sp: 0x007F_FFC0,
            size_resource: None,
        };

        runner.init_app(&app);

        assert_eq!(
            runner.bus.read_word(CURSOR_TASK_NOOP_ADDR),
            0x4E75,
            "default cursor task target should be a callable RTS stub"
        );
        assert_eq!(
            runner
                .bus
                .read_long(crate::memory::globals::addr::J_CRSR_TASK),
            CURSOR_TASK_NOOP_ADDR,
            "JCrsrTask ($08EE) should boot to a callable no-op vector"
        );
    }

    #[test]
    fn cursor_task_noop_vector_does_not_fire_on_guest_tick() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let interrupted_pc = 0x0002_0000;
        let interrupted_sp = 0x007F_FFC0;

        runner.bus.write_long(
            crate::memory::globals::addr::J_CRSR_TASK,
            CURSOR_TASK_NOOP_ADDR,
        );
        runner.cpu.write_reg(Register::PC, interrupted_pc);
        runner.cpu.write_reg(Register::A7, interrupted_sp);

        runner.advance_guest_tick();

        assert!(runner.active_interrupt_callback.is_none());
        assert_eq!(runner.cursor_task_trampoline, 0);
        assert_eq!(runner.cpu.read_reg(Register::PC), interrupted_pc);
        assert_eq!(runner.cpu.read_reg(Register::A7), interrupted_sp);
        assert_eq!(runner.bus.read_long(crate::memory::globals::addr::TICKS), 1);
    }

    #[test]
    fn cursor_task_callback_arms_interrupt_from_low_memory_vector() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let interrupted_pc = 0x0002_0000;
        let interrupted_sp = 0x007F_FFC0;
        let callback_addr = 0x0004_1234;

        runner
            .bus
            .write_long(crate::memory::globals::addr::J_CRSR_TASK, callback_addr);
        runner.cpu.write_reg(Register::PC, interrupted_pc);
        runner.cpu.write_reg(Register::A7, interrupted_sp);
        runner.cpu.write_reg(Register::D0, 0x1111_1111);
        runner.cpu.write_reg(Register::D7, 0x7777_7777);
        runner.cpu.write_reg(Register::A0, 0xAAAA_0000);
        runner.cpu.write_reg(Register::A6, 0xCCCC_0000);
        runner.cpu.core.set_ccr(0x04);

        runner.advance_guest_tick();

        let active = runner
            .active_interrupt_callback
            .expect("cursor task callback should have been armed");
        assert!(matches!(
            active.source,
            ActiveInterruptCallbackSource::CursorTask
        ));
        assert_eq!(active.resume_pc, interrupted_pc);
        assert_eq!(active.resume_sp, interrupted_sp);
        assert_eq!(active.a_regs[7], interrupted_sp);
        assert_eq!(active.a_regs[6], 0xCCCC_0000);
        assert_eq!(active.d_regs[0], 0x1111_1111);
        assert_eq!(active.d_regs[7], 0x7777_7777);
        assert_eq!(active.ccr, 0x04);

        assert_ne!(runner.cursor_task_trampoline, 0);
        assert_eq!(
            runner.cpu.read_reg(Register::PC),
            runner.cursor_task_trampoline
        );
        assert_eq!(runner.cpu.read_reg(Register::A7), interrupted_sp - 4);
        assert_eq!(runner.bus.read_long(interrupted_sp - 4), interrupted_pc);
        assert_eq!(runner.bus.read_word(runner.cursor_task_trampoline), 0x48E7);
        assert_eq!(
            runner.bus.read_word(runner.cursor_task_trampoline + 4),
            0x4EB9
        );
        assert_eq!(
            runner.bus.read_long(runner.cursor_task_trampoline + 6),
            callback_addr
        );
        assert_eq!(
            runner.bus.read_word(runner.cursor_task_trampoline + 10),
            0x4CDF
        );
        assert_eq!(
            runner.bus.read_word(runner.cursor_task_trampoline + 14),
            0x4E75
        );
    }

    #[test]
    fn timer_callback_snapshot_preserves_interrupted_sp() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let interrupted_pc = 0x0002_8BAC;
        let interrupted_sp = 0x007F_FFC0;

        runner.cpu.write_reg(Register::PC, interrupted_pc);
        runner.cpu.write_reg(Register::D0, 0x1111_1111);
        runner.cpu.write_reg(Register::D7, 0x7777_7777);
        runner.cpu.write_reg(Register::A0, 0xAAAA_0000);
        runner.cpu.write_reg(Register::A6, 0xCCCC_0000);
        runner.cpu.write_reg(Register::A7, interrupted_sp);
        runner.cpu.core.set_ccr(0x1F);

        runner.dispatcher.timer_tasks.push(TimerTask {
            task_ptr: 0x0039_38C8,
            tm_addr: 0x0004_1234,
            active: true,
            fire_at_tick: 10,
        });

        runner.fire_timer_tasks(10);

        let active = runner
            .active_interrupt_callback
            .expect("timer callback should have been armed");

        assert!(matches!(
            active.source,
            ActiveInterruptCallbackSource::Timer
        ));
        assert_eq!(active.resume_pc, interrupted_pc);
        assert_eq!(active.resume_sp, interrupted_sp);
        assert_eq!(active.a_regs[7], interrupted_sp);
        assert_eq!(active.a_regs[6], 0xCCCC_0000);
        assert_eq!(active.d_regs[0], 0x1111_1111);
        assert_eq!(active.d_regs[7], 0x7777_7777);
        assert_eq!(active.ccr, 0x1F);

        assert_ne!(runner.timer_trampoline, 0);
        assert_eq!(runner.cpu.read_reg(Register::PC), runner.timer_trampoline);
        assert_eq!(runner.cpu.read_reg(Register::A7), interrupted_sp - 4);
        assert_eq!(runner.bus.read_long(interrupted_sp - 4), interrupted_pc);
    }

    #[test]
    fn sound_doubleback_callback_resume_restores_ccr_before_branch() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let interrupted_pc = 0x0001_0000;
        let interrupted_sp = 0x007F_FFC0;
        let header_ptr = 0x0020_0000;
        let exhausted_buf_ptr = 0x0020_1000;

        // BEQ.s -> MOVEQ #2,D0 path should be taken when Z is preserved.
        runner.bus.write_word(interrupted_pc, 0x6704);
        runner.bus.write_word(interrupted_pc + 2, 0x7001);
        runner.bus.write_word(interrupted_pc + 4, 0x6002);
        runner.bus.write_word(interrupted_pc + 6, 0x7002);
        runner.bus.write_word(interrupted_pc + 8, 0x4E71);

        runner.cpu.write_reg(Register::PC, interrupted_pc);
        runner.cpu.write_reg(Register::A7, interrupted_sp);
        runner.cpu.write_reg(Register::D0, 0);
        runner.cpu.core.set_ccr(0x04);

        runner.bus.write_long(header_ptr + 12, exhausted_buf_ptr);
        runner.bus.write_long(exhausted_buf_ptr + 4, 0x0000_0001);
        runner
            .dispatcher
            .sound_manager
            .pending_callbacks
            .push(PendingDoubleBackCallback {
                callback_addr: 0x0004_1234,
                chan_ptr: 0x0039_38C8,
                header_ptr,
                exhausted_buffer_index: 0,
            });

        runner.fire_sound_doubleback_callbacks();

        let active = runner
            .active_interrupt_callback
            .expect("sound callback should have been armed");
        assert!(matches!(
            active.source,
            ActiveInterruptCallbackSource::SoundDoubleBack
        ));
        assert_eq!(active.resume_pc, interrupted_pc);
        assert_eq!(active.resume_sp, interrupted_sp);

        // Simulate the trampoline returning to interrupted code with CCR clobbered.
        runner.cpu.write_reg(Register::PC, interrupted_pc);
        runner.cpu.write_reg(Register::A7, interrupted_sp);
        runner.cpu.core.set_ccr(0);

        let (steps, running) = runner.run_steps(3, None);

        assert!(running);
        assert_eq!(steps, 3);
        assert_eq!(runner.cpu.read_reg(Register::D0), 2);
        assert!(runner.active_interrupt_callback.is_none());
    }

    #[test]
    fn sound_doubleback_callback_trampoline_stacks_classic_pascal_order() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let interrupted_pc = 0x0001_0000;
        let interrupted_sp = 0x007F_FFC0;
        let callback_addr = runner.bus.alloc(2);
        let header_ptr = 0x0020_0000;
        let chan_ptr = 0x0039_38C8;
        let exhausted_buf_ptr = 0x0020_1000;

        runner.bus.write_word(callback_addr, 0x4E75); // RTS without popping args.
        runner.bus.write_word(interrupted_pc, 0x60FE); // BRA.S *-0
        runner.cpu.write_reg(Register::PC, interrupted_pc);
        runner.cpu.write_reg(Register::A7, interrupted_sp);

        runner.bus.write_long(header_ptr + 12, exhausted_buf_ptr);
        runner.bus.write_long(exhausted_buf_ptr + 4, 0x0000_0001);
        runner
            .dispatcher
            .sound_manager
            .pending_callbacks
            .push(PendingDoubleBackCallback {
                callback_addr,
                chan_ptr,
                header_ptr,
                exhausted_buffer_index: 0,
            });

        runner.fire_sound_doubleback_callbacks();
        let (_steps, running) = runner.run_steps(24, None);

        assert!(running);
        assert!(runner.active_interrupt_callback.is_none());
        let saved_regs_sp = interrupted_sp - 4 - 32;
        assert_eq!(
            runner.bus.read_long(saved_regs_sp - 4),
            chan_ptr,
            "first declared Pascal argument is deeper on the stack"
        );
        assert_eq!(
            runner.bus.read_long(saved_regs_sp - 8),
            exhausted_buf_ptr,
            "last declared Pascal argument is nearest the return address"
        );
    }

    #[test]
    fn mix_audio_loads_ready_double_buffer_without_boundary_silence() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let chan_ptr = 0x0039_38C8;
        let callback_addr = 0x0004_1234;
        let header_ptr = runner.bus.alloc(24);
        let buf0_ptr = runner.bus.alloc(18);
        let buf1_ptr = runner.bus.alloc(18);

        runner.bus.write_word(header_ptr, 1);
        runner.bus.write_word(header_ptr + 2, 8);
        runner.bus.write_long(header_ptr + 8, OUTPUT_RATE << 16);
        runner.bus.write_long(header_ptr + 12, buf0_ptr);
        runner.bus.write_long(header_ptr + 16, buf1_ptr);
        runner.bus.write_long(header_ptr + 20, callback_addr);
        write_double_buffer(&mut runner.bus, buf0_ptr, &[0x90, 0x91]);
        write_double_buffer(&mut runner.bus, buf1_ptr, &[0xA0, 0xA1]);

        let mut chan = SndChannel::new(chan_ptr, false);
        chan.double_buffer = Some(DoubleBufferState {
            header_ptr,
            current_buffer: 0,
            callback_addr,
            chan_ptr,
            sample_rate: OUTPUT_RATE << 16,
            num_channels: 1,
            sample_size: 8,
            last_buffer_seen: false,
            waiting_for_callback: false,
            pending_callback_buffers: [false; 2],
        });
        crate::trap::TrapDispatcher::load_double_buffer_samples(
            &mut runner.bus,
            &mut chan,
            buf0_ptr,
            OUTPUT_RATE << 16,
            1,
            8,
        );
        runner.dispatcher.sound_manager.channels.push(chan);

        runner.mix_audio(3);

        assert_eq!(
            runner.audio_buffer,
            vec![0x90, 0x91, 0xA0],
            "host mixing must continue into the ready paired buffer, not emit boundary silence"
        );
        assert_eq!(
            runner.bus.read_long(buf0_ptr + 4) & 0x01,
            0x01,
            "dbBufferReady stays set until the doubleback callback starts"
        );
        assert_eq!(
            runner.bus.read_long(buf1_ptr + 4) & 0x01,
            0x01,
            "the paired buffer is still marked ready while it is playing"
        );
        assert_eq!(
            runner.dispatcher.sound_manager.pending_callbacks.len(),
            1,
            "exhausting buffer 0 still queues its doubleback refill"
        );
        assert_eq!(
            runner.dispatcher.sound_manager.pending_callbacks[0].exhausted_buffer_index,
            0
        );

        let chan = &runner.dispatcher.sound_manager.channels[0];
        assert!(chan.is_playing(), "buffer 1 should still be playing");
        let db = chan.double_buffer.as_ref().expect("double-buffer active");
        assert_eq!(db.current_buffer, 1);
        assert!(db.waiting_for_callback);
    }

    #[test]
    fn mix_audio_can_queue_other_doubleback_while_callback_is_active() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let chan_ptr = 0x0039_38C8;
        let callback_addr = 0x0004_1234;
        let header_ptr = runner.bus.alloc(24);
        let buf0_ptr = runner.bus.alloc(17);
        let buf1_ptr = runner.bus.alloc(17);
        let interrupted_pc = 0x0001_0000;
        let interrupted_sp = 0x007F_FFC0;

        runner.bus.write_word(interrupted_pc, 0x4E71);
        runner.cpu.write_reg(Register::PC, interrupted_pc);
        runner.cpu.write_reg(Register::A7, interrupted_sp);

        runner.bus.write_word(header_ptr, 1);
        runner.bus.write_word(header_ptr + 2, 8);
        runner.bus.write_long(header_ptr + 8, OUTPUT_RATE << 16);
        runner.bus.write_long(header_ptr + 12, buf0_ptr);
        runner.bus.write_long(header_ptr + 16, buf1_ptr);
        runner.bus.write_long(header_ptr + 20, callback_addr);
        write_double_buffer(&mut runner.bus, buf0_ptr, &[0xA0]);
        runner.bus.write_long(buf1_ptr, 1);
        runner.bus.write_long(buf1_ptr + 4, 0);

        let mut chan = SndChannel::new(chan_ptr, false);
        chan.double_buffer = Some(DoubleBufferState {
            header_ptr,
            current_buffer: 0,
            callback_addr,
            chan_ptr,
            sample_rate: OUTPUT_RATE << 16,
            num_channels: 1,
            sample_size: 8,
            last_buffer_seen: false,
            waiting_for_callback: false,
            pending_callback_buffers: [false; 2],
        });
        crate::trap::TrapDispatcher::load_double_buffer_samples(
            &mut runner.bus,
            &mut chan,
            buf0_ptr,
            OUTPUT_RATE << 16,
            1,
            8,
        );
        runner.dispatcher.sound_manager.channels.push(chan);

        runner.mix_audio(1);
        assert_eq!(runner.dispatcher.sound_manager.pending_callbacks.len(), 1);
        assert!(
            runner.dispatcher.sound_manager.channels[0]
                .double_buffer
                .as_ref()
                .expect("double-buffer active")
                .waiting_for_callback
        );

        runner.fire_sound_doubleback_callbacks();
        assert!(matches!(
            runner
                .active_interrupt_callback
                .expect("doubleback callback should be active")
                .source,
            ActiveInterruptCallbackSource::SoundDoubleBack
        ));
        assert!(
            runner.dispatcher.sound_manager.channels[0]
                .double_buffer
                .as_ref()
                .expect("double-buffer active")
                .waiting_for_callback,
            "callback remains outstanding until guest refills a buffer"
        );

        runner.mix_audio(16);

        assert_eq!(
            runner.dispatcher.sound_manager.pending_callbacks.len(),
            1,
            "the paired unready buffer may queue its own callback while buffer 0 is active"
        );
        assert_eq!(
            runner.dispatcher.sound_manager.pending_callbacks[0].exhausted_buffer_index, 1,
            "buffer 0 must not be duplicated; buffer 1 gets the new callback"
        );
        let db = runner.dispatcher.sound_manager.channels[0]
            .double_buffer
            .as_ref()
            .expect("double-buffer active");
        assert!(db.waiting_for_callback);
        assert_eq!(db.pending_callback_buffers, [true, true]);
    }

    #[test]
    fn mix_audio_does_not_load_ready_double_buffer_while_callback_is_active() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let chan_ptr = 0x0039_38C8;
        let callback_addr = 0x0004_1234;
        let header_ptr = runner.bus.alloc(24);
        let buf0_ptr = runner.bus.alloc(17);

        runner.bus.write_word(header_ptr, 1);
        runner.bus.write_word(header_ptr + 2, 8);
        runner.bus.write_long(header_ptr + 8, OUTPUT_RATE << 16);
        runner.bus.write_long(header_ptr + 12, buf0_ptr);
        runner.bus.write_long(header_ptr + 20, callback_addr);
        write_double_buffer(&mut runner.bus, buf0_ptr, &[0xA0]);

        let mut chan = SndChannel::new(chan_ptr, false);
        chan.double_buffer = Some(DoubleBufferState {
            header_ptr,
            current_buffer: 0,
            callback_addr,
            chan_ptr,
            sample_rate: OUTPUT_RATE << 16,
            num_channels: 1,
            sample_size: 8,
            last_buffer_seen: false,
            waiting_for_callback: true,
            pending_callback_buffers: [true, false],
        });
        runner.dispatcher.sound_manager.channels.push(chan);
        runner.active_interrupt_callback = Some(ActiveInterruptCallback {
            source: ActiveInterruptCallbackSource::SoundDoubleBack,
            resume_pc: 0x0001_0000,
            resume_sp: 0x007F_FFC0,
            d_regs: [0; 8],
            a_regs: [0; 8],
            ccr: 0,
            restore_port: None,
        });

        runner.mix_audio(1);

        assert_eq!(
            runner.bus.read_long(buf0_ptr + 4) & 0x01,
            0x01,
            "ready buffer must not be consumed before the callback returns"
        );
        assert!(
            !runner.dispatcher.sound_manager.channels[0].is_playing(),
            "callback-active buffer load should be deferred"
        );
        assert_eq!(
            runner.audio_buffer,
            vec![0x80],
            "the host stream stays alive with silence while waiting"
        );

        runner.active_interrupt_callback = None;
        runner.try_load_pending_double_buffers();

        assert_eq!(
            runner.bus.read_long(buf0_ptr + 4) & 0x01,
            0x01,
            "returned callback buffer stays marked ready while playback owns it"
        );
        assert!(
            runner.dispatcher.sound_manager.channels[0].is_playing(),
            "returned callback makes the refilled buffer available to the mixer"
        );
        let db = runner.dispatcher.sound_manager.channels[0]
            .double_buffer
            .as_ref()
            .expect("double-buffer active");
        assert_eq!(db.pending_callback_buffers, [false, false]);

        runner.mix_audio(1);
        assert_eq!(runner.audio_buffer, vec![0x80, 0xA0]);
    }

    #[test]
    fn try_load_pending_double_buffers_recovers_ready_alternate_after_underrun() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let chan_ptr = 0x0039_38C8;
        let callback_addr = 0x0004_1234;
        let header_ptr = runner.bus.alloc(24);
        let buf0_ptr = runner.bus.alloc(18);
        let buf1_ptr = runner.bus.alloc(18);

        runner.bus.write_word(header_ptr, 1);
        runner.bus.write_word(header_ptr + 2, 8);
        runner.bus.write_long(header_ptr + 8, OUTPUT_RATE << 16);
        runner.bus.write_long(header_ptr + 12, buf0_ptr);
        runner.bus.write_long(header_ptr + 16, buf1_ptr);
        runner.bus.write_long(header_ptr + 20, callback_addr);
        write_double_buffer(&mut runner.bus, buf0_ptr, &[0xA0, 0xA1]);
        runner.bus.write_long(buf1_ptr, 2);
        runner.bus.write_long(buf1_ptr + 4, 0);

        let mut chan = SndChannel::new(chan_ptr, false);
        chan.double_buffer = Some(DoubleBufferState {
            header_ptr,
            current_buffer: 1,
            callback_addr,
            chan_ptr,
            sample_rate: OUTPUT_RATE << 16,
            num_channels: 1,
            sample_size: 8,
            last_buffer_seen: false,
            waiting_for_callback: false,
            pending_callback_buffers: [false; 2],
        });
        runner.dispatcher.sound_manager.channels.push(chan);

        runner.try_load_pending_double_buffers();

        let chan = &runner.dispatcher.sound_manager.channels[0];
        assert!(chan.is_playing(), "ready alternate buffer should load");
        let db = chan.double_buffer.as_ref().expect("double-buffer active");
        assert_eq!(db.current_buffer, 0);
        assert!(
            !db.waiting_for_callback,
            "loading a ready buffer completes the outstanding refill wait"
        );
        assert_eq!(
            runner.bus.read_long(buf0_ptr + 4) & 0x01,
            0x01,
            "loading a ready alternate must not clear dbBufferReady before playback exhausts"
        );
    }

    #[test]
    fn try_load_pending_double_buffers_does_not_replay_callback_pending_slot() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let chan_ptr = 0x0039_38C8;
        let callback_addr = 0x0004_1234;
        let header_ptr = runner.bus.alloc(24);
        let buf0_ptr = runner.bus.alloc(17);
        let buf1_ptr = runner.bus.alloc(17);

        runner.bus.write_word(header_ptr, 1);
        runner.bus.write_word(header_ptr + 2, 8);
        runner.bus.write_long(header_ptr + 8, OUTPUT_RATE << 16);
        runner.bus.write_long(header_ptr + 12, buf0_ptr);
        runner.bus.write_long(header_ptr + 16, buf1_ptr);
        runner.bus.write_long(header_ptr + 20, callback_addr);
        write_double_buffer(&mut runner.bus, buf0_ptr, &[0xA0]);
        runner.bus.write_long(buf1_ptr, 1);
        runner.bus.write_long(buf1_ptr + 4, 0);

        let mut chan = SndChannel::new(chan_ptr, false);
        chan.double_buffer = Some(DoubleBufferState {
            header_ptr,
            current_buffer: 0,
            callback_addr,
            chan_ptr,
            sample_rate: OUTPUT_RATE << 16,
            num_channels: 1,
            sample_size: 8,
            last_buffer_seen: false,
            waiting_for_callback: true,
            pending_callback_buffers: [true, false],
        });
        runner.dispatcher.sound_manager.channels.push(chan);
        runner
            .dispatcher
            .sound_manager
            .pending_callbacks
            .push(PendingDoubleBackCallback {
                callback_addr,
                chan_ptr,
                header_ptr,
                exhausted_buffer_index: 0,
            });

        runner.try_load_pending_double_buffers();

        assert!(
            !runner.dispatcher.sound_manager.channels[0].is_playing(),
            "an exhausted slot must not replay just because dbBufferReady remains set"
        );
        assert_eq!(
            runner.bus.read_long(buf0_ptr + 4) & 0x01,
            0x01,
            "the flag remains ready until fire_sound_doubleback_callbacks clears it"
        );
    }

    #[test]
    fn sound_command_callback_trampoline_passes_sndcommand_pointer() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let interrupted_pc = 0x0001_0000;
        let interrupted_sp = 0x007F_FFC0;
        runner.cpu.write_reg(Register::PC, interrupted_pc);
        runner.cpu.write_reg(Register::A7, interrupted_sp);

        runner
            .dispatcher
            .sound_manager
            .pending_sound_callbacks
            .push(crate::sound::PendingSoundCallback::Command {
                callback_addr: 0x0004_5678,
                chan_ptr: 0x0039_38C8,
                cmd: crate::sound::SndCommand {
                    cmd: crate::sound::cmd::CALLBACK,
                    param1: 0x1234,
                    param2: 0x0001_43FC,
                },
            });

        runner.fire_sound_callbacks();

        let active = runner
            .active_interrupt_callback
            .expect("sound callback should have been armed");
        assert!(matches!(
            active.source,
            ActiveInterruptCallbackSource::SoundCallback
        ));
        assert_eq!(active.resume_pc, interrupted_pc);
        assert_eq!(active.resume_sp, interrupted_sp);

        let tramp = runner.sound_callback_trampoline;
        let cmd_ptr = tramp + 34;
        let saved_regs_sp = interrupted_sp - 4 - 32;
        assert_eq!(runner.bus.read_long(tramp + 6), 0x0039_38C8);
        assert_eq!(runner.bus.read_long(tramp + 12), cmd_ptr);
        assert_eq!(runner.bus.read_long(tramp + 18), 0x0004_5678);
        assert_eq!(runner.bus.read_long(tramp + 24), saved_regs_sp);
        assert_eq!(runner.bus.read_word(cmd_ptr), crate::sound::cmd::CALLBACK);
        assert_eq!(runner.bus.read_word(cmd_ptr + 2), 0x1234);
        assert_eq!(runner.bus.read_long(cmd_ptr + 4), 0x0001_43FC);
    }

    #[test]
    fn sound_command_callback_trampoline_tolerates_one_long_pascal_cleanup() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let interrupted_pc = 0x0001_0000;
        let interrupted_sp = 0x007F_FFC0;
        let callback_addr = runner.bus.alloc(4);

        // Some Pascal callback epilogues pop one long argument by copying the
        // return address over it, then RTS.
        runner.bus.write_word(callback_addr, 0x2E9F); // MOVE.L (SP)+,(SP)
        runner.bus.write_word(callback_addr + 2, 0x4E75); // RTS
        runner.bus.write_word(interrupted_pc, 0x4E71); // NOP
        runner.cpu.write_reg(Register::PC, interrupted_pc);
        runner.cpu.write_reg(Register::A7, interrupted_sp);

        runner
            .dispatcher
            .sound_manager
            .pending_sound_callbacks
            .push(crate::sound::PendingSoundCallback::Command {
                callback_addr,
                chan_ptr: 0x0039_38C8,
                cmd: crate::sound::SndCommand {
                    cmd: crate::sound::cmd::CALLBACK,
                    param1: 0x1234,
                    param2: 0x0001_43FC,
                },
            });

        runner.fire_sound_callbacks();
        let (steps, running) = runner.run_steps(10, None);

        assert!(running, "callback trampoline should resume foreground code");
        assert_eq!(steps, 10);
        assert!(runner.active_interrupt_callback.is_none());
        assert_eq!(runner.cpu.read_reg(Register::PC), interrupted_pc + 2);
        assert_eq!(runner.cpu.read_reg(Register::A7), interrupted_sp);
        assert!(!runner.is_halted());
    }

    #[test]
    fn sound_file_completion_callback_trampoline_tolerates_c_style_cleanup() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let interrupted_pc = 0x0001_0000;
        let interrupted_sp = 0x007F_FFC0;
        let callback_addr = runner.bus.alloc(2);

        runner.bus.write_word(callback_addr, 0x4E75); // RTS without popping chan.
        runner.bus.write_word(interrupted_pc, 0x4E71); // NOP
        runner.cpu.write_reg(Register::PC, interrupted_pc);
        runner.cpu.write_reg(Register::A7, interrupted_sp);

        runner
            .dispatcher
            .sound_manager
            .pending_sound_callbacks
            .push(crate::sound::PendingSoundCallback::FileCompletion {
                callback_addr,
                chan_ptr: 0x0039_38C8,
            });

        runner.fire_sound_callbacks();
        let (steps, running) = runner.run_steps(10, None);

        assert!(
            running,
            "file completion trampoline should resume foreground code"
        );
        assert_eq!(steps, 10);
        assert!(runner.active_interrupt_callback.is_none());
        assert_eq!(runner.cpu.read_reg(Register::A7), interrupted_sp);
        assert!(!runner.is_halted());
    }

    #[test]
    fn sound_doubleback_callback_trampoline_tolerates_c_style_cleanup() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let interrupted_pc = 0x0001_0000;
        let interrupted_sp = 0x007F_FFC0;
        let callback_addr = runner.bus.alloc(2);
        let header_ptr = 0x0020_0000;
        let exhausted_buf_ptr = 0x0020_1000;

        runner.bus.write_word(callback_addr, 0x4E75); // RTS without popping args.
        runner.bus.write_word(interrupted_pc, 0x4E71); // NOP
        runner.cpu.write_reg(Register::PC, interrupted_pc);
        runner.cpu.write_reg(Register::A7, interrupted_sp);

        runner.bus.write_long(header_ptr + 12, exhausted_buf_ptr);
        runner.bus.write_long(exhausted_buf_ptr + 4, 0x0000_0001);
        runner
            .dispatcher
            .sound_manager
            .pending_callbacks
            .push(PendingDoubleBackCallback {
                callback_addr,
                chan_ptr: 0x0039_38C8,
                header_ptr,
                exhausted_buffer_index: 0,
            });

        runner.fire_sound_doubleback_callbacks();
        let (steps, running) = runner.run_steps(12, None);

        assert!(
            running,
            "doubleback trampoline should resume foreground code"
        );
        assert_eq!(steps, 12);
        assert!(runner.active_interrupt_callback.is_none());
        assert_eq!(runner.cpu.read_reg(Register::A7), interrupted_sp);
        assert!(!runner.is_halted());
    }

    #[test]
    fn run_pending_sound_work_does_not_advance_ticks_or_foreground_code() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let interrupted_pc = 0x0001_0000;
        let interrupted_sp = 0x007F_FFC0;
        let callback_addr = runner.bus.alloc(2);

        runner.bus.write_word(callback_addr, 0x4E75); // RTS without popping args.
        runner.bus.write_word(interrupted_pc, 0x4E71); // foreground NOP
        runner.cpu.write_reg(Register::PC, interrupted_pc);
        runner.cpu.write_reg(Register::A7, interrupted_sp);
        runner.bus.write_long(0x016A, 41);
        runner.dispatcher.tick_count = 41;
        runner.set_instructions_per_tick(1);
        runner.tick_budget = 0;

        runner
            .dispatcher
            .sound_manager
            .pending_sound_callbacks
            .push(PendingSoundCallback::Command {
                callback_addr,
                chan_ptr: 0x0039_38C8,
                cmd: SndCommand {
                    cmd: crate::sound::cmd::CALLBACK,
                    param1: 0,
                    param2: 0,
                },
            });

        let (steps, running) = runner.run_pending_sound_work(32);

        assert!(running);
        assert!(steps > 0, "sound callback trampoline should execute");
        assert_eq!(
            runner.guest_tick(),
            41,
            "callback-only slices must not advance application-visible ticks"
        );
        assert_eq!(
            runner.cpu.read_reg(Register::PC),
            interrupted_pc,
            "sound callback service must stop before resumed foreground code runs"
        );
        assert_eq!(runner.cpu.read_reg(Register::A7), interrupted_sp);
        assert!(runner.active_interrupt_callback.is_none());
        assert!(!runner.has_pending_sound_work());
    }

    #[test]
    fn run_steps_paces_pending_sound_doublebacks_to_one_per_slice() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let interrupted_pc = 0x0001_0000;
        let interrupted_sp = 0x007F_FFC0;
        let callback_addr = runner.bus.alloc(2);
        let header_ptr = runner.bus.alloc(24);
        let buf0_ptr = runner.bus.alloc(16);
        let buf1_ptr = runner.bus.alloc(16);

        runner.bus.write_word(callback_addr, 0x4E75); // RTS without popping args.
        for offset in (0..512).step_by(2) {
            runner.bus.write_word(interrupted_pc + offset, 0x4E71); // NOP
        }
        runner.cpu.write_reg(Register::PC, interrupted_pc);
        runner.cpu.write_reg(Register::A7, interrupted_sp);

        runner.bus.write_long(header_ptr + 12, buf0_ptr);
        runner.bus.write_long(header_ptr + 16, buf1_ptr);
        runner.bus.write_long(buf0_ptr + 4, 0x0000_0001);
        runner.bus.write_long(buf1_ptr + 4, 0x0000_0001);
        runner
            .dispatcher
            .sound_manager
            .pending_callbacks
            .push(PendingDoubleBackCallback {
                callback_addr,
                chan_ptr: 0x0039_38C8,
                header_ptr,
                exhausted_buffer_index: 0,
            });
        runner
            .dispatcher
            .sound_manager
            .pending_callbacks
            .push(PendingDoubleBackCallback {
                callback_addr,
                chan_ptr: 0x0039_38C8,
                header_ptr,
                exhausted_buffer_index: 1,
            });

        let (_steps, running) = runner.run_steps(96, None);

        assert!(running);
        assert!(runner.active_interrupt_callback.is_none());
        assert_eq!(
            runner.dispatcher.sound_manager.pending_callbacks.len(),
            1,
            "one CPU slice must not drain back-to-back doubleback interrupts"
        );
        assert_eq!(
            runner.dispatcher.sound_manager.pending_callbacks[0].exhausted_buffer_index,
            1
        );

        let (_steps, running) = runner.run_steps(96, None);

        assert!(running);
        assert!(runner.active_interrupt_callback.is_none());
        assert!(
            runner.dispatcher.sound_manager.pending_callbacks.is_empty(),
            "the next CPU slice may dispatch the next pending doubleback"
        );
    }

    #[test]
    fn vbl_callback_arms_interrupt_with_task_ptr_in_a0() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let interrupted_pc = 0x0002_0000;
        let interrupted_sp = 0x007F_FFC0;
        let task_ptr = 0x0020_2000;

        runner.cpu.write_reg(Register::PC, interrupted_pc);
        runner.cpu.write_reg(Register::A7, interrupted_sp);
        runner.cpu.write_reg(Register::A0, 0xAAAA_0000);
        runner.cpu.core.set_ccr(0x04);

        runner.bus.write_word(task_ptr + 4, 1); // qType = vType
        runner.bus.write_long(task_ptr + 6, 0x0004_1234); // vblAddr
        runner.bus.write_word(task_ptr + 10, 1); // vblCount
        runner.bus.write_word(task_ptr + 12, 0); // vblPhase
        runner.dispatcher.vbl_tasks.push(VblTask {
            task_ptr,
            slot: Some(9),
        });

        runner.fire_vbl_tasks();

        let active = runner
            .active_interrupt_callback
            .expect("vbl callback should have been armed");
        assert!(matches!(active.source, ActiveInterruptCallbackSource::Vbl));
        assert_eq!(active.resume_pc, interrupted_pc);
        assert_eq!(active.resume_sp, interrupted_sp);
        assert_eq!(runner.bus.read_word(task_ptr + 10), 0);

        assert_ne!(runner.vbl_trampoline, 0);
        assert_eq!(runner.cpu.read_reg(Register::PC), runner.vbl_trampoline);
        assert_eq!(runner.cpu.read_reg(Register::A7), interrupted_sp - 4);
        assert_eq!(runner.bus.read_long(interrupted_sp - 4), interrupted_pc);
        assert_eq!(runner.bus.read_word(runner.vbl_trampoline + 4), 0x207C);
        assert_eq!(runner.bus.read_long(runner.vbl_trampoline + 6), task_ptr);
        assert_eq!(
            runner.bus.read_long(runner.vbl_trampoline + 12),
            0x0004_1234
        );
    }

    #[test]
    fn custom_instructions_per_tick_controls_tick_cadence() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let program_start = 0x0001_0000;
        let program_words = 14;

        for offset in (0..program_words).step_by(2) {
            runner.bus.write_word(program_start + offset, 0x4E71);
        }

        runner.cpu.write_reg(Register::PC, program_start);
        runner.cpu.write_reg(Register::A7, 0x007F_FFC0);
        runner.bus.write_long(0x016A, 0);
        runner.set_instructions_per_tick(3);

        let (steps, running) = runner.run_steps(7, None);

        assert!(running);
        assert_eq!(steps, 7);
        assert_eq!(runner.bus.read_long(0x016A), 2);
    }

    #[test]
    fn non_idle_hle_trap_cost_advances_tick_budget() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let base = 0x0001_0000u32;
        let sp = 0x0010_0000u32;
        let rect = 0x0020_0000u32;

        runner.bus.write_word(base, 0xA8A8); // _OffsetRect
        runner.cpu.write_reg(Register::PC, base);
        runner.cpu.write_reg(Register::A7, sp);
        runner.bus.write_word(sp, 1); // dv
        runner.bus.write_word(sp + 2, 2); // dh
        runner.bus.write_long(sp + 4, rect);
        runner.bus.write_word(rect, 10);
        runner.bus.write_word(rect + 2, 20);
        runner.bus.write_word(rect + 4, 30);
        runner.bus.write_word(rect + 6, 40);
        runner.bus.write_long(0x016A, 0);
        runner.dispatcher.tick_count = 0;
        runner.set_instructions_per_tick(5);

        let (steps, running) = runner.run_steps(1, None);

        assert!(running);
        assert_eq!(steps, 1);
        assert_eq!(
            runner.guest_tick(),
            1,
            "non-idle HLE traps should consume tick budget beyond the base instruction"
        );
        assert_eq!(runner.bus.read_word(rect), 11);
        assert_eq!(runner.bus.read_word(rect + 2), 22);
    }

    #[test]
    fn idle_hle_traps_do_not_apply_extra_tick_cost() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let base = 0x0001_0000u32;

        runner.bus.write_word(base, 0xA975); // _TickCount
        runner.cpu.write_reg(Register::PC, base);
        runner.cpu.write_reg(Register::A7, 0x0010_0000);
        runner.bus.write_long(0x016A, 42);
        runner.dispatcher.tick_count = 42;
        runner.set_instructions_per_tick(5);

        let (steps, running) = runner.run_steps(1, None);

        assert!(running);
        assert_eq!(steps, 1);
        assert_eq!(
            runner.guest_tick(),
            42,
            "polling traps should not add synthetic HLE manager cost"
        );
        assert_eq!(runner.tick_budget, 4);
    }

    #[test]
    fn hle_trap_cost_stops_gui_slice_at_tick_cap() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let base = 0x0001_0000u32;
        let sp = 0x0010_0000u32;
        let rect = 0x0020_0000u32;

        runner.bus.write_word(base, 0xA8A8); // _OffsetRect
        runner.bus.write_word(base + 2, 0x4E71); // NOP that must wait for the next GUI slice
        runner.cpu.write_reg(Register::PC, base);
        runner.cpu.write_reg(Register::A7, sp);
        runner.bus.write_word(sp, 1);
        runner.bus.write_word(sp + 2, 2);
        runner.bus.write_long(sp + 4, rect);
        runner.bus.write_word(rect, 10);
        runner.bus.write_word(rect + 2, 20);
        runner.bus.write_word(rect + 4, 30);
        runner.bus.write_word(rect + 6, 40);
        runner.bus.write_long(0x016A, 0);
        runner.dispatcher.tick_count = 0;
        runner.set_instructions_per_tick(5);

        let (steps, running) = runner.run_gui_slice_with_audio(8, 1, 0);

        assert!(running);
        assert_eq!(steps, 1);
        assert_eq!(runner.guest_tick(), 1);
        assert_eq!(
            runner.cpu.read_reg(Register::PC),
            base + 2,
            "the next guest instruction should be deferred once HLE cost reaches the GUI tick cap"
        );
    }

    /// Regression gate for the `tick_count`-sync invariant.
    /// `advance_guest_tick` keeps bus `$016A` and
    /// `dispatcher.tick_count` lockstep; the unfreeze path also
    /// updates both. Any future change that writes `$016A` without
    /// updating `dispatcher.tick_count` (or vice versa) will desync
    /// double-click detection + the TickCount handler + diagnostic
    /// tick printouts.
    #[test]
    fn dispatcher_tick_count_stays_in_sync_with_bus() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let program_start = 0x0001_0000;
        let program_words = 20;

        // NOPs keep the CPU stepping without producing traps that
        // could interfere with tick accounting.
        for offset in (0..program_words).step_by(2) {
            runner.bus.write_word(program_start + offset, 0x4E71);
        }

        runner.cpu.write_reg(Register::PC, program_start);
        runner.cpu.write_reg(Register::A7, 0x007F_FFC0);
        runner.bus.write_long(0x016A, 0);
        // Set both sides of the invariant to the same initial value.
        runner.dispatcher.tick_count = 0;
        runner.set_instructions_per_tick(3);

        // Step a few times; ticks should advance roughly every 3
        // instructions. After each run_steps, bus and dispatcher
        // must agree.
        for _ in 0..3 {
            let (_, running) = runner.run_steps(3, None);
            assert!(running);
            assert_eq!(
                runner.bus.read_long(0x016A),
                runner.dispatcher.tick_count,
                "bus $016A ({}) diverged from dispatcher.tick_count ({})",
                runner.bus.read_long(0x016A),
                runner.dispatcher.tick_count,
            );
        }
    }

    /// Regression gate for the TickCount spin fast-forward template A
    /// (classic MOVE+SUBQ+CMP+BHI with register target). Builds a
    /// synthetic spin body in RAM, calls the fast-forward directly,
    /// asserts the exit state matches what the guest loop's final
    /// fall-through iteration would produce.
    #[test]
    fn spin_fastfwd_template_a_advances_ticks_and_skips_loop() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let base = 0x0001_0000u32;
        // Synthesised spin body:
        //   $base+0: SUBQ.W #4, A7   (0x594F)
        //   $base+2: _TickCount      (0xA975) ← trap fires before call site
        //   $base+4: MOVE.L (A7)+, D0 (0x201F)
        //   $base+6: SUBQ.L #1, D0   (0x5380)
        //   $base+8: CMP.L D0, D3    (0xB680)
        //   $base+10: BHI.S *-12     (0x62F4)
        //   $base+12: sentinel       (0x4E71 NOP)
        runner.bus.write_word(base, 0x594F);
        runner.bus.write_word(base + 2, 0xA975);
        runner.bus.write_word(base + 4, 0x201F);
        runner.bus.write_word(base + 6, 0x5380);
        runner.bus.write_word(base + 8, 0xB680);
        runner.bus.write_word(base + 10, 0x62F4);
        runner.bus.write_word(base + 12, 0x4E71);

        // Initial tick 100, target D3=500 so target_tick = 501.
        runner.bus.write_long(0x016A, 100);
        runner.dispatcher.tick_count = 100;
        runner.cpu.write_reg(Register::D3, 500);
        runner.cpu.write_reg(Register::A7, 0x0010_0000);

        let pc_after_trap = base + 4;
        let mut count = 0usize;
        let hit_cap = runner.try_tickcount_spin_fastfwd(pc_after_trap, None, &mut count);

        assert!(!hit_cap, "no tick_cap was set, cap should not trip");
        assert_eq!(runner.dispatcher.tick_count, 501, "advanced to D3+imm");
        assert_eq!(runner.bus.read_long(0x016A), 501, "bus $016A in sync");
        // After fall-through: Dn = final_tick - imm = 501 - 1 = 500 (= D3).
        assert_eq!(runner.cpu.read_reg(Register::D0), 500);
        // A7 += 4 (the popped tick slot).
        assert_eq!(runner.cpu.read_reg(Register::A7), 0x0010_0004);
        // PC past BHI (base + 12).
        assert_eq!(runner.cpu.read_reg(Register::PC), base + 12);
        // 4 synthesised instructions accounted for.
        assert_eq!(count, 4);
    }

    /// Rejection case — `MOVE.L (A7)+, D1` followed by `SUBQ.L #imm,
    /// D0` (different registers) must NOT match. Ensures the
    /// register-consistency check in `try_spin_template_a` guards
    /// against false positives where an unrelated MOVE happens to
    /// precede a SUBQ+CMP+BHI.
    #[test]
    fn spin_fastfwd_rejects_register_mismatch() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let base = 0x0001_0000u32;
        // Same as template A but MOVE.L (A7)+ targets D1, while
        // SUBQ/CMP operate on D0. Template detector must reject.
        runner.bus.write_word(base, 0x594F);
        runner.bus.write_word(base + 2, 0xA975);
        runner.bus.write_word(base + 4, 0x221F); // MOVE.L (A7)+, D1 (NOT D0)
        runner.bus.write_word(base + 6, 0x5380); // SUBQ.L #1, D0
        runner.bus.write_word(base + 8, 0xB680); // CMP.L D0, D3
        runner.bus.write_word(base + 10, 0x62F4); // BHI.S

        runner.bus.write_long(0x016A, 100);
        runner.dispatcher.tick_count = 100;
        runner.cpu.write_reg(Register::D3, 500);
        runner.cpu.write_reg(Register::A7, 0x0010_0000);
        let pc_after_trap = base + 4;
        let mut count = 0usize;
        runner.try_tickcount_spin_fastfwd(pc_after_trap, None, &mut count);

        // No change: template rejected, tick_count stays at 100.
        assert_eq!(runner.dispatcher.tick_count, 100);
        // PC stays where it was (we passed pc_after_trap but the
        // fast-forward must have returned without mutating PC).
        assert_eq!(runner.cpu.read_reg(Register::PC), 0);
        assert_eq!(count, 0);
    }

    /// Regression gate for spin fast-forward template B (memory target,
    /// BLS variant). Sets up the post-trap state with A6 pointing at
    /// a stack frame and a target tick stored at `-4(A6)`; asserts the
    /// matcher advances to the memory target and synthesises the
    /// correct exit.
    #[test]
    fn spin_fastfwd_template_b_memory_target_variant() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let base = 0x0001_0000u32;
        // $base+0: SUBQ.W #4, A7   (0x594F) — pre-trap SP adjust
        // $base+2: _TickCount      (0xA975) — trap
        // $base+4: MOVE.L (A7)+, D0 (0x201F)
        // $base+6: CMP.L (-4, A6), D0 — opcode 0xB0AE, d16=0xFFFC
        //          (1011 000 010 101 110 = 0xB0AE; next word 0xFFFC = -4)
        // $base+10: BLS.S *-12    (0x63F2) — target = $base+12 + (-14)
        //           = $base - 2. So target should be BEFORE $base.
        // $base+12: sentinel NOP  (0x4E71)
        runner.bus.write_word(base, 0x594F);
        runner.bus.write_word(base + 2, 0xA975);
        runner.bus.write_word(base + 4, 0x201F);
        runner.bus.write_word(base + 6, 0xB0AE);
        runner.bus.write_word(base + 8, 0xFFFC);
        // Branch target must be < pc_after_trap. pc_after_trap = base+4.
        // Simplest: target = base + 2 → disp = target - (base+12) = -10
        // (since branch_src = base+10, branch_src+2 = base+12).
        // disp8 = -10 = 0xF6.
        runner.bus.write_word(base + 10, 0x63F6);
        runner.bus.write_word(base + 12, 0x4E71);

        // Memory target at -4(A6). A6 points at mid-stack; -4(A6)
        // holds the target tick.
        let a6 = 0x0010_1000u32;
        runner.bus.write_long(a6.wrapping_sub(4), 400);

        // Initial state
        runner.bus.write_long(0x016A, 100);
        runner.dispatcher.tick_count = 100;
        runner.cpu.write_reg(Register::A6, a6);
        runner.cpu.write_reg(Register::A7, 0x0010_0000);

        let pc_after_trap = base + 4;
        let mut count = 0usize;
        let hit_cap = runner.try_tickcount_spin_fastfwd(pc_after_trap, None, &mut count);

        assert!(!hit_cap);
        // target_tick = mem_target + 1 = 400 + 1 = 401.
        assert_eq!(runner.dispatcher.tick_count, 401);
        assert_eq!(runner.bus.read_long(0x016A), 401);
        // Template B exit: D0 = final_tick (no SUBQ).
        assert_eq!(runner.cpu.read_reg(Register::D0), 401);
        assert_eq!(runner.cpu.read_reg(Register::A7), 0x0010_0004);
        assert_eq!(runner.cpu.read_reg(Register::PC), base + 12);
        // Template B synthesises 3 instructions (MOVE, CMP, BLS).
        assert_eq!(count, 3);
    }

    /// Regression gate for the TickCount spin fast-forward absolute
    /// LongInt target variant:
    ///
    ///   SUBQ.W #4,A7
    ///   _TickCount
    ///   MOVE.L (A7)+,Dn
    ///   CMP.L  (xxx).L,Dn
    ///   BCS.S  back-to-SUBQ
    ///
    /// This is the same wait-until-Ticks-reaches-memory-target shape as
    /// template B, but older MPW/Think-era code may address the target
    /// through an absolute long global instead of an A-register frame.
    #[test]
    fn spin_fastfwd_template_c_absolute_long_target_variant() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let base = 0x0001_0000u32;
        let target_addr = 0x0002_FE44u32;

        // $base+0:  SUBQ.W #4, A7      (0x594F)
        // $base+2:  _TickCount         (0xA975)
        // $base+4:  MOVE.L (A7)+, D0   (0x201F)
        // $base+6:  CMP.L (xxx).L, D0  (0xB0B9 + absolute long)
        // $base+12: BCS.S $base        (0x65F2; base+14-14)
        // $base+14: sentinel NOP
        runner.bus.write_word(base, 0x594F);
        runner.bus.write_word(base + 2, 0xA975);
        runner.bus.write_word(base + 4, 0x201F);
        runner.bus.write_word(base + 6, 0xB0B9);
        runner.bus.write_long(base + 8, target_addr);
        runner.bus.write_word(base + 12, 0x65F2);
        runner.bus.write_word(base + 14, 0x4E71);

        runner.bus.write_long(target_addr, 400);
        runner.bus.write_long(0x016A, 100);
        runner.dispatcher.tick_count = 100;
        runner.cpu.write_reg(Register::A7, 0x0010_0000);

        let pc_after_trap = base + 4;
        let mut count = 0usize;
        let hit_cap = runner.try_tickcount_spin_fastfwd(pc_after_trap, None, &mut count);

        assert!(!hit_cap);
        assert_eq!(runner.dispatcher.tick_count, 400);
        assert_eq!(runner.bus.read_long(0x016A), 400);
        assert_eq!(runner.cpu.read_reg(Register::D0), 400);
        assert_eq!(runner.cpu.read_reg(Register::A7), 0x0010_0004);
        assert_eq!(runner.cpu.read_reg(Register::PC), base + 14);
        assert_eq!(count, 3);
    }

    #[test]
    fn spin_fastfwd_leaves_interrupt_callback_state_unsynthesized() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let base = 0x0001_0000u32;
        let target_addr = 0x0002_FE44u32;
        let task_ptr = 0x0020_2000u32;
        let sp = 0x0010_0000u32;

        // Same absolute-long TickCount spin as template C. The VBL task
        // becomes due during the accelerated tick advance, before the
        // loop reaches its target tick.
        runner.bus.write_word(base, 0x594F);
        runner.bus.write_word(base + 2, 0xA975);
        runner.bus.write_word(base + 4, 0x201F);
        runner.bus.write_word(base + 6, 0xB0B9);
        runner.bus.write_long(base + 8, target_addr);
        runner.bus.write_word(base + 12, 0x65F2);
        runner.bus.write_word(base + 14, 0x4E71);

        runner.bus.write_long(target_addr, 400);
        runner.bus.write_long(0x016A, 100);
        runner.dispatcher.tick_count = 100;
        runner.cpu.write_reg(Register::PC, base + 4);
        runner.cpu.write_reg(Register::A7, sp);
        runner.cpu.write_reg(Register::D0, 0xDEAD_BEEF);
        runner.bus.write_long(sp, 100);

        runner.bus.write_word(task_ptr + 4, 1);
        runner.bus.write_long(task_ptr + 6, 0x0004_1234);
        runner.bus.write_word(task_ptr + 10, 1);
        runner.bus.write_word(task_ptr + 12, 0);
        runner.dispatcher.vbl_tasks.push(VblTask {
            task_ptr,
            slot: None,
        });

        let mut count = 0usize;
        let hit_cap = runner.try_tickcount_spin_fastfwd(base + 4, None, &mut count);

        assert!(!hit_cap);
        assert_eq!(runner.dispatcher.tick_count, 101);
        assert_eq!(runner.bus.read_long(0x016A), 101);
        assert_eq!(count, 0);
        assert_eq!(runner.cpu.read_reg(Register::D0), 0xDEAD_BEEF);
        assert_eq!(runner.cpu.read_reg(Register::PC), runner.vbl_trampoline);
        assert_eq!(runner.cpu.read_reg(Register::A7), sp - 4);
        assert_eq!(runner.bus.read_long(sp - 4), base + 4);

        let active = runner
            .active_interrupt_callback
            .expect("VBL callback should remain active for normal resume handling");
        assert!(matches!(active.source, ActiveInterruptCallbackSource::Vbl));
        assert_eq!(active.resume_pc, base + 4);
        assert_eq!(active.resume_sp, sp);
    }

    /// Regression gates for the tri-state spin-fastfwd gate. Tests the
    /// pure decision function so `OnceLock`-cached env vars don't
    /// interfere across tests.
    #[test]
    fn spin_fastfwd_gate_default_headless_on_gui_off() {
        // Neither force_on nor force_off → default behaviour:
        //   headless (yield_for_ui = false) → enabled
        //   GUI     (yield_for_ui = true)  → disabled
        assert!(spin_wait_fastfwd_gate(false, false, false));
        assert!(!spin_wait_fastfwd_gate(false, false, true));
    }

    #[test]
    fn spin_fastfwd_gate_force_off_wins() {
        // force_off must dominate force_on and override the default in
        // either mode.
        assert!(!spin_wait_fastfwd_gate(false, true, false));
        assert!(!spin_wait_fastfwd_gate(false, true, true));
        assert!(!spin_wait_fastfwd_gate(true, true, false));
        assert!(!spin_wait_fastfwd_gate(true, true, true));
    }

    #[test]
    fn spin_fastfwd_gate_force_on_overrides_gui_default() {
        // force_on (without force_off) flips GUI from off → on.
        assert!(spin_wait_fastfwd_gate(true, false, false));
        assert!(spin_wait_fastfwd_gate(true, false, true));
    }

    /// Regression gates for the ModalDialog noop-refire skip. The GUI
    /// gate is the most critical because tick-driven animations
    /// require real refires.
    #[test]
    fn modaldialog_refire_skip_gui_mode_never_fires() {
        // yield_for_ui=true should ALWAYS prevent the skip,
        // regardless of the other conditions.
        for has_tracking in [false, true] {
            for events in [false, true] {
                assert!(
                    !modaldialog_refire_is_noop(
                        true, // yield_for_ui = GUI
                        has_tracking,
                        true, // all "noop" conditions
                        true,
                        true,
                        true,
                        events,
                    ),
                    "GUI mode must never skip refires (has_tracking={}, events={})",
                    has_tracking,
                    events
                );
            }
        }
    }

    #[test]
    fn tracking_refire_freeze_policy_keeps_modaldialog_ticks_live() {
        // Menu/control tracking may freeze app-visible ticks while the GUI
        // renders intermediate tracking frames.
        assert!(tracking_refire_should_freeze_ticks(0xA93D));
        assert!(tracking_refire_should_freeze_ticks(0xAD3D));
        assert!(tracking_refire_should_freeze_ticks(0xA80B));
        assert!(tracking_refire_should_freeze_ticks(0xAC0B));
        assert!(tracking_refire_should_freeze_ticks(0xA968));
        assert!(tracking_refire_should_freeze_ticks(0xAD68));

        // ModalDialog must keep ticks/VBL/sound callbacks live. EV's pilot
        // dialog flow plays music through this path.
        assert!(!tracking_refire_should_freeze_ticks(0xA991));
        assert!(!tracking_refire_should_freeze_ticks(0xAD91));
    }

    #[test]
    fn gui_modaldialog_idle_refire_advances_one_tick() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let base = 0x0001_0000u32;
        runner.bus.write_word(base, 0xA991); // _ModalDialog
        runner.cpu.write_reg(Register::PC, base);
        runner.cpu.write_reg(Register::A7, 0x0010_0000);
        runner.bus.write_long(0x016A, 0);
        runner.dispatcher.tick_count = 0;
        runner.set_instructions_per_tick(1_000_000);
        runner.dispatcher.dialog_tracking = Some(dialog_tracking_for_test(0, 0));

        let (steps, running) = runner.run_gui_slice_with_audio(1, 1, 0);

        assert!(running);
        assert_eq!(steps, 1);
        assert_eq!(runner.guest_tick(), 1);
        assert_eq!(runner.tick_budget, runner.instructions_per_tick() as i32);
        assert_eq!(runner.cpu.read_reg(Register::PC), base);
    }

    #[test]
    fn gui_modaldialog_idle_refire_runs_until_tick_cap() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let base = 0x0001_0000u32;
        runner.bus.write_word(base, 0xA991); // _ModalDialog
        runner.cpu.write_reg(Register::PC, base);
        runner.cpu.write_reg(Register::A7, 0x0010_0000);
        runner.bus.write_long(0x016A, 0);
        runner.dispatcher.tick_count = 0;
        runner.set_instructions_per_tick(1_000_000);
        runner.dispatcher.dialog_tracking = Some(dialog_tracking_for_test(0, 0));

        let (steps, running) = runner.run_gui_slice_with_audio(16, 2, 0);

        assert!(running);
        assert_eq!(steps, 2);
        assert_eq!(runner.guest_tick(), 2);
        assert_eq!(runner.cpu.read_reg(Register::PC), base);
    }

    #[test]
    fn gui_modaldialog_refire_unfreezes_prior_control_tracking() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let base = 0x0001_0000u32;
        runner.bus.write_word(base, 0xA991); // _ModalDialog
        runner.cpu.write_reg(Register::PC, base);
        runner.cpu.write_reg(Register::A7, 0x0010_0000);
        runner.bus.write_long(0x016A, 182);
        runner.dispatcher.tick_count = 182;
        runner.frozen_ticks = Some(182);
        runner.set_instructions_per_tick(1_000_000);
        runner.dispatcher.dialog_tracking = Some(dialog_tracking_for_test(0, 0));

        let (steps, running) = runner.run_gui_slice_with_audio(16, 184, 0);

        assert!(running);
        assert_eq!(steps, 1);
        assert_eq!(runner.frozen_ticks, None);
        assert_eq!(runner.guest_tick(), 184);
        assert_eq!(runner.dispatcher.tick_count, 184);
    }

    #[test]
    fn gui_modaldialog_null_filter_fires_at_tick_cap() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let base = 0x0001_0000u32;
        let filter_proc = 0x0001_1000u32;
        runner.bus.write_word(base, 0xA991); // _ModalDialog
        runner.bus.write_word(filter_proc, 0x4E56); // LINK A6, valid filter entry
        runner.cpu.write_reg(Register::PC, base);
        runner.cpu.write_reg(Register::A7, 0x0010_0000);
        runner.bus.write_long(0x016A, 0);
        runner.dispatcher.tick_count = 0;
        runner.dispatcher.dialog_tracking =
            Some(dialog_tracking_for_test(filter_proc, 0x0010_0100));

        let (steps, running) = runner.run_gui_slice_with_audio(1, 0, 0);

        assert!(running);
        assert_eq!(steps, 1);
        assert_eq!(runner.guest_tick(), 0);
        assert_ne!(runner.cpu.read_reg(Register::PC), base);
        assert!(!runner.has_pending_sound_work());
        assert!(
            !runner
                .dispatcher
                .dialog_tracking
                .as_ref()
                .unwrap()
                .rendered_pixels_final
        );
    }

    #[test]
    fn gui_modaldialog_update_filter_fires_at_tick_cap() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let base = 0x0001_0000u32;
        let filter_proc = 0x0001_1000u32;
        runner.bus.write_word(base, 0xA991); // _ModalDialog
        runner.bus.write_word(filter_proc, 0x4E56); // LINK A6, valid filter entry
        runner.cpu.write_reg(Register::PC, base);
        runner.cpu.write_reg(Register::A7, 0x0010_0000);
        runner.bus.write_long(0x016A, 0);
        runner.dispatcher.tick_count = 0;
        runner.dispatcher.event_queue.push_back(QueuedEvent {
            what: 6,
            message: 0,
            where_v: 0,
            where_h: 0,
            modifiers: 0,
        });
        runner.dispatcher.dialog_tracking =
            Some(dialog_tracking_for_test(filter_proc, 0x0010_0100));

        let (steps, running) = runner.run_gui_slice_with_audio(1, 0, 0);

        assert!(running);
        assert_eq!(steps, 1);
        assert_eq!(runner.guest_tick(), 0);
        assert_ne!(runner.cpu.read_reg(Register::PC), base);
        assert!(
            !runner
                .dispatcher
                .dialog_tracking
                .as_ref()
                .unwrap()
                .rendered_pixels_final
        );
    }

    #[test]
    fn gui_modaldialog_mouse_down_goes_to_filter_before_default_handling() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let base = 0x0001_0000u32;
        let filter_proc = 0x0001_1000u32;
        runner.bus.write_word(base, 0xA991); // _ModalDialog
        runner.bus.write_word(filter_proc, 0x4E56); // LINK A6, valid filter entry
        runner.cpu.write_reg(Register::PC, base);
        runner.cpu.write_reg(Register::A7, 0x0010_0000);
        runner.bus.write_long(0x016A, 0);
        runner.dispatcher.tick_count = 0;
        runner.dispatcher.event_queue.push_back(QueuedEvent {
            what: 1,
            message: 0,
            where_v: 12,
            where_h: 24,
            modifiers: 0,
        });
        let mut tracking = dialog_tracking_for_test(filter_proc, 0x0010_0100);
        tracking.items.push(DialogItem {
            item_type: 4,
            rect: (8, 16, 20, 30),
            text: String::from("OK"),
            resource_id: 0,
            proc_ptr: 0,
            sel_start: 0,
            sel_end: 0,
        });
        runner.dispatcher.dialog_tracking = Some(tracking);

        let (steps, running) = runner.run_gui_slice_with_audio(1, 0, 0);

        assert!(running);
        assert_eq!(steps, 1);
        assert_ne!(runner.cpu.read_reg(Register::PC), base);
        let event_ptr = runner.dialog_filter_event;
        assert_eq!(runner.bus.read_word(event_ptr), 1);
        assert_eq!(runner.bus.read_word(event_ptr + 10), 12);
        assert_eq!(runner.bus.read_word(event_ptr + 12), 24);
        assert!(
            runner.dispatcher.event_queue.is_empty(),
            "the filter callback should consume a queued button mouseDown event"
        );
    }

    #[test]
    fn modaldialog_filter_null_event_is_paced_per_guest_tick() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let filter_proc = 0x0001_1000u32;
        let dialog_ptr = 0x0020_0000u32;
        runner.dispatcher.dialog_tracking =
            Some(dialog_tracking_for_test(filter_proc, 0x0010_0100));
        runner.dispatcher.tick_count = 42;
        runner.bus.write_long(0x016A, 42);

        assert!(runner.should_fire_dialog_filter_proc());

        runner.dialog_filter_last_null_event_tick = Some((dialog_ptr, 42));
        assert!(
            !runner.should_fire_dialog_filter_proc(),
            "a synthetic null event should not refire twice in the same guest tick"
        );

        runner.dispatcher.tick_count = 43;
        runner.bus.write_long(0x016A, 43);
        assert!(
            runner.should_fire_dialog_filter_proc(),
            "the next guest tick should allow another ModalDialog null-event filter call"
        );
    }

    #[test]
    fn modaldialog_filter_real_events_bypass_null_event_pacing() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let filter_proc = 0x0001_1000u32;
        let dialog_ptr = 0x0020_0000u32;
        runner.dispatcher.dialog_tracking =
            Some(dialog_tracking_for_test(filter_proc, 0x0010_0100));
        runner.dispatcher.tick_count = 42;
        runner.bus.write_long(0x016A, 42);
        runner.dialog_filter_last_null_event_tick = Some((dialog_ptr, 42));
        runner.dispatcher.event_queue.push_back(QueuedEvent {
            what: 1,
            message: 0,
            where_v: 12,
            where_h: 34,
            modifiers: 0,
        });

        assert!(
            runner.should_fire_dialog_filter_proc(),
            "mouse/key/update events must still enter the filter immediately"
        );

        runner.dispatcher.event_queue.clear();
        let window_ptr = runner.bus.alloc(170);
        runner.dispatcher.init_cgraf_window(
            &mut runner.bus,
            &mut runner.cpu,
            window_ptr,
            0,
            100,
            120,
            220,
            360,
            "",
            2,
            true,
            false,
            false,
            0,
        );
        runner
            .dispatcher
            .dialog_tracking
            .as_mut()
            .unwrap()
            .dialog_ptr = window_ptr;
        runner.dialog_filter_last_null_event_tick = Some((window_ptr, 42));

        assert!(
            runner.should_fire_dialog_filter_proc(),
            "a pending updateEvt for the active dialog must bypass null-event pacing"
        );
    }

    #[test]
    fn modaldialog_refire_skip_headless_requires_all_conditions() {
        // In headless mode, ALL noop conditions must be true.
        // Each condition false alone must prevent the skip.
        assert!(modaldialog_refire_is_noop(
            false, true, true, true, true, true, true,
        ));

        // Each one off in turn should prevent the skip.
        assert!(!modaldialog_refire_is_noop(
            false, false, true, true, true, true, true,
        ));
        assert!(!modaldialog_refire_is_noop(
            false, true, false, true, true, true, true,
        ));
        assert!(!modaldialog_refire_is_noop(
            false, true, true, false, true, true, true,
        ));
        assert!(!modaldialog_refire_is_noop(
            false, true, true, true, false, true, true,
        ));
        assert!(!modaldialog_refire_is_noop(
            false, true, true, true, true, false, true,
        ));
        assert!(!modaldialog_refire_is_noop(
            false, true, true, true, true, true, false,
        ));
    }

    #[test]
    fn spin_fastfwd_rejects_wrong_branch_target() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let base = 0x0001_0000u32;
        runner.bus.write_word(base, 0x594F);
        runner.bus.write_word(base + 2, 0xA975);
        runner.bus.write_word(base + 4, 0x201F);
        runner.bus.write_word(base + 6, 0x5380);
        runner.bus.write_word(base + 8, 0xB680);
        // BHI.S with disp8 = 0xF6 (= -10, not -12). Target would
        // land at base+8, not at the SUBQ.W #4, A7 at base+0.
        runner.bus.write_word(base + 10, 0x62F6);

        runner.bus.write_long(0x016A, 100);
        runner.dispatcher.tick_count = 100;
        runner.cpu.write_reg(Register::D3, 500);
        runner.cpu.write_reg(Register::A7, 0x0010_0000);
        let pc_after_trap = base + 4;
        let mut count = 0usize;
        runner.try_tickcount_spin_fastfwd(pc_after_trap, None, &mut count);

        assert_eq!(runner.dispatcher.tick_count, 100);
        assert_eq!(count, 0);
    }

    /// Regression gate for the `inline_skipped` counter on the
    /// TickCount fast path. Without this, a future change that
    /// removes the increment (or moves it to a path that doesn't
    /// actually fire) would silently produce wrong real-vs-inline
    /// counts in the timing histogram, masking real per-dispatch
    /// costs.
    #[test]
    fn tickcount_inline_skip_increments_inline_skipped() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let base = 0x0001_0000u32;
        // Plain TickCount call: SUBQ.W #4, A7 ; _TickCount ; NOP
        // The runner's pre-dispatch fast path recognises 0xA975,
        // writes the tick to (A7), and continues without calling
        // dispatch().
        runner.bus.write_word(base, 0x594F); // SUBQ.W #4, A7 (reserve LONGINT slot)
        runner.bus.write_word(base + 2, 0xA975); // _TickCount
        runner.bus.write_word(base + 4, 0x4E71); // NOP (sentinel)
        runner.cpu.write_reg(Register::PC, base);
        runner.cpu.write_reg(Register::A7, 0x0010_0000);
        runner.dispatcher.tick_count = 0;
        runner.bus.write_long(0x016A, 0);
        runner.set_instructions_per_tick(1_000_000);

        let idx = (0xA975u16 & 0xFFF) as usize;
        let before = runner.dispatcher.inline_skipped[idx];

        // Two steps: the SUBQ first, then the trap that triggers the inline.
        let (steps, running) = runner.run_steps(2, None);
        assert!(running, "runner should not halt on a plain trap fast path");
        assert_eq!(steps, 2);

        let after = runner.dispatcher.inline_skipped[idx];
        assert_eq!(
            after - before,
            1,
            "TickCount fast path must increment inline_skipped[$0175]"
        );
        assert_eq!(
            runner.dispatcher.trap_histogram[idx], 1,
            "the same path must also increment trap_histogram[$0175]"
        );
    }

    #[test]
    fn halted_by_exit_to_shell_classifies_clean_application_quit() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let base = 0x0001_0000u32;
        runner.bus.write_word(base, 0xA9F4); // _ExitToShell
        runner.cpu.write_reg(Register::PC, base);
        runner.cpu.write_reg(Register::A7, 0x0010_0000);

        let (_steps, running) = runner.run_steps(1, None);

        assert!(!running, "ExitToShell should stop the runner");
        assert!(runner.is_halted());
        assert_eq!(runner.halted_trap(), Some(0xA9F4));
        assert!(
            runner.halted_by_exit_to_shell(),
            "ExitToShell halt must be classified as a clean application exit"
        );
    }

    #[test]
    fn halted_by_exit_to_shell_rejects_invalid_pc_halts() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        runner.cpu.write_reg(Register::PC, runner.bus.ram_size());
        runner.cpu.write_reg(Register::A7, 0x0010_0000);

        let (_steps, running) = runner.run_steps(1, None);

        assert!(!running, "invalid PC should stop the runner");
        assert!(runner.is_halted());
        assert_eq!(runner.halted_trap(), None);
        assert!(
            !runner.halted_by_exit_to_shell(),
            "invalid-PC halts must not be reported as clean application exits"
        );
    }

    #[test]
    fn ptinrect_inline_path_matches_pascal_stack_contract() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let base = 0x0001_0000u32;
        let sp = 0x0010_0000u32;
        let rect = 0x0020_0000u32;

        runner.bus.write_word(base, 0xA8AD); // _PtInRect
        runner.cpu.write_reg(Register::PC, base);
        runner.cpu.write_reg(Register::A7, sp);
        runner.set_instructions_per_tick(1_000_000);

        runner.bus.write_long(sp, rect);
        runner.bus.write_word(sp + 4, 20); // pt.v
        runner.bus.write_word(sp + 6, 30); // pt.h
        runner.bus.write_word(rect, 10); // top
        runner.bus.write_word(rect + 2, 25); // left
        runner.bus.write_word(rect + 4, 40); // bottom
        runner.bus.write_word(rect + 6, 50); // right

        let idx = (0xA8ADu16 & 0xFFF) as usize;
        let before_inline = runner.dispatcher.inline_skipped[idx];
        let before_game = runner.dispatcher.game_trap_count;

        let (steps, running) = runner.run_steps(1, None);

        assert!(running, "runner should not halt on PtInRect inline path");
        assert_eq!(steps, 1);
        assert_eq!(runner.cpu.read_reg(Register::PC), base + 2);
        assert_eq!(runner.cpu.read_reg(Register::A7), sp + 8);
        assert_eq!(runner.bus.read_word(sp + 8), 0x0100);
        assert_eq!(runner.dispatcher.inline_skipped[idx] - before_inline, 1);
        assert_eq!(runner.dispatcher.trap_histogram[idx], 1);
        assert_eq!(runner.dispatcher.game_trap_count - before_game, 1);
    }

    #[test]
    fn eventavail_inline_path_peeks_without_dequeueing() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let base = 0x0001_0000u32;
        let sp = 0x0010_0000u32;
        let event = 0x0020_0000u32;

        runner.bus.write_word(base, 0xA971); // _EventAvail
        runner.cpu.write_reg(Register::PC, base);
        runner.cpu.write_reg(Register::A7, sp);
        runner.set_instructions_per_tick(1_000_000);
        runner.bus.write_long(sp, event);
        runner.bus.write_word(sp + 4, 0x0008); // keyDownMask
        runner.dispatcher.push_key_down(0x31, b' ');

        let idx = (0xA971u16 & 0xFFF) as usize;
        let before_inline = runner.dispatcher.inline_skipped[idx];
        let before_game = runner.dispatcher.game_trap_count;

        let (steps, running) = runner.run_steps(1, None);

        assert!(running, "runner should not halt on EventAvail inline path");
        assert_eq!(steps, 1);
        assert_eq!(runner.cpu.read_reg(Register::PC), base + 2);
        assert_eq!(runner.cpu.read_reg(Register::A7), sp + 6);
        assert_eq!(runner.bus.read_word(sp + 6), 0xFFFF);
        assert_eq!(runner.bus.read_word(event), 3);
        assert_eq!(
            runner.bus.read_long(event + 2),
            (0x31u32 << 8) | u32::from(b' ')
        );
        assert_eq!(
            runner.dispatcher.event_queue.len(),
            1,
            "EventAvail must not dequeue the matching event"
        );
        assert_eq!(runner.dispatcher.inline_skipped[idx] - before_inline, 1);
        assert_eq!(runner.dispatcher.trap_histogram[idx], 1);
        assert_eq!(
            runner.dispatcher.game_trap_count, before_game,
            "EventAvail remains excluded from game_trap_count as an idle trap"
        );
    }

    /// Regression gate for the `inline_skipped` counter on the
    /// ModalDialog batched no-op refire path. The runner's pre-
    /// dispatch fast path increments `inline_skipped[$0191]` once
    /// for the entry plus `BATCH-1=63` times in the inner loop.
    /// Without this test, a regression that drops the increment
    /// would silently make ModalDialog look ~99% inline-skipped
    /// without surfacing anywhere else.
    #[test]
    fn modaldialog_batched_skip_increments_inline_skipped_by_batch() {
        use crate::trap::dispatch::DialogTrackingState;
        use std::collections::VecDeque;

        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let base = 0x0001_0000u32;
        // Bare ModalDialog at PC. The runner-level fast path rewinds
        // PC after each fire, so re-firing repeatedly into the same
        // trap word is the production behaviour.
        runner.bus.write_word(base, 0xA991); // _ModalDialog
        runner.cpu.write_reg(Register::PC, base);
        runner.cpu.write_reg(Register::A7, 0x0010_0000);
        runner.dispatcher.tick_count = 0;
        runner.bus.write_long(0x016A, 0);
        runner.set_instructions_per_tick(1_000_000);

        // Populate dialog_tracking so the noop_refire pure-decision
        // function returns true. modaldialog_refire_is_noop requires
        // ALL of: tracking present, filter_proc=0, flash_remaining=0,
        // draw_procs_done, rendered_pixels_final, event queue empty
        // (and yield_for_ui = false in headless run_steps).
        runner.dispatcher.dialog_tracking = Some(DialogTrackingState {
            dialog_ptr: 0x0020_0000,
            bounds: (0, 0, 32, 32),
            title: String::new(),
            proc_id: 1,
            items: Vec::new(),
            default_item: 0,
            cancel_item: 0,
            edit_text: String::new(),
            edit_item: 0,
            saved_pixels: Vec::new(),
            stack_ptr: 0,
            item_hit_ptr: 0,
            rendered_pixels: Vec::new(),
            flash_remaining: 0,
            flash_delay: 0,
            flash_item: 0,
            edit_text_modified: false,
            draw_proc_queue: VecDeque::new(),
            draw_procs_done: true,
            rendered_pixels_final: true,
            filter_proc: 0,
            game_managed: false,
            last_filter_event: None,
            popup_draws: Vec::new(),
            active_popup: None,
            active_button: None,
            active_user_item: None,
        });

        let idx = (0xA991u16 & 0xFFF) as usize;
        let before_inline = runner.dispatcher.inline_skipped[idx];
        let before_hist = runner.dispatcher.trap_histogram[idx];

        // BATCH=64 in the runner. With max_steps=64 we should observe
        // exactly one entry + 63 batched iterations = 64 increments.
        let (steps, _running) = runner.run_steps(64, None);

        assert_eq!(
            steps, 64,
            "max_steps cap exhausted by 64 batched no-op refires"
        );
        let after_inline = runner.dispatcher.inline_skipped[idx];
        let after_hist = runner.dispatcher.trap_histogram[idx];
        assert_eq!(
            after_inline - before_inline,
            64,
            "batched skip must increment inline_skipped[$0191] by BATCH=64"
        );
        assert_eq!(
            after_hist - before_hist,
            64,
            "trap_histogram and inline_skipped must increment in lockstep on the inline path"
        );
    }

    #[test]
    fn modaldialog_batched_skip_applies_after_paced_filter_null_event() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let base = 0x0001_0000u32;
        let filter_proc = 0x0001_1000u32;
        let dialog_ptr = 0x0020_0000u32;
        runner.bus.write_word(base, 0xA991); // _ModalDialog
        runner.cpu.write_reg(Register::PC, base);
        runner.cpu.write_reg(Register::A7, 0x0010_0000);
        runner.dispatcher.tick_count = 42;
        runner.bus.write_long(0x016A, 42);
        runner.set_instructions_per_tick(1_000_000);
        runner.dispatcher.dialog_tracking =
            Some(dialog_tracking_for_test(filter_proc, 0x0010_0100));
        runner.dialog_filter_last_null_event_tick = Some((dialog_ptr, 42));

        let idx = (0xA991u16 & 0xFFF) as usize;
        let before_inline = runner.dispatcher.inline_skipped[idx];
        let before_hist = runner.dispatcher.trap_histogram[idx];

        let (steps, running) = runner.run_steps(64, None);

        assert!(running);
        assert_eq!(steps, 64);
        assert_eq!(runner.cpu.read_reg(Register::PC), base);
        assert_eq!(runner.dispatcher.inline_skipped[idx] - before_inline, 64);
        assert_eq!(runner.dispatcher.trap_histogram[idx] - before_hist, 64);
    }

    #[test]
    fn tick_progress_persists_across_multiple_run_slices() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let program_start = 0x0001_0000;
        let program_words = 12;

        for offset in (0..program_words).step_by(2) {
            runner.bus.write_word(program_start + offset, 0x4E71);
        }

        runner.cpu.write_reg(Register::PC, program_start);
        runner.cpu.write_reg(Register::A7, 0x007F_FFC0);
        runner.bus.write_long(0x016A, 0);
        runner.set_instructions_per_tick(5);

        let (steps1, running1) = runner.run_steps(3, None);
        let (steps2, running2) = runner.run_steps(3, None);

        assert!(running1);
        assert!(running2);
        assert_eq!(steps1, 3);
        assert_eq!(steps2, 3);
        assert_eq!(runner.bus.read_long(0x016A), 1);
    }

    #[test]
    fn tick_override_breaks_once_target_tick_is_reached() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let program_start = 0x0001_0000;
        let program_words = 16;

        for offset in (0..program_words).step_by(2) {
            runner.bus.write_word(program_start + offset, 0x4E71);
        }

        runner.cpu.write_reg(Register::PC, program_start);
        runner.cpu.write_reg(Register::A7, 0x007F_FFC0);
        runner.bus.write_long(0x016A, 0);
        runner.set_instructions_per_tick(4);

        let (steps, running) = runner.run_steps_with_audio(16, Some(0), 0);

        assert!(running);
        assert_eq!(steps, 3);
        assert_eq!(runner.bus.read_long(0x016A), 0);
    }

    #[test]
    fn pending_wait_sleep_ticks_advance_in_headless_mode() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let program_start = 0x0001_0000;

        runner.bus.write_word(program_start, 0x4E71);
        runner.cpu.write_reg(Register::PC, program_start);
        runner.cpu.write_reg(Register::A7, 0x007F_FFC0);
        runner.bus.write_long(0x016A, 0);
        runner.dispatcher.pending_wait_sleep_ticks = 3;

        let (steps, running) = runner.run_steps(1, None);

        assert!(running);
        assert_eq!(steps, 1);
        assert_eq!(runner.bus.read_long(0x016A), 3);
        assert_eq!(runner.dispatcher.pending_wait_sleep_ticks, 0);
    }

    #[test]
    fn pending_wait_sleep_ticks_capped_to_zero_in_headless() {
        // `cap=Some(0)` is the scripted default — `WaitNextEvent`
        // sleep is treated as a zero-cost return (matching real Mac OS
        // where WNE doesn't directly tick; only the VBL hardware
        // interrupt does).
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let program_start = 0x0001_0000;

        runner.bus.write_word(program_start, 0x4E71);
        runner.cpu.write_reg(Register::PC, program_start);
        runner.cpu.write_reg(Register::A7, 0x007F_FFC0);
        runner.bus.write_long(0x016A, 0);
        runner.set_wait_sleep_cap_in_headless(Some(0));
        runner.dispatcher.pending_wait_sleep_ticks = 60;

        let (_steps, _running) = runner.run_steps(1, None);

        // Zero ticks advanced (cap=0).
        assert_eq!(runner.bus.read_long(0x016A), 0);
        // But pending sleep is cleared so the game resumes immediately.
        assert_eq!(runner.dispatcher.pending_wait_sleep_ticks, 0);
    }

    #[test]
    fn pending_wait_sleep_ticks_capped_in_headless_when_opt_in() {
        // Headless callers (e.g. scripted harnesses) can opt in to a
        // per-WNE-call sleep tick cap matching GUI mode, preventing
        // tick counts from racing ahead of real-Mac VBL pacing during
        // event-loop-heavy gameplay.
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let program_start = 0x0001_0000;

        runner.bus.write_word(program_start, 0x4E71);
        runner.cpu.write_reg(Register::PC, program_start);
        runner.cpu.write_reg(Register::A7, 0x007F_FFC0);
        runner.bus.write_long(0x016A, 0);
        runner.set_wait_sleep_cap_in_headless(Some(1));
        runner.dispatcher.pending_wait_sleep_ticks = 60;

        let (steps, running) = runner.run_steps(1, None);

        assert!(running);
        assert_eq!(steps, 1);
        // Only 1 tick advanced (cap), not the full 60.
        assert_eq!(runner.bus.read_long(0x016A), 1);
        assert_eq!(runner.dispatcher.pending_wait_sleep_ticks, 0);
        assert_eq!(runner.wait_sleep_cap_in_headless(), Some(1));
    }

    #[test]
    fn pending_wait_sleep_ticks_capped_to_one_in_gui_mode() {
        // In GUI mode (tick_override=Some), WNE sleep is capped to 1 tick
        // per call. The full sleep duration is a hint, not a requirement.
        // This prevents long WNE sleeps (e.g. 60 ticks) from starving the
        // game loop. Macintosh Toolbox Essentials 1992, 2-22
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let program_start = 0x0001_0000;

        runner.bus.write_word(program_start, 0x4E71);
        runner.cpu.write_reg(Register::PC, program_start);
        runner.cpu.write_reg(Register::A7, 0x007F_FFC0);
        runner.bus.write_long(0x016A, 0);
        runner.dispatcher.pending_wait_sleep_ticks = 60;

        let (steps, _running) = runner.run_steps(1, Some(10));

        assert_eq!(steps, 1);
        // Only 1 tick advanced (not the full 60).
        assert_eq!(runner.bus.read_long(0x016A), 1);
        // Remaining sleep cleared — game resumes immediately.
        assert_eq!(runner.dispatcher.pending_wait_sleep_ticks, 0);
    }

    #[test]
    fn pending_delay_ticks_advance_in_gui_mode() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let program_start = 0x0001_0000;

        runner.bus.write_word(program_start, 0x4E71);
        runner.cpu.write_reg(Register::PC, program_start);
        runner.cpu.write_reg(Register::A7, 0x007F_FFC0);
        runner.bus.write_long(0x016A, 0);
        runner.dispatcher.pending_delay_ticks = 3;

        let (steps, _running) = runner.run_steps(1, Some(10));

        assert_eq!(steps, 1);
        assert_eq!(runner.bus.read_long(0x016A), 3);
        assert_eq!(runner.dispatcher.pending_delay_ticks, 0);
        assert_eq!(runner.cpu.read_reg(Register::D0), 3);
    }

    #[test]
    fn dialog_filter_synthesized_null_event_uses_live_modifiers() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let filter_proc = 0x0004_2000u32;

        runner.bus.write_word(filter_proc, 0x4E56);
        runner.cpu.write_reg(Register::PC, 0x0001_0000);
        runner.cpu.write_reg(Register::A7, 0x007F_FFC0);
        runner.dispatcher.set_mouse_position(222, 333);
        runner.dispatcher.dialog_tracking = Some(crate::trap::dispatch::DialogTrackingState {
            dialog_ptr: 0x0020_0000,
            bounds: (100, 200, 200, 360),
            title: String::new(),
            proc_id: 2,
            items: Vec::new(),
            default_item: 1,
            cancel_item: 2,
            edit_text: String::new(),
            edit_item: 0,
            saved_pixels: Vec::new(),
            stack_ptr: 0x007F_FFC0,
            item_hit_ptr: 0x0030_0000,
            rendered_pixels: Vec::new(),
            flash_remaining: 0,
            flash_delay: 0,
            flash_item: 0,
            edit_text_modified: false,
            draw_proc_queue: std::collections::VecDeque::new(),
            draw_procs_done: true,
            rendered_pixels_final: true,
            filter_proc,
            game_managed: true,
            last_filter_event: None,
            popup_draws: Vec::new(),
            active_popup: None,
            active_button: None,
            active_user_item: None,
        });

        assert!(runner.fire_dialog_filter_proc());
        let event_ptr = runner.dialog_filter_event;
        assert_eq!(runner.bus.read_word(event_ptr), 0);
        assert_eq!(runner.bus.read_word(event_ptr + 10), 222);
        assert_eq!(runner.bus.read_word(event_ptr + 12), 333);
        assert_eq!(
            runner.bus.read_word(event_ptr + 14),
            runner.dispatcher.current_event_modifiers()
        );
        assert_eq!(
            runner.dialog_filter_last_null_event_tick,
            Some((0x0020_0000, 0))
        );
    }

    #[test]
    fn dialog_filter_uses_active_dialog_pending_update_before_null_event() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let filter_proc = 0x0004_2000u32;
        let dialog_ptr = runner.bus.alloc(170);

        runner.bus.write_word(filter_proc, 0x4E56);
        runner.cpu.write_reg(Register::PC, 0x0001_0000);
        runner.cpu.write_reg(Register::A7, 0x007F_FFC0);
        runner.dispatcher.init_cgraf_window(
            &mut runner.bus,
            &mut runner.cpu,
            dialog_ptr,
            0,
            100,
            120,
            220,
            360,
            "",
            2,
            true,
            false,
            false,
            0,
        );
        runner.dispatcher.event_queue.clear();
        runner.dispatcher.dialog_tracking =
            Some(dialog_tracking_for_test(filter_proc, 0x0030_0000));
        runner
            .dispatcher
            .dialog_tracking
            .as_mut()
            .unwrap()
            .dialog_ptr = dialog_ptr;

        assert!(runner.fire_dialog_filter_proc());
        let event_ptr = runner.dialog_filter_event;
        assert_eq!(runner.bus.read_word(event_ptr), 6);
        assert_eq!(runner.bus.read_long(event_ptr + 2), dialog_ptr);
        assert_eq!(runner.dialog_filter_last_null_event_tick, None);
    }

    #[test]
    fn dialog_filter_proc_leaves_dialog_port_current() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let interrupted_pc = 0x0001_0000u32;
        let interrupted_sp = 0x007F_FFC0u32;
        let main_port = runner.bus.alloc(170);
        let dialog_ptr = runner.bus.alloc(170);

        runner.bus.write_word(interrupted_pc, 0x60FE); // BRA.S *-0
        runner.cpu.write_reg(Register::PC, interrupted_pc);
        runner.cpu.write_reg(Register::A7, interrupted_sp);

        runner.dispatcher.init_cgraf_window(
            &mut runner.bus,
            &mut runner.cpu,
            main_port,
            0,
            0,
            0,
            600,
            800,
            "",
            2,
            true,
            false,
            false,
            0,
        );
        runner.dispatcher.init_cgraf_window(
            &mut runner.bus,
            &mut runner.cpu,
            dialog_ptr,
            0,
            120,
            180,
            240,
            420,
            "",
            2,
            true,
            false,
            false,
            0,
        );
        runner
            .dispatcher
            .set_current_port_state(&mut runner.bus, &mut runner.cpu, main_port, None);
        let filter_proc = runner.bus.alloc(8);
        runner.bus.write_word(filter_proc, 0x4E56); // LINK A6, valid filter entry

        runner.dispatcher.dialog_tracking =
            Some(dialog_tracking_for_test(filter_proc, 0x0030_0000));
        runner
            .dispatcher
            .dialog_tracking
            .as_mut()
            .unwrap()
            .dialog_ptr = dialog_ptr;

        assert!(runner.fire_dialog_filter_proc());
        assert_eq!(runner.dispatcher.current_port, dialog_ptr);
        assert_eq!(
            runner
                .active_interrupt_callback
                .as_ref()
                .and_then(|callback| callback.restore_port),
            None
        );

        runner.cpu.write_reg(Register::PC, interrupted_pc);
        runner.cpu.write_reg(Register::A7, interrupted_sp);
        let (_steps, running) = runner.run_steps(1, None);

        assert!(running);
        assert_eq!(runner.dispatcher.current_port, dialog_ptr);
        assert!(runner.active_interrupt_callback.is_none());
    }

    #[test]
    fn dialog_draw_proc_trampoline_passes_item_first_and_tolerates_plain_rts() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let interrupted_pc = 0x0001_0000u32;
        let interrupted_sp = 0x007F_FFC0u32;
        let dialog_ptr = 0x0020_0000u32;
        let proc_addr = 0x0004_2000u32;
        let item_no = 5i16;

        // Keep foreground execution stable after the callback returns.
        runner.bus.write_word(interrupted_pc, 0x60FE); // BRA.S *-0
        runner.cpu.write_reg(Register::PC, interrupted_pc);
        runner.cpu.write_reg(Register::A7, interrupted_sp);

        // MPW-style proc prologue shape. It returns with plain RTS, leaving
        // callback parameters on the stack; the trampoline must restore A7.
        runner.bus.write_word(proc_addr, 0x4E56); // LINK A6,#0
        runner.bus.write_word(proc_addr + 2, 0x0000);
        runner.bus.write_word(proc_addr + 4, 0x4E5E); // UNLK A6
        runner.bus.write_word(proc_addr + 6, 0x4E75); // RTS

        runner.dispatcher.dialog_tracking = Some(crate::trap::dispatch::DialogTrackingState {
            dialog_ptr,
            bounds: (0, 0, 64, 64),
            title: String::new(),
            proc_id: 1,
            items: Vec::new(),
            default_item: 0,
            cancel_item: 0,
            edit_text: String::new(),
            edit_item: 0,
            saved_pixels: Vec::new(),
            stack_ptr: interrupted_sp,
            item_hit_ptr: 0,
            rendered_pixels: Vec::new(),
            flash_remaining: 0,
            flash_delay: 0,
            flash_item: 0,
            edit_text_modified: false,
            draw_proc_queue: VecDeque::from([(proc_addr, item_no)]),
            draw_procs_done: false,
            rendered_pixels_final: false,
            filter_proc: 0,
            game_managed: false,
            last_filter_event: None,
            popup_draws: Vec::new(),
            active_popup: None,
            active_button: None,
            active_user_item: None,
        });

        assert!(runner.fire_dialog_draw_procs());
        let tramp = runner.dialog_draw_trampoline;
        assert_eq!(runner.bus.read_word(tramp), 0x48E7);
        assert_eq!(runner.bus.read_word(tramp + 4), 0x2F3C);
        assert_eq!(runner.bus.read_long(tramp + 6), dialog_ptr);
        assert_eq!(runner.bus.read_word(tramp + 10), 0x3F3C);
        assert_eq!(runner.bus.read_word(tramp + 12), item_no as u16);
        assert_eq!(runner.bus.read_word(tramp + 14), 0x4EB9);
        assert_eq!(runner.bus.read_long(tramp + 16), proc_addr);
        assert_eq!(runner.bus.read_word(tramp + 20), 0x4FF9);
        assert_eq!(runner.bus.read_long(tramp + 22), interrupted_sp - 36);

        let (_steps, running) = runner.run_steps(16, None);

        assert!(running);
        assert!(
            runner.active_interrupt_callback.is_none(),
            "dialog callback should have resumed foreground code"
        );
        assert_eq!(runner.cpu.read_reg(Register::PC), interrupted_pc);
        assert_eq!(runner.cpu.read_reg(Register::A7), interrupted_sp);
    }

    #[test]
    fn modeless_dialog_draw_proc_accepts_a5_relative_proc_ptr() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let interrupted_pc = 0x0001_0000u32;
        let interrupted_sp = 0x007F_FFC0u32;
        let a5 = 0x0020_0000u32;
        let proc_offset = 0x0000_4200u32;
        let proc_addr = a5 + proc_offset;
        let dialog_ptr = runner.bus.alloc(170);

        runner.bus.write_word(interrupted_pc, 0x60FE);
        runner.cpu.write_reg(Register::PC, interrupted_pc);
        runner.cpu.write_reg(Register::A7, interrupted_sp);
        runner.cpu.write_reg(Register::A5, a5);
        runner.dispatcher.init_cgraf_window(
            &mut runner.bus,
            &mut runner.cpu,
            dialog_ptr,
            0,
            120,
            180,
            240,
            420,
            "",
            2,
            true,
            false,
            false,
            0,
        );

        runner.bus.write_word(proc_addr, 0x4E56); // LINK A6,#0
        runner.bus.write_word(proc_addr + 2, 0x0000);
        runner.bus.write_word(proc_addr + 4, 0x4E5E); // UNLK A6
        runner.bus.write_word(proc_addr + 6, 0x4E75); // RTS
        runner
            .dispatcher
            .modeless_dialog_draw_proc_queue
            .push_back((dialog_ptr, proc_offset, 5));

        assert!(runner.fire_modeless_dialog_draw_proc());

        let tramp = runner.dialog_draw_trampoline;
        assert_eq!(runner.bus.read_long(tramp + 16), proc_addr);
        assert_eq!(
            runner.dispatcher.active_modeless_dialog_draw_proc,
            Some(dialog_ptr)
        );
    }

    #[test]
    fn modeless_dialog_draw_procs_drain_after_plain_trap() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let base = 0x0001_0000u32;
        let interrupted_sp = 0x007F_FFC0u32;
        let dialog_ptr = runner.bus.alloc(170);
        let proc_1 = 0x0004_2000u32;
        let proc_2 = 0x0004_2100u32;

        runner.bus.write_word(base, 0xA861); // _Random
        runner.bus.write_word(base + 2, 0x60FE); // BRA.S *-0
        runner.cpu.write_reg(Register::PC, base);
        runner.cpu.write_reg(Register::A7, interrupted_sp);
        runner.dispatcher.init_cgraf_window(
            &mut runner.bus,
            &mut runner.cpu,
            dialog_ptr,
            0,
            120,
            180,
            240,
            420,
            "",
            2,
            true,
            false,
            false,
            0,
        );

        for proc_addr in [proc_1, proc_2] {
            runner.bus.write_word(proc_addr, 0x4E56); // LINK A6,#0
            runner.bus.write_word(proc_addr + 2, 0x0000);
            runner.bus.write_word(proc_addr + 4, 0x4E5E); // UNLK A6
            runner.bus.write_word(proc_addr + 6, 0x4E75); // RTS
        }
        runner.dispatcher.modeless_dialog_draw_proc_queue =
            VecDeque::from([(dialog_ptr, proc_1, 3), (dialog_ptr, proc_2, 5)]);

        let (_steps, running) = runner.run_steps(128, None);

        assert!(running);
        assert!(runner.dispatcher.modeless_dialog_draw_proc_queue.is_empty());
        assert_eq!(runner.dispatcher.active_modeless_dialog_draw_proc, None);
        assert!(
            runner.active_interrupt_callback.is_none(),
            "modeless draw callbacks should have returned to foreground code"
        );
    }

    #[test]
    fn dialog_draw_proc_does_not_restore_over_guest_selected_dialog_port() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let interrupted_pc = 0x0001_0000u32;
        let interrupted_sp = 0x007F_FFC0u32;
        let main_port = runner.bus.alloc(170);
        let dialog_ptr = runner.bus.alloc(170);
        let proc_addr = 0x0004_2000u32;
        let item_no = 5i16;

        runner.bus.write_word(interrupted_pc, 0x60FE); // BRA.S *-0
        runner.cpu.write_reg(Register::PC, interrupted_pc);
        runner.cpu.write_reg(Register::A7, interrupted_sp);

        runner.dispatcher.init_cgraf_window(
            &mut runner.bus,
            &mut runner.cpu,
            main_port,
            0,
            0,
            0,
            600,
            800,
            "",
            2,
            true,
            false,
            false,
            0,
        );
        runner.dispatcher.init_cgraf_window(
            &mut runner.bus,
            &mut runner.cpu,
            dialog_ptr,
            0,
            120,
            180,
            240,
            420,
            "",
            2,
            true,
            false,
            false,
            0,
        );
        runner
            .dispatcher
            .set_current_port_state(&mut runner.bus, &mut runner.cpu, main_port, None);

        runner.bus.write_word(proc_addr, 0x4E56); // LINK A6,#0
        runner.bus.write_word(proc_addr + 2, 0x0000);
        runner.bus.write_word(proc_addr + 4, 0x2F3C); // MOVE.L #dialog,-(SP)
        runner.bus.write_long(proc_addr + 6, dialog_ptr);
        runner.bus.write_word(proc_addr + 10, 0xA873); // _SetPort
        runner.bus.write_word(proc_addr + 12, 0x4E5E); // UNLK A6
        runner.bus.write_word(proc_addr + 14, 0x4E75); // RTS

        runner.dispatcher.dialog_tracking = Some(crate::trap::dispatch::DialogTrackingState {
            dialog_ptr,
            bounds: (120, 180, 240, 420),
            title: String::new(),
            proc_id: 1,
            items: Vec::new(),
            default_item: 0,
            cancel_item: 0,
            edit_text: String::new(),
            edit_item: 0,
            saved_pixels: Vec::new(),
            stack_ptr: interrupted_sp,
            item_hit_ptr: 0,
            rendered_pixels: Vec::new(),
            flash_remaining: 0,
            flash_delay: 0,
            flash_item: 0,
            edit_text_modified: false,
            draw_proc_queue: VecDeque::from([(proc_addr, item_no)]),
            draw_procs_done: false,
            rendered_pixels_final: false,
            filter_proc: 0,
            game_managed: false,
            last_filter_event: None,
            popup_draws: Vec::new(),
            active_popup: None,
            active_button: None,
            active_user_item: None,
        });

        assert!(runner.fire_dialog_draw_procs());
        assert_eq!(
            runner
                .active_interrupt_callback
                .as_ref()
                .and_then(|callback| callback.restore_port),
            None
        );

        let (_steps, running) = runner.run_steps(32, None);

        assert!(running);
        assert!(runner.active_interrupt_callback.is_none());
        assert_eq!(
            runner.dispatcher.current_port, dialog_ptr,
            "Dialog Manager must leave the dialog port current after the draw proc"
        );
    }

    #[test]
    fn dialog_draw_proc_pascal_stack_places_item_number_before_window_pointer() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let interrupted_pc = 0x0001_0000u32;
        let interrupted_sp = 0x007F_FFC0u32;
        let dialog_ptr = 0x0029_4240u32;
        let proc_addr = 0x0004_2000u32;
        let item_no = 2i16;
        let seen_item_addr = 0x0004_3000u32;
        let seen_dialog_addr = 0x0004_3004u32;

        runner.bus.write_word(interrupted_pc, 0x60FE); // BRA.S *-0
        runner.cpu.write_reg(Register::PC, interrupted_pc);
        runner.cpu.write_reg(Register::A7, interrupted_sp);

        // PROCEDURE MyItem(theWindow: WindowPtr; itemNo: INTEGER);
        // Inside Macintosh Volume I, I-405. MPW Pascal prologues observe
        // itemNo at 8(A6) and theWindow at 10(A6).
        runner.bus.write_word(proc_addr, 0x4E56); // LINK A6,#0
        runner.bus.write_word(proc_addr + 2, 0x0000);
        runner.bus.write_word(proc_addr + 4, 0x302E); // MOVE.W 8(A6),D0
        runner.bus.write_word(proc_addr + 6, 0x0008);
        runner.bus.write_word(proc_addr + 8, 0x33C0); // MOVE.W D0,(abs).L
        runner.bus.write_long(proc_addr + 10, seen_item_addr);
        runner.bus.write_word(proc_addr + 14, 0x222E); // MOVE.L 10(A6),D1
        runner.bus.write_word(proc_addr + 16, 0x000A);
        runner.bus.write_word(proc_addr + 18, 0x23C1); // MOVE.L D1,(abs).L
        runner.bus.write_long(proc_addr + 20, seen_dialog_addr);
        runner.bus.write_word(proc_addr + 24, 0x4E5E); // UNLK A6
        runner.bus.write_word(proc_addr + 26, 0x4E75); // RTS

        runner.dispatcher.dialog_tracking = Some(crate::trap::dispatch::DialogTrackingState {
            dialog_ptr,
            bounds: (120, 180, 240, 420),
            title: String::new(),
            proc_id: 1,
            items: Vec::new(),
            default_item: 0,
            cancel_item: 0,
            edit_text: String::new(),
            edit_item: 0,
            saved_pixels: Vec::new(),
            stack_ptr: interrupted_sp,
            item_hit_ptr: 0,
            rendered_pixels: Vec::new(),
            flash_remaining: 0,
            flash_delay: 0,
            flash_item: 0,
            edit_text_modified: false,
            draw_proc_queue: VecDeque::from([(proc_addr, item_no)]),
            draw_procs_done: false,
            rendered_pixels_final: false,
            filter_proc: 0,
            game_managed: false,
            last_filter_event: None,
            popup_draws: Vec::new(),
            active_popup: None,
            active_button: None,
            active_user_item: None,
        });

        assert!(runner.fire_dialog_draw_procs());
        let (_steps, running) = runner.run_steps(48, None);

        assert!(running);
        assert!(runner.active_interrupt_callback.is_none());
        assert_eq!(runner.bus.read_word(seen_item_addr) as i16, item_no);
        assert_eq!(runner.bus.read_long(seen_dialog_addr), dialog_ptr);
    }

    #[test]
    fn pending_delay_ticks_fire_vbl_tasks_in_headless_mode() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let interrupted_pc = 0x0001_0000;
        let interrupted_sp = 0x007F_FFC0;
        let task_ptr = 0x0020_2000;

        runner.bus.write_word(interrupted_pc, 0x4E71);
        runner.cpu.write_reg(Register::PC, interrupted_pc);
        runner.cpu.write_reg(Register::A7, interrupted_sp);
        runner.bus.write_long(0x016A, 0);
        runner.dispatcher.pending_delay_ticks = 1;

        runner.bus.write_word(task_ptr + 4, 1);
        runner.bus.write_long(task_ptr + 6, 0x0004_1234);
        runner.bus.write_word(task_ptr + 10, 1);
        runner.bus.write_word(task_ptr + 12, 0);
        runner.dispatcher.vbl_tasks.push(VblTask {
            task_ptr,
            slot: None,
        });

        let (steps, running) = runner.run_steps(1, None);

        assert!(running);
        assert_eq!(steps, 1);
        assert_eq!(runner.bus.read_long(0x016A), 1);
        assert_eq!(runner.dispatcher.pending_delay_ticks, 0);
        assert_eq!(runner.cpu.read_reg(Register::D0), 1);
        assert!(matches!(
            runner.active_interrupt_callback,
            Some(ActiveInterruptCallback {
                source: ActiveInterruptCallbackSource::Vbl,
                ..
            })
        ));
    }

    /// `set_mouse_position` updates both the dispatcher's tracked
    /// position and the six low-memory mouse globals (MTemp $0828,
    /// RawMouse $082C, Mouse $0830) so guest code that polls them
    /// directly sees the new coordinates without waiting for a click.
    /// Inside Macintosh Volume II, II-371.
    #[test]
    fn set_mouse_position_updates_dispatcher_and_low_mem_globals() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());

        runner.set_mouse_position(123, 456);

        assert_eq!(runner.dispatcher.mouse_pos, (123, 456));
        for off in [0x0828u32, 0x082C, 0x0830] {
            assert_eq!(runner.bus.read_word(off), 123u16, "v at ${:04X}", off);
            assert_eq!(runner.bus.read_word(off + 2), 456u16, "h at ${:04X}", off);
        }
    }

    /// Running a `DIVU.W D0,D1` with `D0 = 0` must not halt the
    /// runner. The `load_app_generic` loader installs an RTE stub at
    /// `$00FE` and points vector 5 (`$14`) at it; the m68k crate's
    /// zero-divide trap stacks the *next* PC and jumps to that vector,
    /// so RTE-ing returns past the DIVU and execution continues.
    /// Inside Macintosh Volume I, I-103 (Exception Vector Table);
    /// M68000PRM ("If the source operand is zero, the result of the
    /// operation is unpredictable").
    #[test]
    fn zero_divide_rte_handler_resumes_after_divu_by_zero() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());

        // Mirror what load_app_generic installs: RTE stub + vector.
        runner.bus.write_word(0x00FE, 0x4E73); // RTE
        runner.bus.write_long(0x0014, 0x0000_00FE);

        let prog = 0x0010_0000u32;
        runner.bus.write_word(prog, 0x82C0); // DIVU.W D0, D1
        runner.bus.write_word(prog + 2, 0x4E71); // NOP
        runner.bus.write_word(prog + 4, 0x4E71); // NOP

        runner.cpu.write_reg(Register::PC, prog);
        runner.cpu.write_reg(Register::A7, 0x007F_FFC0);
        runner.cpu.write_reg(Register::D0, 0);
        runner.cpu.write_reg(Register::D1, 100);

        // 1 step: DIVU.W traps, vectors to $00FE.
        // 2nd step: RTE at $00FE pops SR/PC, returns past DIVU.
        // 3rd step: NOP at prog+2.
        let (steps, running) = runner.run_steps(3, None);

        assert!(running, "runner must not halt on zero-divide");
        assert_eq!(steps, 3);
        assert_eq!(
            runner.cpu.read_reg(Register::PC),
            prog + 4,
            "PC must advance past the DIVU+NOP without re-entering the trap"
        );
        assert_eq!(
            runner.cpu.read_reg(Register::D1),
            100,
            "DIVU by zero must leave the destination register unchanged"
        );
    }

    /// CHK exception (vector 6) shares the same `$00FE` RTE stub as
    /// the zero-divide handler. A `CHK.W #5, D0` with `D0 = 100`
    /// exceeds the bound and triggers the trap; on a real Mac the
    /// handler calls SysError, on Systemless we silently RTE so D0 is
    /// preserved and the next instruction runs.
    /// Inside Macintosh Volume I, I-103.
    #[test]
    fn chk_rte_handler_resumes_after_bounds_violation() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());

        runner.bus.write_word(0x00FE, 0x4E73); // RTE
        runner.bus.write_long(0x0018, 0x0000_00FE); // CHK vector

        let prog = 0x0010_0000u32;
        runner.bus.write_word(prog, 0x41BC); // CHK.W #imm, D0
        runner.bus.write_word(prog + 2, 0x0005); // imm = 5
        runner.bus.write_word(prog + 4, 0x4E71); // NOP

        runner.cpu.write_reg(Register::PC, prog);
        runner.cpu.write_reg(Register::A7, 0x007F_FFC0);
        runner.cpu.write_reg(Register::D0, 100);

        // 1 step: CHK fires (100 > 5), vectors to $00FE.
        // 2nd step: RTE pops SR/PC, returns past CHK.
        // 3rd step: NOP executes.
        let (steps, running) = runner.run_steps(3, None);

        assert!(running, "runner must not halt on CHK bounds violation");
        assert_eq!(steps, 3);
        assert_eq!(
            runner.cpu.read_reg(Register::PC),
            prog + 6,
            "PC must advance past CHK (4 bytes) + NOP (2 bytes)"
        );
        assert_eq!(runner.cpu.read_reg(Register::D0), 100);
    }

    /// TRAPV (vector 7) shares the `$00FE` RTE stub. Pre-set the V
    /// flag in CCR via the m68k API and execute TRAPV; the trap fires
    /// because V is set, vectors to the RTE stub, and resumes at the
    /// next instruction. Inside Macintosh Volume I, I-103.
    #[test]
    fn trapv_rte_handler_resumes_when_v_flag_is_set() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());

        runner.bus.write_word(0x00FE, 0x4E73); // RTE
        runner.bus.write_long(0x001C, 0x0000_00FE); // TRAPV vector

        let prog = 0x0010_0000u32;
        runner.bus.write_word(prog, 0x4E76); // TRAPV
        runner.bus.write_word(prog + 2, 0x4E71); // NOP

        runner.cpu.write_reg(Register::PC, prog);
        runner.cpu.write_reg(Register::A7, 0x007F_FFC0);
        runner.cpu.core.set_ccr(0x02); // V flag set

        // 1: TRAPV traps; 2: RTE; 3: NOP.
        let (steps, running) = runner.run_steps(3, None);

        assert!(running, "runner must not halt on TRAPV");
        assert_eq!(steps, 3);
        assert_eq!(runner.cpu.read_reg(Register::PC), prog + 4);
    }

    /// `set_mouse_position` does NOT modify MBState ($0172) — it's a
    /// move-without-button-change, so the button-state byte should
    /// retain its prior value. The default at runner construction is
    /// 0x80 (button up).
    #[test]
    fn set_mouse_position_leaves_mb_state_untouched() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());

        runner.bus.write_byte(0x0172, 0x80);
        runner.set_mouse_position(50, 60);
        assert_eq!(runner.bus.read_byte(0x0172), 0x80);

        runner.bus.write_byte(0x0172, 0x00);
        runner.set_mouse_position(70, 80);
        assert_eq!(runner.bus.read_byte(0x0172), 0x00);
    }

    /// `push_mouse_down` must update MBState ($0172) to 0x00 (button
    /// pressed) immediately AND sync the position globals so guest
    /// code that polls these bytes directly sees the click without
    /// waiting for the next tick advance.
    /// Inside Macintosh Volume I, I-258 (MTemp/RawMouse/Mouse);
    /// Inside Macintosh Volume II, II-371 (MBState polling).
    #[test]
    fn push_mouse_down_writes_mb_state_pressed_and_position() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        runner.bus.write_byte(0x0172, 0x80); // start "button up"

        runner.push_mouse_down(123, 456);

        assert_eq!(
            runner.bus.read_byte(0x0172),
            0x00,
            "MBState must be 0x00 (pressed) immediately after push_mouse_down"
        );
        // All three position globals must mirror the click site so
        // games that poll them directly (Mouse $0830 etc.) see the
        // correct location, not the prior cursor-park position.
        assert_eq!(runner.bus.read_word(0x0828), 123u16);
        assert_eq!(runner.bus.read_word(0x082A), 456u16);
        assert_eq!(runner.bus.read_word(0x082C), 123u16);
        assert_eq!(runner.bus.read_word(0x082E), 456u16);
        assert_eq!(runner.bus.read_word(0x0830), 123u16);
        assert_eq!(runner.bus.read_word(0x0832), 456u16);
    }

    /// `push_mouse_up` must update MBState ($0172) to 0x80 (button
    /// released) immediately. On real hardware the ADB polls at ~200 Hz
    /// so the latency between physical release and MBState=0x80 is a
    /// few ms; deferring to advance_guest_tick (~16 ms) makes
    /// frame-rate-dependent games read the wrong button state for too
    /// many loop iterations after click-up. This test pins the
    /// immediate-sync contract documented at runner.rs `push_mouse_up`.
    #[test]
    fn push_mouse_up_writes_mb_state_released_immediately() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());

        runner.push_mouse_down(10, 20);
        assert_eq!(runner.bus.read_byte(0x0172), 0x00);

        runner.push_mouse_up(10, 20);
        assert_eq!(
            runner.bus.read_byte(0x0172),
            0x80,
            "MBState must flip back to 0x80 (released) immediately on push_mouse_up — \
             not deferred to the next tick"
        );
    }

    /// Regression: advance_guest_tick must NOT keep MBState at 0x00
    /// when both mouseDown and a paired mouseUp are queued and
    /// unconsumed. Polling-only games (Bonkheads-Deluxe class) never
    /// call GetNextEvent — the queue accumulates indefinitely.
    /// Pre-fix, the "any pending mouseDown → pressed" override left
    /// $0172 stuck at 0x00 forever, so Button() always returned TRUE
    /// and click detection broke silently. The fix counts unmatched
    /// mouseDowns (mouseDown count − mouseUp count) and only treats
    /// those as "still pressed".
    #[test]
    fn mb_state_releases_when_paired_mouseup_queued_but_unconsumed() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());

        runner.push_mouse_down(10, 20);
        runner.push_mouse_up(10, 20);
        // Both events still queued (no GetNextEvent has run). Drive the
        // tick boundary that owns the MBState resync.
        runner.advance_guest_tick();

        assert_eq!(
            runner.bus.read_byte(0x0172),
            0x80,
            "advance_guest_tick must release MBState to 0x80 once a \
             paired mouseUp is queued behind the mouseDown — even when \
             nothing has drained the event queue"
        );
        // Sanity-check the events ARE still in the queue (this test is
        // about MBState despite the unconsumed events, not about queue
        // state). The dispatcher field is pub(crate); read it through
        // the same accessor used by the production sync logic.
        assert!(
            runner.dispatcher.event_queue.iter().any(|e| e.what == 1),
            "mouseDown event must remain in the queue (would be drained by GetNextEvent)"
        );
        assert!(
            runner.dispatcher.event_queue.iter().any(|e| e.what == 2),
            "mouseUp event must remain in the queue"
        );
    }

    /// Mirror of `mb_state_releases_when_paired_mouseup_queued_but_unconsumed`:
    /// a SOLO mouseDown queued without a paired mouseUp must still pin
    /// MBState to 0x00 across tick boundaries. This preserves the
    /// original contract — code that hasn't yet started polling when
    /// the click was injected gets at least one TRUE pulse — without
    /// regressing into the stuck-pressed bug.
    #[test]
    fn mb_state_stays_pressed_with_solo_pending_mousedown() {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());

        runner.push_mouse_down(10, 20);
        runner.advance_guest_tick();
        assert_eq!(
            runner.bus.read_byte(0x0172),
            0x00,
            "MBState must stay pressed across a tick advance while only \
             a mouseDown is queued (no paired mouseUp yet)"
        );
    }

    #[test]
    fn set_menu_bar_visible_round_trips_through_public_api() {
        // Pins the FixtureRunner::set_menu_bar_visible / menu_bar_visible
        // pair as the public-API entry point for the kiosk-mode toggle.
        // Library embedders should not need to reach through
        // dispatcher_mut() into TrapDispatcher::menu_bar_hidden — the
        // method-based surface keeps the kiosk-on-by-default contract
        // discoverable from the FixtureRunner type alone.
        //
        // Default (constructor): kiosk on → menu bar NOT visible.
        // After set_menu_bar_visible(true): menu bar IS visible.
        // After set_menu_bar_visible(false): kiosk back on.
        // Skip when SYSTEMLESS_SHOW_MENU_BAR is set in the test env —
        // the env var pre-seeds menu_bar_hidden = false at construction
        // and would race the round-trip assertion.
        if std::env::var_os("SYSTEMLESS_SHOW_MENU_BAR").is_some() {
            return;
        }
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        assert!(
            !runner.menu_bar_visible(),
            "kiosk default: menu_bar_visible() must report false"
        );
        runner.set_menu_bar_visible(true);
        assert!(
            runner.menu_bar_visible(),
            "after set_menu_bar_visible(true), menu_bar_visible() must report true"
        );
        runner.set_menu_bar_visible(false);
        assert!(
            !runner.menu_bar_visible(),
            "after set_menu_bar_visible(false), menu_bar_visible() must report false"
        );
        // Internal field stays in sync with the public API — guards
        // against future refactors that introduce a parallel state
        // field but forget to wire it through the toggle.
        assert!(
            runner.dispatcher().menu_bar_hidden,
            "set_menu_bar_visible(false) must clear the kiosk-bypass bit"
        );
    }

    #[test]
    fn disassemble_at_decodes_known_opcodes_with_correct_advance() {
        // Pins the FixtureRunner::disassemble_at public-API helper.
        // This is the library-level entry point for pixel-divergence
        // and trap-misroute investigations: pair with
        // SYSTEMLESS_TRACE_FB_WRITE_RANGE to see what code lives at a
        // suspect PC.
        //
        // Seed three known instructions in guest RAM, disassemble,
        // and verify:
        //   1. each entry's PC advances by the previous size
        //   2. the mnemonic for $4E71 is "NOP" (well-known fixed
        //      instruction; no operand words to consume)
        //   3. an A-line trap word ($A8EC = CopyBits) comes back as
        //      "DC.W $A8EC" — the m68k crate's convention for opcodes
        //      it doesn't have a regular decoder for
        //   4. the size returned is at least 2 and at most 10 (the
        //      clamp guard that prevents a malformed opcode from
        //      consuming wrap-around amounts)
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let pc = 0x10000u32;
        // $4E71 NOP
        runner.bus.write_word(pc, 0x4E71);
        // $A8EC (CopyBits trap-line word)
        runner.bus.write_word(pc + 2, 0xA8EC);
        // $4E71 NOP again
        runner.bus.write_word(pc + 4, 0x4E71);
        let out = runner.disassemble_at(pc, 3);
        assert_eq!(
            out.len(),
            3,
            "disassemble_at must return exactly count entries"
        );
        assert_eq!(
            out[0].0, pc,
            "first entry's PC must equal the requested start"
        );
        assert!(
            out[0].1.contains("NOP"),
            "$4E71 must disassemble to NOP, got: {}",
            out[0].1
        );
        assert!(
            out[0].2 >= 2 && out[0].2 <= 10,
            "instruction size must be in clamp range [2, 10], got {}",
            out[0].2
        );
        assert_eq!(
            out[1].0,
            pc + out[0].2,
            "second entry's PC must equal first PC + first size"
        );
        assert!(
            out[1].1.contains("$A8EC"),
            "A-line trap $A8EC must surface in mnemonic (DC.W form), got: {}",
            out[1].1
        );
        assert!(
            out[2].1.contains("NOP"),
            "third entry must be the second NOP we seeded"
        );
    }
}